refactor(postsmodel): split domain extensions (#146)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
PostsModel.swift had outgrown its lint ceilings — 1127 lines against the 1000 file-length error, class body 361 against 350; both pre-dated the week and #143 deepened them while naming this split as the follow-up. The six domain extensions after the class move to their own files, domain-grouped: PostsModelOutline.swift (mixed-content guard #111 + Convert to Post #114), PostsModelPasses.swift (pass orchestration #24 + Blind Read #122), PostsModelCards.swift (stored cards #23 + apply/skip/done #25 + promote #26, with their support types). The watcher section (startWatching + rescan) moves to a file-scope extension so the class body drops to 323 — #111's precedent: same-file extensions keep private state file-scoped while type_body_length only counts the class body. Pure moves, mechanically verified line-for-line: the only edits are the 18 private->internal widenings the cross-file moves force (13 private(set) setters + rescan/dismissExternal/wireSession/ isGuardedOutline/openUnguarded, each doc-noted) and the two wrapped-condition guards unwrapped per the #142 learning, clause order preserved. The error ceilings and both opening_brace warnings are gone; the residual default WARNING-tier notices (708/400 file, 323/250 type-body) match the repo's standing posture — the ticket's own ~700-line landing zone makes the 400 tier unreachable. Full suite 574/574 by xcresult executed count (573 unit + 1 UI smoke). Closes #146
This commit is contained in:
1 parent
53c314d4e1
commit
012f91727f
8 files changed
+628
-509
No files matched your search
+87
-506
@@ -8,6 +8,10 @@
|
||||
// the same rescan: one path.
|
||||
// #108: project targeting + the move/archive/restore ops behind the
|
||||
// variant-B library and the Archive pane.
|
||||
// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in
|
||||
// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching
|
||||
// + rescan sit in the file-scope watcher extension below (type-body
|
||||
// ceiling).
|
||||
//
|
||||
|
||||
import CoreServices
|
||||
@@ -88,14 +92,17 @@ final class PostsModel {
|
||||
private(set) var posts: [Post] = []
|
||||
|
||||
/// The selected Post's id; nil = nothing selected (empty editor).
|
||||
private(set) var selectedPostID: String?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var selectedPostID: String?
|
||||
|
||||
/// The in-memory draft for New Post (#62): no folder until first save.
|
||||
private(set) var draft: PostDraft?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var draft: PostDraft?
|
||||
|
||||
/// #19: the open post's editing session; nil while a draft is open or
|
||||
/// nothing is selected.
|
||||
private(set) var session: EditorSession?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var session: EditorSession?
|
||||
|
||||
/// #92: the external buffer's guest slot — one at a time, transient per
|
||||
/// launch. Takes the editor column; opening a Post or draft dismisses it
|
||||
@@ -109,7 +116,8 @@ final class PostsModel {
|
||||
/// #108: the explicit target for the NEXT new piece — set by New Project
|
||||
/// once the folder exists; outranks selection. Cleared when the draft
|
||||
/// lands (saveDraft) or the ask is canceled.
|
||||
private(set) var pendingProject: String?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var pendingProject: String?
|
||||
|
||||
/// #108: File ▸ New Project… stages its ask here — commands can't
|
||||
/// present sheets, so the model holds the flag and WorkspaceView
|
||||
@@ -120,40 +128,49 @@ final class PostsModel {
|
||||
/// lags one rescan (the FSEvents window), so the freshly-opened
|
||||
/// session can't read its type from the scan yet and would flash the
|
||||
/// prose editor. True only between saveDraft and the next selection.
|
||||
private(set) var lastDraftWasOutline = false
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var lastDraftWasOutline = false
|
||||
|
||||
/// #111 (S7): a mixed-content outline piece whose open is held for the
|
||||
/// guard ask. Non-nil = the ask is up (no session — the ask presents
|
||||
/// over an empty editor); cleared by any answer.
|
||||
private(set) var outlineGuardPieceID: String?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var outlineGuardPieceID: String?
|
||||
|
||||
/// #111 (S7): the piece the guard's Prose answer opened in prose mode —
|
||||
/// a routing override with lastDraftWasOutline's exact lifecycle (dies
|
||||
/// on the next open/draft/guest; the rescan lag window is covered).
|
||||
private(set) var proseOverridePostID: String?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var proseOverridePostID: String?
|
||||
|
||||
/// #114 (S4): the staged Convert to Post ask (row menu → sheet). The
|
||||
/// ask targets a piece id, not the session — it survives background
|
||||
/// selects; the sheet is modal in its window, and the convert itself
|
||||
/// re-derives everything (flush, disk read) at answer time.
|
||||
private(set) var pendingConversion: PendingConversion?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var pendingConversion: PendingConversion?
|
||||
/// #24 (S3.1): the pass currently streaming over the open piece —
|
||||
/// one at a time; nil = idle. Drives the pass bar's Run ↔ Cancel swap.
|
||||
private(set) var runningPass: PassKind?
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var runningPass: PassKind?
|
||||
/// #122: the Blind Read currently judging over the open piece —
|
||||
/// one at a time beside runningPass; false = idle. Shares the pass
|
||||
/// bar's Run ↔ Cancel swap.
|
||||
private(set) var runningBlindRead = false
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var runningBlindRead = false
|
||||
/// #122: does the OPEN piece have a Pass-start snapshot on disk (the
|
||||
/// Blind Read's comparison base)? Refreshed with the cards at the
|
||||
/// rescan tail and open transitions.
|
||||
private(set) var openPieceHasSnapshot = false
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var openPieceHasSnapshot = false
|
||||
/// #23 (M2, slice 3): the OPEN piece's stored fix cards
|
||||
/// (`<piece>/cards/*.json`, newest-first) — what any MCP client
|
||||
/// submitted; nil session (draft/guest/nothing) shows none.
|
||||
private(set) var openPieceCards: [FixCardStore.StoredFixCard] = []
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
var openPieceCards: [FixCardStore.StoredFixCard] = []
|
||||
/// Last failed-op message surfaced in the editor (nil = clean).
|
||||
private(set) var lastError: String?
|
||||
/// #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?
|
||||
private var watcher = PostsWatcher()
|
||||
@@ -173,72 +190,6 @@ final class PostsModel {
|
||||
Task { await rescan() }
|
||||
}
|
||||
|
||||
// MARK: Watcher (#61)
|
||||
|
||||
private func startWatching(home: URL) {
|
||||
guard watchedHome != home else { return }
|
||||
watchedHome = home
|
||||
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
|
||||
for root in roots {
|
||||
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
|
||||
watcher.start(urls: roots)
|
||||
}
|
||||
|
||||
/// Off-main scan; keeps selection valid across the fresh refresh.
|
||||
/// FSEvents already coalesces bursts within its 0.5 s latency window —
|
||||
/// no second debounce on top.
|
||||
private func rescan() async {
|
||||
guard let home = watchedHome else { return }
|
||||
// Scan + the #67 disk read both run off-main (a synced large post.md
|
||||
// must never stall the UI on a watcher burst).
|
||||
let openPostID = session?.postID
|
||||
// #114 audit: identity, not id — a same-id reopen (convert/restore/
|
||||
// move) must not receive the OLD session's stale disk text as a
|
||||
// spurious #67 conflict.
|
||||
let openSession = session
|
||||
let scanMemo = scanCache // detached capture, not a property read
|
||||
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
|
||||
let posts = Post.scan(home: home, cache: scanMemo)
|
||||
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
|
||||
return (posts, disk)
|
||||
}.value
|
||||
guard !Task.isCancelled else { return }
|
||||
// #143: @Observable invalidates on assignment regardless of equality —
|
||||
// skip the no-op so panes don't regroup on our own autosave echoes.
|
||||
if scanned != posts {
|
||||
posts = scanned
|
||||
}
|
||||
if let id = selectedPostID, !posts.contains(where: { $0.id == id }),
|
||||
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
|
||||
// current selection — bind's initial rescan (detached scan over the
|
||||
// empty tree) can land its continuation after a select its scan never
|
||||
// saw, "vanishing" a piece that exists. Disk is the truth for
|
||||
// vanished; a stale snapshot must not kill a live session (teardown
|
||||
// cancels the debounce — unflushed edits would die with it).
|
||||
// #137 audit (finish): a scan that outlived a Home repoint speaks
|
||||
// for the OLD tree — never let it kill a session selected under
|
||||
// the NEW home (the id is missing from the old snapshot by
|
||||
// construction); the next rescan under the new home owns it.
|
||||
watchedHome == home, PostStore.folder(of: id, home: home) == nil
|
||||
{
|
||||
selectedPostID = nil // the post vanished (deleted in Finder or here)
|
||||
if let open = session, open.postID == id {
|
||||
open.teardown(flushFirst: false) // post is gone; cancel the debounce
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
// #67: watcher echo check on the open post — equality against the
|
||||
// session's lastFlushedText suppresses our own writes exactly.
|
||||
if openSession === session, let openDiskText {
|
||||
openSession?.diskDidChange(diskText: openDiskText)
|
||||
}
|
||||
// #23: the open piece's stored fix cards ride the same rescan —
|
||||
// the watcher fires on <piece>/cards/ writes too.
|
||||
refreshCards(home: home)
|
||||
}
|
||||
|
||||
// MARK: Own ops (route through the same rescan, #61)
|
||||
|
||||
// ponytail: the PostStore calls here run on MainActor — small single-file
|
||||
@@ -300,7 +251,8 @@ final class PostsModel {
|
||||
/// #92: dismiss the external guest slot, flushing pending edits (the
|
||||
/// guest is always leaving for somewhere — same posture as post
|
||||
/// selection change).
|
||||
private func dismissExternal() {
|
||||
/// #146: internal — the split-out domain extensions dismiss too.
|
||||
func dismissExternal() {
|
||||
externalSession?.teardown(flushFirst: true)
|
||||
externalSession = nil
|
||||
externalWatcher.stop()
|
||||
@@ -680,448 +632,77 @@ final class PostsModel {
|
||||
Task { await rescan() }
|
||||
}
|
||||
|
||||
private func wireSession() {
|
||||
/// #146: internal — the split-out domain extensions wire sessions too.
|
||||
func wireSession() {
|
||||
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
|
||||
session?.onError = route
|
||||
externalSession?.onError = route
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Mixed-content outline guard (#111, S7)
|
||||
// MARK: Watcher (#61) — #146: file-scope extension (type_body_length)
|
||||
|
||||
extension PostsModel {
|
||||
/// A `type: outline` piece that parses with dropped prose — the guard's
|
||||
/// target. The old session already ended by the time this runs; its
|
||||
/// flush was prose-mode, so it couldn't drop anything.
|
||||
/// Type: the scan's word when the list knows it (archive pane opens,
|
||||
/// app-start selection), the frontmatter's word during the rescan lag
|
||||
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
|
||||
/// both. No watched home yet (pre-bind) = post: nothing to guard.
|
||||
private func isGuardedOutline(_ id: String, home: URL) -> Bool {
|
||||
guard 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 {
|
||||
known
|
||||
} else {
|
||||
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
|
||||
private func startWatching(home: URL) {
|
||||
guard watchedHome != home else { return }
|
||||
watchedHome = home
|
||||
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
|
||||
for root in roots {
|
||||
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
|
||||
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
|
||||
watcher.start(urls: roots)
|
||||
}
|
||||
|
||||
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
|
||||
/// 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) {
|
||||
guard let id = outlineGuardPieceID else { return }
|
||||
outlineGuardPieceID = nil
|
||||
proseOverridePostID = id // routing: prose until the next open
|
||||
openUnguarded(id, home: home)
|
||||
}
|
||||
|
||||
func openGuardedOutlineAsOutline(home: URL) {
|
||||
guard let id = outlineGuardPieceID else { return }
|
||||
outlineGuardPieceID = nil
|
||||
openUnguarded(id, home: home)
|
||||
}
|
||||
|
||||
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
|
||||
/// nothing stays selected over the empty editor).
|
||||
func cancelOutlineGuard() {
|
||||
outlineGuardPieceID = nil
|
||||
if session == nil {
|
||||
selectedPostID = nil
|
||||
/// Off-main scan; keeps selection valid across the fresh refresh.
|
||||
/// FSEvents already coalesces bursts within its 0.5 s latency window —
|
||||
/// no second debounce on top.
|
||||
/// #146: internal — the split-out domain extensions trigger rescans.
|
||||
func rescan() async {
|
||||
guard let home = watchedHome else { return }
|
||||
// Scan + the #67 disk read both run off-main (a synced large post.md
|
||||
// must never stall the UI on a watcher burst).
|
||||
let openPostID = session?.postID
|
||||
// #114 audit: identity, not id — a same-id reopen (convert/restore/
|
||||
// move) must not receive the OLD session's stale disk text as a
|
||||
// spurious #67 conflict.
|
||||
let openSession = session
|
||||
let scanMemo = scanCache // detached capture, not a property read
|
||||
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
|
||||
let posts = Post.scan(home: home, cache: scanMemo)
|
||||
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
|
||||
return (posts, disk)
|
||||
}.value
|
||||
guard !Task.isCancelled else { return }
|
||||
// #143: @Observable invalidates on assignment regardless of equality —
|
||||
// skip the no-op so panes don't regroup on our own autosave echoes.
|
||||
if scanned != posts {
|
||||
posts = scanned
|
||||
}
|
||||
}
|
||||
|
||||
/// #111 (S7): the open with the guard passed (either answer or a clean
|
||||
/// parse) — the plain select body. No re-check: the answer is the
|
||||
/// explicit choice the ruling requires.
|
||||
private func openUnguarded(_ id: String, home: URL) {
|
||||
dismissExternal()
|
||||
if let session, session.postID != id {
|
||||
session.teardown(flushFirst: true)
|
||||
}
|
||||
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
|
||||
draft = nil
|
||||
pendingProject = nil
|
||||
lastDraftWasOutline = false
|
||||
outlineGuardPieceID = nil // the open displaces any held ask
|
||||
selectedPostID = id
|
||||
wireSession()
|
||||
refreshCards(home: home) // #23: the newly opened piece's cards, now
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Convert to Post (#114, S4)
|
||||
|
||||
/// The staged ask: which piece, and whether the headings ladder would
|
||||
/// drop prose lines (mixed content — the sheet warns, verbatim keeps
|
||||
/// everything).
|
||||
struct PendingConversion {
|
||||
let id: String
|
||||
let lossy: Bool
|
||||
}
|
||||
|
||||
extension PostsModel {
|
||||
/// #114 (S4): row-menu entry — stage the ask. Outline pieces only.
|
||||
/// 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) {
|
||||
guard post.type == .outline else { return }
|
||||
let body: String = if let session, session.postID == post.id {
|
||||
session.text
|
||||
} else {
|
||||
PostStore.readBody(id: post.id, home: home) ?? ""
|
||||
}
|
||||
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
|
||||
}
|
||||
|
||||
/// #114 (S4): the ask's Cancel (binding dismissal).
|
||||
func cancelConversion() {
|
||||
pendingConversion = nil
|
||||
}
|
||||
|
||||
/// #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) {
|
||||
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
|
||||
}
|
||||
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
|
||||
if session?.postID == pending.id {
|
||||
session?.teardown(flushFirst: false) // flushOrAbort already wrote
|
||||
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
|
||||
// current selection — bind's initial rescan (detached scan over the
|
||||
// empty tree) can land its continuation after a select its scan never
|
||||
// saw, "vanishing" a piece that exists. Disk is the truth for
|
||||
// vanished; a stale snapshot must not kill a live session (teardown
|
||||
// cancels the debounce — unflushed edits would die with it).
|
||||
// #137 audit (finish): a scan that outlived a Home repoint speaks
|
||||
// for the OLD tree — never let it kill a session selected under
|
||||
// the NEW home (the id is missing from the old snapshot by
|
||||
// construction); the next rescan under the new home owns it.
|
||||
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil {
|
||||
selectedPostID = nil // the post vanished (deleted in Finder or here)
|
||||
if let open = session, open.postID == id {
|
||||
open.teardown(flushFirst: false) // post is gone; cancel the debounce
|
||||
session = nil
|
||||
proseOverridePostID = pending.id
|
||||
openUnguarded(pending.id, home: home)
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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, home: URL, 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
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// #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(home: URL, 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 }
|
||||
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.
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Stored fix cards (#23, M2 slice 3)
|
||||
|
||||
extension PostsModel {
|
||||
/// #23 (M2, slice 3): re-derive `openPieceCards` from the OPEN piece's
|
||||
/// `<piece>/cards/` (FixCardStore.scan — any MCP client's submissions,
|
||||
/// newest-first; archive pieces resolve through folder(of:) too). The
|
||||
/// nil-session rule clears: draft, external guest, held guard ask,
|
||||
/// nothing open → []. Called at the rescan tail and the open
|
||||
/// 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 {
|
||||
openPieceCards = []
|
||||
openPieceHasSnapshot = false
|
||||
return
|
||||
}
|
||||
// Plain disk reads re-run on every watcher burst (typing retriggers
|
||||
// rescan) — keep the I/O off MainActor, same posture as rescan's
|
||||
// Post.scan. The id re-check on hop-back drops a scan that raced a
|
||||
// piece switch.
|
||||
Task.detached { [weak self] in
|
||||
let cards = FixCardStore.scan(pieceURL: folder)
|
||||
let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self, session?.postID == id else { return }
|
||||
openPieceCards = cards
|
||||
openPieceHasSnapshot = hasSnapshot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The piece's display title (fallback: id) — runPass, the pass bar,
|
||||
/// and the Fix Cards palette share this one lookup (review: three
|
||||
/// hand-copies).
|
||||
func title(of id: String) -> String {
|
||||
posts.first(where: { $0.id == id })?.title ?? id
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Fix Card apply/skip/done (#25, S3.2/S3.3)
|
||||
|
||||
/// #25 (S3.2/S3.3): what Apply did — the edit landed, the anchor went
|
||||
/// stale (no text touched, card flagged), or the operation refused with
|
||||
/// a reason for the error strip.
|
||||
enum FixCardApplyOutcome: Equatable {
|
||||
case applied
|
||||
case stale
|
||||
case refused(String)
|
||||
}
|
||||
|
||||
extension PostsModel {
|
||||
/// #25 (S3.2/S3.3): Apply a mechanical card — the blocking ask already
|
||||
/// happened in the UI (ask-before trust level); this lands the edit.
|
||||
/// Dirty buffer lands first (Apply reads live text); an unanswered #67
|
||||
/// conflict aborts here with the existing wording. A stale anchor
|
||||
/// 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 {
|
||||
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 {
|
||||
return .refused("open the piece to work its cards")
|
||||
}
|
||||
guard flushOrAbort(postID) else { return .refused(lastError ?? "edits did not land") }
|
||||
guard let newText = FixCardStore.appliedText(of: card, in: session.text) else {
|
||||
// Stale anchor — the Post changed after the card was issued:
|
||||
// persist the honest flag, select and change nothing. A failed
|
||||
// flag write surfaces like the applied path's — never silent.
|
||||
do {
|
||||
_ = try FixCardStore.close(
|
||||
pieceURL: session.passPieceURL, id: card.id, status: .open, anchorStatus: .stale,
|
||||
)
|
||||
} catch {
|
||||
lastError = "card close failed: \(error.localizedDescription)"
|
||||
}
|
||||
refreshCards(home: home)
|
||||
return .stale
|
||||
}
|
||||
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
|
||||
closeCard(card, status: .applied, home: home)
|
||||
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)
|
||||
}
|
||||
|
||||
/// #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)
|
||||
}
|
||||
|
||||
private func closeCard(
|
||||
_ card: FixCardStore.StoredFixCard,
|
||||
status: FixCardStore.StoredFixCard.Status,
|
||||
home: URL,
|
||||
) {
|
||||
guard let session else {
|
||||
lastError = "open the piece to work its cards"
|
||||
return
|
||||
}
|
||||
do {
|
||||
_ = try FixCardStore.close(pieceURL: session.passPieceURL, id: card.id, status: status)
|
||||
} catch {
|
||||
lastError = "card close failed: \(error.localizedDescription)"
|
||||
// #67: watcher echo check on the open post — equality against the
|
||||
// session's lastFlushedText suppresses our own writes exactly.
|
||||
if openSession === session, let openDiskText {
|
||||
openSession?.diskDidChange(diskText: openDiskText)
|
||||
}
|
||||
// #23: the open piece's stored fix cards ride the same rescan —
|
||||
// the watcher fires on <piece>/cards/ writes too.
|
||||
refreshCards(home: home)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Fix Card promote (#26, S4.1/S4.3)
|
||||
|
||||
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
|
||||
/// refused with a reason (the ask sheet shows it; lastError carries it).
|
||||
enum FixCardPromoteOutcome: Equatable {
|
||||
case promoted
|
||||
case refused(String)
|
||||
}
|
||||
|
||||
extension PostsModel {
|
||||
/// #26 (S4.1/S4.3): Promote a card into ONE plain markdown Learning
|
||||
/// under `<home>/learnings/<type>s/` — the writer's EXPLICIT
|
||||
/// confirmation only (one confirm = one entry, never a repetition
|
||||
/// 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 {
|
||||
guard card.promotedAt == nil else { return .refused("card already promoted") }
|
||||
guard let session else { return .refused("open the piece to work its cards") }
|
||||
do {
|
||||
_ = try FixCardStore.promote(pieceURL: session.passPieceURL, card: card)
|
||||
} catch {
|
||||
lastError = "learning write failed: \(error.localizedDescription)"
|
||||
return .refused("learning write failed: \(error.localizedDescription)")
|
||||
}
|
||||
refreshCards(home: home)
|
||||
return .promoted
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user