feat(stats): first-draft stats capture (S5.1) (#31)
CI / ci (push) Canceled after 0s

Measure the writer, not the text. Running Pass 1 or Pass 2 on an
unaided draft (origin: writer, First Draft Pass State, post type -
lenient defaults, so bare legacy posts qualify) computes four style
metrics natively in Swift at the invocation - before the engine sees
anything - and stamps stats_captured plus four stats_* values into
the piece's frontmatter in place, so the S5.2 trend view is a plain
scan of Post.frontmatter. Capture re-fires while still First Draft
(latest draft wins); a cancelled pass keeps its capture; ai-origin
and advanced pieces never qualify.

The capture exposed an erasure class: the existingStamp-to-stamped
block rewrite rebuilt frontmatter from three parsed fields, silently
dropping everything else. advancePassState and overwrite now update
their owned keys in place (stampingFrontmatter, widened internal per
its own third-caller trigger; bare posts still normalize through
stamped), so captured stats and foreign YAML survive pass completion
AND mid-pass editor saves. Both fixes are flip-verified by pins.

DraftStats carries the four metrics (burstiness, type-token ratio,
sentence-length variation, trigram repetition) as a pure Foundation
model - full precision out, %.3f at store time. 16 new pins across
DraftStatsTests, PostStoreTests, and PassRunTests; full unit bundle
396/396 (sequential gate; parallel runs flake under external CPU
load per the #30 learning). Finish-audit fanout (ponytail/security/
review) ran on the diff: its MEDIUM (overwrite erasure) and the
converged deletions landed here.

Closes #31
This commit is contained in:
AlexKucera committed 2026-10-22 19:05:42 +02:00
1 parent ae234350ef
commit 42bcfce9ba
13 files changed
+611 -20

No files matched your search

@@ -0,0 +1,91 @@
# 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*
+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-10-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests |
| 2026-10-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. |
| 2026-10-22 | issue | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) | #29 research rail: submit_research_notes candidates in-session, ask-before keep into research/, resume replay pin, audit fixes — targeted suites green |
| 2026-10-22 | issue | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) | #28 Session lifecycle: multi-session model + names-only roster, pane, pass auto-create, finish-audit with 7 fixes — 359 tests green |