CI / ci (push) Canceled after 0s
Root cause (re-derived live at5915178): WritingLockState.feed -> WritingGoalRun.update counted words for EVERY goal type, and DraftStats.words built the complete lowercased token array (text.split(whereSeparator:).map(lowercased)) just to return .count — O(document) allocation + lowercasing per keystroke on the main actor for minutes goals whose verdict/progress/readout never read the count (argus probe atefbde25c: minutes ~0.32/3.07/16.64 ms per update at 1k/10k/50k words, linear in document size). Fix, two halves, semantics byte-stable: - update(text:) 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: readout, isMet, progress, and the completion note all ride the clock). - DraftStats.words becomes a count-only Character pass over maximal isLetter/isNumber runs — never materializing the lowercased [String]. Identical count by construction: the tokenizer's split (which always omits empty subsequences) yields exactly the maximal runs; equivalence pinned against the split expression over a mixed-script/emoji/punctuation/number corpus in DraftStatsTests. WritingGoalRun.init (arm-time baseline) keeps counting once per arm through the same rail — now also allocation-free. Callers unchanged (update's countWords defaults to DraftStats.words); the words-goal net accounting is pinned unchanged ('a words update takes exactly one word-rail trip' + all existing net-delta pins).
115 lines
4.4 KiB
Swift
115 lines
4.4 KiB
Swift
//
|
||
// DraftStats.swift
|
||
// Museion
|
||
//
|
||
// #31 (S5.1): the four unaided-first-draft style stats (CONTEXT.md
|
||
// 'Unaided First Draft') — computed natively in Swift from the exact
|
||
// text a pass is about to see, so the trend view (S5.2) tracks the
|
||
// writer's own draft, never AI-assisted text. Pure Foundation,
|
||
// deterministic: same body in, same stats out.
|
||
//
|
||
|
||
import Foundation
|
||
|
||
/// One piece's first-draft style metrics (#31). `compute` returns FULL
|
||
/// precision; rounding to three decimals happens only at store time
|
||
/// (`PostStore.captureFirstDraftStats`, `String(format: "%.3f")` — a
|
||
/// period, never a localized comma). Empty input is all zeros, never NaN.
|
||
nonisolated struct DraftStats: Equatable {
|
||
/// (σ − μ) / (σ + μ) over sentence token counts — Bousso-style
|
||
/// burstiness; 0 when there are no sentences at all. A single
|
||
/// sentence → σ = 0 → −1 (correct: maximally regular).
|
||
let burstiness: Double
|
||
/// Unique tokens / total tokens; 0 when the body has no tokens.
|
||
let typeTokenRatio: Double
|
||
/// σ / μ over sentence token counts; 0 when μ = 0.
|
||
let sentenceVariation: Double
|
||
/// (total − unique) / total over consecutive token triples; 0 when
|
||
/// there are fewer than three tokens.
|
||
let trigramRepetition: Double
|
||
|
||
/// #31 (S5.1): the four stats over `body` — the text the engine is
|
||
/// about to see. Sentences are chunks between `.`, `!`, `?`; each
|
||
/// chunk's token count is one sentence length when > 0 (the split
|
||
/// never looks at newlines, so leading heading text gloms into the
|
||
/// first sentence). σ is the POPULATION stddev.
|
||
static func compute(body: String) -> DraftStats {
|
||
let allTokens = tokens(in: body)
|
||
let lengths = body
|
||
.split(whereSeparator: { $0 == "." || $0 == "!" || $0 == "?" })
|
||
.map { tokens(in: String($0)).count }
|
||
.filter { $0 > 0 } // adjacent/trailing terminators are not sentences
|
||
|
||
let typeTokenRatio = allTokens.isEmpty ? 0 : Double(Set(allTokens).count) / Double(allTokens.count)
|
||
|
||
// Consecutive triples keyed by content: [a b c][b c a]… — the
|
||
// repeated-opener tell.
|
||
let tripleCount = max(allTokens.count - 2, 0)
|
||
var trigramRepetition = 0.0
|
||
if tripleCount > 0 {
|
||
var unique: Set<ArraySlice<String>> = []
|
||
for start in 0 ..< tripleCount {
|
||
unique.insert(allTokens[start ..< start + 3])
|
||
}
|
||
trigramRepetition = Double(tripleCount - unique.count) / Double(tripleCount)
|
||
}
|
||
|
||
var burstiness = 0.0
|
||
var sentenceVariation = 0.0
|
||
if !lengths.isEmpty {
|
||
// lengths filter to > 0 above, so mean ≥ 1 and σ + mean > 0
|
||
// always — no NaN path past this point (audit: two guards that
|
||
// could never fire were deleted here, #31 finish-audit).
|
||
let mean = Double(lengths.reduce(0, +)) / Double(lengths.count)
|
||
let sigma = sqrt(lengths.reduce(0) {
|
||
let delta = Double($1) - mean
|
||
return $0 + delta * delta
|
||
} / Double(lengths.count))
|
||
sentenceVariation = sigma / mean
|
||
burstiness = (sigma - mean) / (sigma + mean)
|
||
}
|
||
|
||
return DraftStats(
|
||
burstiness: burstiness,
|
||
typeTokenRatio: typeTokenRatio,
|
||
sentenceVariation: sentenceVariation,
|
||
trigramRepetition: trigramRepetition,
|
||
)
|
||
}
|
||
|
||
/// Word count over the same token semantics every text metric
|
||
/// rides (#161: Cold Turkey net-words counts with this — one
|
||
/// 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 {
|
||
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
|
||
/// one tokenizer both the TTR and the sentence lengths ride.
|
||
/// ponytail ceiling: no apostrophe joining — "writer's" is two tokens
|
||
/// (writer + s); a contraction-aware tokenizer is the upgrade path if
|
||
/// the numbers ever need finer grain.
|
||
private static func tokens(in text: String) -> [String] {
|
||
text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map { $0.lowercased() }
|
||
}
|
||
}
|