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

+1
View File
@@ -23,6 +23,7 @@ Owned by the root AGENTS.md contract.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
- `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
+217
View File
@@ -0,0 +1,217 @@
//
// TrendViewTests.swift
// MuseionTests
//
// #32 (S5.2): the trend view's pure facts.
//
// ## Scenario: See the arc
// From user story #32 (PRD S5.2)
// Given pieces on disk whose unaided first drafts were stats-captured at
// pass invocation (writer origin, First Draft, post type — and only those)
// When the writer opens the Trends pane
// Then each of the four metrics reads as a line across captures over time
// with an honest first→last direction, and never-captured pieces (ai
// origin, outlines, edited before any pass) are absent BY CONSTRUCTION —
// the scan surfaces keys only `captureFirstDraftStats` ever writes, and
// the read-back re-gates on the capture gate's immutable pair, so the
// edited-text leak cannot reach the view through any path.
//
import Foundation
@testable import Museion
import Testing
struct TrendViewTests {
// MARK: Home fixtures (PostLibraryTests' temp-dir convention)
private func trendHome() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("trend-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
return home
}
/// Writes `post.md` under `projects/posts/<id>/` verbatim.
private func writeRaw(_ text: String, id: String, home: URL) throws {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try text.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
/// Writes a writer/post piece carrying ALL FIVE valid `stats_*` keys,
/// with per-key overrides for the case under test — the fixture's one
/// varying fact stays visible at the call site (finish-audit #32).
private func writeStamped(_ id: String, overriding: [String: String] = [:], home: URL) throws {
var keys: [String: String] = [
"type": "post",
"origin": "writer",
"pass_state": "First Draft",
"stats_captured": "2026-10-22T14:23:11",
"stats_burstiness": "-0.412",
"stats_type_token_ratio": "0.800",
"stats_sentence_variation": "0.400",
"stats_trigram_repetition": "0.100",
]
for (key, value) in overriding {
keys[key] = value
}
let block = keys.map { "\($0.key): \($0.value)" }.joined(separator: "\n")
try writeRaw("---\n\(block)\n---\n\nBody.\n", id: id, home: home)
}
// MARK: Scan reads the capture back (#32)
@Test
func `scan reads a real capture back — metric values and capture date`() throws {
let home = try trendHome()
let body = "One two three four. Five six seven! Eight nine ten eleven twelve?"
let post = try PostStore.writeNew(body: body, home: home)
#expect(PostStore.captureFirstDraftStats(id: post.id, body: body, home: home))
let read = Post.scan(home: home).first { $0.id == post.id }
let expected = DraftStats.compute(body: body)
let captured = try #require(read?.firstDraftStats)
// Store rounds to %.3f — compare at that grain, never exact.
#expect(abs(captured.stats.burstiness - expected.burstiness) < 0.0005)
#expect(abs(captured.stats.typeTokenRatio - expected.typeTokenRatio) < 0.0005)
#expect(abs(captured.stats.sentenceVariation - expected.sentenceVariation) < 0.0005)
#expect(abs(captured.stats.trigramRepetition - expected.trigramRepetition) < 0.0005)
// The parsed date round-trips through the exact stamp format — the
// symmetric-read proof, locale-independent by construction.
let onDisk = try Post.frontmatter(
of: String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"),
encoding: .utf8,
),
)["stats_captured"]
#expect(FixCardStore.formatted(captured.captured, "yyyy-MM-dd'T'HH:mm:ss") == onDisk)
}
@Test
func `never-captured pieces scan nil — absence by construction, not filtering`() throws {
let home = try trendHome()
// An ai-origin piece whose capture RAN: refused at the eligibility
// gate, no keys ever stamped — the leak path this AC pins shut.
let aiPiece = try PostStore.writeNew(body: "Mentor prose here.", origin: .ai, home: home)
#expect(!PostStore.captureFirstDraftStats(id: aiPiece.id, body: "Mentor prose here.", home: home))
// An outline and an untouched writer post: no keys either.
_ = try PostStore.writeNew(body: "- one\n- two", type: .outline, home: home)
_ = try PostStore.writeNew(body: "Never passed.", home: home)
for post in Post.scan(home: home) {
#expect(post.firstDraftStats == nil)
}
}
@Test
func `partial or malformed stats keys never half-load`() throws {
let home = try trendHome()
// These fixtures vary key PRESENCE, so they write raw blocks.
try writeRaw(
"""
---
type: post
stats_captured: 2026-10-22T14:23:11
stats_burstiness: -0.412
---
Body.
""",
id: "partial", home: home,
)
try writeRaw(
"""
---
type: post
stats_captured: not-a-date
stats_burstiness: -0.412
stats_type_token_ratio: 0.800
stats_sentence_variation: 0.400
stats_trigram_repetition: 0.100
---
Body.
""",
id: "bad-date", home: home,
)
for post in Post.scan(home: home) {
#expect(post.firstDraftStats == nil)
}
}
@Test
func `non-finite stats values never load`() throws {
// Finish-audit #32: `Double("nan")` and `Double("inf")` DO parse —
// every other key valid so ONLY the finiteness guard trips. A
// non-finite peak traps the chart's y-domain (`0 ... max(nan, 1)`)
// and a NaN delta reads "steady" in the verdict.
let home = try trendHome()
try writeStamped("nan-peak", overriding: ["stats_burstiness": "nan"], home: home)
try writeStamped("inf-ratio", overriding: ["stats_type_token_ratio": "inf"], home: home)
for post in Post.scan(home: home) {
#expect(post.firstDraftStats == nil)
}
}
@Test
func `read-back gates on the immutable pair — imported ai or outline pieces never render`() throws {
// `stats_*` keys CAN arrive by import (external YAML rides verbatim)
// — the read-back gate is the capture gate's immutable pair (origin
// writer, type post), NOT pass_state (it legitimately advances).
let home = try trendHome()
try writeStamped("ai-stamped", overriding: ["origin": "ai"], home: home)
try writeStamped("outline-stamped", overriding: ["type": "outline"], home: home)
// A migrated writer post keeps its real arc — pair right, state advanced.
try writeStamped("migrated-writer", overriding: ["pass_state": "Pass-1 Done"], home: home)
let posts = Post.scan(home: home)
#expect(posts.first { $0.id == "ai-stamped" }?.firstDraftStats == nil)
#expect(posts.first { $0.id == "outline-stamped" }?.firstDraftStats == nil)
#expect(posts.first { $0.id == "migrated-writer" }?.firstDraftStats != nil)
}
// MARK: The pure read: direction and scale (TrendMetric)
@Test
func `verdict reads first → last, honoring each metric's better-direction`() {
// A higher-is-better metric (burstiness): the raw delta decides.
#expect(TrendMetric.burstiness.verdict(first: 0.1, last: 0.2) == .improving)
#expect(TrendMetric.burstiness.verdict(first: 0.2, last: 0.1) == .slipping)
#expect(TrendMetric.burstiness.verdict(first: 0.1, last: 0.105) == .steady)
// Trigram repetition is the inverted metric: falling reads improving.
#expect(TrendMetric.trigramRepetition.verdict(first: 0.5, last: 0.2) == .improving)
#expect(TrendMetric.trigramRepetition.verdict(first: 0.2, last: 0.5) == .slipping)
#expect(TrendMetric.trigramRepetition.verdict(first: 0.2, last: 0.205) == .steady)
// Exactly AT the tolerance reads steady — the comparisons are
// strict (0 and 0.01/0.02 are exact-representable, so the delta
// equals the band rather than approximating it).
#expect(TrendMetric.burstiness.verdict(first: 0, last: 0.01) == .steady)
#expect(TrendMetric.burstiness.verdict(first: 0, last: 0.02) == .improving)
}
@Test
func `y-domains keep a single capture visible and scales comparable`() {
#expect(TrendMetric.burstiness.domain(peak: 0.9) == -1 ... 1)
#expect(TrendMetric.typeTokenRatio.domain(peak: 1) == 0 ... 1)
#expect(TrendMetric.trigramRepetition.domain(peak: 0.3) == 0 ... 1)
// Sentence variation is unbounded: the domain scales to the peak…
let scaled = TrendMetric.sentenceVariation.domain(peak: 1.5).upperBound
#expect(abs(scaled - 1.8) < 0.001)
// …but never flattens below 1 while the arc is small.
#expect(TrendMetric.sentenceVariation.domain(peak: 0.3) == 0 ... 1)
}
@Test
func `every metric carries a distinct plain-language gloss`() {
let glosses = Set(TrendMetric.allCases.map(\.explain))
// One non-empty line each, no two metrics sharing a gloss — a
// fifth metric added without its explain fails here.
#expect(glosses.count == TrendMetric.allCases.count)
for gloss in glosses {
#expect(!gloss.isEmpty)
#expect(gloss.contains("higher means") || gloss.contains("lower means"))
}
}
}