# M4: First-draft stats capture (S5.1) > **Date:** 2026-10-22 > **Type:** issue > **Reference:** Gitea issue #31 (AlexKucera/Museion), PRD S5.1 ## Goal Measure the writer, not the text: compute the four style stats (burstiness, type-token ratio, sentence-length variation, trigram repetition) natively in Swift at the first pass invocation of any kind — before the engine sees anything — for `origin: writer` posts still in First Draft Pass State, stored per post so the S5.2 trend view is a scan of `posts/`. ## What Was Done - `Museion/DraftStats.swift` (new) — pure deterministic model: `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ), population σ, −1 for a single sentence), typeTokenRatio, sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive word triples). Tokens = lowercased `isLetter||isNumber` runs; sentences = chunks between `.!?` with a token count > 0. - `Museion/PostStore.swift` — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, never throws into the pass): eligibility from the FILE's own frontmatter via the lenient defaults (writer / First Draft / post — a bare legacy post qualifies), five flat `stats_*` keys stamped IN PLACE through `stampingFrontmatter`; `advancePassState` switched from the `existingStamp→stamped` block rewrite to an in-place `pass_state` key stamp (bare posts still normalize through `stamped`). - `Museion/PostsModel.swift` — `runPass` calls the capture after the pre-pass snapshot, before `beginPassSession`/`sendPrompt` — literally before the engine sees anything; the Bool is ignored. - `Museion/LearningDecay.swift` — `stampingFrontmatter` widened private→internal (its own ponytail comment's third-caller trigger fired). - `Museion/PostStore.swift` `overwrite` (finish-audit fix) — same in-place treatment: the `stamped()` round-trip rebuilt the block from three parsed fields and erased captured stats + foreign frontmatter on every editor save; now blocked files update the three owned keys in place and swap only the body. - Tests: `MuseionTests/DraftStatsTests.swift` (new, 5 pins over hand-derived expectations, scenario header), PostStoreTests +8 pins (capture gate matrix, in-place stamp proof, bare-legacy eligibility, recapture overwrite, advancePassState + overwrite regression pins, bare-post normalization), PassRunTests +3 wiring pins (full-run capture, cancelled-pass capture at invocation, ai-origin refusal). ## Decisions & Rationale | Decision | Rationale | |----------|-----------| | Five flat `stats_*` keys, not a nested `museion:` YAML block | The lenient flat frontmatter parser (`Post.frontmatter`) maps `key: value` lines; a nested block's indented children would be promoted to colliding top-level keys. PRD's "museion: block" reads as "the block Museion owns". | | In-place key stamps for `advancePassState` + `overwrite` | The `stamped()` full-block rewrite carries only type/pass_state/origin and silently erased everything else. Root-cause fix at the write-path class, not per-symptom. | | Capture re-fires while still First Draft (latest wins) | A cancelled pass leaves the state at First Draft; the next pass re-captures the current draft. Falls out of the in-place overwrite stamp. | | Fire at invocation, not completion | PRD S5.1 pins it ("before the engine sees anything"); cancelled/refused passes keep their stats. | | `.post` type gate | CONTEXT.md vocabulary: Post ≠ Outline; prose metrics on a bullet tree are noise. | | `now: Date` clock param deleted | Untested seam — ProfileBackup injects a clock because it TESTS one; YAGNI. | | `stampingFrontmatter` widened, not extracted | The function's own ponytail comment set the trigger ("third caller"); PostStore's enum body is genuinely at its 250-line lint ceiling (347). | ## Gotchas & Fixes | Problem | Root Cause | Fix | |---------|------------|-----| | End-to-end wiring pin failed 3/3 full-suite runs while "passing" in isolation | The isolated runs were VACUOUS: `-only-testing` with a single test name executed 0 tests (free-function Swift Testing tests have no suite; the banner still prints TEST SUCCEEDED). Confirmed via `xcresulttool get test-results summary` → `passedTests: 0`. | Always read the executed count from the xcresult, never the banner. Single-test filtering works only with the backtick-identifier form and is unreliable through wrappers. | | Stats keys absent after a completed pass (deterministic) | `advancePassState`'s `existingStamp→stamped` rewrite rebuilt the block from three parsed fields. Found by a temporary on-disk diagnostic dump (print() is swallowed by the test harness; write to a scratch file instead). | In-place `pass_state` stamp; regression pin `advance pass state preserves stats and foreign keys in place`. | | Same erasure class live in `overwrite` (found by the finish-audit security reviewer) | Editor saves mid-pass route through `overwrite` → stats destroyed by ordinary editing; the draft then aged out of eligibility. | In-place key update in `overwrite`; two pins (blocked + bare branch); flip-verified (revert → exactly the new pin fails). | | Full-suite runs flake on rig pins under machine load (Classis.app at 70% CPU → load 6.4) | Fresh fake-ACP spawn + handshake timeouts under CPU contention — the documented #30 learning, seen again. | Sequential run (`-parallel-testing-enabled NO`) is the honest gate under load; failures verified green in isolation via the executed-count check. | ## Files Changed | File | Change Summary | |------|---------------| | `Museion/DraftStats.swift` | New — the four-metric pure model | | `Museion/PostStore.swift` | `captureFirstDraftStats`; `advancePassState` + `overwrite` switched to in-place key stamps | | `Museion/PostsModel.swift` | `runPass` capture call after the snapshot, before engine traffic | | `Museion/LearningDecay.swift` | `stampingFrontmatter` private→internal (+ comment update) | | `MuseionTests/DraftStatsTests.swift` | New — 5 metric pins | | `MuseionTests/PostStoreTests.swift` | +10 capture/advance/overwrite pins incl. 2 regression pins | | `MuseionTests/PassRunTests.swift` | +3 end-to-end wiring pins | | `Museion/AGENTS.md` / `MuseionTests/AGENTS.md` | DOX pass: file entries, mechanism corrections, pin inventories | | `CHANGELOG.md` | Unreleased → added: first-draft stats capture | ## Open Items & Next Steps - [ ] S5.2 trend view — reads the `stats_*` keys via `Post.frontmatter`; consider `stats_captured` date parsing + per-metric charting. - [ ] Pre-existing SwiftLint ceilings on `PostsModel.swift` (file_length ERROR at HEAD, 1027→1032 lines) and `runPass` body — need their own extraction ticket. - [ ] `MuseionUITests.testAppLaunches` fails with "Failed to activate application" — environmental, pre-existing, not addressed here. - [ ] `convert` still uses the `stamped()` rewrite (outline→post only, outlines carry no stats — no live erasure, noted for the record). --- *Log written by write-log skill*