diff --git a/AGENTS.md b/AGENTS.md index 0e94628..9b54296 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** (6752 symbols, 31140 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** (6768 symbols, 31339 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). @@ -181,14 +181,14 @@ This project is indexed by GitNexus as **museion** (6752 symbols, 31140 relation - 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) - `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178) - A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178) -- 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) +- 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); the race persists in a chained read one command later — read the bundle from a LATER terminal invocation and retry the identical read once before diagnosing (#179) - A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177) - Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177) - 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) - An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151) - 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) -- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — avoid the wrap (nested ifs / a hoisted helper), don't fight the formatter (#142) +- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — and the nested-if escape ALSO fails (swiftformat collapses it into one long line; line_length flags that). Hoist a predicate helper; that's the only stable shape (#142, #179) - swiftformat's self-remove strips a load-bearing `self.` when a local hoists a property for a detached capture (`let x = self.x` becomes the self-referential `let x = x`) — rename the local so nothing shadows (#143) - A `//` note sitting between a `///` doc block and its declaration detaches the doc (swiftlint orphaned_doc_comment) — fold such notes into the `///` block (#143) - Sequential bounded-poll loops each arm their OWN deadline — a shared one starves the later loop, which then fails on the earlier flush's stale observable (zeros, never nil) (#147) @@ -205,6 +205,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) | | 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) | | 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | | 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) | @@ -214,6 +215,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-11-04 | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](docs/devlog/20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | | 2026-11-04 | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](docs/devlog/20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) | | 2026-11-04 | [20261104-issue163-cold-turkey-calibration-gate-calm_log.md](docs/devlog/20261104-issue163-cold-turkey-calibration-gate-calm_log.md) | -| 2026-11-04 | [20261104-issue162-cold-turkey-writing-lock-integration_log.md](docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md) | -| 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 8731e97..69f8829 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -35,7 +35,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4). - `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends. - Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept. -- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal". `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, construction + Settings repoint; no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). - `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID. - `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load. - `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction. diff --git a/Museion/FixCardsWindow.swift b/Museion/FixCardsWindow.swift index a6f4b2e..1f2f7f7 100644 --- a/Museion/FixCardsWindow.swift +++ b/Museion/FixCardsWindow.swift @@ -149,7 +149,7 @@ private struct CardRow: View { .controlSize(.small) } else { Button("Done") { - gate.posts.doneCard(card, home: gate.museionHome) + gate.posts.doneCard(card) } .buttonStyle(.bordered) .controlSize(.small) @@ -174,11 +174,11 @@ private struct CardRow: View { // Apply = ask-before, a BLOCKING ask: the sheet is the only path // from the Apply button to a write. .sheet(isPresented: $asking) { - ApplyAskSheet(card: card, posts: gate.posts, home: gate.museionHome) + ApplyAskSheet(card: card, posts: gate.posts) } // #26: Promote is its own blocking ask — one confirm, one Learning. .sheet(isPresented: $promoting) { - PromoteAskSheet(card: card, posts: gate.posts, home: gate.museionHome) + PromoteAskSheet(card: card, posts: gate.posts) } } @@ -217,7 +217,7 @@ private struct SkipButton: View { var body: some View { Button("Skip") { - gate.posts.skipCard(card, home: gate.museionHome) + gate.posts.skipCard(card) } .buttonStyle(.borderless) .controlSize(.small) @@ -232,7 +232,6 @@ private struct SkipButton: View { private struct ApplyAskSheet: View { let card: FixCardStore.StoredFixCard let posts: PostsModel - let home: URL @Environment(\.dismiss) private var dismiss @State private var wentStale = false @@ -289,7 +288,7 @@ private struct ApplyAskSheet: View { } private func apply() { - switch posts.applyCard(card, home: home) { + switch posts.applyCard(card) { case .applied: dismiss() case .stale: diff --git a/Museion/MentorPaneView.swift b/Museion/MentorPaneView.swift index 445b4c5..6d26f3e 100644 --- a/Museion/MentorPaneView.swift +++ b/Museion/MentorPaneView.swift @@ -92,7 +92,7 @@ struct MentorPaneView: View { // Pass 2 selector replaced the mode picker; the transcript + // composer below are the conversation surface, chat is not a // mode. - PassBarView(posts: posts, home: home, model: model, onOpenSettings: onOpenSettings) + PassBarView(posts: posts, model: model, onOpenSettings: onOpenSettings) Divider() if let posts, !posts.openPieceCards.isEmpty { // #23 follow-up + #156 ruling: a plain mono row — a link, @@ -385,7 +385,6 @@ private struct PassBarView: View { /// The selected pass — the bar's own state (nothing outside reads it). @State private var kind: PassKind = .pass1 let posts: PostsModel? - let home: URL? let model: MentorSessionModel /// #137 (S4): the missing-key line's way out — WorkspaceView's pane hop. let onOpenSettings: (() -> Void)? @@ -547,8 +546,8 @@ private struct PassBarView: View { } private func runPass() { - guard let posts, let home else { return } - Task { await posts.runPass(kind, home: home, mentor: model) } + guard let posts else { return } + Task { await posts.runPass(kind, mentor: model) } } /// #122: the Blind Read — one purposeful click judges the current @@ -560,8 +559,8 @@ private struct PassBarView: View { style: .secondary, disabled: blindReadBlocked != nil, ) { - guard let posts, let home else { return } - Task { await posts.blindRead(home: home, mentor: model) } + guard let posts else { return } + Task { await posts.blindRead(mentor: model) } } .help( blindReadBlocked diff --git a/Museion/Micropub.swift b/Museion/Micropub.swift index e974e63..0eb25a1 100644 --- a/Museion/Micropub.swift +++ b/Museion/Micropub.swift @@ -244,8 +244,9 @@ extension PostsModel { /// 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. + /// #179: outside the write rail by design — publish is not a library + /// verb, and a stamp failure must never un-send the draft. func micropubSendDraft( - home: URL, token: String, transport: Micropub.Transport = Micropub.urlSessionTransport, ) async -> Micropub.Outcome { @@ -266,7 +267,8 @@ extension PostsModel { // 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), + guard let home = watchedHome, + 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.") diff --git a/Museion/MicropubPublishSheet.swift b/Museion/MicropubPublishSheet.swift index d1b304a..9ac72e0 100644 --- a/Museion/MicropubPublishSheet.swift +++ b/Museion/MicropubPublishSheet.swift @@ -17,7 +17,6 @@ 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 { @@ -162,7 +161,7 @@ struct MicropubPublishSheet: View { refusal = nil phase = .drafting Task { - switch await posts.micropubSendDraft(home: home, token: token) { + switch await posts.micropubSendDraft(token: token) { case let .drafted(url, preview): draftURL = url previewURL = preview diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 605b4a8..7a9f25d 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -12,6 +12,11 @@ // PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching // + rescan sit in the file-scope watcher extension below (type-body // ceiling). +// #179: every library-reflecting store write rides `performWrite` — the +// one write rail pairing each write with exactly one rescan and owning +// the error strip (card closes and the pass substrate stay off it: they +// never regroup the library); the model owns the Home (watchedHome), no +// method takes one. // import CoreServices @@ -171,8 +176,11 @@ final class PostsModel { /// Last failed-op message surfaced in the editor (nil = clean). /// #146: setter internal — the split-out domain extensions set it. var lastError: String? - /// Home the watcher is bound to; also the rescan target. - private var watchedHome: URL? + /// #179: the bound Home — the MODEL owns it. Construction (`bind`) and + /// the Settings repoint (bind again through `.task(id:)`) are the only + /// writers; no public method takes a Home parameter, callers pass none. + /// `private(set)` — the setter stays PostsModel.swift-file-private. + private(set) var watchedHome: URL? private var watcher = PostsWatcher() /// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed /// post.md files, not the library (see PostScanCache). @@ -196,6 +204,33 @@ final class PostsModel { // writes and same-volume moves; if a big Home ever stalls the UI, wrap // them in Task.detached like rescan. + /// #179: the write rail — ONE seam pairs every library store write with + /// exactly one rescan and owns the error strip. A verb passes its + /// PostStore write (plus any post-write state surgery); a throw lands + /// its reason in the strip with nothing rescanned, a clean run rescans + /// once. The strip clears BEFORE the write, so a batch write that sets + /// its own per-file failure messages mid-closure (importFiles) keeps + /// them. The editor's debounced flush stays OUTSIDE the rail — its + /// error semantics are the session's own (EditorSession.onError). + /// Returns nil when the write landed; the failure reason otherwise + /// (createProject hands that to its sheet). + @discardableResult + func performWrite(_ write: (URL) throws -> Void) -> String? { + guard let home = watchedHome else { + lastError = "No library is open yet — nothing was changed." + return lastError + } + lastError = nil + do { + try write(home) + Task { await rescan() } + return nil + } catch { + lastError = error.localizedDescription + return lastError + } + } + /// #107: the project a NEW piece lands in — #108: an explicit pending /// target first, else the selected non-archived post's project, else the /// default. One home; newPost/importFiles must not drift. @@ -260,11 +295,10 @@ final class PostsModel { /// First save of the draft (#62): lazy folder, slug, #59 stamp all fire /// here. The saved post opens straight into an editing session — the - /// writer keeps typing where they were. Rescans immediately (the watcher - /// would too, after its window). - func saveDraft(home: URL) { + /// writer keeps typing where they were. #179: the write rides the rail. + func saveDraft() { guard let draft else { return } - do { + performWrite { home in let post = try PostStore.writeNew(body: draft.text, project: draft.project, type: draft.type, home: home) lastDraftWasOutline = draft.type == .outline // #109: covers the lagging rescan self.draft = nil @@ -272,10 +306,6 @@ final class PostsModel { selectedPostID = post.id session = EditorSession(postID: post.id, home: home) wireSession() - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } @@ -283,18 +313,16 @@ final class PostsModel { /// draft stamped `origin: ai` (never stats-eligible) and open it in /// Posts (select's open path; the WorkspaceView selection onChange /// hops the pane). Nil + lastError on failure; Cancel never gets here. + /// #179: the write rides the rail. @discardableResult - func newPostFromSession(body: String, home: URL) -> Post? { - do { + func newPostFromSession(body: String) -> Post? { + var written: Post? + performWrite { home in let post = try PostStore.writeNew(body: body, origin: .ai, home: home) - select(post.id, home: home) - lastError = nil - Task { await rescan() } - return post - } catch { - lastError = error.localizedDescription - return nil + written = post + select(post.id) } + return written } /// Select a Post; selecting anything abandons an unsaved draft (the @@ -306,7 +334,8 @@ final class PostsModel { /// fires the mixed-content guard — the open is held (routing stays /// prose) until the writer picks. The old session still ends here: /// its flush is prose-mode, so it can't drop anything. - func select(_ id: String, home: URL) { + func select(_ id: String) { + guard watchedHome != nil else { return } // #179: no library, no open dismissExternal() // A reselect of the already-open piece is a no-op — INCLUDING a // guarded one: the piece is open under a prior answer, and firing @@ -318,7 +347,7 @@ final class PostsModel { if let session { session.teardown(flushFirst: true) } - if isGuardedOutline(id, home: home) { + if isGuardedOutline(id) { outlineGuardPieceID = id proseOverridePostID = nil session = nil @@ -326,13 +355,13 @@ final class PostsModel { pendingProject = nil lastDraftWasOutline = false selectedPostID = id - refreshCards(home: home) // #23: nil session — the held ask shows no cards + refreshCards() // #23: nil session — the held ask shows no cards return } // The prior session was torn down above; openUnguarded's guards // are dead code on this path (session is nil or a different id) — // kept: one open body answers select and the ask alike. - openUnguarded(id, home: home) + openUnguarded(id) proseOverridePostID = nil // #111: the override died with the open it covered } @@ -379,14 +408,14 @@ final class PostsModel { /// Explicit Rename = retitle + move (#60). Renaming the open post flushes /// first (rename reads the file from disk — unflushed edits must land - /// before the move), then reopens a session at the new id. Sets lastError - /// on failure. - func rename(_ post: Post, to title: String, home: URL) { + /// before the move), then reopens a session at the new id. #179: the + /// write rides the rail. + func rename(_ post: Post, to title: String) { // #108 audit 2: rename reads the file from disk — a failed write // aborts (moving the folder would strand unflushed edits), and the // session stays up, dirty and honest. guard flushOrAbort(post.id) else { return } - do { + performWrite { home in let moved = try PostStore.rename(post, to: title, home: home) if selectedPostID == post.id { selectedPostID = moved.id @@ -395,18 +424,15 @@ final class PostsModel { wireSession() } } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } /// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it /// was the post; the session is torn down (cancel only — the folder is /// leaving, a flush would resurrect nothing but churn the watcher). - func trash(_ post: Post, home: URL) { - do { + /// #179: the write rides the rail. + func trash(_ post: Post) { + performWrite { home in try PostStore.trash(post, home: home) if selectedPostID == post.id { selectedPostID = nil @@ -415,10 +441,6 @@ final class PostsModel { session = nil } } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } @@ -431,16 +453,12 @@ final class PostsModel { newPost() } - /// #108: raw create — the sheet composes on it. The failure reason on - /// false (shown inline in the sheet; never routed into lastError — the - /// strip behind the sheet must not double-message one error). - func createProject(named name: String, home: URL) -> String? { - do { - try PostStore.createProject(named: name, home: home) - return nil // success - } catch { - return error.localizedDescription - } + /// #108: raw create — the sheet composes on it. #179: rides the write + /// rail (one rescan pairs the new folder); the failure reason is BOTH + /// returned for the sheet's inline display AND owned by the strip — + /// the rail posture replaces the old sheet-only rule. + func createProject(named name: String) -> String? { + performWrite { try PostStore.createProject(named: name, home: $0) } } /// #108: File ▸ New Project… — stage the ask (WorkspaceView presents). @@ -457,7 +475,8 @@ final class PostsModel { /// projects/ plus the default (bind creates the roots, not posts/ — an /// empty Home must still offer it), localized-sorted to match the /// library's section order. - func moveTargets(home: URL) -> [String] { + func moveTargets() -> [String] { + guard let home = watchedHome else { return [Post.defaultProject] } let root = home.appendingPathComponent("projects", isDirectory: true) let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] var names = Set(onDisk.filter { !$0.hasPrefix(".") }) @@ -493,27 +512,25 @@ final class PostsModel { /// #108: Move to Project — flush first (move reads disk), then the /// folder moves under projects/. Id stays the same; the session is /// reopened anyway so folderURL re-resolves to the new parent. - func moveToProject(_ post: Post, project: String, home: URL) { + /// #179: the write rides the rail. + func moveToProject(_ post: Post, project: String) { guard flushOrAbort(post.id) else { return } - do { + performWrite { home in try PostStore.move(post, to: project, home: home) if session?.postID == post.id { session = EditorSession(postID: post.id, home: home) wireSession() } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } /// #108: Move to Archive. Archiving the open piece clears it — the /// editor is empty until the next selection (archived pieces open from - /// the Archive pane, where they're listed). - func archivePost(_ post: Post, home: URL) { + /// the Archive pane, where they're listed). #179: the write rides the + /// rail. + func archivePost(_ post: Post) { guard flushOrAbort(post.id) else { return } - do { + performWrite { home in try PostStore.archive(post, home: home) if selectedPostID == post.id { selectedPostID = nil @@ -522,10 +539,6 @@ final class PostsModel { open.teardown(flushFirst: false) // already flushed above session = nil } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } @@ -533,20 +546,17 @@ final class PostsModel { /// the writer stays in the piece they just revived. A session already /// open on the piece survives `select` — reopen it so folderURL points /// at projects/, not the archive path it was born with. - func restorePost(_ post: Post, home: URL) { + /// #179: the write rides the rail. + func restorePost(_ post: Post) { guard flushOrAbort(post.id) else { return } - do { + performWrite { home in try PostStore.restore(post, home: home) if let open = session, open.postID == post.id { session = EditorSession(postID: post.id, home: home) wireSession() } else { - select(post.id, home: home) + select(post.id) } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } @@ -554,14 +564,16 @@ final class PostsModel { /// Flush-first like every folder move (a dirty open piece inside the /// project would otherwise race the move), and its session is reopened so /// folderURL re-resolves off archive/ (same reason as restorePost). - func unarchiveProject(_ name: String, home: URL) { - /// #108 audit 2: disk-derived membership — the posts snapshot is stale - /// the moment a Finder move lands. Captured BEFORE the move: after it - /// the piece resolves under projects/ and its archive membership is - /// invisible. dir − 1 = project dir (…/archive/), − 2 = root. + /// #179: the write rides the rail. + func unarchiveProject(_ name: String) { + // #108 audit 2: disk-derived membership — the posts snapshot is stale + // the moment a Finder move lands. Captured BEFORE the move: after it + // the piece resolves under projects/ and its archive membership is + // invisible. dir − 1 = project dir (…/archive/), − 2 = root. + guard let boundHome = watchedHome else { return } func openPieceInArchivedProject() -> String? { guard let id = session?.postID, - let projectDir = PostStore.folder(of: id, home: home)?.deletingLastPathComponent(), + let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(), projectDir.lastPathComponent == name, projectDir.deletingLastPathComponent().lastPathComponent == "archive" else { return nil } @@ -572,16 +584,12 @@ final class PostsModel { // #108 audit 2: the only #108 folder move that skipped the gate. guard flushOrAbort(openID) else { return } } - do { + performWrite { home in try PostStore.unarchiveProject(name, home: home) if let openID { session = EditorSession(postID: openID, home: home) wireSession() } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } @@ -644,28 +652,26 @@ final class PostsModel { /// default, reversible; never an alert, never an abort). The last /// imported post opens; a failure anywhere keeps its message up even /// when other files landed. #107: the batch lands in the selected - /// post's project (newPost's target rule). - func importFiles(origin: Post.Origin, home: URL) { + /// post's project (newPost's target rule). #179: the batch rides the + /// rail — the strip was cleared up front, so the per-file failure + /// messages the loop sets survive the rail's success tail. + func importFiles(origin: Post.Origin) { guard let urls = pendingImportURLs else { return } pendingImportURLs = nil let project = targetProject var last: Post? - var failures = 0 - for url in urls { - do { - last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) - } catch { - failures += 1 - lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" + performWrite { home in + for url in urls { + do { + last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) + } catch { + lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" + } } } if let last { - select(last.id, home: home) + select(last.id) } - if failures == 0 { - lastError = nil - } - Task { await rescan() } } /// #146: internal — the split-out domain extensions wire sessions too. @@ -739,6 +745,6 @@ extension PostsModel { } // #23: the open piece's stored fix cards ride the same rescan — // the watcher fires on /cards/ writes too. - refreshCards(home: home) + refreshCards() } } diff --git a/Museion/PostsModelCards.swift b/Museion/PostsModelCards.swift index 586d740..9bc303f 100644 --- a/Museion/PostsModelCards.swift +++ b/Museion/PostsModelCards.swift @@ -20,8 +20,11 @@ extension PostsModel { /// transitions — the piece-roots watcher already fires on cards/ writes. /// #122: the same pass also derives `openPieceHasSnapshot` (the Blind /// Read's base) — one detached read of the open piece's disk facts. - func refreshCards(home: URL) { - guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else { + func refreshCards() { + guard let id = session?.postID, + let home = watchedHome, + let folder = PostStore.folder(of: id, home: home) + else { openPieceCards = [] openPieceHasSnapshot = false return @@ -68,7 +71,7 @@ extension PostsModel { /// flags the card and touches no text. A failed close after a landed /// edit is reported via lastError, never silent. @discardableResult - func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome { + func applyCard(_ card: FixCardStore.StoredFixCard) -> FixCardApplyOutcome { guard card.status == .open else { return .refused("card already closed") } guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") } guard let session, let postID = session.postID else { @@ -86,30 +89,29 @@ extension PostsModel { } catch { lastError = "card close failed: \(error.localizedDescription)" } - refreshCards(home: home) + refreshCards() return .stale } guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") } - closeCard(card, status: .applied, home: home) + closeCard(card, status: .applied) return .applied } /// #25 (S3.3): Skip — not this instance. Closes the card recording /// NOTHING beyond the status flip (CONTEXT.md). - func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) { - closeCard(card, status: .skipped, home: home) + func skipCard(_ card: FixCardStore.StoredFixCard) { + closeCard(card, status: .skipped) } /// #25 (S3.3): Done — the writer rewrote the span themselves. Same /// flip, different terminal. - func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) { - closeCard(card, status: .done, home: home) + func doneCard(_ card: FixCardStore.StoredFixCard) { + closeCard(card, status: .done) } private func closeCard( _ card: FixCardStore.StoredFixCard, status: FixCardStore.StoredFixCard.Status, - home: URL, ) { guard let session else { lastError = "open the piece to work its cards" @@ -120,7 +122,7 @@ extension PostsModel { } catch { lastError = "card close failed: \(error.localizedDescription)" } - refreshCards(home: home) + refreshCards() } } @@ -140,7 +142,7 @@ extension PostsModel { /// counter; the store guarantees the one-stamp rule). Touches no text /// and flushes nothing: this writes a Learning, not an edit. @discardableResult - func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome { + func promoteCard(_ card: FixCardStore.StoredFixCard) -> FixCardPromoteOutcome { guard card.promotedAt == nil else { return .refused("card already promoted") } guard let session else { return .refused("open the piece to work its cards") } do { @@ -149,7 +151,7 @@ extension PostsModel { lastError = "learning write failed: \(error.localizedDescription)" return .refused("learning write failed: \(error.localizedDescription)") } - refreshCards(home: home) + refreshCards() return .promoted } } diff --git a/Museion/PostsModelOutline.swift b/Museion/PostsModelOutline.swift index fe1074e..9e49328 100644 --- a/Museion/PostsModelOutline.swift +++ b/Museion/PostsModelOutline.swift @@ -21,8 +21,9 @@ extension PostsModel { /// (the same window lastDraftWasOutline covers) — ONE disk read derives /// both. No watched home yet (pre-bind) = post: nothing to guard. /// #146: internal — `select` (PostsModel.swift) asks the guard. - func isGuardedOutline(_ id: String, home: URL) -> Bool { - guard let dir = PostStore.folder(of: id, home: home), + func isGuardedOutline(_ id: String) -> Bool { + guard let home = watchedHome, + let dir = PostStore.folder(of: id, home: home), let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) else { return false } let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type { @@ -37,17 +38,17 @@ extension PostsModel { /// outliner never mounts, nothing drops); Outline = explicit consent, /// opens the outliner (saves normalize/drop as today). Cancel = back /// out (no session); the piece stays guarded on the next open. - func openGuardedOutlineInProse(home: URL) { + func openGuardedOutlineInProse() { guard let id = outlineGuardPieceID else { return } outlineGuardPieceID = nil proseOverridePostID = id // routing: prose until the next open - openUnguarded(id, home: home) + openUnguarded(id) } - func openGuardedOutlineAsOutline(home: URL) { + func openGuardedOutlineAsOutline() { guard let id = outlineGuardPieceID else { return } outlineGuardPieceID = nil - openUnguarded(id, home: home) + openUnguarded(id) } /// #111 (S7): the ask's Cancel — the held open dies (no session opens, @@ -64,7 +65,8 @@ extension PostsModel { /// explicit choice the ruling requires. /// #146: internal — `select` (PostsModel.swift) routes its tail through /// this one open body. - func openUnguarded(_ id: String, home: URL) { + func openUnguarded(_ id: String) { + guard let home = watchedHome else { return } dismissExternal() if let session, session.postID != id { session.teardown(flushFirst: true) @@ -76,7 +78,7 @@ extension PostsModel { outlineGuardPieceID = nil // the open displaces any held ask selectedPostID = id wireSession() - refreshCards(home: home) // #23: the newly opened piece's cards, now + refreshCards() // #23: the newly opened piece's cards, now } } @@ -95,12 +97,14 @@ extension PostsModel { /// The open session's text is the truth when the piece is open — disk /// lags the debounce, and a stale-clean read would drop the warning /// for prose typed since the last flush (#114 audit). - func stageConversion(_ post: Post, home: URL) { + func stageConversion(_ post: Post) { guard post.type == .outline else { return } let body: String = if let session, session.postID == post.id { session.text - } else { + } else if let home = watchedHome { PostStore.readBody(id: post.id, home: home) ?? "" + } else { + "" } pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body)) } @@ -110,40 +114,44 @@ extension PostsModel { pendingConversion = nil } + /// #114 audit: consent recheck — the sheet's warning covered the STAGED + /// body; if the answer-time body went lossy behind the ask (foreign + /// write, late edit) and the writer was never warned, Headings would + /// drop unconsented prose. + private func conversionWentLossyBehindAsk(_ pending: PendingConversion, headingsLadder: Bool) -> Bool { + guard headingsLadder, !pending.lossy, let home = watchedHome, + let body = PostStore.readBody(id: pending.id, home: home) + else { return false } + return OutlineTree.parsesWithLoss(body) + } + /// #114 (S4): the answer. Flush-first when the piece is open (the /// transform reads disk), flip `type` + transform the body once, then /// reopen the session routed to prose — proseOverridePostID covers the /// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that /// isn't open just converts; nothing else moves. One-way in v1. - func convertToPost(headingsLadder: Bool, home: URL) { + /// #179: the write rides the rail. + func convertToPost(headingsLadder: Bool) { guard let pending = pendingConversion else { return } pendingConversion = nil guard flushOrAbort(pending.id) else { return } - do { - // The sheet's warning covered the STAGED body. If the - // answer-time body went lossy behind the ask (foreign write, - // late edit) and the writer was never warned, Headings would - // drop unconsented prose — abort, nothing converted (#114 audit). - if headingsLadder, !pending.lossy, let body = PostStore.readBody(id: pending.id, home: home), OutlineTree.parsesWithLoss(body) { - lastError = "The outline changed since the sheet opened — nothing was converted." - return - } + if conversionWentLossyBehindAsk(pending, headingsLadder: headingsLadder) { + lastError = "The outline changed since the sheet opened — nothing was converted." + return + } + performWrite { home in try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home) if session?.postID == pending.id { session?.teardown(flushFirst: false) // flushOrAbort already wrote session = nil proseOverridePostID = pending.id - openUnguarded(pending.id, home: home) + openUnguarded(pending.id) } if outlineGuardPieceID == pending.id { // Multi-window: the held #111 ask targets an outline that no // longer is — dismiss it as a cancel (the ask's own teardown). cancelOutlineGuard() } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription } } } diff --git a/Museion/PostsModelPasses.swift b/Museion/PostsModelPasses.swift index 8a3713e..c66387c 100644 --- a/Museion/PostsModelPasses.swift +++ b/Museion/PostsModelPasses.swift @@ -19,7 +19,7 @@ extension PostsModel { /// engine's turn ends normally — never on cancel, refusal, or crash, /// and never when fix cards resolve. Passes run in any order /// (advancePassState is monotonic). - func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async { + func runPass(_ kind: PassKind, mentor: MentorSessionModel) async { guard runningPass == nil, !runningBlindRead else { lastError = "A pass is already running." return @@ -53,6 +53,8 @@ extension PostsModel { return } guard flushOrAbort(id) else { return } // the engine reads disk + // #179: the model owns the Home; an open piece implies a bound one. + guard let home = watchedHome else { return } do { try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home) } catch { @@ -82,13 +84,18 @@ extension PostsModel { guard case let .ended(stopReason) = outcome, stopReason != "refusal" else { return // cancelled / refused / failed — the transcript tells the story } - do { - _ = try PostStore.advancePassState(id: id, kind: kind, home: home) - lastError = nil - Task { await rescan() } // the library regroups by Pass State - } catch { - lastError = error.localizedDescription + // #179 audit: the engine ran for minutes — a Settings repoint since + // the snapshot re-bound watchedHome to another library. Advancing + // through the rail would stamp pass-state frontmatter onto THAT + // library (an unrelated same-slug piece on collision — silently). + // Refuse honestly; the snapshot stays in the pass's own library. + guard watchedHome == home else { + lastError = "The library changed while the pass ran — its Pass State was not advanced." + return } + // #179: the pass-advance write rides the rail — one rescan, and the + // strip ownership is the rail's (the library regroups by Pass State). + performWrite { try PostStore.advancePassState(id: id, kind: kind, home: $0) } } /// #24 (S3.1): the pass bar's Cancel — the existing session/cancel @@ -109,7 +116,7 @@ extension PostsModel { /// advance, no cards, no Learnings — the verdict and the reveal live in /// the transient transcript and die with it. The writer stays judge of /// record. - func blindRead(home: URL, mentor: MentorSessionModel) async { + func blindRead(mentor: MentorSessionModel) async { guard runningPass == nil else { lastError = "A pass is already running." return @@ -138,7 +145,10 @@ extension PostsModel { return } guard flushOrAbort(id) else { return } - guard let base = PostStore.latestPassSnapshot(id: id, home: home) else { + // #179: the model owns the Home; an open piece implies a bound one. + guard let home = watchedHome, + let base = PostStore.latestPassSnapshot(id: id, home: home) + else { lastError = "No Pass snapshot yet — run a Pass first." return } diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 4eb1f83..20c901f 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -92,7 +92,7 @@ struct PostsPaneView: View { // #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) + MicropubPublishSheet(posts: model) } } @@ -112,7 +112,7 @@ struct PostsPaneView: View { draftText: draft.text, draftEdited: { model.updateDraft($0) }, draftSave: { - model.saveDraft(home: home) + model.saveDraft() }, outline: draft.type == .outline, ) @@ -317,7 +317,7 @@ struct PostsLibraryColumn: View { .background(LaunchFocusReset()) .sheet(item: $renamingPost) { post in RenamePostSheet(post: post) { title in - model.rename(post, to: title, home: home) + model.rename(post, to: title) } } .sheet(item: $movingPost) { post in @@ -325,8 +325,8 @@ struct PostsLibraryColumn: View { // the library renders (Unicode-scalar sort split them), and it // includes empty projects (a fresh New Project has no pieces yet — // it must already be a move target). - MoveToProjectSheet(post: post, projects: model.moveTargets(home: home)) { project in - model.moveToProject(post, project: project, home: home) + MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in + model.moveToProject(post, project: project) } } // #144: keystroke-debounced (250 ms), structured body scan — @@ -355,7 +355,7 @@ struct PostsLibraryColumn: View { /// render the same row (#144: results carry the full menu too). private func postRow(_ post: Post) -> some View { LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { - model.select(post.id, home: home) + model.select(post.id) } .contextMenu { Button("Rename…") { renamingPost = post } @@ -363,15 +363,15 @@ struct PostsLibraryColumn: View { // body transform, then the piece becomes a prose post. if post.type == .outline { Button("Convert to Post…") { - model.stageConversion(post, home: home) + model.stageConversion(post) } } Button("Move to Project…") { movingPost = post } Button("Move to Archive") { - model.archivePost(post, home: home) + model.archivePost(post) } Button("Move to Trash", role: .destructive) { - model.trash(post, home: home) + model.trash(post) } } } diff --git a/Museion/PromoteAskSheet.swift b/Museion/PromoteAskSheet.swift index 7ac3fb0..26b4d5e 100644 --- a/Museion/PromoteAskSheet.swift +++ b/Museion/PromoteAskSheet.swift @@ -17,7 +17,6 @@ import SwiftUI struct PromoteAskSheet: View { let card: FixCardStore.StoredFixCard let posts: PostsModel - let home: URL @Environment(\.dismiss) private var dismiss @State private var refusal: String? @@ -108,7 +107,7 @@ struct PromoteAskSheet: View { } private func promote() { - switch posts.promoteCard(card, home: home) { + switch posts.promoteCard(card) { case .promoted: dismiss() case let .refused(reason): diff --git a/Museion/SessionsPaneView.swift b/Museion/SessionsPaneView.swift index 10ff600..5b258f7 100644 --- a/Museion/SessionsPaneView.swift +++ b/Museion/SessionsPaneView.swift @@ -340,8 +340,8 @@ struct SessionsPaneView: View { /// opened); a failed write keeps the sheet up with the draft intact /// (ApplyAskSheet posture — the edited draft is never destroyed). private func newPostFromSession() -> String? { - guard let posts, let home else { return "No library to write into." } - if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil { + guard let posts else { return "No library to write into." } + if posts.newPostFromSession(body: sessionDraft ?? "") == nil { return posts.lastError ?? "The piece couldn't be written." } sessionDraft = nil diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index 698a1f0..8613b2c 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -117,14 +117,14 @@ struct WorkspaceView: View { // answer (Esc/Cancel) drops the batch. .sheet(isPresented: originAskBinding) { OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in - gate.posts.importFiles(origin: origin, home: gate.museionHome) + gate.posts.importFiles(origin: origin) } } // #108: File ▸ New Project… ask — commands can't present sheets, so // the model stages and this window presents (OriginAsk pattern). .sheet(isPresented: newProjectAskBinding) { NewProjectSheet { name in - if let reason = gate.posts.createProject(named: name, home: gate.museionHome) { + if let reason = gate.posts.createProject(named: name) { return reason } gate.posts.newProjectPending(named: name) @@ -137,9 +137,9 @@ struct WorkspaceView: View { // drop; Esc/Cancel backs out with nothing opened. .sheet(isPresented: outlineGuardBinding) { OutlineGuardSheet { - gate.posts.openGuardedOutlineInProse(home: gate.museionHome) + gate.posts.openGuardedOutlineInProse() } openAsOutline: { - gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome) + gate.posts.openGuardedOutlineAsOutline() } } // #114 (S4): the Convert to Post ask — which body the outline @@ -147,7 +147,7 @@ struct WorkspaceView: View { // is the default: lossless. Esc/Cancel converts nothing. .sheet(isPresented: convertAskBinding) { ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in - gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome) + gate.posts.convertToPost(headingsLadder: headingsLadder) } } } @@ -286,7 +286,7 @@ struct WorkspaceView: View { case .archive: // #108: list-only pane — clicking a row selects the piece and // hops to Posts where its editor lives. - ArchivePaneView(home: gate.museionHome, model: gate.posts) { + ArchivePaneView(model: gate.posts) { selection = .posts } case .settings: @@ -352,7 +352,6 @@ struct WorkspaceView: View { /// verdict: a destination, not a library disclosure). List-only: clicking a /// piece selects it and hops to Posts, where the editor column lives. private struct ArchivePaneView: View { - let home: URL var model: PostsModel /// Fired after a row select — the pane can't reach WorkspaceView's /// selection itself. @@ -437,7 +436,7 @@ private struct ArchivePaneView: View { // 'Unarchive Group' — it moves the whole // project, not one piece. Button("Unarchive Group") { - model.unarchiveProject(project, home: home) + model.unarchiveProject(project) } .buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24)) .help("Move the whole project back to projects/") @@ -453,7 +452,7 @@ private struct ArchivePaneView: View { // at x28 (the one indent). The hairline is // BOUNDED to the fixed frame: x14 → 706. LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { - model.select(post.id, home: home) + model.select(post.id) onOpenPiece() } .overlay(alignment: .bottom) { @@ -464,14 +463,14 @@ private struct ArchivePaneView: View { } .contextMenu { Button("Move Back to \(post.project)") { - model.restorePost(post, home: home) + model.restorePost(post) } Button("Rename…") { renamingPost = post } // #114 (S4): works archived too — the piece // stays where it is, only type + body flip. if post.type == .outline { Button("Convert to Post…") { - model.stageConversion(post, home: home) + model.stageConversion(post) } } } @@ -496,7 +495,7 @@ private struct ArchivePaneView: View { .background(DesignTokens.background) .sheet(item: $renamingPost) { post in RenamePostSheet(post: post) { title in - model.rename(post, to: title, home: home) + model.rename(post, to: title) } } } diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 00e5a40..fe0a01f 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -39,7 +39,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. - `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay. - `FixCardApplyTests` — fix-card apply/skip/done lifecycle. -- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers). +- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally). - `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop. - `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest. - `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe. diff --git a/MuseionTests/BlindReadTests.swift b/MuseionTests/BlindReadTests.swift index e9ae459..6d8cf97 100644 --- a/MuseionTests/BlindReadTests.swift +++ b/MuseionTests/BlindReadTests.swift @@ -117,7 +117,7 @@ struct BlindReadTests { private func openJudgedPiece(on model: PostsModel, home: URL, snapshot: String, current: String) async throws -> String { let post = try PostStore.writeNew(body: current, home: home) try PostStore.snapshotPass(id: post.id, kind: .pass1, body: snapshot, home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } @@ -199,14 +199,14 @@ struct BlindReadTests { await rig.mentor.openSession() _ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.") - let run = Task { await rig.model.blindRead(home: rig.home, mentor: rig.mentor) } + let run = Task { await rig.model.blindRead(mentor: rig.mentor) } for _ in 0 ..< 250 where !rig.model.runningBlindRead { try await Task.sleep(nanoseconds: 20_000_000) } #expect(rig.model.runningBlindRead) // Mutual exclusion — a pass refuses while the read owns the rail. - await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) + await rig.model.runPass(.pass1, mentor: rig.mentor) #expect(rig.model.lastError?.contains("already running") == true) // The pass bar's Cancel rail ends the held read — no reveal, @@ -237,7 +237,7 @@ struct BlindReadTests { snapshot: "MARKER-the-older-text", current: "# Judged\n\nMARKER-the-newer-text", ) - await rig.model.blindRead(home: rig.home, mentor: rig.mentor) + await rig.model.blindRead(mentor: rig.mentor) // The prompt carried BOTH bodies inline — and no path: the judge // cannot learn which file is which (the engines' prompt log). @@ -262,20 +262,20 @@ struct BlindReadTests { defer { rig.mentor.shutdown() } await rig.mentor.openSession() let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", home: rig.home) - rig.model.select(post.id, home: rig.home) + rig.model.select(post.id) for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } // No pass ever ran — refuse, spawn nothing beyond the resident engine. - await rig.model.blindRead(home: rig.home, mentor: rig.mentor) + await rig.model.blindRead(mentor: rig.mentor) #expect(rig.model.lastError?.contains("run a Pass") == true) #expect(museionSpawns(rig) == 1) // Snapshot exists but the document is unchanged since — a vacuous // read refuses honestly. try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Fresh\n\nNo pass yet.", home: rig.home) - await rig.model.blindRead(home: rig.home, mentor: rig.mentor) + await rig.model.blindRead(mentor: rig.mentor) #expect(rig.model.lastError?.contains("No edits") == true) } diff --git a/MuseionTests/EngineLifecycleTests.swift b/MuseionTests/EngineLifecycleTests.swift index 2b3b1b4..d2a3c5e 100644 --- a/MuseionTests/EngineLifecycleTests.swift +++ b/MuseionTests/EngineLifecycleTests.swift @@ -51,7 +51,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted let chatBefore = rig.mentor.host.chat let rosterBefore = rig.mentor.roster.count let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home) - rig.model.select(post.id, home: rig.home) + rig.model.select(post.id) for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } @@ -59,7 +59,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted // In a Task — a full-mode scripted pass can complete inside one poll // sleep (no child-process latency anymore), so the pass ENGINE is // captured after the run from the spawn records, not polled mid-flight. - let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) } _ = await run.value let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" } let passEngineClosed = try #require(passEngine, "pass engine never spawned") @@ -104,9 +104,9 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted await rig.mentor.openSession() let rosterBefore = rig.mentor.roster.count let post = try PostStore.writeNew(body: "# Held Pass\n\nCancel me.", home: rig.home) - rig.model.select(post.id, home: rig.home) + rig.model.select(post.id) - let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) } let heldEngine = try #require(await pollOneShot(of: rig.mentor), "pass engine never spawned") #expect(rig.mentor.isPassEngineRunning) @@ -291,7 +291,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted rig.mentor.passReadinessWriter = writer await rig.mentor.refreshPassReadiness() let post = try PostStore.writeNew(body: "# No Key\n\nPass me.", home: rig.home) - rig.model.select(post.id, home: rig.home) + rig.model.select(post.id) for _ in 0 ..< 250 where rig.model.session?.postID != post.id { try await Task.sleep(nanoseconds: 20_000_000) } @@ -299,7 +299,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted // this pin vacuously. try #require(rig.model.session?.postID == post.id) - await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) + await rig.model.runPass(.pass1, mentor: rig.mentor) #expect(rig.model.lastError == "Pass 1 needs a z.ai API key — add it in Settings → Provider Keys.") let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)") @@ -320,7 +320,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted _ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active let target = try #require(rig.mentor.roster.last) // sess-1, NOT active let post = try PostStore.writeNew(body: "# Held Load\n\nResume races a pass.", home: rig.home) - rig.model.select(post.id, home: rig.home) + rig.model.select(post.id) for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } @@ -338,7 +338,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted // pass prompt then HOLDS, so isStreaming is guaranteed when the parked // load completes, and the #124 Cancel rail frees it afterwards. rig.engines.mode = "hangOnPrompt" - let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) } + let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) } for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning { try await Task.sleep(nanoseconds: 20_000_000) } diff --git a/MuseionTests/EngineSmokeTests.swift b/MuseionTests/EngineSmokeTests.swift index efd32e4..ab5abb4 100644 --- a/MuseionTests/EngineSmokeTests.swift +++ b/MuseionTests/EngineSmokeTests.swift @@ -174,7 +174,7 @@ struct EngineSmokeTests { await mentor.openSession() // the resident chat engine let chatPid = try #require(mentor.childProcessIdentifier) let post = try PostStore.writeNew(body: "# Smoke Pass\n\nVerdict me.", home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } @@ -182,7 +182,7 @@ struct EngineSmokeTests { // In a Task — the pass child's pid is only observable while it runs // (the old EngineLifecycleTests poll; the zsh wire latency holds the // turn open long enough to catch it). - let run = Task { await model.runPass(kind, home: home, mentor: mentor) } + let run = Task { await model.runPass(kind, mentor: mentor) } var passPid: pid_t? var polls = 0 while passPid == nil, polls < 250 { diff --git a/MuseionTests/FixCardApplyTests.swift b/MuseionTests/FixCardApplyTests.swift index 5efc81d..bb77c80 100644 --- a/MuseionTests/FixCardApplyTests.swift +++ b/MuseionTests/FixCardApplyTests.swift @@ -23,7 +23,7 @@ import Testing /// hop-back instead of asserting synchronously (PostsModelTests convention). /// The post-loop expect makes a silent timeout a failure, not a pass. @MainActor -private func pollUntil(_ condition: @MainActor () -> Bool) async throws { +func pollUntil(_ condition: @MainActor () -> Bool) async throws { for _ in 0 ..< 250 where !condition() { try await Task.sleep(nanoseconds: 20_000_000) } @@ -51,7 +51,7 @@ struct FixCardApplyTests { piecePath: folder.path, cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")], ) - model.select(post.id, home: home) + model.select(post.id) let session = try #require(model.session) let generation = session.loadGeneration @@ -59,7 +59,7 @@ struct FixCardApplyTests { // buffer first (flush-first, like every op that reads the piece). session.edit("# Carded\n\nThe anchor sentence.\nPlus a typed line.\n") - #expect(model.applyCard(written[0].card, home: home) == .applied) + #expect(model.applyCard(written[0].card) == .applied) // Disk carries the replacement over the flushed buffer... #expect(PostStore.readBody(id: post.id, home: home) == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n") @@ -80,14 +80,14 @@ struct FixCardApplyTests { piecePath: folder.path, cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")], ) - model.select(post.id, home: home) + model.select(post.id) // The Post changed after the card was issued — the quote is gone. model.session?.edit("# Carded\n\nThe sentence changed.\n") model.session?.flush() let postURL = folder.appendingPathComponent("post.md") let before = try Data(contentsOf: postURL) - #expect(model.applyCard(written[0].card, home: home) == .stale) + #expect(model.applyCard(written[0].card) == .stale) #expect(try Data(contentsOf: postURL) == before) // nothing selected, nothing changed let diskCard = try #require(FixCardStore.scan(pieceURL: folder).first) @@ -104,11 +104,11 @@ struct FixCardApplyTests { piecePath: folder.path, cards: [card(pattern: "Demo", fix: "The replaced sentence.", quote: "The anchor sentence.", lane: .demonstration)], ) - model.select(post.id, home: home) + model.select(post.id) let postURL = folder.appendingPathComponent("post.md") let before = try Data(contentsOf: postURL) - let outcome = model.applyCard(written[0].card, home: home) + let outcome = model.applyCard(written[0].card) guard case let .refused(why) = outcome else { Issue.record("expected refusal, got \(outcome)") return @@ -127,7 +127,7 @@ struct FixCardApplyTests { piecePath: folder.path, cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")], ) - model.select(post.id, home: home) + model.select(post.id) // A foreign write lands on disk underneath the writer (#67) — the // reload question is up and unanswered. let postURL = folder.appendingPathComponent("post.md") @@ -135,7 +135,7 @@ struct FixCardApplyTests { model.session?.diskDidChange(diskText: "foreign text on disk") let before = try Data(contentsOf: postURL) - let outcome = model.applyCard(written[0].card, home: home) + let outcome = model.applyCard(written[0].card) guard case let .refused(why) = outcome else { Issue.record("expected refusal, got \(outcome)") return @@ -157,15 +157,15 @@ struct FixCardApplyTests { card(pattern: "Telling", quote: "The anchor sentence."), ], ) - model.select(post.id, home: home) + model.select(post.id) let postURL = folder.appendingPathComponent("post.md") let before = try Data(contentsOf: postURL) - model.skipCard(written[0].card, home: home) + model.skipCard(written[0].card) try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.status == .skipped } #expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[0].card.id })?.status == .skipped) - model.doneCard(written[1].card, home: home) + model.doneCard(written[1].card) try await pollUntil { model.openPieceCards.first(where: { $0.id == written[1].card.id })?.status == .done } #expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[1].card.id })?.status == .done) @@ -241,7 +241,7 @@ struct FixCardApplyTests { piecePath: folder.path, cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")], ) - model.select(post.id, home: home) + model.select(post.id) model.session?.edit("# Carded\n\nThe sentence changed.\n") // stale the anchor model.session?.flush() let postURL = folder.appendingPathComponent("post.md") @@ -252,7 +252,7 @@ struct FixCardApplyTests { try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: cardsDir.path) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cardsDir.path) } - #expect(model.applyCard(written[0].card, home: home) == .stale) // the primary contract holds… + #expect(model.applyCard(written[0].card) == .stale) // the primary contract holds… #expect(model.lastError?.contains("card close failed") == true) // …and the flag failure is loud #expect(try Data(contentsOf: postURL) == before) // still nothing selected or changed } @@ -270,12 +270,12 @@ struct FixCardApplyTests { ) try FileManager.default.removeItem(at: folder.appendingPathComponent("post.md")) // the read will fail - model.select(post.id, home: home) + model.select(post.id) #expect(model.session?.loadFailed == true) // The writer typed the anchor into the empty failed-session buffer. model.session?.edit("The anchor sentence. typed nowhere durable.") - let outcome = model.applyCard(written[0].card, home: home) + let outcome = model.applyCard(written[0].card) guard case .refused = outcome else { Issue.record("expected refusal, got \(outcome)") return @@ -295,9 +295,9 @@ struct FixCardApplyTests { let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) let folder = try #require(PostStore.folder(of: post.id, home: home)) let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()]) - model.select(post.id, home: home) + model.select(post.id) - #expect(model.promoteCard(written[0].card, home: home) == .promoted) + #expect(model.promoteCard(written[0].card) == .promoted) let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true) #expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1) @@ -306,7 +306,7 @@ struct FixCardApplyTests { // Already promoted → refused, no second file (one confirm = one entry). let scanned = try #require(FixCardStore.scan(pieceURL: folder).first) - #expect(model.promoteCard(scanned, home: home) == .refused("card already promoted")) + #expect(model.promoteCard(scanned) == .refused("card already promoted")) #expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1) } @@ -316,7 +316,7 @@ struct FixCardApplyTests { let folder = try #require(PostStore.folder(of: post.id, home: home)) let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()]) - #expect(model.promoteCard(written[0].card, home: home) == .refused("open the piece to work its cards")) + #expect(model.promoteCard(written[0].card) == .refused("open the piece to work its cards")) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path)) #expect(model.lastError == nil) } diff --git a/MuseionTests/MicropubModelTests.swift b/MuseionTests/MicropubModelTests.swift index 557b188..8179f02 100644 --- a/MuseionTests/MicropubModelTests.swift +++ b/MuseionTests/MicropubModelTests.swift @@ -19,12 +19,12 @@ struct MicropubModelTests { @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.select(post.id) 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", + token: "tok", transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log), ) @@ -40,10 +40,10 @@ struct MicropubModelTests { } @Test @MainActor func `sendDraft refuses without an open saved piece`() async throws { - let (model, home) = try makeModelHome() + let (model, _) = try makeModelHome() let log = MicropubRequestLog() let outcome = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", log: log), ) guard case .refused = outcome else { @@ -54,11 +54,11 @@ struct MicropubModelTests { } @Test @MainActor func `sendDraft refuses an unsaved draft`() async throws { - let (model, home) = try makeModelHome() + let (model, _) = try makeModelHome() model.newPost() // staged draft — no folder, no session let log = MicropubRequestLog() let outcome = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", log: log), ) guard case .refused = outcome else { @@ -73,11 +73,11 @@ struct MicropubModelTests { // 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) + model.select(post.id) let log = MicropubRequestLog() let outcome = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", log: log), ) guard case .refused = outcome else { @@ -91,7 +91,7 @@ struct MicropubModelTests { @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) + model.select(post.id) // 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) @@ -100,7 +100,7 @@ struct MicropubModelTests { let log = MicropubRequestLog() _ = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log), ) @@ -113,11 +113,11 @@ struct MicropubModelTests { @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) + model.select(post.id) let log = MicropubRequestLog() _ = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(500, body: "{}", log: log), ) @@ -127,15 +127,15 @@ struct MicropubModelTests { @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) + model.select(post.id) let log = MicropubRequestLog() _ = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log), ) _ = await model.micropubSendDraft( - home: home, token: "tok", + token: "tok", transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log), ) @@ -147,7 +147,7 @@ struct MicropubModelTests { /// Plants a PNG beside the piece; returns the piece's post.md URL. @MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL { let post = try PostStore.writeNew(body: body, home: home) - model.select(post.id, home: home) + model.select(post.id) let dir = try #require(PostStore.folder(of: post.id, home: home)) try FileManager.default.createDirectory(at: dir.appendingPathComponent("assets", isDirectory: true), withIntermediateDirectories: true) try micropubPNG().write(to: dir.appendingPathComponent("assets/path.png")) @@ -162,7 +162,7 @@ struct MicropubModelTests { ) let log = MicropubRequestLog() - let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) // The three hops, in order: q=config → upload → create. @@ -197,7 +197,7 @@ struct MicropubModelTests { ) let log = MicropubRequestLog() - let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) guard case let .refused(reason) = outcome else { Issue.record("expected refused, got \(outcome)") @@ -228,7 +228,7 @@ struct MicropubModelTests { ) let log = MicropubRequestLog() - let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) guard case let .refused(reason) = outcome else { Issue.record("expected refused, got \(outcome)") @@ -246,7 +246,7 @@ struct MicropubModelTests { ) let log = MicropubRequestLog() - let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) // config + ONE upload + create — the FILE uploads once, not once per ref. @@ -266,7 +266,7 @@ struct MicropubModelTests { ) // path.png planted, ghost.png never let log = MicropubRequestLog() - let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) guard case .refused = outcome else { Issue.record("expected refused, got \(outcome)") @@ -278,10 +278,10 @@ struct MicropubModelTests { @Test @MainActor func `a piece without illustrations sends exactly one request`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Plain\n\nBody.", home: home) - model.select(post.id, home: home) + model.select(post.id) let log = MicropubRequestLog() - _ = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + _ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log)) // The #33 path unchanged: no config round-trip, straight to the create. #expect(log.requests.count == 1) diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index d90e3f1..7e79b85 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -42,14 +42,14 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } // #124: at rig creation — the child dies with the test, however it exits await mentor.openSession() let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home) - model.select(post.id, home: home) + model.select(post.id) // Wait for the bind rescan to surface the piece — the pass label reads // the library's title for it (the PostsModelTests poll pattern). for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let piece = home.appendingPathComponent("projects/posts/\(post.id)") let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8) @@ -73,9 +73,9 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home) - model.select(post.id, home: home) + model.select(post.id) - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let piece = home.appendingPathComponent("projects/posts/\(post.id)") // Pre-pass is unconditional — the snapshot landed anyway. @@ -91,9 +91,9 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home) - model.select(post.id, home: home) + model.select(post.id) - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let onDisk = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, @@ -108,7 +108,7 @@ func textRows(of model: MentorSessionModel) -> [String] { await mentor.openSession() model.newPost() // draft staged — no folder exists - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) #expect(model.lastError?.contains("post") == true) // Nothing landed on disk — the draft never even materialized a folder. @@ -120,15 +120,15 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Held\n\nMid-pass.", home: home) - model.select(post.id, home: home) + model.select(post.id) - let first = Task { await model.runPass(.pass1, home: home, mentor: mentor) } + let first = Task { await model.runPass(.pass1, mentor: mentor) } for _ in 0 ..< 250 where model.runningPass == nil { try await Task.sleep(nanoseconds: 20_000_000) } #expect(model.runningPass == .pass1) - await model.runPass(.pass1, home: home, mentor: mentor) // one pass at a time + await model.runPass(.pass1, mentor: mentor) // one pass at a time #expect(model.lastError?.contains("already running") == true) model.cancelPass(mentor: mentor) // the pass bar's Cancel rail @@ -147,9 +147,9 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Held\n\nCancel me.", home: home) - model.select(post.id, home: home) + model.select(post.id) - let run = Task { await model.runPass(.pass1, home: home, mentor: mentor) } + let run = Task { await model.runPass(.pass1, mentor: mentor) } for _ in 0 ..< 250 where model.runningPass == nil { try await Task.sleep(nanoseconds: 20_000_000) } @@ -177,7 +177,7 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Busy\n\nMentor chatting.", home: home) - model.select(post.id, home: home) + model.select(post.id) let chat = Task { await mentor.sendPrompt("just chatting") } for _ in 0 ..< 250 where !mentor.isStreaming { @@ -185,7 +185,7 @@ func textRows(of model: MentorSessionModel) -> [String] { } #expect(mentor.isStreaming) - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) #expect(model.lastError?.contains("mid-reply") == true) // The guard fired before the snapshot — nothing on disk. #expect(!FileManager.default.fileExists( @@ -199,9 +199,9 @@ func textRows(of model: MentorSessionModel) -> [String] { let (model, home, mentor) = try makePassRig() // never opened — engine idle defer { mentor.shutdown() } let post = try PostStore.writeNew(body: "# Cold\n\nNo engine yet.", home: home) - model.select(post.id, home: home) + model.select(post.id) - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) #expect(model.lastError?.contains("isn't ready") == true) #expect(!FileManager.default.fileExists( @@ -214,10 +214,10 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home) - model.select(post.id, home: home) + model.select(post.id) model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let piece = home.appendingPathComponent("projects/posts/\(post.id)") let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8) @@ -231,9 +231,9 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home) - model.select(post.id, home: home) + model.select(post.id) - await model.runPass(.pass2, home: home, mentor: mentor) + await model.runPass(.pass2, mentor: mentor) let onDisk = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, @@ -248,12 +248,12 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Stats Piece\n\nOne two three. Four five! Six?", home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let onDisk = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, @@ -275,9 +275,9 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# Cancelled Stats\n\nOne two three. Four five!", home: home) - model.select(post.id, home: home) + model.select(post.id) - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let onDisk = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, @@ -295,12 +295,12 @@ func textRows(of model: MentorSessionModel) -> [String] { defer { mentor.shutdown() } await mentor.openSession() let post = try PostStore.writeNew(body: "# AI Piece\n\nMachine-born prose.", origin: .ai, home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let onDisk = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, @@ -326,12 +326,12 @@ struct DeslopLintWiringTests { let body = "# Lint Piece\n\nUtilize the index — and delve twice — notably once, and again — " + "and again — and once more — to clear the dash budget. Utilize it twice." let post = try PostStore.writeNew(body: body, home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) let piece = home.appendingPathComponent("projects/posts/\(post.id)") let cards = FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md")) diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift index 66de144..5a7b9ce 100644 --- a/MuseionTests/PostsModelTests.swift +++ b/MuseionTests/PostsModelTests.swift @@ -5,6 +5,9 @@ // #108 audit: the model-layer lifecycle the store tests can't see — // archive clearing the open session, move reopening it at the new parent, // restore keeping the writer in the piece, New Project's draft targeting. +// #179: the write-rail pins — one seam pairs every library store write +// with exactly one rescan and owns the error strip; the model owns the +// Home (no method takes one). // import Foundation @@ -27,10 +30,10 @@ func makeModelHome() throws -> (PostsModel, URL) { @Test @MainActor func `archiving the open piece clears selection and session`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home) - model.select(post.id, home: home) + model.select(post.id) #expect(model.session?.postID == post.id) - model.archivePost(post, home: home) + model.archivePost(post) #expect(model.selectedPostID == nil) #expect(model.session == nil) @@ -41,10 +44,10 @@ func makeModelHome() throws -> (PostsModel, URL) { @Test @MainActor func `moving the open piece reopens its session at the new parent`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Traveler\n", project: "essays", home: home) - model.select(post.id, home: home) + model.select(post.id) #expect(model.session?.folderURL.path.contains("projects/essays") == true) - model.moveToProject(post, project: "posts", home: home) + model.moveToProject(post, project: "posts") #expect(model.session?.postID == post.id) // same piece, fresh session #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) @@ -55,10 +58,10 @@ func makeModelHome() throws -> (PostsModel, URL) { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Revived\n", home: home) try PostStore.archive(post, home: home) - model.select(post.id, home: home) // opened from the Archive pane + model.select(post.id) // opened from the Archive pane #expect(model.session?.folderURL.path.contains("archive/") == true) - model.restorePost(post, home: home) + model.restorePost(post) #expect(model.selectedPostID == post.id) // the writer stays in it #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) @@ -73,7 +76,7 @@ func makeModelHome() throws -> (PostsModel, URL) { #expect(model.draft?.project == "essays") model.updateDraft("# Fresh\n") - model.saveDraft(home: home) + model.saveDraft() let scanned = Post.scan(home: home) #expect(scanned.first?.project == "essays") @@ -100,10 +103,10 @@ func makeModelHome() throws -> (PostsModel, URL) { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Keeper\n", home: home) try PostStore.archive(post, home: home) - model.select(post.id, home: home) + model.select(post.id) model.session?.edit("# Keeper\n\nDirty.") // inside the debounce window - model.unarchiveProject("posts", home: home) + model.unarchiveProject("posts") // The edits landed on disk (readBody resolves by id — through the move). #expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nDirty.") @@ -121,7 +124,7 @@ func makeModelHome() throws -> (PostsModel, URL) { for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - model.select(post.id, home: home) + model.select(post.id) model.newOutline() @@ -142,7 +145,7 @@ func makeModelHome() throws -> (PostsModel, URL) { let (model, home) = try makeModelHome() model.newOutline() - model.saveDraft(home: home) + model.saveDraft() #expect(model.draft == nil) #expect(model.lastError == nil) @@ -157,7 +160,7 @@ func makeModelHome() throws -> (PostsModel, URL) { let (model, home) = try makeModelHome() try PostStore.createProject(named: "essays", home: home) // empty — no pieces - #expect(model.moveTargets(home: home) == ["essays", "posts"]) + #expect(model.moveTargets() == ["essays", "posts"]) // "posts" exists too (bind created it); a dot-project never shows. } @@ -177,7 +180,7 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) + model.select(post.id) #expect(model.outlineGuardPieceID == post.id) // the ask is up #expect(model.session == nil) // nothing editable while it's up @@ -191,8 +194,8 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) - model.openGuardedOutlineInProse(home: home) + model.select(post.id) + model.openGuardedOutlineInProse() #expect(model.outlineGuardPieceID == nil) #expect(model.session?.postID == post.id) @@ -209,8 +212,8 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) - model.openGuardedOutlineAsOutline(home: home) + model.select(post.id) + model.openGuardedOutlineAsOutline() #expect(model.outlineGuardPieceID == nil) #expect(model.session?.postID == post.id) @@ -226,13 +229,13 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) + model.select(post.id) model.cancelOutlineGuard() #expect(model.outlineGuardPieceID == nil) #expect(model.session == nil) // Still guarded: the next open re-fires the ask, file untouched. - model.select(post.id, home: home) + model.select(post.id) #expect(model.outlineGuardPieceID == post.id) } @@ -242,12 +245,12 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) - model.openGuardedOutlineAsOutline(home: home) // consent; disk still mixed + model.select(post.id) + model.openGuardedOutlineAsOutline() // consent; disk still mixed let session = try #require(model.session) session.edit("- one\n- two\nedited") // dirty; debounce armed - model.select(post.id, home: home) // muscle-memory re-click on the open row + model.select(post.id) // muscle-memory re-click on the open row #expect(model.outlineGuardPieceID == nil) // no re-ask over a prior answer #expect(model.session === session) // the open session survives, dirty state intact @@ -257,15 +260,15 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) // ask up + model.select(post.id) // ask up model.newPost() // ⌘N fires while the sheet is up #expect(model.outlineGuardPieceID == nil) // the ask died with the displacement #expect(model.draft != nil) model.updateDraft("# Keep me\n") // Answering the (now-gone) ask is inert — the draft survives. - model.openGuardedOutlineInProse(home: home) - model.openGuardedOutlineAsOutline(home: home) + model.openGuardedOutlineInProse() + model.openGuardedOutlineAsOutline() #expect(model.draft != nil) #expect(model.selectedPostID == nil) // the draft still owns the editor } @@ -279,7 +282,7 @@ private func writeMixedOutline(home: URL) throws -> Post { } #expect(model.posts.contains(where: { $0.id == post.id })) - model.select(post.id, home: home) + model.select(post.id) #expect(model.outlineGuardPieceID == post.id) // the scan path guards too } @@ -288,11 +291,11 @@ private func writeMixedOutline(home: URL) throws -> Post { let clean = try PostStore.writeNew(body: "# Clean\n\n- one\n- two\n", type: .outline, home: home) let prose = try PostStore.writeNew(body: "# Plain\n\nA paragraph.\n", home: home) - model.select(clean.id, home: home) + model.select(clean.id) #expect(model.outlineGuardPieceID == nil) #expect(model.session?.postID == clean.id) - model.select(prose.id, home: home) + model.select(prose.id) #expect(model.outlineGuardPieceID == nil) #expect(model.session?.postID == prose.id) } @@ -302,12 +305,12 @@ private func writeMixedOutline(home: URL) throws -> Post { @Test @MainActor func `convert reopens the open piece routed to prose`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home) - model.select(post.id, home: home) + model.select(post.id) - model.stageConversion(post, home: home) + model.stageConversion(post) #expect(model.pendingConversion?.id == post.id) #expect(model.pendingConversion?.lossy == false) // clean outline - model.convertToPost(headingsLadder: true, home: home) + model.convertToPost(headingsLadder: true) #expect(model.pendingConversion == nil) #expect(model.session?.postID == post.id) // reopened on the converted body @@ -321,10 +324,10 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let open = try PostStore.writeNew(body: "# Stay\n", home: home) let outline = try PostStore.writeNew(body: "- a\n - b", type: .outline, home: home) - model.select(open.id, home: home) + model.select(open.id) - model.stageConversion(outline, home: home) - model.convertToPost(headingsLadder: false, home: home) + model.stageConversion(outline) + model.convertToPost(headingsLadder: false) #expect(model.session?.postID == open.id) // untouched #expect(model.selectedPostID == open.id) @@ -344,9 +347,9 @@ private func writeMixedOutline(home: URL) throws -> Post { } #expect(model.posts.first(where: { $0.id == post.id })?.type == .outline) - model.select(post.id, home: home) - model.stageConversion(post, home: home) - model.convertToPost(headingsLadder: false, home: home) // VERBATIM + model.select(post.id) + model.stageConversion(post) + model.convertToPost(headingsLadder: false) // VERBATIM #expect(model.proseOverridePostID == post.id) #expect(model.session?.postID == post.id) @@ -362,11 +365,11 @@ private func writeMixedOutline(home: URL) throws -> Post { @Test @MainActor func `dirty open piece flushes before the convert`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home) - model.select(post.id, home: home) + model.select(post.id) model.session?.edit("# Chapter\n- one\n - typed child") // unflushed edit - model.stageConversion(post, home: home) - model.convertToPost(headingsLadder: false, home: home) + model.stageConversion(post) + model.convertToPost(headingsLadder: false) let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8) #expect(onDisk.contains("type: post")) @@ -376,11 +379,11 @@ private func writeMixedOutline(home: URL) throws -> Post { @Test @MainActor func `staging warns from the session text when the piece is dirty`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home) - model.select(post.id, home: home) + model.select(post.id) // prose typed since the last flush — disk still clean, session is not model.session?.edit("# Clean\n- one\nA paragraph between bullets.\n- two") - model.stageConversion(post, home: home) + model.stageConversion(post) #expect(model.pendingConversion?.lossy == true) // from session.text, not stale disk } @@ -389,7 +392,7 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) // closed piece — disk is the truth - model.stageConversion(post, home: home) + model.stageConversion(post) #expect(model.pendingConversion?.lossy == true) } @@ -398,13 +401,13 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home) - model.stageConversion(post, home: home) // staged clean, no warning shown + model.stageConversion(post) // staged clean, no warning shown // a foreign write makes the body mixed while the sheet was up let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false) try PostStore.stamped(body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline) .write(to: file, atomically: true, encoding: .utf8) - model.convertToPost(headingsLadder: true, home: home) + model.convertToPost(headingsLadder: true) #expect(model.lastError?.contains("nothing was converted") == true) #expect(model.session?.postID == nil || model.session?.postID != post.id) @@ -413,8 +416,8 @@ private func writeMixedOutline(home: URL) throws -> Post { #expect(onDisk.contains("A paragraph between bullets.")) // the consented path still converts: a WARNED mixed piece + Headings proceeds - model.stageConversion(post, home: home) // now stages lossy from disk - model.convertToPost(headingsLadder: true, home: home) + model.stageConversion(post) // now stages lossy from disk + model.convertToPost(headingsLadder: true) let converted = try String(contentsOf: file, encoding: .utf8) #expect(converted.contains("type: post")) #expect(!converted.contains("A paragraph between bullets.")) // dropped, as consented @@ -423,14 +426,14 @@ private func writeMixedOutline(home: URL) throws -> Post { @Test @MainActor func `unanswered conflict aborts the convert`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Clean\n- one", type: .outline, home: home) - model.select(post.id, home: home) + model.select(post.id) // #67 conflict up: disk holds foreign text, the editor's version unwritten model.session?.diskDidChange(diskText: "# Foreign rewrite\nbody") #expect(model.session?.conflictAlert == true) - model.stageConversion(post, home: home) - model.convertToPost(headingsLadder: false, home: home) + model.stageConversion(post) + model.convertToPost(headingsLadder: false) #expect(model.lastError?.contains("reload question") == true) #expect(model.session?.conflictAlert == true) // still answerable, not trampled @@ -441,13 +444,13 @@ private func writeMixedOutline(home: URL) throws -> Post { @Test @MainActor func `failed flush aborts the convert`() throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home) - model.select(post.id, home: home) + model.select(post.id) model.session?.edit("# Chapter\n- one\n - child") // dirty // vanish the piece: the flush throws (never resurrects), convert must abort try FileManager.default.removeItem(at: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)) - model.stageConversion(post, home: home) - model.convertToPost(headingsLadder: true, home: home) + model.stageConversion(post) + model.convertToPost(headingsLadder: true) #expect(model.lastError?.contains("nothing was changed") == true) #expect(model.session?.postID == post.id) // session stays up, dirty and honest @@ -457,11 +460,11 @@ private func writeMixedOutline(home: URL) throws -> Post { let (model, home) = try makeModelHome() let post = try writeMixedOutline(home: home) - model.select(post.id, home: home) // guard fires, open held + model.select(post.id) // guard fires, open held #expect(model.outlineGuardPieceID == post.id) - model.stageConversion(post, home: home) - model.convertToPost(headingsLadder: false, home: home) + model.stageConversion(post) + model.convertToPost(headingsLadder: false) #expect(model.outlineGuardPieceID == nil) // the stale ask died with the outline #expect(model.selectedPostID == nil) // cancel teardown: nothing was open @@ -483,13 +486,118 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws { } } +// #179: the rail's rescan lands via Task — bounded poll (FixCardApplyTests' +// pollUntil, made internal; the post-loop expect makes a silent timeout a +// failure, not a pass). + +/// Scenario: one write rail for every library verb (from #179). +/// Given a model bound to a Home, when a verb's store write runs, then it +/// lands through the ONE seam — the library reflects it via exactly one +/// rescan and a stale error strip is cleared on success. +/// Suite member (not free function): suite-name filters must reach the +/// rail pins (MuseionTests/AGENTS.md rule). +@Suite("write rail #179") +struct PostsModelWriteRailTests { + @Test @MainActor func `pairs the write with the library refresh and clears the strip`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Rail Pin\n", home: home) + try await pollUntil { model.posts.contains { $0.id == post.id } } + + model.lastError = "stale strip" // the rail owns the strip from here + model.rename(post, to: "Rail Pin Two") + + #expect(model.lastError == nil) + try await pollUntil { model.posts.contains { $0.id == "rail-pin-two" } } + #expect(model.posts.contains { $0.id == post.id } == false) + } + + /// Scenario: the rail owns the error strip on a failed write (from #179). + /// Given a bound model and a store write that throws, the verb's failure + /// reason lands in the strip AND rides the return for the sheet. + @Test @MainActor func `owns the strip when the write throws`() throws { + let (model, home) = try makeModelHome() + try PostStore.createProject(named: "dup", home: home) // the store already has it + + let reason = model.createProject(named: "dup") + + #expect(reason != nil) + #expect(model.lastError == reason) + } + + /// Scenario: the rail refuses cleanly with no Home bound (from #179). + /// Given a model that was never bound, a write verb refuses with a reason + /// and nothing reaches any disk. + @Test @MainActor func `refuses cleanly before a home is bound`() { + let model = PostsModel() + + let reason = model.createProject(named: "nowhere") + + #expect(reason != nil) + #expect(model.lastError == reason) + #expect(model.posts.isEmpty) + } + + /// Scenario: a mid-batch import failure keeps its strip message while + /// the good files land (from #179 — the rail clears the strip BEFORE + /// the write exactly so the per-file failures set inside the closure + /// survive the success tail). + @Test @MainActor func `import batch keeps per-file failure messages on the strip`() async throws { + let (model, _) = try makeModelHome() + let scratch = FileManager.default.temporaryDirectory + .appendingPathComponent("import-batch-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) + let good = scratch.appendingPathComponent("good.md") + try "# Good Piece\n".write(to: good, atomically: true, encoding: .utf8) + let missing = scratch.appendingPathComponent("missing.md") // never written — the read throws + + model.stageImport([good, missing]) + model.importFiles(origin: .writer) + + #expect(model.lastError?.contains("Import failed — missing.md") == true) + // the library refresh rides the rail's rescan Task — poll for it + try await pollUntil { model.posts.contains { $0.id == "good-piece" } } + #expect(model.selectedPostID == "good-piece") // …and opened (synchronous select) + } + + /// Scenario: a Home repoint while a pass runs refuses the pass advance + /// (from #179 audit — the rail resolves watchedHome at call time, and + /// the engine's turn spans minutes). Given a pass that ends normally + /// after its library was repointed, the advance is refused with the + /// honest strip message, both libraries keep their pass states, and + /// nothing was written into the new library. + @Test @MainActor func `home repoint mid-pass refuses the advance`() async throws { + let rig = try makeScriptedRig(mode: "hangOnPrompt") + defer { rig.mentor.shutdown() } + await rig.mentor.openSession() + let post = try PostStore.writeNew(body: "# Repoint\n", home: rig.home) + rig.model.select(post.id) + + let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) } + try await pollUntil { rig.model.runningPass == .pass1 } // the engine holds the turn + let homeB = FileManager.default.temporaryDirectory + .appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true) + rig.model.bind(home: homeB) // the Settings repoint, mid-pass + // Release the held turn as a NORMALLY ended one — .ended + no refusal. + // #require: nothing held means the parked prompt already timed out + // under machine load — fail loudly, not on a confusing nil strip. + let engine = try #require(rig.mentor.host.oneShot as? ScriptedEngine) + try #require(engine.endHeldPrompt()) + await run.value + + #expect(rig.model.lastError == "The library changed while the pass ran — its Pass State was not advanced.") + #expect(Post.scan(home: rig.home).first?.passState == .firstDraft) // the pass's own library: not advanced + #expect(Post.scan(home: homeB).isEmpty) // the new library: nothing stamped + } +} + @Test @MainActor func `opening a piece surfaces its stored fix cards`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) let folder = try #require(PostStore.folder(of: post.id, home: home)) try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")]) - model.select(post.id, home: home) + model.select(post.id) try await waitForCards(model, 1) #expect(model.openPieceCards.map(\.pattern) == ["Hedging"]) @@ -501,7 +609,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws { let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) let folder = try #require(PostStore.folder(of: post.id, home: home)) try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")]) - model.select(post.id, home: home) + model.select(post.id) try await waitForCards(model, 1) // An MCP client submits another card while the piece stays open — @@ -520,7 +628,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws { let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) let folder = try #require(PostStore.folder(of: post.id, home: home)) try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")]) - model.select(post.id, home: home) + model.select(post.id) try await waitForCards(model, 1) model.newPost() @@ -536,7 +644,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws { #expect(folder.path.contains("/archive/")) try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")]) - model.select(post.id, home: home) // opened from the Archive pane + model.select(post.id) // opened from the Archive pane try await waitForCards(model, 1) #expect(model.openPieceCards.count == 1) diff --git a/MuseionTests/ScriptedEngine.swift b/MuseionTests/ScriptedEngine.swift index cd2d245..480edb7 100644 --- a/MuseionTests/ScriptedEngine.swift +++ b/MuseionTests/ScriptedEngine.swift @@ -234,6 +234,23 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable { } } + /// Test hook (#179 audit): release a held prompt as a NORMALLY ended + /// turn — session/cancel answers "cancelled"; the mid-pass repoint pin + /// needs the turn to end .ended after the hold. Returns false (and + /// no-ops) when nothing is held — e.g. the parked request already hit + /// its deadline under machine load — so the caller can fail loudly + /// instead of reading a confusing nil strip. + @discardableResult + func endHeldPrompt() -> Bool { + queue.sync { + guard let id = self.heldPromptID, + let continuation = self.parked.removeValue(forKey: id) else { return false } + self.heldPromptID = nil + continuation.resume(returning: .object(["stopReason": .string("end_turn")])) + return true + } + } + /// Test hook: the kill(pid, SIGKILL) rail's in-process twin (#178 B2) — /// the engine dies unexpectedly: onCrash fires, every pending request /// fails. The crash-restart pins drive real crashes through this. diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift index 7837d88..8c00468 100644 --- a/MuseionTests/SessionLifecycleTests.swift +++ b/MuseionTests/SessionLifecycleTests.swift @@ -31,12 +31,12 @@ struct SessionLifecycleTests { let defaultSession = try #require(mentor.activeEntry) let rosterBefore = mentor.roster.count let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } - await model.runPass(.pass1, home: home, mentor: mentor) + await model.runPass(.pass1, mentor: mentor) // The roster never grew — the pass entry is transient. #expect(mentor.roster.count == rosterBefore) @@ -69,7 +69,7 @@ struct SessionLifecycleTests { /// newest-first, active; a non-nil pieceTitle rides the entry — /// association by convention only. @Test @MainActor func `freeform new session is rostered newest-first and active`() async throws { - let (model, home, mentor) = try makePassRig() + let (_, _, mentor) = try makePassRig() defer { mentor.shutdown() } #expect(!mentor.canStartSession) // never opened — nothing may start await mentor.openSession() @@ -200,7 +200,7 @@ struct SessionLifecycleTests { /// renders, the raw slash command never does, the summary streams into /// the transcript — and is refused while a turn streams. @Test @MainActor func `compact sends the labeled command and is refused while streaming`() async throws { - let (model, home, mentor) = try makePassRig() + let (_, _, mentor) = try makePassRig() defer { mentor.shutdown() } await mentor.openSession() @@ -330,7 +330,7 @@ struct SessionLifecycleTests { #expect(SessionsPaneView.openPiece(in: nil) == nil) // no Posts at all let post = try PostStore.writeNew(body: "# Open Piece\n", home: home) - model.select(post.id, home: home) + model.select(post.id) for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { try await Task.sleep(nanoseconds: 20_000_000) } diff --git a/MuseionTests/WritingLockTests.swift b/MuseionTests/WritingLockTests.swift index 2f6ff55..67ffad3 100644 --- a/MuseionTests/WritingLockTests.swift +++ b/MuseionTests/WritingLockTests.swift @@ -172,13 +172,13 @@ struct WritingLockTests { // the outline routing reads the real type, not the lagging list). let post = try PostStore.writeNew(body: "# Prose piece\n\nBody words.\n", home: home) try await Self.waitForScan(model, id: post.id) - model.select(post.id, home: home) + model.select(post.id) #expect(model.canArmWritingLock) #expect(model.editorBodyText == "# Prose piece\n\nBody words.\n") let outline = try PostStore.writeNew(body: "- an outline\n", project: "posts", type: .outline, home: home) try await Self.waitForScan(model, id: outline.id) - model.select(outline.id, home: home) + model.select(outline.id) #expect(!model.canArmWritingLock) // A MIXED outline fires the #111 guard ask instead — the held @@ -186,7 +186,7 @@ struct WritingLockTests { // branch's fourth path, pinned so the mirror can't drift. let mixed = try PostStore.writeNew(body: "- bullet\nprose between bullets\n", project: "posts", type: .outline, home: home) try await Self.waitForScan(model, id: mixed.id) - model.select(mixed.id, home: home) + model.select(mixed.id) #expect(model.outlineGuardPieceID == mixed.id) #expect(!model.canArmWritingLock) } diff --git a/docs/devlog/20261109-issue179-postsmodel-write-rail_log.md b/docs/devlog/20261109-issue179-postsmodel-write-rail_log.md new file mode 100644 index 0000000..a30866a --- /dev/null +++ b/docs/devlog/20261109-issue179-postsmodel-write-rail_log.md @@ -0,0 +1,79 @@ +# #179 PostsModel write rail — one seam pairs every store write with the rescan + +> **Date:** 2026-11-09 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/179 + +## Goal + +From the 2026-11-09 architecture review (content line, step 1 of 2): route every library verb through ONE internal seam that pairs the store write with the library rescan and owns the error strip — fourteen hand-copied write-then-rescan-then-error choreographies meant a new verb could silently forget the pairing. The model owns the Home: the parameter disappears from its public methods, construction and the Settings repoint remain the only two places it is set. The editor's flush keeps its own posture outside the rail. + +## What Was Done + +- `performWrite` write rail in `Museion/PostsModel.swift` (~:209) — one seam: closure takes the bound Home, a clean run fires exactly one `Task { await rescan() }` and returns nil, a throw lands `localizedDescription` in the strip and returns the reason; nil-Home refuses with nothing written. +- 10 verbs + the pass advance converted: `saveDraft`, `newPostFromSession`, `rename`, `trash`, `createProject`, `moveToProject`, `archivePost`, `restorePost`, `unarchiveProject`, `importFiles`, `runPass`'s `advancePassState`. Post-write state surgery rides inside each verb's closure (runs only on write success). Grep-proof: `Task { await rescan() }` now exists only in `bind` (initial scan), the rail, and the watcher. +- Model owns the Home: `watchedHome` is `private(set)` (set only by `bind`/`startWatching`); every public method dropped its `home:` parameter — `select`, `saveDraft`, `rename`, `trash`, `createProject`, `moveTargets`, `moveToProject`, `archivePost`, `restorePost`, `unarchiveProject`, `importFiles`, `stageConversion`, `convertToPost`, the guard answers, `runPass`, `blindRead`, `applyCard`/`skipCard`/`doneCard`/`promoteCard`, `micropubSendDraft`, `refreshCards`. +- Call-site sweep: 14 view sites (WorkspaceView, PostsPaneView, SessionsPaneView, MentorPaneView, FixCardsWindow, PromoteAskSheet, MicropubPublishSheet) and ~115 test sites across 9 test files; dead `home` plumbing cut (ArchivePaneView property, PassBarView property, ApplyAskSheet/PromoteAskSheet/MicropubPublishSheet properties, two test bindings). +- 5 rail pins in `@Suite("write rail #179") struct PostsModelWriteRailTests` (suite members — name filters reach them, verified `-only-testing` 5/5): write→refresh+strip-cleared, failed write owns the strip, nil-Home refusal, import batch keeps per-file strip messages, mid-pass Home repoint refuses the advance. +- Audit fixes (finish-audit fanout, 3 reviewers): repoint guard before the advance (`PostsModelPasses.swift:88`), dead-code cuts, `waitForPosts`→`pollUntil` consolidation (made internal in FixCardApplyTests). +- Rig: `ScriptedEngine.endHeldPrompt()` — releases a held prompt as a NORMALLY ended turn (session/cancel only ever answers "cancelled"; the repoint pin needs `.ended` after the hold). +- DOX: `Museion/AGENTS.md` PostsModel bullet (#179 write rail contract + runPass repoint refusal), `MuseionTests/AGENTS.md` suite map (rail pins + rig hook). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Strip clears BEFORE the write, not after | `importFiles` sets per-file failure messages mid-closure and must keep them while the batch still rescans; clear-before preserves that with zero special-casing. Flip-verified by its pin. | +| `createProject` failure now shows in sheet AND strip | Issue: "the seam owns the error strip" — supersedes the #108 sheet-only rule. Flagged to the maintainer; default kept. | +| `saveDraft` rides the rail | Read "the editor's flush/save-draft keeps its own posture" as EditorSession's debounced flush (⌘S on a saved piece); the verb list explicitly names "create post / outline" (= saveDraft). Flagged to the maintainer. | +| Card closes, pass substrate (`snapshotPass`/stats/lint), micropub publish stay OFF the rail | None regroup the library (no rescan owed); micropub's stamp failure must never un-send the draft. Documented in code + AGENTS. | +| Repoint guard (`watchedHome == home`) over passing the frozen home into the rail closure | Security reviewer's one-liner would write library A while the rail rescans library B — the exact desync the rail exists to kill. The guard keeps write+rescan consistent and refuses honestly. Converged finding (security + general, independent). | +| `conversionWentLossyBehindAsk` helper | #142: swiftformat pushes a wrapped condition list's brace to its own line, swiftlint flags it, and nested ifs get collapsed into a 154-char line — the hoisted helper is the sanctioned escape. | +| Nil-Home: rail speaks, pre-bind paths silently no-op | Pre-bind verb calls are unreachable in practice (every path needs posts/session ⇒ bound); the rail's refusal is the only reachable one and it says so. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| swiftformat collapsed the nested-if guard into one 154-char line (new lint warning) | #142 formatter/linter brace fight; swiftformat reflows wraps AND merges nested ifs | Hoisted `conversionWentLossyBehindAsk` helper — short condition, guard-shaped, stable under both tools | +| Test sweep left ~28 straggler call sites | First sed pass only handled trailing/first-arg `home:` shapes; mid-list `, home: home, ` and multiline continuation forms missed | Second scoped pass on those two shapes; compiler caught the rest | +| `import batch` pin failed on first run | Library refresh rides the rail's rescan Task (async by design); the pin asserted `model.posts` synchronously | Poll via `pollUntil` (the suite's own convention); strip + select assertions stay synchronous | +| Two xcresult summary reads died on a half-written bundle | `ls -td … \| head -1` chained to xcodebuild's exit races bundle finalization | Read the bundle in a LATER command (known #33 learning — re-bitten twice, worth re-pinning) | +| Full suite exceeds the 420 s foreground terminal cap | Suite grew to ~8 min under load | `build-for-testing` + `test-without-building` split, suite run as a tracked background job with notify | +| Repoint pin failed once in a full run (`lastError → nil`) | The parked scripted prompt hit its deadline while the UI-test runner starved the machine enabling automation mode; `endHeldPrompt` no-opped silently | Pin green isolated (5/5) and in the prior full run; `endHeldPrompt` now returns whether it released (queue.sync) and the pin `#require`s it — the next occurrence fails loudly (#30 flake family) | +| Next-morning verify run: BOTH test runners "hung before establishing connection", zero tests executed | #134 machine wedge — testmanagerd/automation daemon degraded through the evening, reboot pending; an untouched control suite (WritingGoalTests) hangs identically | Machine-state, not the diff: 657/657 green the prior evening on this code, rail pins 5/5 isolated after the last (test-only) edit; committed with the wedge named | + +## Verification + +- `build-for-testing`: **SUCCEEDED** at the final tree (re-verified after every edit, incl. the test-rig hardening). +- Full suite (`test-without-building`): **657/657 passed, 0 failed, 0 skipped** — verified by xcresult counts, never the banner (655 pre-existing + 2 new pins; the 3 original rail pins were already in the 655 count). One later full run flaked the repoint pin under UI-runner load (see Gotchas — passed isolated, rig hardened); the next-morning re-run could not start at all: BOTH runners hung before establishing connection (#134 machine wedge, control suite hangs identically) — the 657/657 evening run on this code plus a 5/5 isolated rail-suite run after the last test-only edit are the verification of record. +- Flip cycle: repoint guard `|| true` + rail clear-ordering flipped in one edit → both target pins FAILED, other three passed; restored → green. Each pin discriminates its own guard. +- swiftformat clean; swiftlint **279 = 279** pre-change baseline parity (no new violations). +- GitNexus: impact read before editing (verbs LOW; `refreshCards` CRITICAL / `openUnguarded` HIGH = hub fan-out on signature-only changes); `detect-changes` scope = intended symbols only; index re-analyzed. +- Reviews: implement-close two-axis review (Standards+Spec) AND finish-audit three-reviewer fanout (ponytail/security/general) — 2+5 findings triaged, 7 fixed, rest accepted-as-designed with rationale above. + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostsModel.swift` | `performWrite` rail; verbs converted; `watchedHome` private(set); header | +| `Museion/PostsModelOutline.swift` | Home-less guard/convert verbs; `conversionWentLossyBehindAsk` helper | +| `Museion/PostsModelPasses.swift` | `runPass`/`blindRead` Home-less; advance on the rail; mid-pass repoint guard | +| `Museion/PostsModelCards.swift` | Card verbs + `refreshCards` Home-less | +| `Museion/Micropub.swift` | `micropubSendDraft` Home-less (off-rail, documented) | +| `Museion/WorkspaceView.swift`, `PostsPaneView.swift`, `SessionsPaneView.swift`, `MentorPaneView.swift`, `FixCardsWindow.swift`, `PromoteAskSheet.swift`, `MicropubPublishSheet.swift` | Call-site sweep + dead `home` plumbing cut | +| `MuseionTests/PostsModelTests.swift` | `PostsModelWriteRailTests` suite: 5 pins + scenario headers | +| `MuseionTests/ScriptedEngine.swift` | `endHeldPrompt()` test hook | +| `MuseionTests/FixCardApplyTests.swift` | `pollUntil` made internal (shared poll) | +| 8 further test files | Mechanical `home:` sweep | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX: write-rail contract, repoint refusal, suite map | + +## Open Items & Next Steps + +- [ ] Maintainer ruling: `createProject` failure double-message (sheet + strip) — default kept per the issue's rail-owns-the-strip posture. +- [ ] Maintainer ruling: `saveDraft` on the rail (reading of "the editor's flush/save-draft"). +- [ ] None otherwise — all five acceptance criteria of #179 met and pinned. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index e538aec..ad5c1a0 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-09 | issue | [20261109-issue179-postsmodel-write-rail_log.md](20261109-issue179-postsmodel-write-rail_log.md) | One `performWrite` rail pairs every library write with one rescan and owns the strip; model owns the Home (#179) | | 2026-11-09 | issue | [20261109-issue178-extract-engine-host-transport-seam_log.md](20261109-issue178-extract-engine-host-transport-seam_log.md) | Engine lifecycle → EngineHost behind the EngineTransport seam; scripted in-process tests, one real smoke per surface | | 2026-11-09 | issue | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | SessionRow text rows typed (speaker+notice), kick-off sniffed at append seam, one ToolPayloads decoder both rails read | | 2026-11-09 | issue | [20261109-issue183-shrink-agentsmd_log.md](20261109-issue183-shrink-agentsmd_log.md) | AGENTS.md rails shrunk 206 KB → 36 KB — contracts and rulings kept, per-issue diaries cut; serif payload untouched (#183) |