feat(stats): trend view — the writer's arc (#32)
CI / ci (push) Canceled after 0s
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:
1 parent
97e86cf62d
commit
3ee6756467
11 files changed
+679
-8
No files matched your search
+4
-3
@@ -21,11 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 titLine truncated
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media querieLine truncated
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc.
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
|
||||
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`).
|
||||
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
|
||||
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
|
||||
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
|
||||
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
|
||||
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
|
||||
|
||||
@@ -15,7 +15,7 @@ import Foundation
|
||||
/// precision; rounding to three decimals happens only at store time
|
||||
/// (`PostStore.captureFirstDraftStats`, `String(format: "%.3f")` — a
|
||||
/// period, never a localized comma). Empty input is all zeros, never NaN.
|
||||
nonisolated struct DraftStats {
|
||||
nonisolated struct DraftStats: Equatable {
|
||||
/// (σ − μ) / (σ + μ) over sentence token counts — Bousso-style
|
||||
/// burstiness; 0 when there are no sentences at all. A single
|
||||
/// sentence → σ = 0 → −1 (correct: maximally regular).
|
||||
|
||||
@@ -28,10 +28,64 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
var project: String
|
||||
/// True when the piece lives under archive/ (#107).
|
||||
var isArchived: Bool
|
||||
/// #32 (S5.2): the captured first-draft stats — present ONLY when
|
||||
/// `captureFirstDraftStats` stamped the piece at a pass invocation
|
||||
/// (writer origin, First Draft, post type, decided there against the
|
||||
/// file's own frontmatter), and read back only for the same immutable
|
||||
/// pair (scan's gate — see `Post.scan`). Presence is the trend view's
|
||||
/// whole eligibility story: app-internal edit paths never grow these
|
||||
/// keys, and non-writer or outline pieces never render them.
|
||||
var firstDraftStats: FirstDraftStats?
|
||||
|
||||
/// New pieces land here when no project is selected (#107).
|
||||
static let defaultProject = "posts"
|
||||
|
||||
/// One stats capture, read back from the five flat `stats_*`
|
||||
/// frontmatter keys (#31 wrote them; #32 reads them back).
|
||||
nonisolated struct FirstDraftStats: Equatable {
|
||||
/// When the pass invocation captured the draft
|
||||
/// (`yyyy-MM-dd'T'HH:mm:ss`, lexically sortable — #31's stamp).
|
||||
let captured: Date
|
||||
let stats: DraftStats
|
||||
|
||||
/// Nil unless EVERY key parses to a finite Double — a half-loaded
|
||||
/// arc would lie, and `Double("nan")`/`Double("inf")` DO parse:
|
||||
/// a non-finite peak traps the chart's y-domain construction and
|
||||
/// reads "steady" in the verdict (finish-audit #32).
|
||||
init?(frontmatter: [String: String]) {
|
||||
guard
|
||||
let captured = frontmatter["stats_captured"].flatMap(Self.parseCaptured),
|
||||
let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
|
||||
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
|
||||
let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite),
|
||||
let trigramRepetition = frontmatter["stats_trigram_repetition"].flatMap(Self.finite)
|
||||
else { return nil }
|
||||
self.captured = captured
|
||||
stats = DraftStats(
|
||||
burstiness: burstiness,
|
||||
typeTokenRatio: typeTokenRatio,
|
||||
sentenceVariation: sentenceVariation,
|
||||
trigramRepetition: trigramRepetition,
|
||||
)
|
||||
}
|
||||
|
||||
/// The symmetric read of the capture stamp (`FixCardStore.formatted`,
|
||||
/// local time) — per-access formatter, the repo's no-static convention.
|
||||
private static func parseCaptured(_ stamp: String) -> Date? {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
return formatter.date(from: stamp)
|
||||
}
|
||||
|
||||
/// Frontmatter is external data (hand-edits, imports): reject the
|
||||
/// non-finite doubles Swift's `Double(String)` happily parses.
|
||||
private static func finite(_ raw: String) -> Double? {
|
||||
guard let value = Double(raw), value.isFinite else { return nil }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// The two roots that hold pieces, in resolution order (#107): projects/
|
||||
/// is searched before archive/.
|
||||
static let containerRoots = ["projects", "archive"]
|
||||
@@ -89,15 +143,26 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8), seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
posts.append(
|
||||
Post(
|
||||
id: dir.lastPathComponent,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer,
|
||||
type: ContentType(rawValue: frontmatter["type"] ?? "") ?? .post,
|
||||
origin: origin,
|
||||
type: type,
|
||||
project: projectDir.lastPathComponent,
|
||||
isArchived: isArchived,
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,10 @@ struct WorkspaceView: View {
|
||||
case posts
|
||||
case sessions
|
||||
case learnings
|
||||
/// #32 (S5.2): the trend view — the writer's arc across unaided
|
||||
/// first-draft captures, sibling of Learnings (measurement beside
|
||||
/// memory).
|
||||
case trends
|
||||
/// #108: the archive rail destination — archive/ as a first-class
|
||||
/// pane (prototype variant B/C verdict: a destination, not a
|
||||
/// library disclosure).
|
||||
@@ -211,6 +215,10 @@ struct WorkspaceView: View {
|
||||
// #26: list-only pane over <home>/learnings/ — read side;
|
||||
// promoting a fix card (the fix-card rail) writes the files.
|
||||
LearningsPaneView(home: gate.museionHome)
|
||||
case .trends:
|
||||
// #32 (S5.2): the arc — rides PostsModel's watched scan, so
|
||||
// the pane refreshes with the library, no scan of its own.
|
||||
TrendsPaneView(model: gate.posts)
|
||||
case .archive:
|
||||
// #108: list-only pane — clicking a row selects the piece and
|
||||
// hops to Posts where its editor lives.
|
||||
@@ -249,6 +257,8 @@ struct WorkspaceView: View {
|
||||
RailButton(pane: .posts, selection: $selection, label: "Posts", systemImage: "doc.text")
|
||||
RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left")
|
||||
RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube")
|
||||
// #32: Trends after Learnings — measurement beside memory.
|
||||
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
|
||||
Spacer()
|
||||
// #108: Archive at the rail bottom, above Settings (prototype's
|
||||
// box icon).
|
||||
|
||||
Reference in new issue
Block a user