// // 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//` 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")) } } }