feat(cold-turkey): the writing lock (#162)
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:
AlexKucera committed 2026-11-04 15:58:47 +01:00
1 parent 7b6abb5d65
commit a9e199fce4
16 files changed
+1167 -19

No files matched your search

+265
View File
@@ -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 }))
}
}