refactor(lint): clear the last five error spots (#147)
CI / ci (push) Canceled after 0s

The repo contract "SwiftFormat + SwiftLint must both stay clean" had
five error spots left beyond #146's PostsModel split, all mechanical.

PostStore's enum body spanned 354 against 350 — the cursor-sidecar
group (#66: CursorState + stateURL/readCursor/writeCursor, already its
own MARK section) moves verbatim into a same-file nonisolated
extension slotted chronologically before the #141 ingest MARK; the
enum body lands at 334 and PostStore.CursorState keeps its qualified
name, so no caller changes. Six single-char locals in
ProseListTextView's dropIndex/rectY/isGap get real names (plus lo/hi
in the same function — same violation class), one in ImageIngestTests'
bandedRectY. The 194-char guard in ProseList.indent and the 221-char
guard in OutlineEditorView.endDrag wrap in the house
else-carries-the-brace form (#142 landmine avoided).

PostStoreTests crossed its 1000-line ceiling at 1061 — split at the
Pass substrate MARK per the MicropubModelTests precedent: the
pass-adjacent write sides (#24/#29/#31) move byte-identical into
PostStorePassTests.swift, shared helpers storeHome/readPost/readPiece
stay internal in the original, and the #29 scenario header travels
with its tests. 63 tests in, 63 out.

The split's new parallel schedule exposed two latent test races,
reproduced idle (~50% for the first) and fixed at the root:
EditorSessionTests' sidecar poll inherited loop 1's deadline and timed
out holding flush 1's default-zero sidecar (zeros, never nil — the
telltale) — each loop now arms its own. SessionLifecycleTests' three
stderrTail asserts raced the client's main-queue stderr drain (the #30
class) — a drainStderr bounded poll now precedes each.

swiftlint reports zero errors on both targets; residual warning-tier
notices match the standing #146 posture (the error tier is the bar;
the one new notice is PostStorePassTests at 473/400 — a 1070-line
suite cannot split into two files both under 400). swiftformat clean.

Full suite 574/574 by xcresult executed count (573 unit + 1 UI smoke),
twice consecutively plus the finish-up rerun.

Closes #147
This commit is contained in:
AlexKucera committed 2026-11-03 13:47:01 +01:00
1 parent 012f91727f
commit 4606fd4628
13 files changed
+639 -526

No files matched your search

