Files
museion/MuseionTests/FixCardApplyTests.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

324 lines
16 KiB
Swift

//
// FixCardApplyTests.swift
// MuseionTests
//
// #25 · Slice 2 — Scenario: the writer's hand stays on the wheel
// From issue #25 (S3.2/S3.3): Apply writes the mechanical edit into the
// piece under the ask-before trust level; Skip and Done close the card,
// recording nothing; a stale anchor — the Post changed after the card was
// issued — alerts and touches no text.
// Given an open piece carrying a mechanical fix card,
// when the writer applies, skips, or closes it done, or the anchor went
// stale,
// then the edit lands through the editing session (buffer and disk agree,
// card closes applied), skip and done flip only the status, and the stale
// anchor selects and changes no text while the card flags itself stale.
//
import Foundation
@testable import Museion
import Testing
/// refreshCards hops off MainActor (Task.detached scan) — poll for the
/// hop-back instead of asserting synchronously (PostsModelTests convention).
/// The post-loop expect makes a silent timeout a failure, not a pass.
@MainActor
func pollUntil(_ condition: @MainActor () -> Bool) async throws {
for _ in 0 ..< 250 where !condition() {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(condition())
}
/// Throwaway piece folder under a throwaway Home — a REAL piece via
/// PostStore.writeNew, so the store's own layout rules apply.
private func makePiece() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("fixcard-apply-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
return try #require(PostStore.folder(of: post.id, home: home))
}
struct FixCardApplyTests {
// MARK: Apply / Skip / Done through the model (#25, S3.2/S3.3)
@Test @MainActor func `apply on a dirty buffer lands the edit buffer and disk agree`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id)
let session = try #require(model.session)
let generation = session.loadGeneration
// The writer typed since the last flush — Apply must land the dirty
// 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) == .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")
// ...and the session re-seeded + saved (the adoptText rail).
#expect(session.text == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n")
#expect(session.saveState == .saved)
#expect(session.loadGeneration == generation + 1)
// The card closed applied on disk.
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .applied)
#expect(model.lastError == nil)
}
@Test @MainActor func `apply with a stale anchor flags the card and touches no text`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
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) == .stale)
#expect(try Data(contentsOf: postURL) == before) // nothing selected, nothing changed
let diskCard = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(diskCard.status == .open) // still open — the writer decides
#expect(diskCard.anchorStatus == .stale) // the honest flag persisted
#expect(model.session?.text == "# Carded\n\nThe sentence changed.\n")
}
@Test @MainActor func `apply on a demonstration card refuses and changes nothing`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(pattern: "Demo", fix: "The replaced sentence.", quote: "The anchor sentence.", lane: .demonstration)],
)
model.select(post.id)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(why == "demonstration cards close Done or Skip")
#expect(try Data(contentsOf: postURL) == before)
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open)
#expect(model.lastError == nil)
}
@Test @MainActor func `apply under an unanswered conflict refuses and keeps disk untouched`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
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")
try "foreign text on disk".write(to: postURL, atomically: true, encoding: .utf8)
model.session?.diskDidChange(diskText: "foreign text on disk")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(why.contains("reload question"))
#expect(try Data(contentsOf: postURL) == before) // disk untouched
#expect(model.session?.conflictAlert == true) // the alert stays answerable
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open)
}
@Test @MainActor func `skip and done flip only the card status`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [
card(pattern: "Hedging", quote: "The anchor sentence."),
card(pattern: "Telling", quote: "The anchor sentence."),
],
)
model.select(post.id)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
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)
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)
// Skip records NOTHING beyond the status flip (CONTEXT.md).
#expect(try Data(contentsOf: postURL) == before)
#expect(model.lastError == nil)
}
// MARK: Store addenda (#25 slice 2): scan rank order + close anchorStatus
/// Rank is the persona's ranked order, not the filename's — pattern slugs
/// sort differently than the submit order here, and rank must win.
// ponytail: same-submit cards share a disk timestamp (whole seconds), so
// this pins the microsecond straddle away only probabilistically — a
/// submit-time clock injection if it ever flakes.
@Test func `scan orders a submit by rank regardless of slug order`() throws {
let piece = try makePiece()
_ = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(pattern: "Zebra"), card(pattern: "alpha"), card(pattern: "Mid")],
)
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["Zebra", "alpha", "Mid"])
}
/// Two submits: the newest submission leads. The disk timestamp is
/// whole-second, so the test spans a second boundary deliberately.
@Test func `scan lands the newest submit first`() async throws {
let piece = try makePiece()
_ = try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: "Earlier")])
try await Task.sleep(nanoseconds: 1_100_000_000)
_ = try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: "Later")])
#expect(FixCardStore.scan(pieceURL: piece).first?.pattern == "Later")
}
/// Pre-#25 cards (no rank key) sit AFTER ranked cards of the same submit —
/// filenames here would order them the other way, proving rank decides.
@Test func `scan sorts nil ranks after ranked cards of the same submit`() throws {
let piece = try makePiece()
let dir = piece.appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let stamp = Date(timeIntervalSince1970: 1000)
try FixCardStore.encoder.encode(storedCard(pattern: "Ranked", submittedAt: stamp, rank: 2))
.write(to: dir.appendingPathComponent("a-ranked.json"))
try FixCardStore.encoder.encode(storedCard(pattern: "Old", submittedAt: stamp, rank: nil))
.write(to: dir.appendingPathComponent("b-old.json"))
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["Ranked", "Old"])
}
@Test func `close refreshes anchorStatus when given and preserves it when not`() throws {
let piece = try makePiece()
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let id = written[0].card.id
// A non-nil anchorStatus rides the rewrite — even a status-only close.
let flagged = try FixCardStore.close(pieceURL: piece, id: id, status: .open, anchorStatus: .stale)
#expect(flagged.status == .open) // only the flag flipped
#expect(flagged.anchorStatus == .stale)
// nil preserves it — Skip/Done never touch the anchor verdict.
let skipped = try FixCardStore.close(pieceURL: piece, id: id, status: .skipped)
#expect(skipped.status == .skipped)
#expect(skipped.anchorStatus == .stale)
}
/// A failed stale-flag close surfaces its error — the flag write is
/// honest or loud, never silently skipped (audit: the applied path
/// already reported; this pins the stale sibling).
@Test @MainActor func `stale flag close failure surfaces its error`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
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")
let before = try Data(contentsOf: postURL)
// The cards dir goes unreadable — close can't find the card.
let cardsDir = folder.appendingPathComponent("cards", isDirectory: true)
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) == .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
}
/// A session that never loaded (post.md unreadable/vanished at open)
/// refuses Apply — the card must not close .applied over a write that
/// never landed (audit: flush reports success on a clean no-op).
@Test @MainActor func `apply on a session that never loaded refuses without writing`() 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))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
try FileManager.default.removeItem(at: folder.appendingPathComponent("post.md")) // the read will fail
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)
guard case .refused = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open) // card stays open
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
}
// MARK: Promote (#26, S4.1)
/// Scenario: the mentor remembers — promoting through the model writes
/// the Learning under the open piece's Home, refreshes the palette's
/// cards (promotedAt visible), and refuses a second confirm; with no
/// open piece it refuses before touching anything.
@Test @MainActor func `promote through the model writes one learning and refuses repeats`() 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))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
model.select(post.id)
#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)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.promotedAt != nil }
#expect(model.lastError == nil)
// Already promoted → refused, no second file (one confirm = one entry).
let scanned = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(model.promoteCard(scanned) == .refused("card already promoted"))
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
}
@Test @MainActor func `promote without an open piece refuses and writes nothing`() 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))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
#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)
}
}