Files
museion/Museion/PostsModelPasses.swift
T
AlexKucera f49e4b6ca0
CI / ci (push) Canceled after 0s
refactor(settings): provider facts as data
#181: ModelProvider is the provider-descriptor table — label, effort
ladder, flagship, endpoint, env var joined by wire dialect (chat/models
paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's
header pair), keyless (nous rides the Portal login), and the ONE
trailing-slash endpoint trim. The probe's URL builders, auth headers,
and stream-decoder picks select by data; the per-dialect bodies and
decoders stay separate functions, not switch clothing.

ProviderCredential.resolve is the ONE credential rail (provider key,
else the shared Portal session key for keyless providers — official
endpoint ONLY, never a user-set URL). Settings' Test Connection and the
new PassReadiness module both call it; the twice-implemented #175
fallback can no longer drift. One deliberate tightening, reviewer-
blessed: a nous pass profile on a custom base_url with no pasted key now
reads missingKey where the old session-model fallback said ready — the
old copy had no endpoint gate at all.

Pass readiness leaves the session model (PassReadiness.swift maps each
pass surface to ready/missingKey/unknown over the descriptor;
MentorSessionModel stores the verdicts and reads no keys or auth
files). runPass and blindRead run their guards through one shared rail
(guardOpenPieceRun) — identical refusal strings, blockers named
honestly. No app-side model-settings store (ADR-0014 red line).

Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt
before releasing the held turn — runningPass flips before the one-shot
engine parks its prompt, so firing into that window false-failed under
parallel-suite load.

Full suite 668/668 (xcresult executed count). Finish-audit: three
reviewers (ponytail/security/general), zero findings above LOW; two
ponytail trims and one pin tightening applied.

Closes #181
2026-11-10 10:58:29 +01:00

171 lines
7.3 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
/// and session — the run's target — or nil (refused).
func guardOpenPieceRun(
_ action: String,
mentor: MentorSessionModel,
) -> (id: String, session: EditorSession)? {
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,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session)
}
}
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) = 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; 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 let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { 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.
}
}