diff --git a/AGENTS.md b/AGENTS.md index 18da96a..ad4b34d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (5834 symbols, 24313 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (5849 symbols, 24595 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -197,6 +197,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-03 | [20261103-issue147-app-target-lint-clean-five-error-spots_log.md](docs/devlog/20261103-issue147-app-target-lint-clean-five-error-spots_log.md) | | 2026-11-03 | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | | 2026-11-03 | [20261103-issue144-library-search-across-titles-and-bodies_log.md](docs/devlog/20261103-issue144-library-search-across-titles-and-bodies_log.md) | | 2026-11-03 | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](docs/devlog/20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | @@ -206,5 +207,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-31 | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](docs/devlog/20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | | 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](docs/devlog/20261031-issue32-m4-trend-view-s5-2_log.md) | | 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](docs/devlog/20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | -| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](docs/devlog/20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | diff --git a/Museion/OutlineEditorView.swift b/Museion/OutlineEditorView.swift index c9cab46..34ebfcf 100644 --- a/Museion/OutlineEditorView.swift +++ b/Museion/OutlineEditorView.swift @@ -678,7 +678,10 @@ extension OutlineEditorView { private func endDrag(at point: CGPoint?, frames: [UUID: CGRect]?) { let info = drag drag = nil - guard let point, let info, let frames, let target = OutlinePresenter.hitTestDrop(point: point, rows: materializedRows(frames: frames)), OutlinePresenter.applyDrop(target, moving: info.moving, in: &nodes) else { return } + guard let point, let info, let frames, + let target = OutlinePresenter.hitTestDrop(point: point, rows: materializedRows(frames: frames)), + OutlinePresenter.applyDrop(target, moving: info.moving, in: &nodes) + else { return } selectionAnchor = info.moving.first focusedID = info.moving.last pendingCaret = nil diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index 07b0441..d8b3a83 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -338,38 +338,6 @@ nonisolated enum PostStore { .write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } - // MARK: Cursor-state sidecar (#66) - - /// Cursor state for one post: selection + scroll, `.museion-state.json` - /// in the post folder — Finder-invisible, human-diffable, dies with the - /// folder on Trash. Drafts skip it (#62). - struct CursorState: Codable, Equatable { - var selectionLocation: Int = 0 - var selectionLength: Int = 0 - var scrollOffset: Double = 0 - } - - private static func stateURL(id: String, home: URL) -> URL? { - folder(of: id, home: home)?.appendingPathComponent(".museion-state.json") - } - - /// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine). - static func readCursor(id: String, home: URL) -> CursorState? { - guard let url = stateURL(id: id, home: home), - let data = try? Data(contentsOf: url) - else { return nil } - return try? JSONDecoder().decode(CursorState.self, from: data) - } - - /// Write the sidecar. Best-effort by design — a failed cursor write must - /// never read as a failed content save, so failures are swallowed here. - static func writeCursor(_ state: CursorState, id: String, home: URL) { - guard let url = stateURL(id: id, home: home), - let data = try? JSONEncoder().encode(state) - else { return } - try? data.write(to: url, options: .atomic) - } - /// Explicit Rename (#60): rewrite the `# Title` line as the first /// non-empty body line, then move the folder to the new slug — within /// the SAME parent (ADR-0012: the piece stays in its project, archived @@ -789,6 +757,43 @@ nonisolated extension PostStore { } } +// MARK: Cursor-state sidecar (#66) + +/// #66: the sidecar group, moved to a same-file extension at the enum's +/// type-body ceiling (#147) — the PostsModel treatment. Same file as the +/// enum: `private` members stay reachable at file scope. +nonisolated extension PostStore { + /// Cursor state for one post: selection + scroll, `.museion-state.json` + /// in the post folder — Finder-invisible, human-diffable, dies with the + /// folder on Trash. Drafts skip it (#62). + struct CursorState: Codable, Equatable { + var selectionLocation: Int = 0 + var selectionLength: Int = 0 + var scrollOffset: Double = 0 + } + + private static func stateURL(id: String, home: URL) -> URL? { + folder(of: id, home: home)?.appendingPathComponent(".museion-state.json") + } + + /// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine). + static func readCursor(id: String, home: URL) -> CursorState? { + guard let url = stateURL(id: id, home: home), + let data = try? Data(contentsOf: url) + else { return nil } + return try? JSONDecoder().decode(CursorState.self, from: data) + } + + /// Write the sidecar. Best-effort by design — a failed cursor write must + /// never read as a failed content save, so failures are swallowed here. + static func writeCursor(_ state: CursorState, id: String, home: URL) { + guard let url = stateURL(id: id, home: home), + let data = try? JSONEncoder().encode(state) + else { return } + try? data.write(to: url, options: .atomic) + } +} + // MARK: - #141 Illustration ingest /// #141's refusal reasons — the drop surface shows `localizedDescription` diff --git a/Museion/ProseList.swift b/Museion/ProseList.swift index 42f8efd..5cd756d 100644 --- a/Museion/ProseList.swift +++ b/Museion/ProseList.swift @@ -153,7 +153,9 @@ nonisolated extension ProseList { /// minus our indent. No previous sibling → nil (boundary no-op). static func indent(_ item: Item, caret: Int, in text: String) -> Edit? { let scanned = lines(in: text) - guard let idx = lineIndex(of: item.markerLine.location, in: scanned), let sibIdx = adjacentSiblingLine(scanned, from: idx, through: idx, indent: item.indent, direction: -1) else { return nil } + guard let idx = lineIndex(of: item.markerLine.location, in: scanned), + let sibIdx = adjacentSiblingLine(scanned, from: idx, through: idx, indent: item.indent, direction: -1) + else { return nil } let delta = contentColumn(scanned[sibIdx].text) - item.indent guard delta > 0 else { return nil } let body = blockBody(text, item.block) diff --git a/Museion/ProseListTextView.swift b/Museion/ProseListTextView.swift index 0271a6e..e740182 100644 --- a/Museion/ProseListTextView.swift +++ b/Museion/ProseListTextView.swift @@ -295,37 +295,37 @@ final class ProseListTextView: NSTextView { guard length > 0 else { return 0 } var lastAbove: Int? var firstInBand = -1 - for s in 0 ... sampleCount { - let i = min(length - 1, s * length / sampleCount) - let y = rectY(i) - guard y >= bandMinY, y <= bandMaxY else { continue } + for sample in 0 ... sampleCount { + let index = min(length - 1, sample * length / sampleCount) + let sampleY = rectY(index) + guard sampleY >= bandMinY, sampleY <= bandMaxY else { continue } if firstInBand < 0 { - firstInBand = i + firstInBand = index } - if y >= targetY { - lastAbove = i // at-or-above the drop on screen - } else if let above = lastAbove, above < i { - // Bracket [above, i] straddles the drop; both ends are + if sampleY >= targetY { + lastAbove = index // at-or-above the drop on screen + } else if let above = lastAbove, above < index { + // Bracket [above, index] straddles the drop; both ends are // in-band (laid out, monotone) so the search probes real rects. - var lo = above - var hi = i - while lo < hi { - let mid = (lo + hi) / 2 + var lowerBound = above + var upperBound = index + while lowerBound < upperBound { + let mid = (lowerBound + upperBound) / 2 if rectY(mid) >= targetY { - lo = mid + 1 + lowerBound = mid + 1 } else { - hi = mid + upperBound = mid } } - return min(lo, length) + return min(lowerBound, length) } } return min(lastAbove ?? max(firstInBand, 0), length) } - private func rectY(_ i: Int, of length: Int) -> CGFloat { - guard window != nil, i >= 0, i < length else { return -1 } // viewless (tests): land at index 0 - return firstRect(forCharacterRange: NSRange(location: i, length: 1), actualRange: nil).midY + private func rectY(_ charIndex: Int, of length: Int) -> CGFloat { + guard window != nil, charIndex >= 0, charIndex < length else { return -1 } // viewless (tests): land at index 0 + return firstRect(forCharacterRange: NSRange(location: charIndex, length: 1), actualRange: nil).midY } /// #141's SwiftUI entry — the window `.dropDestination`'s perform @@ -357,14 +357,14 @@ final class ProseListTextView: NSTextView { targetY: mouse.y, bandMinY: screenVisible.minY, bandMaxY: screenVisible.maxY, - ) { i in - rectY(i, of: length) + ) { charIndex in + rectY(charIndex, of: length) } // Never splice inside a word or link — slide to the next gap // (a drop ON an existing ref appends after it, dogfood 2026-11-02). let buffer = string as NSString - func isGap(_ c: unichar) -> Bool { - guard let scalar = Unicode.Scalar(Int(c)) else { return false } + func isGap(_ char: unichar) -> Bool { + guard let scalar = Unicode.Scalar(Int(char)) else { return false } return CharacterSet.whitespacesAndNewlines.contains(scalar) } if index > 0, index < length, diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 1c1510f..221fd1e 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -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 `-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `-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-` 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 `/profiles/` (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 mcp list`/`mcp add` (per-profile marker `mcp-registered-` = already registered, invocation log `mcp-add-invocation-` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p config set` (argv log `config-set-`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-` map (dedup per key), and the fake speaks `config get ` (store value, or the not-set line on stderr exit 1) and `config unset ` (argv log `config-unset-`, 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///` + `archive///` (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///` + #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///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///` + #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///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]()` — 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). diff --git a/MuseionTests/EditorSessionTests.swift b/MuseionTests/EditorSessionTests.swift index bae48a2..ce98dbc 100644 --- a/MuseionTests/EditorSessionTests.swift +++ b/MuseionTests/EditorSessionTests.swift @@ -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) } diff --git a/MuseionTests/ImageIngestTests.swift b/MuseionTests/ImageIngestTests.swift index 7537709..86b4982 100644 --- a/MuseionTests/ImageIngestTests.swift +++ b/MuseionTests/ImageIngestTests.swift @@ -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`() { diff --git a/MuseionTests/PostStorePassTests.swift b/MuseionTests/PostStorePassTests.swift new file mode 100644 index 0000000..668e8d4 --- /dev/null +++ b/MuseionTests/PostStorePassTests.swift @@ -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.") +} diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 2dbf583..7d86294 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -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.") -} diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift index 450207c..a075968 100644 --- a/MuseionTests/SessionLifecycleTests.swift +++ b/MuseionTests/SessionLifecycleTests.swift @@ -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)) + } +} diff --git a/docs/devlog/20261103-issue147-app-target-lint-clean-five-error-spots_log.md b/docs/devlog/20261103-issue147-app-target-lint-clean-five-error-spots_log.md new file mode 100644 index 0000000..559851f --- /dev/null +++ b/docs/devlog/20261103-issue147-app-target-lint-clean-five-error-spots_log.md @@ -0,0 +1,65 @@ +# #147 App-target lint clean: the remaining five error spots + +> **Date:** 2026-11-03 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/147 + +## Goal + +Clear the last five swiftlint error spots beyond #146 so `swiftlint lint Museion MuseionTests` reports zero errors repo-wide — all mechanical, zero production behavior change: PostStore enum body 354>350, six single-char locals in ProseListTextView, one in ImageIngestTests, two long lines (ProseList 194, OutlineEditorView 221), and PostStoreTests 1061>1000 split at a natural suite boundary. + +## What Was Done + +- `Museion/PostStore.swift` — the cursor-sidecar group (#66: `CursorState` + `stateURL`/`readCursor`/`writeCursor`, already its own MARK section) moved verbatim into a new same-file `nonisolated extension PostStore` slotted between the #33 micropub extension and the #141 ingest MARK (chronological order). Enum body 354 → 334 (≤350). `PostStore.CursorState` keeps its qualified name — extension nesting, zero caller changes; `private` unchanged (same file). +- `Museion/ProseListTextView.swift` — `dropIndex` locals `s/i/y` → `sample/index/sampleY`; `lo/hi` → `lowerBound/upperBound` (same violation class, same function); `rectY(_ i:)` param and the `Self.dropIndex` closure param → `charIndex`; `isGap(_ c:)` → `char`. +- `MuseionTests/ImageIngestTests.swift` — `bandedRectY(_ i:)` → `charIndex`. +- `Museion/ProseList.swift` — the 194-char indent guard wrapped house-style (`guard …,\n\t …\n\telse { return nil }` — `else` carries the brace, the #142 landmine avoided). +- `Museion/OutlineEditorView.swift` — the 221-char `endDrag` guard wrapped the same way. +- `MuseionTests/PostStoreTests.swift` 1061 → 606 lines; new `MuseionTests/PostStorePassTests.swift` (464) — cut at the `// MARK: Pass substrate (#24)` line, everything from there to EOF moved byte-identical (#24 pass substrate, #29 research notes, #31 stats capture — the pass-adjacent write sides; the #29 scenario header moved with its tests). Shared helpers `storeHome`/`readPost`/`readPiece` stay in the original, `private`→internal; `researchDay`/`threeDecimals` moved with their only consumers. +- Test-robustness fixes from review (test-only, both the repo's bounded-poll idiom): `EditorSessionTests` sidecar poll arms its own `sidecarDeadline` (was inheriting loop 1's spent budget); `SessionLifecycleTests` gains `drainStderr(_:containing:)` awaited before the three `stderrTail` asserts. +- DOX: `MuseionTests/AGENTS.md` — PostStoreTests bullet loses the #24/#29/#31 tail, new PostStorePassTests bullet carries it; internal-helpers note added. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| AC "zero warnings on every touched file" read as the ERROR tier + no new warnings, residual warning-tier notices flagged | Same spec-internal conflict #146 hit and its three audit reviewers ruled on: default warning tiers (400 file / 250 body) are unreachable at these sizes and predate the change; 14+ repo files carry them. Only genuinely new warning: PostStorePassTests 473/400 — a 1070-line suite can't split into two files both <400 | +| Cursor-sidecar group chosen for the PostStore extension move | Already a cohesive MARKed unit (struct + three functions, ~30 body lines); grew the file's documented same-file-extension pattern instead of inventing a new one | +| Split cut at the Pass substrate MARK (contiguous tail) | One clean cut at a suite boundary; cohesive theme (pass-adjacent write sides); MicropubTests → MicropubModelTests precedent; pure move = 63 tests in = 63 out | +| `lo/hi` renamed beyond the ticket's named six | Same violation class in the same function being edited; 2 pre-existing warnings gone for a trivial diff — flagged as one inch beyond spec | +| No `.serialized`/restructure for the flaky test | Root cause was the shared deadline (test bug), not parallelism per se; one-line deadline fix at the real seam | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Full suite 573/574 with the diff (~50% on idle machine) — EditorSessionTests debounce test | Splitting a test file changes Swift Testing's parallel schedule → loop 1 of the poll test ate the shared 5s deadline, loop 2 timed out holding flush #1's default-zero sidecar (`restored` = zeros, never nil — the tell) | Second loop arms its own `sidecarDeadline` after loop 1 completes | +| Full suite 573/574 once more — `fork stderr` assertion | The three `stderrTail` asserts read immediately after the awaited wire response; stderr drains via `client.onStderrLine` → `DispatchQueue.main.async` — a race the new schedule exposed (#30 class) | `drainStderr` bounded poll before each assert | +| First review round produced contradictory evidence (their 2/2 red vs my green) | Both review sub-agents ran CONCURRENTLY in the same worktree — one's stash/unstash cycles and lint load collided with the other's xcodebuild runs | Reproduced idle per the #30 protocol before acting; reviewers now dispatched with git-write ops forbidden | +| 574 executed vs "573 at filing" in the AC | A commit landed between filing and the run; the split itself is count-neutral (63 = 36 + 27) | Verified structurally, reported the delta | +| `grep -c` on `git diff` output under-reported deletions (461 → 1) via the session reviewer | The `rtk` shell wrapper mangles piped diff output | Reviewer routed around with `git diff --output=`; known trap for future diff-review through this harness | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostStore.swift` | Cursor-sidecar group → same-file extension (enum body 334) | +| `Museion/ProseListTextView.swift` | Nine identifier renames in `dropIndex`/`rectY`/`isGap`/closure | +| `Museion/ProseList.swift` | Guard wrap (194→3 lines, house style) | +| `Museion/OutlineEditorView.swift` | Guard wrap (221→4 lines, house style) | +| `MuseionTests/ImageIngestTests.swift` | `bandedRectY` param rename | +| `MuseionTests/PostStoreTests.swift` | Tail 448 lines moved out; helpers internal; header updated (606 lines) | +| `MuseionTests/PostStorePassTests.swift` | NEW — pass-adjacent suites #24/#29/#31 (464 lines) | +| `MuseionTests/EditorSessionTests.swift` | Sidecar poll gets its own deadline | +| `MuseionTests/SessionLifecycleTests.swift` | `drainStderr` helper + three awaited asserts | +| `MuseionTests/AGENTS.md` | Split documented, helpers-internal note | +| `AGENTS.md` | GitNexus counter block auto-update only | + +## Open Items & Next Steps + +- [ ] Deferred LOW (finish-audit): collapse the duplicated `drainStderr`/assert literal pairs in SessionLifecycleTests when those lines are next touched. +- [ ] With #146 + this, the repo-wide lint-clean claim holds at the ERROR tier; literal warning-zero would need either further file splits (three more files) or `.swiftlint.yml` tier configuration — a deliberate owner call, not assumed. + +--- + +*Log written by write-log skill. Verification at commit time: swiftformat --lint 0/114, swiftlint 0 errors, xcodebuild test rc=0 with 574/574 by xcresult count (plus one earlier ×2 consecutive green pair on the identical tree).* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 02a08de..e6c8468 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-03 | issue | [20261103-issue147-app-target-lint-clean-five-error-spots_log.md](20261103-issue147-app-target-lint-clean-five-error-spots_log.md) | #147: last five lint error spots — sidecar to extension, renames, guard wraps, PostStoreTests split; two flaky-test root causes fixed | | 2026-11-03 | issue | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | #146: PostsModel split under lint ceilings — six extensions to three domain files, watcher to file-scope extension; pure move, 574 green | | 2026-11-03 | issue | [20261103-issue144-library-search-across-titles-and-bodies_log.md](20261103-issue144-library-search-across-titles-and-bodies_log.md) | #144: library search — trimmed-id debounce, structured off-main body scan (audit: detached → nonisolated), postRow menu for results | | 2026-11-03 | issue | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | #143: path+mtime+size parse memo — rescans re-read only changed post.md; pre-read stamp closes the overlap race; equality-gated posts assignment |