feat(cold-turkey): the writing lock (#162)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Wires #161's goal engine and #160's contract into the app: armed from a corner dot or View ▸ Start Cold Turkey…, enforced by the macOS app-kiosk (7-option presentation combo + fullscreen, restored on completion), readout with hairline + near-goal terracotta, and a completion note fading back into focus. While held: focus exit, reading, new buffers, ⌘W/⌃⌘F/⌘N refused (key-code-matched monitor — character matching is layout/Caps-blind; no .closeItem placement exists), ⌘Q asks once per #163's ruling. Typing continuity holds by construction — lock ⇒ focus freezes the branch under the editor and chrome mounts as overlays only. Arm values type directly (1…1000 words / 1…60 min, defaults 250/5). Nothing persists. Wayfinder map #158 Build S2; suite 620, flip-verified pins.
This commit is contained in:
1 parent
7b6abb5d65
commit
a9e199fce4
16 files changed
+1167
-19
No files matched your search
@@ -16,8 +16,8 @@
|
||||
// files build rigs on it) + the client/model suites that pin its contract.
|
||||
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
@testable import Museion
|
||||
import SwiftUI
|
||||
import Testing
|
||||
|
||||
// MARK: - Fake ACP server + helpers
|
||||
|
||||
@@ -25,6 +25,7 @@ Owned by the root AGENTS.md 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.
|
||||
- `WritingGoalTests.swift` (#161, Cold Turkey S1 — scenario header at file top, `@Suite("WritingGoalTests")`; BARE `@Suite` is stripped by this repo's swiftformat — always give the attribute its string argument) — the goal engine's 11 pins: arm baseline + zero net, exact-target completion (499 ≠ met), delete-below-baseline (net −2, progress clamps 0), 2000-word paste counts in full, undo-to-baseline nets zero, words-goal ignores the clock (`secondsRemaining` nil), minutes deadline boundary (−1 s not met, on-the-second met, remaining 60/0), minutes-goal ignores words + deadline immovable, an absurd `.minutes(.max)` never traps the countdown (the Int-seam clamp pin — flip-verified), tokenizer parity with DraftStats ("writer's" 2 / "writer's note" 3 / headings count / digits count / punctuation-only 0), and the `progress(now:)` fractions for both goal kinds.
|
||||
- `WritingLockTests.swift` (#162, Cold Turkey S2 — scenario header at file top, `@Suite`; machine tests `@MainActor`) — the lock machine's pins: words block completes on the tick after the target lands (note "2 words · 14:02"), minutes block completes exactly on the deadline tick and not a second early, deleting below baseline keeps the hold, a second start while locked is refused (armedAt unchanged), feed/tick at rest are no-ops; the #160 contract shapes — readout (words net "212 / 500", countdown "13:27 left"), clock spans (mm:ss under an hour, h:mm:ss above), near-goal at the 0.8 boundary, completion note text, arm scales (250/50/1…1000, 5/5/1…60 + clamps — 2026-11-04 amendments: what's typed is what arms, ceilings 1000 words / 60 min); the #159 recipe — `WritingLockKiosk.lockOptions` equals the 7-bit set; the canArm mirror over `makeModelHome` (nothing open false, prose draft true, outline draft false, prose piece true + `editorBodyText` reads its disk body, outline piece false — scan-poll waited so the routing reads the real type) and the external-guest pins; and the lock ⇒ focus invariant (`AppGateState.startWritingLock` forces `isFocused` and runs the block over the open draft). the refusal key set (keyCode + exact modifiers + lowercased character net — layout/Caps-Lock cases), `ArmScale.parse` (garbage/empty/overflow → default), the #111 mixed-outline guard hold disarming canArm, and the quit delegate's unlocked pass-through. Kiosk calls no-op under hosted tests by construction — never pinned by driving them. Machine tests pass `spawnsTicker: false` (the real 1 s ticker could complete a met goal before an injected tick under a >1 s main-actor stall — the #30/#147 flake family).
|
||||
- `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 `` — 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).
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//
|
||||
// WritingLockTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #162 (Cold Turkey S2, map #158): the writing lock's machine + contract
|
||||
// facts. Scenario: arm the state machine over small bodies with injected
|
||||
// clocks and drive the decisive ticks by hand (the 1 s ticker's real-now
|
||||
// ticks can never fire first — deadlines are minutes out); the arm
|
||||
// scales, readout shapes, kiosk recipe, and the canArm mirror of the
|
||||
// editor branch are pinned against the #160 contract render and the
|
||||
// #159 factsheet. Kiosk calls no-op under hosted tests by construction.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("WritingLockTests")
|
||||
struct WritingLockTests {
|
||||
// MARK: - Machine
|
||||
|
||||
@Test @MainActor
|
||||
func `a words block completes on the tick after the target lands`() {
|
||||
let lock = WritingLockState()
|
||||
let arm = Date()
|
||||
lock.start(goal: .words(2), body: "one two", at: arm, spawnsTicker: false)
|
||||
#expect(lock.isLocked)
|
||||
#expect(lock.run?.baselineWords == 2)
|
||||
#expect(!lock.showsArmBar) // Start consumed the bar
|
||||
|
||||
lock.feed(text: "one two three four") // net +2 — met
|
||||
lock.tick(at: arm.addingTimeInterval(842))
|
||||
#expect(!lock.isLocked)
|
||||
#expect(lock.run == nil)
|
||||
#expect(lock.completionNote == "2 words · 14:02")
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `a minutes block completes exactly on the deadline tick and not a second early`() {
|
||||
let lock = WritingLockState()
|
||||
let arm = Date()
|
||||
lock.start(goal: .minutes(30), body: "", at: arm, spawnsTicker: false)
|
||||
lock.tick(at: arm.addingTimeInterval(1799))
|
||||
#expect(lock.isLocked)
|
||||
lock.tick(at: arm.addingTimeInterval(1800)) // inclusive boundary
|
||||
#expect(!lock.isLocked)
|
||||
#expect(lock.completionNote == "30 min · 30:00")
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `deleting below baseline keeps the hold — the count is net`() {
|
||||
let lock = WritingLockState()
|
||||
let arm = Date()
|
||||
lock.start(goal: .words(5), body: "one two", at: arm, spawnsTicker: false)
|
||||
lock.feed(text: "one") // net −1
|
||||
lock.tick(at: arm.addingTimeInterval(10))
|
||||
#expect(lock.isLocked) // deleting costs — no completion
|
||||
lock.feed(text: "one two three four five six seven eight")
|
||||
lock.tick(at: arm.addingTimeInterval(11))
|
||||
#expect(!lock.isLocked)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `a second start while locked is refused`() {
|
||||
let lock = WritingLockState()
|
||||
let arm = Date()
|
||||
lock.start(goal: .words(10), body: "seed", at: arm, spawnsTicker: false)
|
||||
lock.start(goal: .minutes(180), body: "seed", at: arm.addingTimeInterval(99), spawnsTicker: false)
|
||||
#expect(lock.isLocked)
|
||||
#expect(lock.run?.goal == .words(10))
|
||||
#expect(lock.run?.armedAt == arm) // one block per moment — unchanged
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `feed and tick at rest are no-ops`() {
|
||||
let lock = WritingLockState()
|
||||
lock.feed(text: "anything")
|
||||
lock.tick(at: Date())
|
||||
#expect(!lock.isLocked)
|
||||
#expect(lock.run == nil)
|
||||
#expect(lock.completionNote == nil)
|
||||
}
|
||||
|
||||
// MARK: - Readout + note formatting (#160 contract)
|
||||
|
||||
@Test @MainActor
|
||||
func `readout shapes the words net and the minutes countdown`() {
|
||||
let arm = Date(timeIntervalSince1970: 1_000_000)
|
||||
var words = WritingGoalRun(goal: .words(500), armedAt: arm, body: "one two")
|
||||
#expect(WritingLockState.readout(words, now: arm).numerals == "0 / 500")
|
||||
#expect(WritingLockState.readout(words, now: arm).unit == "words")
|
||||
words.update(text: String(repeating: "word ", count: 212) + "one two")
|
||||
#expect(WritingLockState.readout(words, now: arm).numerals == "212 / 500")
|
||||
|
||||
let minutes = WritingGoalRun(goal: .minutes(30), armedAt: arm, body: "")
|
||||
let shape = WritingLockState.readout(minutes, now: arm.addingTimeInterval(30 * 60 - 807))
|
||||
#expect(shape.numerals == "13:27")
|
||||
#expect(shape.unit == "left")
|
||||
}
|
||||
|
||||
@Test
|
||||
func `clock spans minutes and hours`() {
|
||||
#expect(WritingLockState.clockString(seconds: 0) == "00:00")
|
||||
#expect(WritingLockState.clockString(seconds: 59) == "00:59")
|
||||
#expect(WritingLockState.clockString(seconds: 60) == "01:00")
|
||||
#expect(WritingLockState.clockString(seconds: 842) == "14:02")
|
||||
#expect(WritingLockState.clockString(seconds: 3600) == "1:00:00")
|
||||
#expect(WritingLockState.clockString(seconds: 3722) == "1:02:02")
|
||||
}
|
||||
|
||||
@Test
|
||||
func `near-goal fires inside the last twenty percent`() {
|
||||
#expect(!WritingLockState.isNearGoal(progress: 0.79))
|
||||
#expect(WritingLockState.isNearGoal(progress: 0.8))
|
||||
#expect(WritingLockState.isNearGoal(progress: 1))
|
||||
#expect(!WritingLockState.isNearGoal(progress: 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
func `completion note names the goal and the elapsed`() {
|
||||
#expect(WritingLockState.completionNoteText(goal: .words(500), elapsed: 842) == "500 words · 14:02")
|
||||
#expect(WritingLockState.completionNoteText(goal: .minutes(30), elapsed: 1800) == "30 min · 30:00")
|
||||
}
|
||||
|
||||
// MARK: - Kiosk recipe + arm scales (#159 factsheet, #160 render)
|
||||
|
||||
@Test
|
||||
func `kiosk options are the factsheet recipe plus the corner switch`() {
|
||||
#expect(WritingLockKiosk.lockOptions == [
|
||||
.hideDock,
|
||||
.hideMenuBar,
|
||||
.disableProcessSwitching,
|
||||
.disableForceQuit,
|
||||
.disableSessionTermination,
|
||||
.disableHideApplication,
|
||||
.disableScreenCornerInteractions,
|
||||
])
|
||||
}
|
||||
|
||||
@Test
|
||||
func `arm scales carry the render's defaults ranges and clamps`() {
|
||||
let words = WritingLockState.ArmScale.words
|
||||
#expect(words.defaultValue == 250) // 2026-11-04 amendment: 250 words / 5 min
|
||||
#expect(words.step == 50)
|
||||
#expect(words.range == 1 ... 1000) // what's typed is what arms (2026-11-04 amendment)
|
||||
#expect(words.clamp(0) == 1)
|
||||
#expect(words.clamp(10) == 10) // the dogfood case — 10 words STAYS 10
|
||||
#expect(words.clamp(1001) == 1000)
|
||||
|
||||
let minutes = WritingLockState.ArmScale.minutes
|
||||
#expect(minutes.defaultValue == 5)
|
||||
#expect(minutes.step == 5)
|
||||
#expect(minutes.range == 1 ... 60)
|
||||
#expect(minutes.clamp(0) == 1)
|
||||
#expect(minutes.clamp(61) == 60)
|
||||
}
|
||||
|
||||
// MARK: - The canArm mirror (PostsModel)
|
||||
|
||||
@Test @MainActor
|
||||
func `canArmWritingLock gates on the open surface`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
#expect(!model.canArmWritingLock) // nothing open
|
||||
|
||||
model.newPost() // prose draft
|
||||
#expect(model.canArmWritingLock)
|
||||
|
||||
model.newOutline() // outline draft replaces it
|
||||
#expect(!model.canArmWritingLock)
|
||||
|
||||
// A prose piece on disk, opened as a session (wait for the scan so
|
||||
// the outline routing reads the real type, not the lagging list).
|
||||
let post = try PostStore.writeNew(body: "# Prose piece\n\nBody words.\n", home: home)
|
||||
try await Self.waitForScan(model, id: post.id)
|
||||
model.select(post.id, home: home)
|
||||
#expect(model.canArmWritingLock)
|
||||
#expect(model.editorBodyText == "# Prose piece\n\nBody words.\n")
|
||||
|
||||
let outline = try PostStore.writeNew(body: "- an outline\n", project: "posts", type: .outline, home: home)
|
||||
try await Self.waitForScan(model, id: outline.id)
|
||||
model.select(outline.id, home: home)
|
||||
#expect(!model.canArmWritingLock)
|
||||
|
||||
// A MIXED outline fires the #111 guard ask instead — the held
|
||||
// guard (no session, empty editor) must disarm too: the editor
|
||||
// branch's fourth path, pinned so the mirror can't drift.
|
||||
let mixed = try PostStore.writeNew(body: "- bullet\nprose between bullets\n", project: "posts", type: .outline, home: home)
|
||||
try await Self.waitForScan(model, id: mixed.id)
|
||||
model.select(mixed.id, home: home)
|
||||
#expect(model.outlineGuardPieceID == mixed.id)
|
||||
#expect(!model.canArmWritingLock)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `the external guest can arm and carries its live text`() throws {
|
||||
let (model, _) = try makeModelHome()
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("guest-\(UUID().uuidString).md", isDirectory: false)
|
||||
try "# Guest words\n".write(to: url, atomically: true, encoding: .utf8)
|
||||
model.openExternal(url)
|
||||
#expect(model.canArmWritingLock)
|
||||
#expect(model.editorBodyText == "# Guest words\n")
|
||||
}
|
||||
|
||||
// MARK: - The lock ⇒ focus invariant (AppGateState)
|
||||
|
||||
@Test @MainActor
|
||||
func `startWritingLock forces focus and runs the block over the open draft`() {
|
||||
let gate = AppGateState()
|
||||
gate.posts.newPost()
|
||||
gate.posts.draft?.text = "seed words here"
|
||||
#expect(!gate.isFocused)
|
||||
gate.startWritingLock(goal: .words(2))
|
||||
#expect(gate.isFocused) // the invariant, settled at start
|
||||
#expect(gate.writingLock.isLocked)
|
||||
gate.writingLock.feed(text: "seed words here plus two more")
|
||||
gate.writingLock.tick()
|
||||
#expect(!gate.writingLock.isLocked)
|
||||
}
|
||||
|
||||
@Test
|
||||
func `the refusal key set matches key codes with the exact modifiers`() {
|
||||
// keyCode net: physical key, layout- and case-independent.
|
||||
#expect(WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command]))
|
||||
#expect(WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command, .control]))
|
||||
#expect(WritingLockKiosk.refusesKey(keyCode: 45, characters: nil, modifiers: [.command]))
|
||||
// character net: Caps-Lock case and plain text both match.
|
||||
#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "W", modifiers: [.command]))
|
||||
#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "f", modifiers: [.command, .control]))
|
||||
// near misses stay live: extra modifiers, wrong keys, bare letters.
|
||||
#expect(!WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command, .option]))
|
||||
#expect(!WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command]))
|
||||
#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "w", modifiers: []))
|
||||
#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "q", modifiers: [.command]))
|
||||
}
|
||||
|
||||
@Test
|
||||
func `arm parse falls to the default on garbage and overflow`() {
|
||||
let words = WritingLockState.ArmScale.words
|
||||
#expect(words.parse("10") == 10)
|
||||
#expect(words.parse("") == 250)
|
||||
#expect(words.parse("abc") == 250)
|
||||
#expect(words.parse("999999999999999999999999999999") == 250) // Int(String) nil on overflow, never traps
|
||||
#expect(words.parse("1001") == 1000)
|
||||
#expect(WritingLockState.ArmScale.minutes.parse("7") == 7)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func `the quit delegate passes an unlocked app straight through`() {
|
||||
// The locked branch is a modal ask — unpinnable headless; the
|
||||
// unlocked path is the seam this pins.
|
||||
let delegate = WritingLockAppDelegate()
|
||||
#expect(delegate.applicationShouldTerminate(NSApplication.shared) == .terminateNow)
|
||||
}
|
||||
|
||||
/// Bounded poll for the watched scan to surface a piece (the
|
||||
/// PostsModelTests poll pattern — the FSEvents latency window).
|
||||
@MainActor
|
||||
private static func waitForScan(_ model: PostsModel, id: String) async throws {
|
||||
for _ in 0 ..< 200 where !model.posts.contains(where: { $0.id == id }) {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
#expect(model.posts.contains(where: { $0.id == id }))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user