feat(stats): trend view — the writer's arc (#32)
CI / ci (push) Canceled after 0s

A Trends pane (rail destination after Learnings — measurement beside
memory): one line chart per style metric (burstiness, type-token ratio,
sentence variation, trigram repetition) across unaided-first-draft
CAPTURES over time. Points are capture moments, never draft grades —
the pane answers "am I getting better," not "is this draft good." Each
card carries a first-to-last read (improving/steady/slipping at ±0.01,
direction inverted for trigram repetition — the one falling-is-better
metric; one capture shows its value with no verdict), an up/down-better
hint, and a one-line plain-language gloss of the term.

The edited-text leak is closed by construction: Post.scan reads the
five stats_* frontmatter keys into firstDraftStats only when every key
parses to a finite double AND the piece carries the capture gate's
immutable pair (origin writer, type post — not pass_state, which
legitimately advances after the capture). Import carries external YAML
verbatim, so imported ai pieces or outlines with hand-stamped keys
never render, while a migrated writer piece keeps its real arc. The
finite gate also kills a deterministic crash: Double("nan") parses, and
a non-finite peak traps the chart's y-domain construction.

The pane rides PostsModel's watched scan — no scan of its own — so it
refreshes with the library. Fixed y-domains keep single captures
visible (sentence variation scales to its peak); offset-keyed chart
identity and a title tie-break make same-second capture twins
deterministic; the empty state names how the data arrives.

Finish-audit (3 reviewers) fixed the nan/inf crash, the import leak,
same-second ordering, and cut the injectable tolerance parameter and a
label-switch enum down to raw values. Suite 508; the non-finite and
read-back-gate pins are flip-verified.

Closes #32
This commit is contained in:
AlexKucera committed 2026-10-31 15:12:45 +01:00
1 parent 97e86cf62d
commit 3ee6756467
11 files changed
+679 -8

No files matched your search

