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
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (5336 symbols, 20660 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **museion** (5420 symbols, 21204 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
@@ -190,6 +190,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) |
|
||||
| 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) |
|
||||
| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) |
|
||||
| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) |
|
||||
@@ -199,5 +200,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) |
|
||||
| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) |
|
||||
| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) |
|
||||
| 2026-10-22 | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) |
|
||||
<!-- write-log: window-end -->
|
||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **stats:** Trend view — the writer's arc (PRD S5.2) — 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, each card carrying an honest first→last read (`improving`/`steady`/`slipping` at ±0.01, direction inverted for trigram repetition — the one ↓-better metric; one capture shows its value with no verdict) plus the per-metric ↑/↓-better hint and a one-line plain-language gloss of the term beneath each chart (grain + better-direction, pinned distinct). Points are capture moments, never draft grades — the pane answers "am I getting better," not "is this draft good." 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) — so ai-origin pieces, outlines, edited-before-first-pass drafts, and imported or hand-edited frontmatter (non-finite values, stamped ai pieces) carry nothing to show, while a migrated writer piece keeps its real arc. The pane rides PostsModel's watched scan (no scan of its own, refreshes with the library); fixed y-domains keep single captures visible (sentence variation scales to its peak); the empty state names how the data arrives (issue #32)
|
||||
|
||||
- **mentor:** Blind Read — writer-triggered advisory A/B judgment (#122, decision #120) — a purposeful "Blind Read" button beside Run Pass in the pass bar judges the current document against the Pass-start snapshot (the newest `passes/pass-N.md` on disk): both versions travel INLINE in one prompt under neutral A/B position labels with randomized order (origin words never appear — the judge can't know which is the rewrite), a fresh one-shot engine on the same `museion` chat profile renders its pick + one-line reason into the transient transcript, and the A/B↔origin reveal lands only AFTER the verdict so it can never leak; cancelled, refused, and spawn-failed turns reveal nothing. Advisory-only per #120: nothing advances, no cards, no Learnings, the roster never grows — the verdict dies with the transcript and the writer stays judge of record. Honest refusals: no snapshot yet ("run a Pass first"), an unchanged document ("No edits since…"), or a busy rail (passes and reads refuse each other; one Cancel ends either). The pass engine's spawn/session/teardown block became one shared `runOneShot` rail (failure rows speak the run's own name), the fake ACP gained a prompt-log observable, and the GLOSSARY "Blind Read" term landed. Finish-audit (3 reviewers) fixed the refusal-reveal gate (a refusal still ends `.ended` — gate on the stopReason; flip-verified), the hardcoded "Pass failed" copy, and pinned the Cancel/exclusivity rail. Suite 500 (issue #122)
|
||||
|
||||
- **mentor:** Native deslop lint at pass invocation (PRD S3.4) — running a pass now computes the deslop skill's deterministic findings (banned-vocab tiers + em-dash density) natively in Swift at the invocation — after first-draft stats capture, before the engine turn, no engine round-trip — and each finding lands as a real fix card (emitter `lint`) under `<piece>/cards/`, rendered by the existing Fix Cards palette with ask-before Apply on mechanical mapping cards (mapped phrases like `utilize`→`use` carry the replacement; unmapped ones land demonstration for judgment). One card per phrase over its tier allowance, case-insensitive whole-word matching (`delved` never fires `delve`), anchor = the first match with case preserved, em-dash density card first when over budget, tiers ranked by first match. The tier data ships as `Resources/deslop-lint.json` mirroring the deslop doctrine verbatim (`key`/`landscape`/`highlight`/bare `underscore` deliberately omitted as POS-ambiguous — add via `<home>/deslop-lint.json`, which wins whenever it exists and decodes); emit dedups against OPEN cards before submit so re-runs make progress (closed cards never block) and the engine never re-cards a live lint finding. A failed lint never blocks the pass (the stats-capture posture). Suite 487 (issue #6)
|
||||
|
||||
+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).
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
# M4: Trend view (S5.2)
|
||||
|
||||
> **Date:** 2026-10-31
|
||||
> **Type:** issue
|
||||
> **Reference:** Gitea issue #32 (AlexKucera/Museion), PRD S5.2; blocked-by #31 (closed)
|
||||
|
||||
## Goal
|
||||
|
||||
The writer sees per-metric trends across unaided first drafts over time — the view
|
||||
answers "am I getting better," never "is this draft good." Only stats-eligible
|
||||
drafts feed it: the edited-text leak must be impossible by construction, not by
|
||||
filtering.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- `Museion/TrendsPaneView.swift` (new) — the Trends pane: one Swift Charts
|
||||
`LineMark`+`PointMark` card per metric (adaptive ≥340 2-col grid), a mono-11
|
||||
`first → last · improving/steady/slipping` readout at ±0.01 (direction
|
||||
inverted for trigram repetition — the one ↓-better metric), per-metric ↑/↓
|
||||
hint, a plain-language gloss line beneath each chart (user follow-up
|
||||
request), fixed y-domains (burstiness −1…1, TTR + trigram 0…1,
|
||||
sentenceVariation 1.2× peak, floor 1). Offset-keyed chart identity and a
|
||||
title tie-break make same-second capture twins deterministic.
|
||||
- `Museion/PostLibrary.swift` — `Post.firstDraftStats: FirstDraftStats?`:
|
||||
`Post.scan` reads the five `stats_*` keys back, nil unless every key parses
|
||||
to a FINITE Double, and only when the piece carries the capture gate's
|
||||
immutable pair (origin writer, type post). Origin/type decode hoisted to
|
||||
locals so the gate and the Post fields share one decode.
|
||||
- `Museion/WorkspaceView.swift` — rail destination `Trends`
|
||||
(`chart.xyaxis.line`, after Learnings — measurement beside memory).
|
||||
- `Museion/DraftStats.swift` — `Equatable` re-added (#31 removed it as unused;
|
||||
Post's synthesized equality rides `firstDraftStats`).
|
||||
- Tests: `MuseionTests/TrendViewTests.swift` (new, `@Suite`) — 9 tests:
|
||||
real-capture round-trip (%.3f grain + stamp-format date proof), absence by
|
||||
construction, partial/malformed keys, non-finite values, read-back gate
|
||||
(imported ai/outline pieces with hand-stamped keys scan nil; a Pass-1-Done
|
||||
writer piece keeps its arc), verdict pins incl. the exact ±0.01 boundary,
|
||||
y-domains, distinct glosses. Non-finite + gate pins flip-verified (each
|
||||
fails on its own guard).
|
||||
- Docs: `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `CHANGELOG.md`.
|
||||
- Finish-audit (3 reviewers: ponytail / security / general) — accepted and
|
||||
fixed: the nan/inf crash (security MEDIUM, reproduced), the import leak
|
||||
(read-back gate), same-second twin ordering, ponytail cuts (injectable
|
||||
`tolerance` param, `TrendDirection.label` switch → String rawValue, dead
|
||||
`?? .distantPast` fallbacks). Deferred: the x-axis ordering pin (comparator
|
||||
lives inside the View; extraction for one comparator isn't worth it).
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Read-back gate = origin writer + type post, NOT pass_state | Import carries external `stats_*` verbatim (reviewer finding), so presence alone overstated "by construction". The immutable pair mirrors the capture gate exactly; pass_state legitimately advances after the first capture, so gating on First Draft would hide every real arc. A migrated writer piece keeps its history. |
|
||||
| `isFinite` on every parsed metric key | `Double("nan")`/`"inf")` parse; a non-finite sentenceVariation peak traps `0 ... max(nan, 1)` in `chartYScale` — a deterministic crash from one imported file. One guard at the parse point every consumer (chart, verdict, readout) routes through. |
|
||||
| Pane rides `PostsModel.posts` (the watched scan) | Zero new scan/watcher machinery; refreshes with the library for free. |
|
||||
| Verdict = first→last, one word, ±0.01 noise band | The AC asks for the arc, never a draft grade. Strict comparisons pinned at exactly the tolerance. |
|
||||
| Gloss line below each chart, not tooltips | User-requested shape ("text below the graphs"); always visible beats hover-discovery for terms learned once. Copy pinned distinct + direction-bearing. |
|
||||
| Fixed y-domains; variation scales to peak | A single capture's dot never flattens into an empty axis; scales stay comparable across sessions. |
|
||||
| Per-access POSIX DateFormatter for the stamp parse | Repo convention (no non-Sendable statics); symmetric with `FixCardStore.formatted` on the write side. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| `Double?.filter(\.isFinite)` does not compile | Optional has no `filter` in the stdlib (reviewer-suggested shape) | Explicit `guard let value = Double(raw), value.isFinite`; reviewer remediations are guesses until probed |
|
||||
| Type-checker timeout on the series chain | compactMap→sorted→map over tuples with an inline ternary comparator | Broken into `captured`/`ordered` sub-expressions with labeled tuple elements |
|
||||
| Scripted flip-restore nested a function declaration inside itself | The restore replaced the flipped BODY line with the whole function decl | Repaired by patch; the build-first check caught it before a wasted suite run — exactly the failure mode finish-audit warns about |
|
||||
| Executed-count pipes failing in background shells | The rtk wrapper mangles `ls`/xcresulttool output; `ls` prints dirs with trailing colons | Read counts in the foreground with an explicit xcresult path (`ls -td`) |
|
||||
| Suite-log greps counting 0 passed | Swift Testing logs `Test "x" passed`, not XCTest's `Test case` | Authoritative counts always from `xcresulttool get test-results summary` |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/TrendsPaneView.swift` | New — the pane, TrendMetric, TrendDirection, MetricCard |
|
||||
| `Museion/PostLibrary.swift` | `Post.FirstDraftStats` (finite-parse), scan read-back + origin/type gate |
|
||||
| `Museion/WorkspaceView.swift` | `.trends` pane case + rail button |
|
||||
| `Museion/DraftStats.swift` | `Equatable` re-added |
|
||||
| `MuseionTests/TrendViewTests.swift` | New — 9 tests incl. 2 flip-verified audit pins |
|
||||
| `Museion/AGENTS.md` / `MuseionTests/AGENTS.md` | DOX pass — file entries, gate/gloss facts, pin inventory |
|
||||
| `CHANGELOG.md` | Unreleased → added: trend view |
|
||||
| `AGENTS.md` (root) | GitNexus index-counter line (its own `analyze` output) |
|
||||
|
||||
## Verification
|
||||
|
||||
- Build: `xcodebuild … build` **SUCCEEDED**, no new warnings.
|
||||
- Full unit suite (sequential, executed count from xcresult): **508/508**
|
||||
(500 at #122 + 8 new; the 9th test folds into an existing pin set).
|
||||
- SwiftFormat: 0/102 files require formatting. SwiftLint: all touched files
|
||||
clean (the 2 WorkspaceView warnings predate the session — verified against
|
||||
HEAD).
|
||||
- Flip cycle: finiteness guard + read-back guard batched off → exactly the
|
||||
two pins failed, each on its own guard; restored → green.
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] X-axis ordering pin deferred — the comparator lives inside the View;
|
||||
extract only if a second consumer ever needs the ordered series.
|
||||
- [ ] Pre-existing lint ceilings (PostsModelTests/PostStoreTests file length,
|
||||
WorkspaceView file length) — own extraction ticket.
|
||||
- [ ] `MuseionUITests.testAppLaunches` still fails environmentally
|
||||
("Failed to activate application") — pre-existing, per the #31 log.
|
||||
- [ ] v2 parking lot: periodization — trends naming the dominant persistent
|
||||
weakness + the matching drill (PRD v2 lot, idea ⑫).
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -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-31 | issue | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | #32 trend view: four metric charts over first-draft captures, read-back origin/type gate + finite parse; audit fixed nan/inf crash — 508 tests |
|
||||
| 2026-10-30 | issue | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | #122 Blind Read: advisory whole-document A/B on a fresh museion session, randomized unlabeled pair, reveal after verdict; 500 tests |
|
||||
| 2026-10-30 | issue | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | #6 native deslop lint: banned-vocab tiers + em-dash budget as data, emitter-lint cards at pass invocation; audit fixes — 489 tests |
|
||||
| 2026-10-30 | issue | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) | #1 prompt-end constraints: ACP audit, draft-first-rules-last persona pin, layout factsheet, real-run verify |
|
||||
|
||||
Reference in new issue
Block a user