+2 -1
View File
@@ -21,7 +21,8 @@ Owned by the root AGENTS.md contract.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles 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. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #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, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) 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`. **#143:** the scan-cache pins over `PostScanCache`'s hit/miss observables — cold scan misses once per file, warm scan all hits with identical output, a changed file re-parses (title moves) while untouched files hit, a moved piece re-parses at its new path (path-keying — a folder move keeps bytes and mtime but `isArchived` re-derives), and a late store carrying a stale pre-read stamp never pins stale content (the overlapping-rescan race's end-state, same-size rewrite so the mtime axis alone carries it).
- `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). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#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 in-place `pass_state` stamp since #31, formerly the block rewrite; 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 — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern; #147: the shared helpers are internal — PostStorePassTests.swift reuses them): 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). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#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).
- `PostStorePassTests.swift` (#147 split — PostStoreTests crossed its file-length ceiling; MicropubTests → MicropubModelTests precedent; shared helpers stay in PostStoreTests.swift) — the pass-adjacent write sides: **#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 in-place `pass_state` stamp since #31, formerly the block rewrite; 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 — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `![alt](<url>)` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
- `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
+6 -2
View File
@@ -49,12 +49,16 @@ struct EditorSessionTests {
#expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.")
// Sidecar: written on flush, reads back. Await the sidecar rather
// than sleeping a fixed window — same starvation rule as above.
// than sleeping a fixed window — same starvation rule as above, with
// its OWN deadline: the first loop's waits must not eat this one's
// budget (until flush #2 lands, readCursor sees flush #1's
// default-zero sidecar — a zero value, never nil).
let cursor = PostStore.CursorState(selectionLocation: 3, selectionLength: 2, scrollOffset: 128)
session.cursorUpdate(cursor)
session.edit("# Alpha\n\nOne. Two. Three.")
var restored: PostStore.CursorState?
while restored != cursor, ContinuousClock.now < deadline {
let sidecarDeadline = ContinuousClock.now.advanced(by: .seconds(5))
while restored != cursor, ContinuousClock.now < sidecarDeadline {
try await Task.sleep(for: .milliseconds(20))
restored = PostStore.readCursor(id: "alpha", home: home)
}
+3 -3
View File
@@ -170,9 +170,9 @@ struct ImageIngestTests {
/// Viewport band [200, 800]; characters 2000…6000 laid out with y
/// decreasing 800→400; everything off-screen reports 0 (the lie
/// non-contiguous layout tells). MidY at i = 800 − 0.1·(i − 2000).
private func bandedRectY(_ i: Int) -> CGFloat {
guard i >= 2000, i <= 6000 else { return 0 }
return CGFloat(800.0 - 0.1 * Double(i - 2000))
private func bandedRectY(_ charIndex: Int) -> CGFloat {
guard charIndex >= 2000, charIndex <= 6000 else { return 0 }
return CGFloat(800.0 - 0.1 * Double(charIndex - 2000))
}
@Test func `dropIndex lands on the drop line`() {
+473
View File
@@ -0,0 +1,473 @@
//
// PostStorePassTests.swift
// MuseionTests
//
// #147 split (MicropubTests -> MicropubModelTests precedent): the
// pass-adjacent write sides out of PostStoreTests — that file crossed
// its file-length ceiling. #24 pass substrate, #29 research notes,
// #31 first-draft stats capture; the shared helpers (storeHome/
// readPost/readPiece) live in PostStoreTests.swift.
//
// ## Scenario: candidate rail and the keep write
// From #29 (S8.1/S8.2)
// Given a piece in the library and the mentor researching mid-pass
// When the engine delivers findings as submit_research_notes tool calls
// Then well-formed candidates are accepted with a received count and
// nothing is written anywhere; malformed ones answer a tool error
// And the pass prompt names that rail
// And when the writer keeps one, one plain markdown note with provenance
// lands in the piece's research/ — nothing else auto-saves.
//
import Foundation
@testable import Museion
import Testing
// MARK: Pass substrate (#24)
@Test func `snapshotPass writes the pre-pass body verbatim under passes`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snapshot\n\nPre-pass body.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snapshot\n\nPre-pass body.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snapshot\n\nPre-pass body.") // body only, no frontmatter
}
@Test func `snapshotPass re-run overwrites keeping latest per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nAfter the first pass.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snap\n\nAfter the first pass.")
}
@Test func `pass snapshots coexist per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Both\n\nBody.", home: home)
let passes = home.appendingPathComponent("projects/posts/\(post.id)/passes", isDirectory: true)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "before pass one", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "before pass two", home: home)
#expect(try String(contentsOf: passes.appendingPathComponent("pass-1.md"), encoding: .utf8) == "before pass one")
#expect(try String(contentsOf: passes.appendingPathComponent("pass-2.md"), encoding: .utf8) == "before pass two")
}
@Test func `snapshotPass on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
try PostStore.snapshotPass(id: "ghost", kind: .pass1, body: "x", home: home)
}
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path))
}
@Test func `advancePassState stamps Pass-1 Done preserving origin type and body`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/essays/essay", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: outline\npass_state: First Draft\norigin: ai\n---\n# Essay\n\nArgued body."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
let newState = try PostStore.advancePassState(id: "essay", kind: .pass1, home: home)
#expect(newState == .pass1Done)
// Stamp round-trip: pass_state advanced, origin/type/body byte-preserved.
#expect(try readPiece(home, root: "projects", project: "essays", "essay")
== "---\ntype: outline\npass_state: Pass-1 Done\norigin: ai\n---\n# Essay\n\nArgued body.")
#expect(PostStore.readBody(id: "essay", home: home) == "# Essay\n\nArgued body.")
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.passState == .pass1Done)
#expect(scanned.origin == .ai)
#expect(scanned.type == .outline)
}
@Test func `advancePassState reaches Pass-2 Done straight from First Draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Direct\n\nBody.", home: home)
// Passes run in any order — Pass 2 first is legal.
#expect(try PostStore.advancePassState(id: post.id, kind: .pass2, home: home) == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
}
@Test func `advancePassState never regresses a higher state`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/done-both", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: post\npass_state: Pass-2 Done\norigin: writer\n---\n# Done\n\nBody."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
// A Pass 1 completing on a Pass-2 Done piece keeps the higher state.
let newState = try PostStore.advancePassState(id: "done-both", kind: .pass1, home: home)
#expect(newState == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
#expect(try readPost(home, "done-both").contains("pass_state: Pass-2 Done"))
}
@Test func `advancePassState is idempotent on re-run`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
_ = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let first = try readPost(home, post.id)
#expect(try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) == .pass1Done)
#expect(try readPost(home, post.id) == first)
}
@Test func `advancePassState on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
_ = try PostStore.advancePassState(id: "ghost", kind: .pass1, home: home)
}
}
@Test func `stub carries pass name piece path research rail and fix-card reminder`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false)
#expect(stub.contains("Pass 1 — paragraph level and up."))
#expect(stub.contains("Piece: /vault/projects/essays/essay/post.md"))
#expect(!stub.contains("Research notes:"))
// #29: the typed research rail is named in the closing block — the
// engine delivers findings, it never writes candidates itself.
let closing = "Critique the piece for this pass. Fact-check claims where needed — research findings "
+ "travel as candidate source-note tool calls (submit_research_notes), never written to disk. "
+ "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). "
+ "Do not write to the piece folder."
#expect(stub.contains(closing))
#expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false)
.contains("Pass 2 — sentence level and below."))
}
@Test func `stub adds the research line only when research exists`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let research = "/vault/projects/essays/essay/research"
#expect(PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: true)
.contains("Research notes: \(research)"))
#expect(!PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false).contains(research))
}
@Test func `estimateTokens is stub plus body chars over four rounded up`() {
let pieceURL = URL(fileURLWithPath: "/vault/essay/post.md")
let body = "# Title\n\nTwo paragraphs of argued prose."
for kind in PassKind.allCases {
for hasResearch in [true, false] {
let total = PassContext.stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch).count + body.count
let expected = total % 4 == 0 ? total / 4 : total / 4 + 1 // ceil — derived independently of the impl
#expect(PassContext.estimateTokens(kind: kind, body: body, pieceURL: pieceURL, hasResearch: hasResearch)
== expected)
}
}
}
// MARK: Research notes (#29)
/// The keep writes "today" — computed at test time like promote's day
/// stamp (a midnight rollover mid-suite is tolerated).
private func researchDay() -> String {
FixCardStore.formatted(Date(), "yyyyMMdd")
}
@Test func `writeResearchNote lands the pinned markdown shape in research`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Kept\n", home: home)
let name = try PostStore.writeResearchNote(
piecePath: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true).path,
title: "The Long Now",
url: "https://example.org/long-now",
quote: "pace layers",
note: "Supports the slowness claim.",
home: home,
)
let day = researchDay()
#expect(name == "\(day)-the-long-now.md")
let markdown = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)"),
encoding: .utf8,
)
let expected = "---\nsource: https://example.org/long-now\nkept: \(day)\n---\n\n"
+ "# The Long Now\n\nSupports the slowness claim.\n\n> pace layers\n"
#expect(markdown == expected)
}
@Test func `writeResearchNote omits absent note and quote sections`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Bare\n", home: home)
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
// Both absent: frontmatter + heading, nothing else.
let name = try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Only A Link", url: "https://example.org/one",
quote: "", note: "", home: home,
)
let bare = try String(contentsOf: pieceDir.appendingPathComponent("research/\(name)"), encoding: .utf8)
#expect(bare == "---\nsource: https://example.org/one\nkept: \(researchDay())\n---\n\n# Only A Link\n")
// Quote without note: the note section goes, the quote stays.
let quoted = try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Quoted", url: "https://example.org/two",
quote: "citation needed", note: "", home: home,
)
let text = try String(contentsOf: pieceDir.appendingPathComponent("research/\(quoted)"), encoding: .utf8)
#expect(text.hasSuffix("\n\n# Quoted\n\n> citation needed\n"))
}
@Test func `writeResearchNote collision takes -2`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Twice\n", home: home)
let piecePath = home.appendingPathComponent("projects/posts/\(post.id)").path
let first = try PostStore.writeResearchNote(
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
quote: "", note: "", home: home,
)
let second = try PostStore.writeResearchNote(
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
quote: "", note: "", home: home,
)
let day = researchDay()
#expect(first == "\(day)-same-source.md")
#expect(second == "\(day)-same-source-2.md")
}
@Test func `writeResearchNote accepts the post.md file form`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# File Form\n", home: home)
let name = try PostStore.writeResearchNote(
piecePath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path,
title: "Via File", url: "https://example.org/file",
quote: "", note: "", home: home,
)
#expect(FileManager.default.fileExists(
atPath: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)").path,
))
}
@Test func `writeResearchNote on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: FixCardStore.CardError(message: "piece not found: /nowhere/post.md")) {
try PostStore.writeResearchNote(
piecePath: "/nowhere/post.md", title: "Ghost", url: "https://example.org",
quote: "", note: "", home: home,
)
}
}
@Test func `writeResearchNote refuses a symlinked research dir`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Guarded\n", home: home)
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(
at: pieceDir.appendingPathComponent("research"),
withDestinationURL: target,
)
let planted = pieceDir.appendingPathComponent("research").path
#expect(throws: FixCardStore.CardError(message: "research path is a symlink: \(planted)")) {
try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Planted", url: "https://example.org",
quote: "", note: "", home: home,
)
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
// MARK: First-draft stats capture (#31, S5.1)
/// Every `stats_` value is the store-time `%.3f` shape (a period, never a
/// localized comma) — the trend view (S5.2) parses them back as Doubles.
private func threeDecimals(_ value: String) -> Bool {
value.range(of: #"^-?\d+\.\d{3}$"#, options: .regularExpression) != nil
}
@Test func `capture stamps five stats keys in place and preserves foreign frontmatter`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nOne two three. Four five! Six?", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
// Hand-add a foreign key INSIDE the block before capturing — the
// in-place stamp must keep it byte-identical.
let withForeign = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try withForeign.write(to: url, atomically: true, encoding: .utf8)
let bodyBefore = PostStore.splitFrontmatter(withForeign).body
let captured = PostStore.captureFirstDraftStats(
id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home,
)
#expect(captured)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after) // the trend-view readiness read
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable
#expect(matter["stats_burstiness"].map(threeDecimals) == true)
#expect(matter["stats_type_token_ratio"].map(threeDecimals) == true)
#expect(matter["stats_sentence_variation"].map(threeDecimals) == true)
#expect(matter["stats_trigram_repetition"].map(threeDecimals) == true)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
// Body byte-identical — the stamp never touches content (#31 in-place proof).
#expect(PostStore.splitFrontmatter(after).body == bodyBefore)
}
@Test func `capture refuses an ai origin piece untouched`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Machine\n\nAI-born text.", origin: .ai, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses a piece past first draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Done Once\n\nAlready critiqued.", home: home)
try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses an outline piece`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "- an outline item", type: .outline, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `recapture while still first draft overwrites latest draft state wins`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Evolving\n\nOne two three. Four five! Six?", home: home)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home))
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home))
let matter = try Post.frontmatter(of: String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
))
#expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won
#expect(matter["stats_type_token_ratio"] == "0.500")
#expect(matter["stats_trigram_repetition"] == "0.250")
}
@Test func `capture qualifies a bare legacy post through the lenient defaults`() throws {
// A bare corpus post (no frontmatter at all) scans writer/First
// Draft/post — the capture gate must reach the same verdict, not
// demand stamps that legacy files never carried.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-legacy", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "# Bare\n\nNo frontmatter here.".write(
to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8,
)
}
#expect(PostStore.captureFirstDraftStats(id: "bare-legacy", body: "No frontmatter here.", home: home))
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil)
#expect(after.contains("# Bare")) // the body survived the fresh-block prepend
}
@Test func `advance pass state preserves stats and foreign keys in place`() throws {
// The #31 regression pin: the advance used to rewrite the block from
// its three parsed fields, erasing the stats captured at the pass's
// own invocation (and any foreign frontmatter). The in-place stamp
// keeps every other line byte-identical.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Kept\n\nBody stays.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "Body stays.", home: home))
let advanced = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
#expect(advanced == .pass1Done)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["pass_state"] == "Pass-1 Done")
#expect(matter["stats_captured"] != nil) // survived the advance
#expect(matter["stats_trigram_repetition"] != nil)
#expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.")
}
@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws {
// The #31 finish-audit regression pin: an editor save mid-pass used to
// route through the stamped() rewrite and erase the stats captured at
// the invocation (plus foreign frontmatter). The in-place update keeps
// every non-owned key and swaps only the body.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nFirst words.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "First words.", home: home))
try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil) // survived the editor save
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
}
@Test func `overwrite normalizes a bare post with the full stamp`() throws {
// The bare-post branch of the #31 audit fix: no block → the #59 stamp
// shape (type first), exactly as before the fix.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-overwrite", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "Bare body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
try PostStore.overwrite(id: "bare-overwrite", body: "Bare body, edited.", home: home)
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.")
}
+6 -461
View File
@@ -8,15 +8,9 @@
// project (#60), Trash delete, save-time normalization.
// #108: project moves, archive/restore, project unarchive + creation.
//
// ## Scenario: candidate rail and the keep write
// From #29 (S8.1/S8.2)
// Given a piece in the library and the mentor researching mid-pass
// When the engine delivers findings as submit_research_notes tool calls
// Then well-formed candidates are accepted with a received count and
// nothing is written anywhere; malformed ones answer a tool error
// And the pass prompt names that rail
// And when the writer keeps one, one plain markdown note with provenance
// lands in the piece's research/ — nothing else auto-saves.
// #147: the pass-adjacent write sides (#24 pass substrate, #29 research
// notes, #31 first-draft stats capture) live in PostStorePassTests.swift;
// the shared helpers (storeHome/readPost/readPiece) stay here, internal.
//
import Foundation
@@ -24,7 +18,7 @@ import Foundation
import Testing
/// Throwaway Home in a temp dir (PostLibraryTests convention).
private func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("poststore-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
@@ -32,7 +26,7 @@ private func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
return home
}
private func readPost(_ home: URL, _ id: String) throws -> String {
func readPost(_ home: URL, _ id: String) throws -> String {
try String(contentsOf: home.appendingPathComponent("projects/posts/\(id)/post.md"), encoding: .utf8)
}
@@ -372,7 +366,7 @@ private func readPost(_ home: URL, _ id: String) throws -> String {
// MARK: Project moves & archive (#108)
/// readPost's path-aware sibling: any piece under any root/project.
private func readPiece(_ home: URL, root: String, project: String, _ id: String) throws -> String {
func readPiece(_ home: URL, root: String, project: String, _ id: String) throws -> String {
try String(
contentsOf: home.appendingPathComponent("\(root)/\(project)/\(id)/post.md", isDirectory: false),
encoding: .utf8,
@@ -610,452 +604,3 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
#expect(onDisk.contains("## one"))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path))
}
// MARK: Pass substrate (#24)
@Test func `snapshotPass writes the pre-pass body verbatim under passes`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snapshot\n\nPre-pass body.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snapshot\n\nPre-pass body.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snapshot\n\nPre-pass body.") // body only, no frontmatter
}
@Test func `snapshotPass re-run overwrites keeping latest per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nAfter the first pass.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snap\n\nAfter the first pass.")
}
@Test func `pass snapshots coexist per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Both\n\nBody.", home: home)
let passes = home.appendingPathComponent("projects/posts/\(post.id)/passes", isDirectory: true)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "before pass one", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "before pass two", home: home)
#expect(try String(contentsOf: passes.appendingPathComponent("pass-1.md"), encoding: .utf8) == "before pass one")
#expect(try String(contentsOf: passes.appendingPathComponent("pass-2.md"), encoding: .utf8) == "before pass two")
}
@Test func `snapshotPass on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
try PostStore.snapshotPass(id: "ghost", kind: .pass1, body: "x", home: home)
}
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path))
}
@Test func `advancePassState stamps Pass-1 Done preserving origin type and body`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/essays/essay", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: outline\npass_state: First Draft\norigin: ai\n---\n# Essay\n\nArgued body."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
let newState = try PostStore.advancePassState(id: "essay", kind: .pass1, home: home)
#expect(newState == .pass1Done)
// Stamp round-trip: pass_state advanced, origin/type/body byte-preserved.
#expect(try readPiece(home, root: "projects", project: "essays", "essay")
== "---\ntype: outline\npass_state: Pass-1 Done\norigin: ai\n---\n# Essay\n\nArgued body.")
#expect(PostStore.readBody(id: "essay", home: home) == "# Essay\n\nArgued body.")
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.passState == .pass1Done)
#expect(scanned.origin == .ai)
#expect(scanned.type == .outline)
}
@Test func `advancePassState reaches Pass-2 Done straight from First Draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Direct\n\nBody.", home: home)
// Passes run in any order — Pass 2 first is legal.
#expect(try PostStore.advancePassState(id: post.id, kind: .pass2, home: home) == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
}
@Test func `advancePassState never regresses a higher state`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/done-both", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: post\npass_state: Pass-2 Done\norigin: writer\n---\n# Done\n\nBody."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
// A Pass 1 completing on a Pass-2 Done piece keeps the higher state.
let newState = try PostStore.advancePassState(id: "done-both", kind: .pass1, home: home)
#expect(newState == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
#expect(try readPost(home, "done-both").contains("pass_state: Pass-2 Done"))
}
@Test func `advancePassState is idempotent on re-run`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
_ = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let first = try readPost(home, post.id)
#expect(try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) == .pass1Done)
#expect(try readPost(home, post.id) == first)
}
@Test func `advancePassState on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
_ = try PostStore.advancePassState(id: "ghost", kind: .pass1, home: home)
}
}
@Test func `stub carries pass name piece path research rail and fix-card reminder`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false)
#expect(stub.contains("Pass 1 — paragraph level and up."))
#expect(stub.contains("Piece: /vault/projects/essays/essay/post.md"))
#expect(!stub.contains("Research notes:"))
// #29: the typed research rail is named in the closing block — the
// engine delivers findings, it never writes candidates itself.
let closing = "Critique the piece for this pass. Fact-check claims where needed — research findings "
+ "travel as candidate source-note tool calls (submit_research_notes), never written to disk. "
+ "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). "
+ "Do not write to the piece folder."
#expect(stub.contains(closing))
#expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false)
.contains("Pass 2 — sentence level and below."))
}
@Test func `stub adds the research line only when research exists`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let research = "/vault/projects/essays/essay/research"
#expect(PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: true)
.contains("Research notes: \(research)"))
#expect(!PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false).contains(research))
}
@Test func `estimateTokens is stub plus body chars over four rounded up`() {
let pieceURL = URL(fileURLWithPath: "/vault/essay/post.md")
let body = "# Title\n\nTwo paragraphs of argued prose."
for kind in PassKind.allCases {
for hasResearch in [true, false] {
let total = PassContext.stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch).count + body.count
let expected = total % 4 == 0 ? total / 4 : total / 4 + 1 // ceil — derived independently of the impl
#expect(PassContext.estimateTokens(kind: kind, body: body, pieceURL: pieceURL, hasResearch: hasResearch)
== expected)
}
}
}
// MARK: Research notes (#29)
/// The keep writes "today" — computed at test time like promote's day
/// stamp (a midnight rollover mid-suite is tolerated).
private func researchDay() -> String {
FixCardStore.formatted(Date(), "yyyyMMdd")
}
@Test func `writeResearchNote lands the pinned markdown shape in research`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Kept\n", home: home)
let name = try PostStore.writeResearchNote(
piecePath: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true).path,
title: "The Long Now",
url: "https://example.org/long-now",
quote: "pace layers",
note: "Supports the slowness claim.",
home: home,
)
let day = researchDay()
#expect(name == "\(day)-the-long-now.md")
let markdown = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)"),
encoding: .utf8,
)
let expected = "---\nsource: https://example.org/long-now\nkept: \(day)\n---\n\n"
+ "# The Long Now\n\nSupports the slowness claim.\n\n> pace layers\n"
#expect(markdown == expected)
}
@Test func `writeResearchNote omits absent note and quote sections`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Bare\n", home: home)
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
// Both absent: frontmatter + heading, nothing else.
let name = try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Only A Link", url: "https://example.org/one",
quote: "", note: "", home: home,
)
let bare = try String(contentsOf: pieceDir.appendingPathComponent("research/\(name)"), encoding: .utf8)
#expect(bare == "---\nsource: https://example.org/one\nkept: \(researchDay())\n---\n\n# Only A Link\n")
// Quote without note: the note section goes, the quote stays.
let quoted = try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Quoted", url: "https://example.org/two",
quote: "citation needed", note: "", home: home,
)
let text = try String(contentsOf: pieceDir.appendingPathComponent("research/\(quoted)"), encoding: .utf8)
#expect(text.hasSuffix("\n\n# Quoted\n\n> citation needed\n"))
}
@Test func `writeResearchNote collision takes -2`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Twice\n", home: home)
let piecePath = home.appendingPathComponent("projects/posts/\(post.id)").path
let first = try PostStore.writeResearchNote(
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
quote: "", note: "", home: home,
)
let second = try PostStore.writeResearchNote(
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
quote: "", note: "", home: home,
)
let day = researchDay()
#expect(first == "\(day)-same-source.md")
#expect(second == "\(day)-same-source-2.md")
}
@Test func `writeResearchNote accepts the post.md file form`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# File Form\n", home: home)
let name = try PostStore.writeResearchNote(
piecePath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path,
title: "Via File", url: "https://example.org/file",
quote: "", note: "", home: home,
)
#expect(FileManager.default.fileExists(
atPath: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)").path,
))
}
@Test func `writeResearchNote on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: FixCardStore.CardError(message: "piece not found: /nowhere/post.md")) {
try PostStore.writeResearchNote(
piecePath: "/nowhere/post.md", title: "Ghost", url: "https://example.org",
quote: "", note: "", home: home,
)
}
}
@Test func `writeResearchNote refuses a symlinked research dir`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Guarded\n", home: home)
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(
at: pieceDir.appendingPathComponent("research"),
withDestinationURL: target,
)
let planted = pieceDir.appendingPathComponent("research").path
#expect(throws: FixCardStore.CardError(message: "research path is a symlink: \(planted)")) {
try PostStore.writeResearchNote(
piecePath: pieceDir.path, title: "Planted", url: "https://example.org",
quote: "", note: "", home: home,
)
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
// MARK: First-draft stats capture (#31, S5.1)
/// Every `stats_` value is the store-time `%.3f` shape (a period, never a
/// localized comma) — the trend view (S5.2) parses them back as Doubles.
private func threeDecimals(_ value: String) -> Bool {
value.range(of: #"^-?\d+\.\d{3}$"#, options: .regularExpression) != nil
}
@Test func `capture stamps five stats keys in place and preserves foreign frontmatter`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nOne two three. Four five! Six?", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
// Hand-add a foreign key INSIDE the block before capturing — the
// in-place stamp must keep it byte-identical.
let withForeign = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try withForeign.write(to: url, atomically: true, encoding: .utf8)
let bodyBefore = PostStore.splitFrontmatter(withForeign).body
let captured = PostStore.captureFirstDraftStats(
id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home,
)
#expect(captured)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after) // the trend-view readiness read
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable
#expect(matter["stats_burstiness"].map(threeDecimals) == true)
#expect(matter["stats_type_token_ratio"].map(threeDecimals) == true)
#expect(matter["stats_sentence_variation"].map(threeDecimals) == true)
#expect(matter["stats_trigram_repetition"].map(threeDecimals) == true)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
// Body byte-identical — the stamp never touches content (#31 in-place proof).
#expect(PostStore.splitFrontmatter(after).body == bodyBefore)
}
@Test func `capture refuses an ai origin piece untouched`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Machine\n\nAI-born text.", origin: .ai, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses a piece past first draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Done Once\n\nAlready critiqued.", home: home)
try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `capture refuses an outline piece`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "- an outline item", type: .outline, home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let before = try String(contentsOf: url, encoding: .utf8)
#expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home))
#expect(try String(contentsOf: url, encoding: .utf8) == before)
}
@Test func `recapture while still first draft overwrites latest draft state wins`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Evolving\n\nOne two three. Four five! Six?", home: home)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home))
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home))
let matter = try Post.frontmatter(of: String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
))
#expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won
#expect(matter["stats_type_token_ratio"] == "0.500")
#expect(matter["stats_trigram_repetition"] == "0.250")
}
@Test func `capture qualifies a bare legacy post through the lenient defaults`() throws {
// A bare corpus post (no frontmatter at all) scans writer/First
// Draft/post — the capture gate must reach the same verdict, not
// demand stamps that legacy files never carried.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-legacy", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "# Bare\n\nNo frontmatter here.".write(
to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8,
)
}
#expect(PostStore.captureFirstDraftStats(id: "bare-legacy", body: "No frontmatter here.", home: home))
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil)
#expect(after.contains("# Bare")) // the body survived the fresh-block prepend
}
@Test func `advance pass state preserves stats and foreign keys in place`() throws {
// The #31 regression pin: the advance used to rewrite the block from
// its three parsed fields, erasing the stats captured at the pass's
// own invocation (and any foreign frontmatter). The in-place stamp
// keeps every other line byte-identical.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Kept\n\nBody stays.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "Body stays.", home: home))
let advanced = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
#expect(advanced == .pass1Done)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["pass_state"] == "Pass-1 Done")
#expect(matter["stats_captured"] != nil) // survived the advance
#expect(matter["stats_trigram_repetition"] != nil)
#expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.")
}
@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws {
// The #31 finish-audit regression pin: an editor save mid-pass used to
// route through the stamped() rewrite and erase the stats captured at
// the invocation (plus foreign frontmatter). The in-place update keeps
// every non-owned key and swaps only the body.
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Draft\n\nFirst words.", home: home)
let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md")
let seeded = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try seeded.write(to: url, atomically: true, encoding: .utf8)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "First words.", home: home))
try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil) // survived the editor save
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
}
@Test func `overwrite normalizes a bare post with the full stamp`() throws {
// The bare-post branch of the #31 audit fix: no block → the #59 stamp
// shape (type first), exactly as before the fix.
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/bare-overwrite", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "Bare body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
try PostStore.overwrite(id: "bare-overwrite", body: "Bare body, edited.", home: home)
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.")
}
+14
View File
@@ -141,7 +141,9 @@ struct SessionLifecycleTests {
})
#expect(texts(in: replayed).contains("Mentor: earlier verdict"))
// The wire calls went out over session/load.
await drainStderr(mentor, containing: "load ghost")
#expect(mentor.stderrTail.contains { $0.contains("load ghost") })
await drainStderr(mentor, containing: "load sess-1")
#expect(mentor.stderrTail.contains { $0.contains("load sess-1") })
}
@@ -167,6 +169,7 @@ struct SessionLifecycleTests {
#expect(mentor.activeEntry == fork)
#expect(try mentor.transcriptRows(of: #require(fork)).isEmpty) // FRESH transcript
#expect(!mentor.transcriptRows(of: source).isEmpty) // original untouched
await drainStderr(mentor, containing: "fork sess-1")
#expect(mentor.stderrTail.contains { $0.contains("fork sess-1") })
// Refusal rig: a session the engine does not know forks into "".
@@ -516,3 +519,14 @@ private func texts(in rows: [SessionRow]) -> [String] {
}
}
}
/// Stderr lines drain through the client's async reader — the awaited wire
/// response can land before the line reaches `stderrTail`. Bounded poll
/// (the hold-load shape above), never a fixed sleep.
@MainActor
private func drainStderr(_ mentor: MentorSessionModel, containing text: String) async {
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
while !mentor.stderrTail.contains(where: { $0.contains(text) }), ContinuousClock.now < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
}