Files
museion/Museion/PostsModelPasses.swift
T
AlexKucera 5bf09552f6
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through one rail
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00

177 lines
7.2 KiB
Swift

//
// PostsModelPasses.swift
// Museion
//
// #146: the engine-run extensions of PostsModel — pass orchestration
// (#24, S3.1) and the Blind Read (#122) — moved from PostsModel.swift
// (file-length ceiling), code unchanged.
//
import Foundation
// MARK: Pass orchestration (#24, S3.1)
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
/// minimal stub (PassContext) crosses the bridge and the critique
/// streams into the mentor pane. Pass State advances ONLY when the
/// 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, mentor: MentorSessionModel) async {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings, BEFORE the open-piece guard so nothing writes
// to disk (not even the pre-pass snapshot).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
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 {
lastError = error.localizedDescription
return
}
// #31 (S5.1): unaided-first-draft stats — fires at the invocation,
// before the engine sees anything; eligibility (writer origin, First
// Draft, post type) is read from disk. A failed capture must never
// fail the pass (decay-clock posture), so the Bool is ignored.
PostStore.captureFirstDraftStats(id: id, body: session.text, home: home)
// #6 (S3.4): the native deslop lint — same invocation posture as the
// stats capture: pure Swift, no engine round-trip, a failure never
// blocks the pass. Cards land in <piece>/cards/ and the palette's
// watcher-driven rescan surfaces them (the #23 path).
DeslopLint.emit(body: session.text, pieceID: id, pieceURL: session.passPieceURL, kind: kind, home: home)
// #137 (S4): runningPass goes live BEFORE the mentor awaits —
// flush/snapshot/capture/lint above are synchronous, so nothing can slip
// between the guards and the flag: the #124 Cancel-visibility
// invariant now holds for the WHOLE run, pass-engine spawn included.
runningPass = kind
defer { runningPass = nil }
let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch)
// #137: the pass runs on its OWN one-shot engine and streams into the
// transient pass transcript — never rostered (#129, ADR-0014).
let outcome = await mentor.runPass(kind: kind, stub: stub, pieceTitle: title(of: id))
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
// #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
/// rail stops the agent; nothing advances (runPass reads .cancelled).
/// #122: the Blind Read shares the rail — Cancel ends either run.
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil || runningBlindRead else { return }
mentor.stopStreaming()
}
}
// MARK: Blind Read (#122)
extension PostsModel {
/// #122: run one Blind Read over the OPEN piece — the current document
/// vs the newest Pass-start snapshot, judged blind by a fresh session
/// of the museion profile. Advisory-only (decision #120): no Pass State
/// 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(mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a Blind Read."
return
}
guard flushOrAbort(id) else { return }
// #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
}
let current = session.text
guard current != base.body else {
lastError = "No edits since the Pass started — the Blind Read judges the current document against the Pass-start snapshot."
return
}
// House posture (runPass's success path): the run is firing — a
// stale guard refusal no longer owns the error strip.
lastError = nil
runningBlindRead = true
defer { runningBlindRead = false }
// Randomized order kills position bias (#120's flagged default);
// the reveal names the mapping only after the verdict.
let snapshotFirst = Bool.random()
_ = await mentor.runBlindRead(
prompt: BlindRead.prompt(snapshot: base.body, current: current, snapshotFirst: snapshotFirst),
pieceTitle: title(of: id),
reveal: BlindRead.reveal(kind: base.kind, snapshotFirst: snapshotFirst),
)
// Advisory-only: nothing to advance or record — the outcome row in
// the transient transcript IS the deliverable.
}
}