Files
museion/docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md
T
AlexKucera e3195d68fd
CI / ci (push) Canceled after 0s
feat(cold-turkey): pure goal engine (#161)
Wayfinder map #158, Build S1: the pure logic slice the writing
lock consumes — no chrome, no clock of its own.

WritingGoal (words | minutes, one goal per block, fixed at arm)
+ WritingGoalRun: update(text:) takes whole-document text and
netNewWords falls out of the delta (deleting costs — net, not
gross; a big paste counts). now is injected into every call, so
the countdown cannot pause by construction; the minutes deadline
is arm+minutes (inclusive), isMet is live truth, unlatched
(delete below target un-mets — complete on the first true tick),
and progress(now:) is the clamped 0…1 the readout hairline rides.
Word counting goes through the new internal DraftStats.words(in:)
— net-words and first-draft stats share one tokenizer and can
never drift.

Finish-audit fanout: the Int() conversion trap in secondsRemaining
fixed at the seam (isFinite + Double(Int.max).nextDown cap — the
naive cap is itself off-by-one at 2^63; flip-verified pin), two
unpinnable > 0 guards in progress deleted, baselineWords narrowed
to let. Equatable and the ?? armedAt fallback kept deliberately
(S2 consumes the former; removing the latter costs formula
duplication). S2 throttle note landed on #162.

Suite 602/602 (xcresult count), swiftformat + swiftlint clean in
app and test targets. Two traps filed to the swift wiki (bare
@Suite stripped by swiftformat; the Double(Int.max) cap).
2026-11-04 12:50:02 +01:00

7.9 KiB
Raw Blame History

Cold Turkey S1 — the goal engine (wayfinder #161)

Date: 2026-11-04 Type: issue Reference: #161 (map: #158, work issue: #140)

Goal

Build the pure logic slice the Cold Turkey writing lock consumes — no chrome, no UI: the WritingGoal model (words | minutes, fixed at arm), a net-words counter on the DraftStats tokenizer (baseline at arm, deleting costs, pastes count), and a never-pausing countdown. Tests pin word-delta math, timer boundaries, and goal-met transitions. AC: pure Swift, suite green with executed tests counted from the xcresult (#31/#134).

What Was Done

  • Museion/WritingGoal.swift (new) — WritingGoal (nonisolated enum: words(Int) | minutes(Int)) + WritingGoalRun (one armed block): baseline/current word counts, update(text:) (whole-document text in, net falls out of the delta), netNewWords, secondsRemaining(now:), isMet(now:) (words: net ≥ target; minutes: now ≥ arm+minutes, inclusive boundary), progress(now:) (0…1, clamped — the readout hairline's number). now is injected everywhere; the struct owns no clock, so the countdown cannot pause by construction.
  • Museion/DraftStats.swift — added static func words(in:) -> Int (tokens(in:).count, internal). One tokenizer for stats AND net-words: the two counts can never drift (the ticket's "cite DraftStats" demand, answered structurally).
  • MuseionTests/WritingGoalTests.swift (new) — @Suite("WritingGoalTests"), 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, minutes deadline boundary (−1 s not met, on-the-second met, secondsRemaining 60/0), minutes-goal ignores words + deadline immovable, tokenizer parity ("writer's" = 2, "writer's note" = 3, headings count, digits count, punctuation-only 0), progress fractions both goal kinds, and the trap pin (.minutes(.max) never traps the countdown — flip-verified: removing the clamp crashes the runner).

Decisions & Rationale

Decision Rationale
WritingGoalRun is a value struct with injected now "Never pauses" is guaranteed by construction — there is no pause API and no owned timer. The lock (S2) owns the ticker and polls; the engine stays pure and testable without clock mocks.
Reuse DraftStats.tokens via a new internal words(in:) The ticket demands consistency with DraftStats counting. Calling the same tokenizer is the only design where consistency cannot rot; a copied counter would drift on the first tokenizer edit.
isMet is live truth, unlatched Deleting below target after touching it un-mets a words goal — the honest readout shows the real net; the lock completes on the first tick isMet reads true.
progress(now:) included in S1 The #160 contract render's readout (numerals + 2px hairline, terracotta near-goal) needs one clamped fraction; it's five pure lines, and S2 would otherwise reopen this file.
Engine named WritingGoalRun, not WritingLock* Charting decision 7 reserves writingLock for S2's app-state machine (WritingLockState, armed → locked → complete); the engine is the goal math only.

Gotchas & Fixes

Problem Root Cause Fix
SwiftFormat error "Unexpected token }" on the new file WritingGoal declared struct with enum cases — swiftc said it first ("enum 'case' is not allowed outside of an enum") nonisolated enum WritingGoal
Compile errors: "static member 'run' cannot be used on instance" Bare run(...) calls inside instance test methods can't reach a private static helper Self.run(...) at every call site
Patch tool mangled = Self.run( into block Self.run( (dropped =) Fuzzy replace of = run(.minutes ate the = while matching Full-file rewrite instead of a third patch
@Suite attribute kept vanishing This repo's SwiftFormat 0.64.3 (--swiftversion 6.3 --language-mode 5) strips a BARE @Suite but keeps argumented ones — every surviving suite in the repo carries @Suite("Name") or @Suite(.serialized) @Suite("WritingGoalTests"); verified it survives a format pass
netNewWords == 500 failed (got 495) Test-authoring bug: fed baseline body + 495 extra words and expected net 500 — the baseline's 5 words ride inside the live text Expect the delta honestly: 500/499 extra words; comment pins the semantics
EditorSessionTests/debounce flushes… failed once in the first full run (saveState .changed) Load flake, the #147 class — a new parallel suite shifts Swift Testing's schedule; the suite is untouched by this diff Verified in isolation (8/8 green) + green in the definitive full run; no code change. Watch it — if it flakes again under future suite growth, its wait window needs the #147 treatment

Files Changed

File Change Summary
Museion/WritingGoal.swift New — WritingGoal enum + WritingGoalRun pure engine
Museion/DraftStats.swift Added internal words(in:) (the shared word-count rail)
MuseionTests/WritingGoalTests.swift New — 10-pin suite

Verification

  • Definitive full run (-only-testing:MuseionTests, settled tree, -resultBundlePath): xcresult 602 executed / 602 passed / 0 failed (601 pre-audit + the flip-verified trap pin; wg161d.xcresult — zero Swift files changed after it). Two earlier red runs were the compile/static-helper errors and the test-authoring bug above.
  • swiftformat + swiftlint clean on all three touched files (post-format tree is what the green run tested); repo-wide swiftlint's 59 serious violations all live in pre-existing spike/ harnesses, none in app or test targets.
  • GitNexus detect_changes: footprint = DraftStats/tokens (additive member) — the medium-risk flag is the type's existing fan-out via captureFirstDraftStats; no existing call site changed.

Finish audit (2026-11-04, three-reviewer fanout)

Accepted and applied:

  • Int-conversion trap (security, LOW — empirically verified by the reviewer): Int() in secondsRemaining SIGTRAPs on .minutes(Int.max) / NaN dates — process death mid-writing-session. Fixed at the conversion seam: isFinite guard + clamp to Double(Int.max).nextDown (the naive Double(Int.max) cap is itself off-by-one — it rounds UP to 2⁶³ and still traps). Pinned; flip-verified (clamp removed → Crash: Museion poisons the runner).
  • Dead guards (ponytail): the two > 0 guards in progress were unpinnable — degenerate zero targets already fall out to 1 through the Double math (probe-verified: min(1, x/0) = 1 for x ≥ 0 and NaN). Deleted.
  • baselineWords → let (ponytail): never mutated after init; private(set) var was dead flexibility.

Deferred (with landing place):

  • Equatable on both types (ponytail: no comparators) — kept: DraftStats pure-model precedent, consumed by S2 next slice; delete-for-a-session is churn.
  • ?? armedAt in isMet (ponytail: unreachable) — kept: removal costs deadline-formula duplication; general reviewer verified it fails open and is the shortest correct form.
  • .words(0) progress-1/isMet-false inconsistency + 0.4 s secondsRemaining rounding edge (general, LOW) — degenerate/arm-bar-forbidden inputs; no action.
  • words(in:) per-call token materialization (security, INFO) → noted on ticket #162: throttle the lock's count onto the readout tick, never per keystroke.

Open Items & Next Steps

  • #162 (Build S2) now unblocked: wire WritingGoalRun into WritingLockState, kiosk per the #159 factsheet, arm-bar/readout per the #160 render. Typing-continuity hard AC rides S2.
  • #163 calibration gate after S2 lands.
  • Fog stays fog: S5.1 tie-in, preset chips — post-calibration calls, not graduated by this slice.

Log written by write-log skill