Merge pull request 'opt(goal): minutes feeds do no word work; word rail goes count-only [cold-turkey-full-tokenization]' (#188) from opt/cold-turkey-full-tokenization into main
CI / ci (push) Canceled after 0s

Reviewed-on: #188
This commit was merged in pull request #188.
This commit is contained in:
AlexKucera committed 2026-11-13 16:51:04 +01:00
commit 7ed304124e
7 files changed
+165 -10

No files matched your search

+2
View File
@@ -12,6 +12,8 @@ All notable changes to this project will be documented in this file. The format
### Changed
- **cold-turkey:** Live word accounting leaves the per-keystroke path (unticketed opt pass, argus 2026-11-09, digest finding cold-turkey-full-tokenization) — the editor's `onTextChange` feed drove `WritingGoalRun.update` through `DraftStats.words` for every goal type, and `words` built the complete lowercased token array (`split(whereSeparator:)` + `map(lowercased)`) just to return its count: O(document) allocation and lowercasing per keystroke on the main actor, linear in document size (argus probe: ~0.32/3.07/16.64 ms per update at 1k/10k/50k words) — while minutes goals never read the count (verdict, progress, readout, and the completion note all ride the clock). A minutes run now does no word work on feed at all (its accounting freezes at the arm-time baseline — dead state either way), and `words` is a count-only Character pass over maximal isLetter/isNumber runs: the token array is never built, semantics byte-identical (split with omitted empty subsequences yields exactly the maximal runs; pinned against the old split expression over a mixed-script/emoji/punctuation/number corpus). Arm-time baselines still count once per arm through the same rail, now allocation-free; words-goal net accounting unchanged (exactly one rail trip per update, pinned). +3 tests — RED-first minutes zero-trips pin through an injectable word-rail seam on `update` (per-call counting; a global counter would race the hosted suite's parallel DraftStats calls), the words one-trip skip boundary, and the corpus equivalence proof. Suite 684 (unticketed opt pass)
- **home:** Fresh installs default to iCloud (#171, resolution of #170/map #167 — plain build slice for #145) — with no stored Home override, launch resolves once and PINS the winner so the Home never silently moves: a legacy `~/Documents/Museion` directory wins (existing Homes migrate manually, never silently; a stray plain file is not a Home and falls through), else `<CloudDocs>/Museion` when iCloud Drive is present (dynamically resolved unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path, plain FileManager probing — no ubiquity entitlements per ADR-0009), else the silent Documents fallback. No dialog, no rail pill — Settings just shows the resolved path. Repoint-only stands (ADR-0004), zero mover code. The probe/defaults seam is injectable and default constructions under hosted tests neither probe nor pin — the runner app's real iCloud state and defaults are never touched. +9 tests incl. the flip-verified CloudDocs spelling pin and the non-destructive hosted no-write guard. Suite 628 (issue #171)
- **cold-turkey:** The writing lock (#162, wayfinder map #158 — Build S2; wires #161's goal engine + #160's contract into the app) — Cold Turkey is live: armed from a quiet dot in focus mode's bottom-right corner (hover-labeled) or View ▸ Start Cold Turkey…, the arm-bar carries a chip that blends into the focus ground (ground color, faintest hairline, no shadow — the bare seat let document text show through) with minutes|words selector, ± steppers AND a directly typeable value (parsed and clamped at every read; what you type is what arms — 1…1000 words / 1…60 min, defaults 250/5); Start enters the macOS app-kiosk per the #159 factsheet (7-option presentation combo + fullscreen, the window restored on completion) and the readout follows — numerals + 2px hairline, terracotta inside the last 20%, on the same blending chip. While the block holds: ⌥⌘F/reading/new-buffer paths refused (the open Piece stays the counted one), library + mentor hover zones suppressed (editor-only), ⌘W/⌃⌘F/⌘N swallowed by a key-code-matched monitor (charactersIgnoringModifiers is layout- and Caps-Lock-blind while AppKit menus match the physical key — the audit-caught hole; no .closeItem placement exists and SwiftUI owns the window delegate), and ⌘Q asks once (#163's ruling): "Walk away from the block?" — Walk Away quits cleanly, Keep Writing holds. Typing is never interrupted by the unlock: lock ⇒ focus freezes the view branch under the editor, chrome mounts as overlays only, and the fullscreen round trip preserves the first responder. Completion returns quietly to focus with a fading mono note ("● 250 words · 14:02"). Nothing persists — the block dies with the session. Glossary term landed; +19 tests incl. flip-verified refusal-key, parse-fallback, and canArm-mirror pins; finish-audit fanout (3 reviewers) landed the key-match fix, a ticker-race test seam, chip dedup, and window-capture-on-exit. Suite 620 (issue #162)
+20 -2
View File
@@ -79,10 +79,28 @@ nonisolated struct DraftStats: Equatable {
/// Word count over the same token semantics every text metric
/// rides (#161: Cold Turkey net-words counts with this — one
/// tokenizer, no drift). "writer's" is two words here, headings
/// word rail, no drift). "writer's" is two words here, headings
/// are body text, frontmatter is not (the editor never shows it).
/// Count-only (opt pass 2026-11-09): one Character pass counting
/// maximal isLetter/isNumber runs — the lowercased [String] the
/// per-keystroke editor feed once paid for is never built. Equal
/// to the tokenizer's split by construction (omitting empty
/// subsequences leaves exactly the maximal runs); pinned against
/// the split expression over a mixed-script corpus.
static func words(in text: String) -> Int {
tokens(in: text).count
var count = 0
var inRun = false
for character in text {
if character.isLetter || character.isNumber {
if !inRun {
count += 1
inRun = true
}
} else {
inRun = false
}
}
return count
}
/// Lowercased runs of Characters where isLetter || isNumber — the
+19 -8
View File
@@ -24,9 +24,9 @@ nonisolated enum WritingGoal: Equatable {
/// (typing, deleting, pasting, undo all land as whole-document
/// text), and `now` is injected, so the countdown can never be
/// paused or deferred from inside the engine. Word counting rides
/// `DraftStats.words` — the one tokenizer all text metrics share, so
/// net-words can never drift from first-draft stats ("writer's" is
/// two words there, headings are body text; frontmatter is not body
/// `DraftStats.words` — the one word-count rail all text metrics
/// share, so net-words can never drift from first-draft stats
/// ("writer's" is two words there, headings are body text; frontmatter is not body
/// text — the editor never shows it, so it never counts).
nonisolated struct WritingGoalRun: Equatable {
let goal: WritingGoal
@@ -35,7 +35,9 @@ nonisolated struct WritingGoalRun: Equatable {
let armedAt: Date
/// Whole-document word count at arm.
let baselineWords: Int
/// Whole-document word count as of the last `update(text:)`.
/// Whole-document word count as of the last `update(text:)` —
/// words goals only; a minutes run freezes at the arm-time
/// count (the verdict never reads it).
private(set) var currentWords: Int
init(goal: WritingGoal, armedAt: Date, body: String) {
@@ -46,10 +48,19 @@ nonisolated struct WritingGoalRun: Equatable {
currentWords = words
}
/// Record the live editor text. The caller passes the whole
/// document every time; the net falls out of the delta.
mutating func update(text: String) {
currentWords = DraftStats.words(in: text)
/// Record the live editor text — words goals only. The caller
/// passes the whole document every time; the net falls out of
/// the delta. A minutes run never re-counts: its verdict and
/// progress ride the clock alone, so the per-keystroke feed
/// does no word work at all (opt pass 2026-11-09 — the feed
/// once tokenized the whole document per keystroke for a count
/// nothing read). `countWords` is the injectable word rail —
/// the pins count rail trips through this seam (a global
/// counter would race the hosted suite's parallel DraftStats
/// calls).
mutating func update(text: String, countWords: (String) -> Int = DraftStats.words(in:)) {
guard case .words = goal else { return }
currentWords = countWords(text)
}
/// Net new words since arm. Deleting costs — net, not gross; a
+37
View File
@@ -75,3 +75,40 @@ import Testing
#expect(abs(DraftStats.compute(body: "Dog dog DOG").typeTokenRatio - 1.0 / 3.0) < 0.001)
#expect(abs(DraftStats.compute(body: "writer's note writer").typeTokenRatio - 3.0 / 4.0) < 0.001)
}
@Test func `word rail equals the split tokenizer over a mixed corpus`() {
/// The count-only word rail (opt pass 2026-11-09) must answer exactly
/// what the lowercased-token array answered: split on
/// !(isLetter || isNumber), empty subsequences omitted. The reference
/// IS the old implementation — the corpus (mixed scripts, emoji,
/// punctuation, numbers, empties) makes any semantic drift (e.g. a
/// whitespace count) fail here.
func reference(_ text: String) -> Int {
text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).count
}
let corpus = [
"",
" \t\n ",
"\n\n\n",
"— — !!!",
"one two three",
"writer's note",
"## Chapter Two — draft 3",
"abc123def",
"3.14 and 2,718,281",
"$5,000 USD",
"naïve café Zürich",
"Привет мир",
"日本語のテキストです",
"مرحبا بالعالم",
"emoji 👨‍👩‍👧‍👦 are not words",
"word—word, word; word: word",
"One two three. Four five! Six?",
]
for text in corpus {
#expect(
DraftStats.words(in: text) == reference(text),
"corpus mismatch for \(text.debugDescription)",
)
}
}
+35
View File
@@ -103,6 +103,41 @@ struct WritingGoalTests {
#expect(block.secondsRemaining(now: Self.arm.addingTimeInterval(60)) == 29 * 60)
}
@Test
func `a minutes update takes zero word-rail trips`() {
// Opt pass 2026-11-09 (unticketed digest finding): a minutes
// verdict rides the clock alone, so the per-keystroke feed must
// not count — let alone tokenize — the whole document. One long
// feed, zero rail trips through the injectable seam.
var block = Self.run(.minutes(30))
var railTrips = 0
block.update(
text: String(repeating: "word ", count: 2000),
countWords: { _ in
railTrips += 1
return 0
},
)
#expect(railTrips == 0)
}
@Test
func `a words update takes exactly one word-rail trip`() {
// The skip boundary: words goals keep live accounting — exactly
// one rail trip per update, and the count lands.
var block = Self.run(.words(500))
var railTrips = 0
block.update(
text: "one two three four five six seven",
countWords: { _ in
railTrips += 1
return 7
},
)
#expect(railTrips == 1)
#expect(block.currentWords == 7)
}
@Test
func `an absurd minutes goal never traps the countdown`() {
// Int() traps past Int.max — the clamp at the conversion seam is the pin
@@ -0,0 +1,51 @@
# Cold Turkey live tokenization — minutes skip + count-only word rail
> **Date:** 2026-11-13
> **Type:** opt
> **Reference:** unticketed digest finding `cold-turkey-full-tokenization` (argus opt pass 2026-11-09, scanned at efbde25c; branch `opt/cold-turkey-full-tokenization` off main 5915178)
## Goal
Kill the O(document) per-keystroke tokenization on the focused writing surface: Cold Turkey feeds every editor edit through whole-document word counting even for minutes blocks whose verdict and progress ignore words entirely, and the word count itself builds a lowercased `[String]` token array just to return `.count`. Behavior byte-stable, cost down.
## What Was Done
- Re-derived the defect live at base 5915178 (tip unmoved from the scan-era drift check; the ~10 commits since efbde25c never touched the seam): `PostEditorView.onTextChange` → `WritingLockState.feed` → `WritingGoalRun.update` → `DraftStats.words` → `tokens(in:)` — `text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map { $0.lowercased() }`, full array materialized per keystroke, main actor, for every goal type. Minutes consumers (`isMet`, `progress`, `readout`, `completionNoteText`) never read the count.
- RED first: injected a per-call word-rail seam on `update(text:countWords:)` (default `DraftStats.words`) and pinned `a minutes update takes zero word-rail trips` — failed at base exactly as designed (base takes one trip per update); companion `a words update takes exactly one word-rail trip` pins the skip boundary; both sides of the boundary in one suite.
- Semantic equivalence pin: `word rail equals the split tokenizer over a mixed corpus` (DraftStatsTests) — the old split expression kept alive as an inline reference over a corpus covering empty, whitespace-only, punctuation-only, mixed scripts (Latin/diacritics/Cyrillic/CJK/Arabic), emoji ZWJ, punctuation, decimal/comma numbers, contiguous alnum runs. Green at base by design — it is the equivalence proof, not a RED.
- Fix (9f4d9ef): `update` guards on `.words` — a minutes run does no word work on feed at all (its accounting freezes at the arm-time baseline; `currentWords` was dead state for minutes runs); `DraftStats.words` becomes a count-only Character pass over maximal `isLetter`/`isNumber` runs — identical count by construction (split with omitted empty subsequences yields exactly the maximal runs), no array, no lowercasing. Arm-time baseline still counts once per arm through the same rail, now allocation-free. All callers unchanged.
- Gates: focused WritingGoalTests RED 12/13 → GREEN 13/13; full unit target 684 executed / 684 passed / 0 failed / 0 skipped (681 base + 3 new); swiftformat 0 dirty; swiftlint 279 violations / 60 serious in 141 files — byte-identical to pristine base 5915178 (all pre-existing, spike/prototypes noise).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Per-call injectable rail seam over a global tokenizer counter | The hosted suite runs Swift Testing tests in parallel — a shared static counter would race concurrent `DraftStats.compute` calls (which legitimately tokenize) and false-RED the zero-trips pin. The per-call closure counts exactly the production path (default argument = the real rail) with no shared state. Precedent: `spawnsTicker`, injectable `at:` — the repo's established seam style. |
| Minutes accounting freezes at baseline rather than being deleted | `WritingGoalRun`'s documented shape keeps `baselineWords`/`currentWords` as arm-time facts; nothing reads `currentWords` for a minutes run (readout/isMet/progress/note all ride the clock), so freezing is observationally identical to the old live tracking for every consumer — the smallest diff that removes the work. |
| `words(in:)` stays the ONE word-count rail (count-only inside it) | Museion/AGENTS.md contract: net-words and first-draft stats can never drift. The count-only pass uses the exact same per-Character predicates as the tokenizer; the corpus pin holds the equivalence forever. Explicitly NOT a whitespace count. |
| `DraftStats.compute`'s sentence-length `tokens(...).count` left alone | Store-time (once per pass at capture), not the per-keystroke seam — one finding per branch; folding it in would scope-creep the opt. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| RED build failed: "Unprintable ASCII character" at DraftStatsTests:91 | The patch layer's JSON escaping wrote a raw TAB (0x09) inside the `" \t\n "` corpus literal — Swift forbids raw tabs inside string literals (the neighboring `\n` escapes landed correctly, masking the asymmetry) | Byte-level replace with proper `\t` escape; scanned all touched files for stray mid-line control bytes; amended into the RED commit (dde99c8, force-with-lease — branch unreviewed at that point, disclosed) |
| 02:27 gateway drop killed the turn between the seam patch and the test patches | Dead turn discarded; the applied seam patch survived on disk, the two unapplied test patches were lost | Re-derived state from `git status`/diff before redoing anything (no double-apply); RED milestone committed + pushed on resume per push-at-first-commit |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/WritingGoal.swift` | `update` guards on `.words` (minutes: no word work on feed); injectable `countWords` rail seam; `currentWords`/header docs updated to the frozen-minutes truth |
| `Museion/DraftStats.swift` | `words(in:)` count-only Character pass — no token array, no lowercasing; equivalence documented |
| `MuseionTests/WritingGoalTests.swift` | Pins: minutes zero rail trips (RED at base), words exactly one rail trip + count lands |
| `MuseionTests/DraftStatsTests.swift` | Corpus equivalence pin: word rail vs the old split expression over mixed scripts/emoji/punctuation/numbers/empties |
| `CHANGELOG.md` | [Unreleased] › Changed entry |
## Open Items & Next Steps
- [ ] None on this seam. Observation for @aegis (NOT folded in): `DraftStats.compute`'s sentence-length `.map { tokens(in: String($0)).count }` still allocates per sentence chunk at store-time — same count-only treatment would apply there if it ever shows up hot, separate finding.
---
*Log written by hand on the brief-23 branch (daedalus).*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 |
| 2026-11-11 | fix | [20261111-fix-library-search-stale-after-mutation_log.md](20261111-fix-library-search-stale-after-mutation_log.md) | Search snapshots re-key on Home + a rescan-rail content revision (list change OR re-read post.md — body-only edits included); stale rows drop to the recompute spinner (#144/#157 mounted gap) |
| 2026-11-10 | follow-up | [20261110-issue179-followup-bind-root-task_log.md](20261110-issue179-followup-bind-root-task_log.md) | Bind hoisted to the WorkspaceView root task (stale watchedHome after repoint); PR #185 closed as superseded by 5bf0955 |
| 2026-11-10 | issue | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) | PR #184 finish-audit: dead Equatable cut, restart-race ceiling named, titled-apply pin + hangOnPromptLoad rig mode |