feat(mentor): apply/skip fix cards (#25)
CI / ci (push) Canceled after 0s

Fix Cards become actionable. Mechanical cards offer Apply behind a
blocking ask-before sheet showing the exact edit (anchored quote ->
replacement, occurrence + context; empty fix cuts); the sheet is the
only path to a write, one card at a time, no apply-all. The edit
lands through the editing session (pending edits flush first, the
editor re-seeds via adoptText, the card closes applied); Skip and
Done close the card in place, recording nothing; demonstration
cards close Done/Skip only (ADR-0006). Cards arrive ranked
(store-stamped, scan-ordered, open-first palette) and capped at ten
per submit — the app keeps the ranked head and the wire reply
discloses the drop. Stale anchors re-validate at apply: no text
selected or changed, the card flags itself. Includes the
finish-audit round (11 fixes, 2 flip-verified pins); 316 tests
green.

Closes #25
This commit is contained in:
AlexKucera committed 2026-10-20 16:46:43 +02:00
1 parent 5700264628
commit 4d33676a08
15 files changed
+1012 -74

No files matched your search

+117 -18
View File
@@ -57,6 +57,14 @@ nonisolated enum FixCardStore {
case valid, stale
}
/// #25 (S3.3): the card's lifecycle state — "open" on submit, one of
/// the CONTEXT.md terminals on close: applied (Apply wrote the edit),
/// skipped (not this instance), done (the writer rewrote the span).
/// A foreign status string on disk fails decode → scan's junk-skip.
enum Status: String, Codable {
case open, applied, skipped, done
}
struct Provenance: Codable, Equatable {
var piece: String
var date: String?
@@ -69,6 +77,10 @@ nonisolated enum FixCardStore {
var id: UUID
var submittedAt: Date
/// #25 (S3.2): the card's rank in its submit — the persona's ranked
/// order, 1-based, stamped by the store like id/submittedAt. Optional:
/// pre-#25 cards on disk carry no rank key.
var rank: Int?
var pattern: String
var problem: String
var diagnosticQuestion: String
@@ -77,8 +89,8 @@ nonisolated enum FixCardStore {
var lane: Lane
var emitter: Emitter
var provenance: Provenance?
/// Always "open" on submit; later states belong to the app slice.
var status: String
/// "open" on submit; a Status terminal once the writer closes it.
var status: Status
var anchorStatus: AnchorStatus
}
@@ -133,18 +145,44 @@ nonisolated enum FixCardStore {
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
}
// MARK: - Apply (pure)
/// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit
/// the card makes in `text`: the anchor's quote occurrence (1-based,
/// non-overlapping — the anchorStatus math) replaced by the fix,
/// everything else untouched. nil = the card must not touch text: a
/// demonstration lane (only a mechanical fix is ever applied,
/// ADR-0006) or an anchor that no longer resolves — edits between
/// issue and accept degrade to a loud no-match, never a wrong-span
/// patch. The caller owns the ask and the file write.
static func appliedText(of card: StoredFixCard, in text: String) -> String? {
guard card.lane == .mechanical,
card.anchor.occurrence >= 1,
!card.anchor.quote.isEmpty,
let range = text.ranges(of: card.anchor.quote).dropFirst(card.anchor.occurrence - 1).first
else { return nil }
return text.replacingCharacters(in: range, with: card.fix)
}
// MARK: - Submit
/// Validate every card first, then write one JSON file per card into
/// `<piece>/cards/` named `<yyyyMMdd-HHmmss>-<slug>.json` (collision →
/// -2, -3…). Stale anchors still land, flagged. No dedup — every
/// submission lands (explicit product decision).
/// #25 (S3.2): the pass ceiling — `passCardCeiling` per submit, the
/// ranked head kept (the persona's cap is the primary filter; this is
/// the backstop). Tail cards drop before validation.
static let passCardCeiling = 10
static func submit(piecePath: String, cards: [Input]) throws -> [(card: StoredFixCard, file: String)] {
let postURL = try resolvePostURL(piecePath)
let text = try String(contentsOf: postURL, encoding: .utf8)
// Whole-call semantics: a malformed card errors the call before
// anything is written.
let materialized = try cards.map { try materialize($0, postText: text) }
let materialized = try cards.prefix(passCardCeiling).enumerated().map { index, input in
try materialize(input, postText: text, rank: index + 1)
}
let dir = postURL.deletingLastPathComponent().appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
@@ -169,7 +207,7 @@ nonisolated enum FixCardStore {
}
/// Trust-boundary validation + server stamping.
private static func materialize(_ input: Input, postText: String) throws -> StoredFixCard {
private static func materialize(_ input: Input, postText: String, rank: Int) throws -> StoredFixCard {
guard !input.pattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw CardError(message: "card pattern must not be empty")
}
@@ -185,6 +223,7 @@ nonisolated enum FixCardStore {
return StoredFixCard(
id: UUID(),
submittedAt: Date(),
rank: rank,
pattern: input.pattern,
problem: input.problem,
diagnosticQuestion: input.diagnosticQuestion ?? "",
@@ -193,7 +232,7 @@ nonisolated enum FixCardStore {
lane: input.lane,
emitter: input.emitter,
provenance: input.provenance,
status: "open",
status: .open,
anchorStatus: anchorStatus(
text: postText,
quote: input.anchor.quote,
@@ -255,24 +294,84 @@ nonisolated enum FixCardStore {
// MARK: - Scan
/// Every stored card under `<piece>/cards/`, newest-first (the stamp
/// prefix sorts lexicographically). Undecodable files are skipped
/// silently — a stranger's hand-edit never crashes the reader. A
/// post.md URL is tolerated (app-side call sites hold the file URL).
static func scan(pieceURL: URL) -> [StoredFixCard] {
/// `<piece>/cards/`, tolerating a post.md URL (app-side call sites
/// hold the file URL).
private static func cardsDir(for pieceURL: URL) -> URL {
var dir = pieceURL
if ["md", "markdown"].contains(dir.pathExtension.lowercased()) {
dir.deleteLastPathComponent()
}
let cards = dir.appendingPathComponent("cards", isDirectory: true)
let files = (try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? []
return files
.filter { $0.hasSuffix(".json") }
.sorted(by: >)
.compactMap { name in
guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)) else { return nil }
return try? decoder.decode(StoredFixCard.self, from: data)
return dir.appendingPathComponent("cards", isDirectory: true)
}
/// Every stored card under `<piece>/cards/`, the persona's ranked order:
/// submittedAt DESC (newest submit first), then rank ASC within a
/// submit, pre-#25 cards (rank nil) AFTER ranked ones of the same
/// submit. Undecodable files are skipped silently — a stranger's
/// hand-edit never crashes the reader. A post.md URL is tolerated
/// (app-side call sites hold the file URL).
static func scan(pieceURL: URL) -> [StoredFixCard] {
decoded(in: cardsDir(for: pieceURL)).sorted { lhs, rhs in
if lhs.card.submittedAt != rhs.card.submittedAt {
return lhs.card.submittedAt > rhs.card.submittedAt
}
switch (lhs.card.rank, rhs.card.rank) {
case let (ranked?, other?) where ranked != other:
return ranked < other
case (.some, nil):
return true // ranked cards lead their unranked siblings
case (nil, .some):
return false
default:
return lhs.file > rhs.file
}
}
.map(\.card)
}
/// The shared cards/ walk — decoded cards with their filenames; scan
/// sorts it, close finds in it. Undecodable files are skipped silently
/// (a stranger's hand-edit never crashes the reader). The comparator's
/// filename tiebreak totally orders unique names, so walk order never
/// matters.
private static func decoded(in cards: URL) -> [(file: String, card: StoredFixCard)] {
let files = ((try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? [])
.filter { $0.hasSuffix(".json") }
return files.compactMap { name in
guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)),
let card = try? decoder.decode(StoredFixCard.self, from: data)
else { return nil }
return (name, card)
}
}
// MARK: - Close
/// #25 (S3.3): close a stored card IN PLACE — its JSON file rewritten
/// with the new status, every other field untouched (Skip records
/// nothing beyond the flip). `anchorStatus`, when non-nil, rides the
/// same rewrite (the stale-anchor flag); nil preserves it. Returns
/// the closed card. Throws when no card with the id sits under the
/// piece (the app surface routes the error); undecodable stranger
/// files are skipped, same as scan.
@discardableResult
static func close(
pieceURL: URL,
id: UUID,
status: StoredFixCard.Status,
anchorStatus: StoredFixCard.AnchorStatus? = nil,
) throws -> StoredFixCard {
let cards = cardsDir(for: pieceURL)
for entry in decoded(in: cards) where entry.card.id == id {
var card = entry.card
card.status = status
if let anchorStatus {
card.anchorStatus = anchorStatus
}
try encoder.encode(card).write(to: cards.appendingPathComponent(entry.file), options: .atomic)
return card
}
throw CardError(message: "card not found: \(id)")
}
// MARK: - Learnings