Files
museion/Museion/PostsModelPasses.swift
AlexKucera 8b0d43aed8
CI / ci (push) Canceled after 0s
fix(editor): Home repoint rides the departure gate; document identity is (Home, ID)
Settings committed the new Home and bind flipped watchedHome without
departing the open session: the session's immutable target kept the
OLD Home, a same-slug piece in the new library made the ID-only
reselect return it, and autosave/Save/quit wrote the old library
while structural operations resolved against the new one. #198's
departure gate never saw this seam; a no-collision piece was torn
down by the vanish path with its dirty buffer dropped.

The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a
document departure through the same sessionMayDepart (all three legs:
unanswered #67, failed flush, never-loaded retype — no parallel
gate); on refusal nothing changes (preference, watchedHome, the
session's (A, id) target, its buffer), on acceptance the departed
piece's state dies with it. AppGateState.repointMuseionHome(to:)
commits the preference and its persistence only after the gate;
WorkspaceView's Settings binding routes through it and the root
.task(id:) binds the model after that commit — the dumb binder. A
refusal speaks the #198 reason the way #200's quit refusal does
(hosted-guarded alert: no Posts strip is in sight from Settings).
Nothing auto-reopens after an accepted repoint — the writer picks
from the new list; the in-memory draft survives (no Home until first
save; dropping it would drop the only copy).

Document identity is (Home, ID) everywhere — EditorSession.targets
is the pair, PostsModel.openSessionTargets the model-side question;
every ID-only session comparison is retired: select's reselect
no-op, openUnguarded, the structural rail (rename/trash/move/archive/
restore/unarchive + flushOrAbort), conversion, the pass guard (its
answer now carries the Home it validated), Micropub's launch, the
lock's arm/body reads. Async continuations re-validate identity at
COMPLETION: refreshCards (launch and hop-back — the old ID-only guard
let a scan from the previous library land its cards on the new
library's same-slug piece) and rescan (the stale-Home verdict is
hoisted: a scan that outlived a repoint applies nothing, not just
the vanish check; the #67 disk read runs only for a session targeting
the scan's own Home). scanPieceCards is the per-model injectable
scanner the deterministic stale-scan pin needs.

Tests: PostsModelRepointTests (7) move to the gated entry and go
green (17/17 with PostsModelDepartureTests — the #198 matrix stays
green and composes); the stale-scan pin's RED is a mutation check
(completion guard reverted to ID-only → only that pin fails, cards
→ ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin
drives the real Settings path now (repoint + bind). swiftformat 0/152,
swiftlint 0.
2026-11-23 20:23:57 +01:00

173 lines
7.7 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)
// MARK: #181: the ONE guard rail behind runPass and blindRead
extension PostsModel {
/// #181: the shared guard grammar every engine run passes before it
/// touches anything — nothing already running (a pass or a Blind
/// Read, named honestly whichever runner asks), the mentor not
/// mid-reply with its engine ready, and an open SAVED piece (never a
/// draft, the external guest, or a held #111 guard ask). The refusal
/// lands in lastError naming the blocker; answers the open piece's id,
/// session and Home — the run's target — or nil (refused).
/// brief-28: identity — the open session must target THIS library's
/// selected piece (Home, ID); a session born under another Home never
/// runs (its snapshot/stats/lint would land in the wrong library).
// swiftlint:disable:next large_tuple
func guardOpenPieceRun(_ action: String, mentor: MentorSessionModel) -> (id: String, session: EditorSession, home: URL)? {
guard runningPass == nil else {
lastError = "A pass is already running."
return nil
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return nil
}
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home), // brief-28
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session, home)
}
}
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 let (id, session, home) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings. Nothing has touched disk yet (the snapshot
// comes after this guard).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity); every write below lands there.
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 let (id, session, home) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
guard flushOrAbort(id) else { return }
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity).
guard 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.
}
}