feat(mentor): apply/skip fix cards (#25)
CI / ci (push) Canceled after 0s
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:
1 parent
5700264628
commit
4d33676a08
15 files changed
+1012
-74
No files matched your search
@@ -22,7 +22,8 @@ Owned by the root AGENTS.md contract.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700.
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1.
|
||||
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
|
||||
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
|
||||
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn through shutdown teardown (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic).
|
||||
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
//
|
||||
// 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
|
||||
private 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, home: home)
|
||||
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, home: home) == .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, home: home)
|
||||
// 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, home: home) == .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, home: home)
|
||||
let postURL = folder.appendingPathComponent("post.md")
|
||||
let before = try Data(contentsOf: postURL)
|
||||
|
||||
let outcome = model.applyCard(written[0].card, home: home)
|
||||
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, home: home)
|
||||
// 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, home: home)
|
||||
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, home: home)
|
||||
let postURL = folder.appendingPathComponent("post.md")
|
||||
let before = try Data(contentsOf: postURL)
|
||||
|
||||
model.skipCard(written[0].card, home: home)
|
||||
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, home: home)
|
||||
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, home: home)
|
||||
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, home: home) == .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, home: home)
|
||||
#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, home: home)
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -102,14 +102,21 @@ struct MCPServerWireTests {
|
||||
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
|
||||
}
|
||||
|
||||
@Test func `submit and query round trip through the wire`() throws {
|
||||
/// One throwaway wire piece: home + `projects/posts/<name>/post.md`
|
||||
/// (the round-trip test adds its learnings dir on top).
|
||||
private func seedWirePiece(_ name: String) throws -> (home: URL, piece: URL) {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
let piece = home.appendingPathComponent("projects/posts/test-piece", isDirectory: true)
|
||||
let piece = home.appendingPathComponent("projects/posts/\(name)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
|
||||
try "---\ntype: post\n---\nThe repeated anchor line.\n"
|
||||
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
return (home, piece)
|
||||
}
|
||||
|
||||
@Test func `submit and query round trip through the wire`() throws {
|
||||
let (home, piece) = try seedWirePiece("test-piece")
|
||||
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
|
||||
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
|
||||
@@ -180,4 +187,41 @@ struct MCPServerWireTests {
|
||||
#expect(error["code"] as? Int == -32700)
|
||||
#expect(replies[0]["id"] is NSNull)
|
||||
}
|
||||
|
||||
/// #25 (S3.2): the ceiling backstop is honest on the wire — 11 valid cards
|
||||
/// submit, the ranked head (10) lands on disk, the reply says one dropped.
|
||||
@Test func `submit over the ceiling drops the tail and reports it`() throws {
|
||||
let (_, piece) = try seedWirePiece("ceiling-piece")
|
||||
|
||||
let cards = (1 ... 11).map { index in
|
||||
[
|
||||
"pattern": "Pattern \(index)",
|
||||
"problem": "The problem \(index).",
|
||||
"anchor": ["quote": "repeated anchor line"],
|
||||
"lane": "mechanical",
|
||||
"emitter": "lint",
|
||||
] as [String: Any]
|
||||
}
|
||||
let request: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"id": 12,
|
||||
"method": "tools/call",
|
||||
"params": ["name": "submit_fix_cards", "arguments": ["piece_path": piece.path, "cards": cards] as [String: Any]],
|
||||
]
|
||||
let line = try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8))
|
||||
|
||||
let replies = try runWire([line])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["isError"] == nil)
|
||||
let payload = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any],
|
||||
)
|
||||
let landed = try #require(payload["cards"] as? [[String: Any]])
|
||||
#expect(landed.count == 10)
|
||||
#expect(payload["dropped_over_ceiling"] as? Int == 1)
|
||||
let onDisk = ((try? FileManager.default.contentsOfDirectory(
|
||||
atPath: piece.appendingPathComponent("cards").path,
|
||||
)) ?? []).filter { $0.hasSuffix(".json") }
|
||||
#expect(onDisk.count == 10)
|
||||
}
|
||||
}
|
||||
@@ -38,40 +38,55 @@ private func writePiece(
|
||||
}
|
||||
|
||||
/// One wire-shaped card with test-friendly defaults. Internal — shared
|
||||
/// with PostsModelTests (review: a hand-copy drifted here).
|
||||
/// with PostsModelTests and FixCardApplyTests (review: a hand-copy drifted
|
||||
/// here). #25: `fix`/`lane` feed the apply pins.
|
||||
func card(
|
||||
pattern: String = "Hedging",
|
||||
problem: String = "The hedge weakens the claim.",
|
||||
diagnosticQuestion: String? = nil,
|
||||
fix: String? = nil,
|
||||
quote: String = "repeated anchor line",
|
||||
occurrence: Int = 1,
|
||||
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
|
||||
) -> FixCardStore.Input {
|
||||
FixCardStore.Input(
|
||||
pattern: pattern,
|
||||
problem: problem,
|
||||
diagnosticQuestion: diagnosticQuestion,
|
||||
fix: nil,
|
||||
fix: fix,
|
||||
anchor: .init(quote: quote, occurrence: occurrence),
|
||||
lane: .mechanical,
|
||||
lane: lane,
|
||||
emitter: .lint,
|
||||
provenance: nil,
|
||||
)
|
||||
}
|
||||
|
||||
/// A fully-stamped card for hand-written fixtures (scan tests).
|
||||
private func storedCard(pattern: String) -> FixCardStore.StoredFixCard {
|
||||
/// A fully-stamped card for hand-written fixtures (scan tests). Defaults
|
||||
/// match the historical shape; apply tests override anchor/lane, the rank
|
||||
/// pins override submittedAt/rank. Internal — FixCardApplyTests shares it
|
||||
/// (the card()/makeModelHome cross-file convention).
|
||||
func storedCard(
|
||||
pattern: String = "P",
|
||||
quote: String = "q",
|
||||
occurrence: Int = 1,
|
||||
fix: String = "",
|
||||
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
|
||||
submittedAt: Date = Date(timeIntervalSince1970: 0),
|
||||
rank: Int? = nil,
|
||||
) -> FixCardStore.StoredFixCard {
|
||||
FixCardStore.StoredFixCard(
|
||||
id: UUID(),
|
||||
submittedAt: Date(timeIntervalSince1970: 0),
|
||||
submittedAt: submittedAt,
|
||||
rank: rank,
|
||||
pattern: pattern,
|
||||
problem: "p",
|
||||
diagnosticQuestion: "",
|
||||
fix: "",
|
||||
anchor: .init(quote: "q", occurrence: 1),
|
||||
lane: .mechanical,
|
||||
fix: fix,
|
||||
anchor: .init(quote: quote, occurrence: occurrence),
|
||||
lane: lane,
|
||||
emitter: .lint,
|
||||
provenance: nil,
|
||||
status: "open",
|
||||
status: .open,
|
||||
anchorStatus: .valid,
|
||||
)
|
||||
}
|
||||
@@ -103,7 +118,8 @@ struct MCPToolsTests {
|
||||
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
|
||||
/// wire; pre-schema cards (no pass key) decode to nil, never error.
|
||||
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
|
||||
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a","pass":2}}"#
|
||||
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":"#
|
||||
+ #"{"piece":"posts/a","pass":2}}"#
|
||||
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
|
||||
#expect(input.provenance?.pass == 2)
|
||||
|
||||
@@ -122,7 +138,7 @@ struct MCPToolsTests {
|
||||
|
||||
#expect(written.count == 1)
|
||||
#expect(written[0].card.anchorStatus == .valid)
|
||||
#expect(written[0].card.status == "open")
|
||||
#expect(written[0].card.status == .open)
|
||||
#expect(written[0].file.hasSuffix("-hedging.json"))
|
||||
|
||||
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
|
||||
@@ -204,6 +220,119 @@ struct MCPToolsTests {
|
||||
#expect(written[0].file != written[1].file)
|
||||
}
|
||||
|
||||
/// #25 (S3.2): the pass ceiling — an attention budget, not infinite
|
||||
/// scroll. The backstop keeps the ranked HEAD (submit order = rank,
|
||||
/// pass-persona doctrine); tail cards drop before validation, so a
|
||||
/// malformed 12th card never errors an otherwise-fine submit.
|
||||
@Test func `submit caps at the ten-card pass ceiling keeping the ranked head`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
var cards = (1 ... 11).map { card(pattern: "P\($0)") }
|
||||
cards.append(card(pattern: " ")) // malformed — and beyond the ceiling
|
||||
let written = try FixCardStore.submit(piecePath: piece.path, cards: cards)
|
||||
|
||||
#expect(written.map(\.card.pattern) == (1 ... 10).map { "P\($0)" })
|
||||
let files = try FileManager.default.contentsOfDirectory(atPath: piece.appendingPathComponent("cards").path)
|
||||
.filter { $0.hasSuffix(".json") }
|
||||
#expect(files.count == 10)
|
||||
}
|
||||
|
||||
/// #25 (S3.2): rank is the submit's array order (the persona's ranked
|
||||
/// call) — the store stamps it 1-based like id/submittedAt. Optional on
|
||||
/// decode: pre-#25 cards on disk carry no rank key.
|
||||
@Test func `submit stamps rank in submit order and old cards decode without it`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
let written = try FixCardStore.submit(
|
||||
piecePath: piece.path,
|
||||
cards: [card(pattern: "Top"), card(pattern: "Mid"), card(pattern: "Tail")],
|
||||
)
|
||||
#expect(written.map(\.card.rank) == [1, 2, 3])
|
||||
|
||||
// The disk round-trip carries it (snake_case "rank").
|
||||
let json = try #require(
|
||||
try JSONSerialization.jsonObject(
|
||||
with: Data(contentsOf: piece.appendingPathComponent("cards/\(written[0].file)")),
|
||||
) as? [String: Any],
|
||||
)
|
||||
#expect(json["rank"] as? Int == 1)
|
||||
|
||||
// A pre-schema card (no rank key) decodes with rank nil, never errors.
|
||||
let oldData = try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
|
||||
let stripped = try #require(
|
||||
try JSONSerialization.jsonObject(with: oldData) as? [String: Any],
|
||||
).filter { $0.key != "rank" }
|
||||
let decoded = try FixCardStore.decoder.decode(
|
||||
FixCardStore.StoredFixCard.self,
|
||||
from: JSONSerialization.data(withJSONObject: stripped),
|
||||
)
|
||||
#expect(decoded.rank == nil)
|
||||
}
|
||||
|
||||
/// #25 (S3.2/S3.3): the pure Apply — the mechanical edit a card makes
|
||||
/// in a text: the anchored occurrence replaced by the fix, nothing
|
||||
/// else. 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).
|
||||
@Test func `applied text replaces only the anchored occurrence`() {
|
||||
let text = "alpha anchor beta anchor gamma"
|
||||
// The nth occurrence, not the first.
|
||||
#expect(
|
||||
FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 2, fix: "FIX"), in: text)
|
||||
== "alpha anchor beta FIX gamma",
|
||||
)
|
||||
#expect(
|
||||
FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX"), in: text)
|
||||
== "alpha FIX beta anchor gamma",
|
||||
)
|
||||
// An empty fix cuts the span.
|
||||
#expect(
|
||||
FixCardStore.appliedText(of: storedCard(quote: "anchor ", occurrence: 2), in: text)
|
||||
== "alpha anchor beta gamma",
|
||||
)
|
||||
// Beyond-count occurrence, vanished quote, empty quote: no edit.
|
||||
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 3, fix: "FIX"), in: text) == nil)
|
||||
#expect(FixCardStore.appliedText(of: storedCard(quote: "gone", fix: "FIX"), in: text) == nil)
|
||||
#expect(FixCardStore.appliedText(of: storedCard(quote: "", fix: "FIX"), in: text) == nil)
|
||||
// Demonstration lane never applies (ADR-0006).
|
||||
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX", lane: .demonstration), in: text) == nil)
|
||||
}
|
||||
|
||||
/// #25 (S3.3): the in-place close — Skip/Done/Apply flip the card's
|
||||
/// status in its own JSON file; every other field travels unchanged
|
||||
/// (Skip records nothing beyond the flip, CONTEXT.md).
|
||||
@Test func `close rewrites the card status in place`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
|
||||
|
||||
let closed = try FixCardStore.close(pieceURL: piece, id: written[0].card.id, status: .skipped)
|
||||
#expect(closed.status == .skipped)
|
||||
#expect(closed.rank == 1)
|
||||
#expect(closed.pattern == "Hedging")
|
||||
|
||||
// The SAME single file, status flipped, everything else intact.
|
||||
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
|
||||
let files = try FileManager.default.contentsOfDirectory(atPath: cardsDir.path)
|
||||
.filter { $0.hasSuffix(".json") }
|
||||
#expect(files == [written[0].file])
|
||||
let json = try #require(
|
||||
try JSONSerialization.jsonObject(
|
||||
with: Data(contentsOf: cardsDir.appendingPathComponent(written[0].file)),
|
||||
) as? [String: Any],
|
||||
)
|
||||
#expect(json["status"] as? String == "skipped")
|
||||
#expect(json["pattern"] as? String == "Hedging")
|
||||
#expect(json["rank"] as? Int == 1)
|
||||
|
||||
// Scan sees the closed card; a foreign id errors, file untouched.
|
||||
#expect(FixCardStore.scan(pieceURL: piece).first?.status == .skipped)
|
||||
#expect(throws: Error.self) {
|
||||
try FixCardStore.close(pieceURL: piece, id: UUID(), status: .done)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `scan returns newest first and skips undecodable`() throws {
|
||||
let home = try toolsHome()
|
||||
let piece = try writePiece(home)
|
||||
|
||||
Reference in new issue
Block a user