+267
View File
@@ -0,0 +1,267 @@
//
// TrendsPaneView.swift
// Museion
//
// #32 (S5.2): the arc — per-metric trends across unaided first drafts
// over time. The pane answers "am I getting better," never "is this
// draft good": points are CAPTURES (pass-invocation moments on eligible
// pieces, #31), not drafts-as-they-are-now, and only pieces whose
// frontmatter carries the stats keys appear — the keys grow only at
// capture time, so edited text can never feed the view. Rides
// PostsModel's watched scan; no scan of its own.
//
import Charts
import SwiftUI
struct TrendsPaneView: View {
var model: PostsModel
/// The captured pieces, oldest capture first — the arc's x-axis.
/// Same-second twins (cancel one pass, start another) tie-break on
/// title so the verdict's first→last stays deterministic — `sorted`
/// is not stable.
private var series: [Post] {
let captured = model.posts.compactMap { post in
post.firstDraftStats.map { (post: post, at: $0.captured) }
}
let ordered = captured.sorted { lhs, rhs in
if lhs.at != rhs.at {
return lhs.at < rhs.at
}
return lhs.post.title.localizedStandardCompare(rhs.post.title) == .orderedAscending
}
return ordered.map(\.post)
}
var body: some View {
VStack(spacing: 0) {
PaneHeader(title: "Trends") {
Text(series.count == 1 ? "1 capture" : "\(series.count) captures")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if series.isEmpty {
emptyState
} else {
ScrollView {
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 340), spacing: 12)],
spacing: 12,
) {
ForEach(TrendMetric.allCases, id: \.self) { metric in
MetricCard(metric: metric, series: series)
}
}
.padding(14)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
}
/// The Learnings-posture empty state: name how the data arrives.
private var emptyState: some View {
VStack(spacing: 8) {
Text("No measurements yet")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text(
"Stats capture the moment a Pass first meets an unaided draft — run Pass 1 or Pass 2 "
+ "on a writer piece still in First Draft, and the arc starts here.",
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// One metric's display facts: name, value rail, better-direction, and a
/// fixed y-domain so single captures stay visible and scales read the
/// same across sessions. Pure — pinned in TrendViewTests.
nonisolated enum TrendMetric: CaseIterable {
case burstiness
case typeTokenRatio
case sentenceVariation
case trigramRepetition
var title: String {
switch self {
case .burstiness: "Burstiness"
case .typeTokenRatio: "Type-Token Ratio"
case .sentenceVariation: "Sentence Variation"
case .trigramRepetition: "Trigram Repetition"
}
}
/// One plain-language line per term (#32 follow-up): the card's
/// always-visible gloss, below the chart. Names the metric's grain
/// and repeats which direction reads better.
var explain: String {
switch self {
case .burstiness:
"The swing between short and long sentences — higher means a livelier rhythm."
case .typeTokenRatio:
"Unique words ÷ total words — higher means a richer vocabulary."
case .sentenceVariation:
"How much sentence length changes from sentence to sentence — higher means more variety."
case .trigramRepetition:
"How often the same three-word runs repeat — lower means less recycled phrasing."
}
}
/// The honest per-metric hint: repetition is the one metric where
/// rising reads worse.
var higherIsBetter: Bool {
self != .trigramRepetition
}
func value(of stats: DraftStats) -> Double {
switch self {
case .burstiness: stats.burstiness
case .typeTokenRatio: stats.typeTokenRatio
case .sentenceVariation: stats.sentenceVariation
case .trigramRepetition: stats.trigramRepetition
}
}
/// Fixed where the metric has a natural range; sentence variation is
/// unbounded, so it scales to 1.2× the observed peak (floor 1) — a
/// single dot never flattens into an empty axis.
func domain(peak: Double) -> ClosedRange<Double> {
switch self {
case .burstiness: -1 ... 1
case .typeTokenRatio, .trigramRepetition: 0 ... 1
case .sentenceVariation: 0 ... max(peak * 1.2, 1)
}
}
/// First capture vs last: the pane's whole judgment, one honest word
/// (#32 AC — the arc, never a draft grade). Deltas inside the noise
/// band read steady: ±0.01 at three-decimal grain.
func verdict(first: Double, last: Double) -> TrendDirection {
let tolerance = 0.01
let delta = (last - first) * (higherIsBetter ? 1 : -1)
if delta > tolerance {
return .improving
}
if delta < -tolerance {
return .slipping
}
return .steady
}
}
/// The first→last read on one metric. Not a grade — a direction. Raw
/// values ARE the display words.
nonisolated enum TrendDirection: String {
case improving
case steady
case slipping
}
/// One metric's card: the chart plus the first→last readout that answers
/// "am I getting better." One capture shows its point with no verdict —
/// an arc needs two.
private struct MetricCard: View {
let metric: TrendMetric
let series: [Post]
private struct MetricPoint {
let captured: Date
let value: Double
}
/// Offset-keyed chart identity — two pieces can capture in the same
/// second (cancel one pass, start another); `id: \.self` would drop
/// the twin point silently.
private var marks: some ChartContent {
ForEach(Array(points.enumerated()), id: \.offset) { _, point in
LineMark(
x: .value("Captured", point.captured),
y: .value(metric.title, point.value),
)
.foregroundStyle(DesignTokens.accent)
PointMark(
x: .value("Captured", point.captured),
y: .value(metric.title, point.value),
)
.foregroundStyle(DesignTokens.accent)
}
}
private var points: [MetricPoint] {
series.compactMap { post in
post.firstDraftStats.map {
MetricPoint(captured: $0.captured, value: metric.value(of: $0.stats))
}
}
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .firstTextBaseline) {
Text(metric.title)
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
Spacer()
Text(metric.higherIsBetter ? "↑ better" : "↓ better")
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
Chart {
marks
}
.chartYScale(domain: metric.domain(peak: points.map(\.value).max() ?? 0))
.chartYAxis {
AxisMarks { _ in
AxisGridLine()
.foregroundStyle(DesignTokens.border)
AxisValueLabel()
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
.frame(height: 130)
.accessibilityLabel("\(metric.title) across \(points.count) captures")
readout
// #32 follow-up: the term's always-visible gloss — prose voice,
// distinct from the mono data lines above it.
Text(metric.explain)
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
}
.padding(14)
.background(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border),
)
}
/// mono-11 first→last line; the color carries the direction (accent up,
/// orange slipping — the stale-anchor deviation color, muted steady).
@ViewBuilder
private var readout: some View {
let values = points.map(\.value)
if values.count >= 2 {
let verdict = metric.verdict(first: values.first!, last: values.last!)
Text("\(Self.fmt(values.first!)) → \(Self.fmt(values.last!)) · \(verdict.rawValue)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(
verdict == .improving ? DesignTokens.accent : verdict == .slipping ? .orange : DesignTokens.muted,
)
} else if let only = values.first {
Text("\(Self.fmt(only)) · one capture")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
/// The store's %.3f grain — a period, never a localized comma.
private static func fmt(_ value: Double) -> String {
String(format: "%.3f", value)
}
}