diff --git a/AGENTS.md b/AGENTS.md index 6f0323d..63f6858 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (4323 symbols, 15235 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** (4372 symbols, 15690 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). @@ -173,6 +173,14 @@ This project is indexed by GitNexus as **museion** (4323 symbols, 15235 relation +## Project Learnings + + + +### Testing +- Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) +- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31) + ## Session Logs Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent: @@ -180,6 +188,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md) | | 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | | 2026-10-22 | [20261022-issue29-research-library-light_log.md](docs/devlog/20261022-issue29-research-library-light_log.md) | | 2026-10-22 | [20261022-issue28-session-lifecycle-ui_log.md](docs/devlog/20261022-issue28-session-lifecycle-ui_log.md) | @@ -189,5 +198,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) | | 2026-10-20 | [20261020-issue24-pass-guard-matrix_log.md](docs/devlog/20261020-issue24-pass-guard-matrix_log.md) | | 2026-10-20 | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](docs/devlog/20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) | -| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 44f5d84..95cd2e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format ### Added +- **stats:** First-draft stats capture (PRD S5.1) — running Pass 1 or Pass 2 on an unaided draft (writer-origin, First Draft Pass State, post type) computes four style metrics natively in Swift at the invocation — before the mentor sees anything — and stamps `stats_captured` plus four `stats_*` values into the piece's frontmatter, so the coming trend view is a scan of `posts/`; a cancelled pass keeps its capture, re-runs while still First Draft overwrite (latest draft wins), and the frontmatter write paths (pass completion, editor save) now update their keys in place instead of rebuilding the block — captured stats and foreign YAML survive (issue #31) - **sessions:** New Post from Session & drill offers (PRD S2.7/S2.8) — a freeform Session births a Post: "New Post" in the Sessions pane opens an ask-before sheet prefilled with the session's last mentor reply (editable, G9), and ONE confirm materializes the piece under `projects/posts/` stamped `origin: ai` — immutable frontmatter, never stats-eligible — and opens it in Posts; a failed write keeps the sheet up with the reason inline and the draft intact. "New Brainstorm" is a session started with an opener prompt (session flavor, no new machinery). The freeform composer (input + liveness + Stop) moved into the shared `SessionTranscriptView`, so both session surfaces are conversations; session-born pieces and the resume rail are pinned (issue #30). Resume now speaks the REAL adapter wire: 0.21.5 answers `session/load` with `_meta.hermes.sessionProvenance.acpSessionId` and no top-level `sessionId` — resume accepts both shapes (live-probed; every prior real-engine resume misread as "unknown") (issue #30) - **mentor:** Research & library-light (PRD S8, G9) — the mentor researches mid-pass and its findings arrive as candidate source-notes with provenance inside their Session: a third museion-tools tool `submit_research_notes` is the typed rail (decode-validate only, replies `{"received": N}`, writes NOTHING — the session is the holding area), candidates ride the transcript as full cards parsed by payload shape (the `notes` array routes before the fix-card parse; titles are display text), and resume re-materializes them for free from the engine's replay (engine-owned cargo, ADR-0007 — dispositions reset honestly). The writer curates in place: Keep opens the ask-before sheet and ONE confirm lands one plain markdown note with provenance (`source`/`kept` frontmatter) into the piece's `research/` — anchored through the one `folder(of:)` id lookup, a symlinked `research/` refuses, collision -2; Reject vanishes, recording nothing. The pass prompt names the rail and forbids the engine writing candidates itself; kept notes flip `hasResearch`, so every later pass consults the library (issue #29) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 4db3b4c..f06a054 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -24,9 +24,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `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 \" 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 `/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 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). - `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///post.md` AND `archive///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). -- `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//` — 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), `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 disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — 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//`), 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 `/passes/pass-.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; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws). **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. +- `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//` — 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 disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — 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//`), 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 `/passes/pass-.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 is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. +- `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`). - `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). -- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#28: `mentor.beginPassSession(kind:pieceTitle:)` — every pass auto-creates its Session (wire session/new, rostered "Pass N · \", activated; the `runningPass` flag goes live only AFTER these awaits — setting it earlier left a window where the #124 Cancel pin could observe the flag with `isStreaming` still false and the cancel refused, the turn hung)** → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · ")` (the label renders, the wire stub never lands; the prompt lands in the pass's OWN session) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#28: `mentor.beginPassSession(kind:pieceTitle:)` — every pass auto-creates its Session (wire session/new, rostered "Pass N · \<title\>", activated; the `runningPass` flag goes live only AFTER these awaits — setting it earlier left a window where the #124 Cancel pin could observe the flag with `isStreaming` still false and the cancel refused, the turn hung)** → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · <title>")` (the label renders, the wire stub never lands; the prompt lands in the pass's OWN session) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). - `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here. - `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions. - `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam). diff --git a/Museion/DraftStats.swift b/Museion/DraftStats.swift new file mode 100644 index 0000000..7829f95 --- /dev/null +++ b/Museion/DraftStats.swift @@ -0,0 +1,88 @@ +// +// DraftStats.swift +// Museion +// +// #31 (S5.1): the four unaided-first-draft style stats (CONTEXT.md +// 'Unaided First Draft') — computed natively in Swift from the exact +// text a pass is about to see, so the trend view (S5.2) tracks the +// writer's own draft, never AI-assisted text. Pure Foundation, +// deterministic: same body in, same stats out. +// + +import Foundation + +/// One piece's first-draft style metrics (#31). `compute` returns FULL +/// 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 { + /// (σ − μ) / (σ + μ) over sentence token counts — Bousso-style + /// burstiness; 0 when there are no sentences at all. A single + /// sentence → σ = 0 → −1 (correct: maximally regular). + let burstiness: Double + /// Unique tokens / total tokens; 0 when the body has no tokens. + let typeTokenRatio: Double + /// σ / μ over sentence token counts; 0 when μ = 0. + let sentenceVariation: Double + /// (total − unique) / total over consecutive token triples; 0 when + /// there are fewer than three tokens. + let trigramRepetition: Double + + /// #31 (S5.1): the four stats over `body` — the text the engine is + /// about to see. Sentences are chunks between `.`, `!`, `?`; each + /// chunk's token count is one sentence length when > 0 (the split + /// never looks at newlines, so leading heading text gloms into the + /// first sentence). σ is the POPULATION stddev. + static func compute(body: String) -> DraftStats { + let allTokens = tokens(in: body) + let lengths = body + .split(whereSeparator: { $0 == "." || $0 == "!" || $0 == "?" }) + .map { tokens(in: String($0)).count } + .filter { $0 > 0 } // adjacent/trailing terminators are not sentences + + let typeTokenRatio = allTokens.isEmpty ? 0 : Double(Set(allTokens).count) / Double(allTokens.count) + + // Consecutive triples keyed by content: [a b c][b c a]… — the + // repeated-opener tell. + let tripleCount = max(allTokens.count - 2, 0) + var trigramRepetition = 0.0 + if tripleCount > 0 { + var unique: Set<ArraySlice<String>> = [] + for start in 0 ..< tripleCount { + unique.insert(allTokens[start ..< start + 3]) + } + trigramRepetition = Double(tripleCount - unique.count) / Double(tripleCount) + } + + var burstiness = 0.0 + var sentenceVariation = 0.0 + if !lengths.isEmpty { + // lengths filter to > 0 above, so mean ≥ 1 and σ + mean > 0 + // always — no NaN path past this point (audit: two guards that + // could never fire were deleted here, #31 finish-audit). + let mean = Double(lengths.reduce(0, +)) / Double(lengths.count) + let sigma = sqrt(lengths.reduce(0) { + let delta = Double($1) - mean + return $0 + delta * delta + } / Double(lengths.count)) + sentenceVariation = sigma / mean + burstiness = (sigma - mean) / (sigma + mean) + } + + return DraftStats( + burstiness: burstiness, + typeTokenRatio: typeTokenRatio, + sentenceVariation: sentenceVariation, + trigramRepetition: trigramRepetition, + ) + } + + /// Lowercased runs of Characters where isLetter || isNumber — the + /// one tokenizer both the TTR and the sentence lengths ride. + /// ponytail ceiling: no apostrophe joining — "writer's" is two tokens + /// (writer + s); a contraction-aware tokenizer is the upgrade path if + /// the numbers ever need finer grain. + private static func tokens(in text: String) -> [String] { + text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map { $0.lowercased() } + } +} diff --git a/Museion/LearningDecay.swift b/Museion/LearningDecay.swift index 49254e5..9ec84d4 100644 --- a/Museion/LearningDecay.swift +++ b/Museion/LearningDecay.swift @@ -184,11 +184,14 @@ nonisolated enum LearningDecay { /// insert absent ones before the closing `---`, preserve every other /// line verbatim (leading hand-edit lines above the opening `---` /// included), keep the block's trailing newline. No frontmatter - /// block at all → prepend a fresh one. + /// block at all → prepend a fresh one. Internal since #31: the + /// first-draft stats capture is the third caller. // ponytail: PostStore.mergedFrontmatter's line-walk duplicated and - // generalized — extracting the shared walk would grow PostStore at its - // type-body ceiling; do it when a third caller appears. - private static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String { + // generalized — extraction would grow PostStore at its type-body + // ceiling; #31's capture is the third caller and it STILL isn't + // extracted (LearningDecay + PostStore stay the two owners; the + // type-body ceilings named above are unchanged). + static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String { let (block, body) = PostStore.splitFrontmatter(text) guard !block.isEmpty else { return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index c2f7d83..6ec9088 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -273,13 +273,25 @@ nonisolated enum PostStore { /// Save an existing Post: body-only text in, file normalized out. The /// file's present `pass_state`/`origin`/`type` are preserved (origin - /// immutable, CONTEXT.md; bare corpus posts normalize on save, #59). A - /// vanished post throws — `writeNew` is the only creator; saving must - /// never resurrect a deleted post with reset metadata. + /// immutable, CONTEXT.md; bare corpus posts normalize on save, #59). + /// **#31 audit fix: blocked files update the three owned keys IN PLACE + /// (stampingFrontmatter) and swap in the caller's body — the old + /// stamped() round-trip rebuilt the block from three parsed fields, + /// erasing the first-draft stats captured at the pass invocation and + /// any foreign frontmatter on every editor save.** A vanished post + /// throws — `writeNew` is the only creator; saving must never + /// resurrect a deleted post with reset metadata. static func overwrite(id: String, body: String, home: URL) throws { let piece = try existingStamp(id: id, home: home) - try stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type) - .write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) + let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8) + let text = try PostStore.splitFrontmatter(raw).block.isEmpty + ? stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type) + : PostStore.splitFrontmatter(LearningDecay.stampingFrontmatter(of: raw, with: [ + ("type", piece.type.rawValue), + ("pass_state", piece.passState.rawValue), + ("origin", piece.origin.rawValue), + ])).block + body + try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } /// #114: the shared read behind `overwrite` and `convert` — resolve the @@ -598,14 +610,21 @@ nonisolated extension PostStore { /// #24 (S3.1): advance `pass_state` when a pass completes. Monotonic: /// the new state is the higher of the file's current state and the /// pass's doneState — passes run in ANY order, so a Pass 1 completing - /// on a Pass-2 Done piece never regresses it. Body/origin/type ride the - /// existingStamp→stamped round-trip unchanged (same preservation as - /// `overwrite`). Returns the state now stamped. A vanished piece throws. + /// on a Pass-2 Done piece never regresses it. **#31 (S5.1): the state + /// update is an IN-PLACE key stamp (stampingFrontmatter), not the + /// existingStamp→stamped block rewrite — the rewrite carried only + /// type/pass_state/origin and silently erased the first-draft stats + /// captured at the invocation (and any foreign frontmatter).** Bare + /// posts (no block) still normalize through the full #59 stamp. + /// Returns the state now stamped. A vanished piece throws. static func advancePassState(id: String, kind: PassKind, home: URL) throws -> Post.PassState { let piece = try existingStamp(id: id, home: home) let advanced = higherState(piece.passState, kind.doneState) - try stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type) - .write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) + let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8) + let text = try PostStore.splitFrontmatter(raw).block.isEmpty + ? stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type) + : LearningDecay.stampingFrontmatter(of: raw, with: [("pass_state", advanced.rawValue)]) + try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) // The decay clock counts completed passes per content type (#27). // try?: a failed clock bump must never fail a completed pass, and // a lagging clock only delays resurfacing (safe direction). @@ -682,3 +701,47 @@ nonisolated extension PostStore { return name } } + +// MARK: First-draft stats capture (#31) + +/// #31 (S5.1): the unaided-first-draft capture write side (CONTEXT.md +/// 'Unaided First Draft'). Same file as the pass substrate: the enum's +/// private helpers (folder(of:)) stay reachable at file scope. +nonisolated extension PostStore { + /// Compute the four `DraftStats` over `body` and stamp them into the + /// piece's frontmatter — runPass fires this at the invocation, before + /// the prompt crosses the bridge. Eligibility is decided by the FILE's + /// own frontmatter alone (same lenient defaults as Post.scan — a bare + /// legacy post qualifies): origin writer, Pass State First Draft, type + /// post. Not eligible → false, file untouched. The stamp is in place + /// (stampingFrontmatter): every non-stats line byte-identical, so a + /// re-invocation while still First Draft overwrites — latest draft + /// state wins. Any read/write failure → false: a failed capture must + /// never fail the pass (the decay-clock posture). + @discardableResult + static func captureFirstDraftStats(id: String, body: String, home: URL) -> Bool { + guard let dir = folder(of: id, home: home), + let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) + else { return false } + let matter = Post.frontmatter(of: text) + // ponytail: third copy of the lenient `?? default` stamp decode + // (Post.scan, existingStamp) — extract one shared decode when a + // fourth caller needs it. + guard Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer == .writer, + Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft == .firstDraft, + Post.ContentType(rawValue: matter["type"] ?? "") ?? .post == .post + else { return false } + let stats = DraftStats.compute(body: body) + let stamped = LearningDecay.stampingFrontmatter(of: text, with: [ + ("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable + ("stats_burstiness", String(format: "%.3f", stats.burstiness)), + ("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)), + ("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)), + ("stats_trigram_repetition", String(format: "%.3f", stats.trigramRepetition)), + ]) + guard (try? stamped.write( + to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8, + )) != nil else { return false } + return true + } +} diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 22b4d17..a7b712b 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -839,6 +839,11 @@ extension PostsModel { lastError = error.localizedDescription return } + // #31 (S5.1): unaided-first-draft stats — fires at the invocation, + // before the engine sees anything; eligibility (writer origin, First + // Draft, post type) is read from disk. A failed capture must never + // fail the pass (decay-clock posture), so the Bool is ignored. + PostStore.captureFirstDraftStats(id: id, body: session.text, home: home) // #28 (S2.3): every pass auto-creates its own session — rostered // 'Pass N · <title>' and activated, so the pass streams into ITS // transcript. The existing ready-guard above stays the refusal pin. diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 5f86b9f..ffe1710 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -21,11 +21,12 @@ Owned by the root AGENTS.md contract. - `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike. - `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests. - `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 stamp round-trip; 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. +- `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. - `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), 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. -- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \<title\>" active (the auto-created session). +- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \<title\>" active (the auto-created session). **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). - `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \<title\>" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key). - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. diff --git a/MuseionTests/DraftStatsTests.swift b/MuseionTests/DraftStatsTests.swift new file mode 100644 index 0000000..44f6405 --- /dev/null +++ b/MuseionTests/DraftStatsTests.swift @@ -0,0 +1,77 @@ +// +// DraftStatsTests.swift +// MuseionTests +// +// #31 (S5.1): the four unaided-first-draft stats, pinned over +// hand-derived expected values (like #24's estimateTokens pin — the +// expectations are derived here, not copied from the implementation). +// +// ## Scenario: first-draft stats capture +// From #31 (PRD S5.1) +// Given a saved origin: writer post still in First Draft Pass State +// When any pass (Pass 1 or Pass 2) is invoked on it +// Then the four stats are computed natively in Swift from the exact +// text the engine is about to see and stamped into the post's +// frontmatter before the prompt crosses the bridge — the pass proceeds +// untouched +// Given instead an ai-origin piece, or one already past First Draft +// When a pass is invoked +// Then nothing is stamped — origin and Pass State alone decide +// + +import Foundation +@testable import Museion +import Testing + +@Test func `draft stats over sentences of three two and one tokens`() { + // Derivation: "One two three. Four five! Six?" → sentences [3, 2, 1]. + // μ = 2; σ = √(((3−2)² + 0 + (1−2)²)/3) = √(2/3) ≈ 0.81650. + // burstiness = (σ − μ)/(σ + μ) ≈ −0.42020; variation = σ/μ ≈ 0.40825. + // Tokens: one two three four five six → TTR = 6/6 = 1. Trigrams: + // [one two three][two three four][three four five][four five six] — + // 4 of 4 unique → repetition 0. + let stats = DraftStats.compute(body: "One two three. Four five! Six?") + #expect(abs(stats.burstiness - -0.42020) < 0.001) + #expect(abs(stats.sentenceVariation - 0.40825) < 0.001) + #expect(abs(stats.typeTokenRatio - 1.0) < 0.001) + #expect(abs(stats.trigramRepetition - 0.0) < 0.001) +} + +@Test func `draft stats regular sentences pin burstiness at minus one`() { + // Derivation: "a b c. a b c." → sentences [3, 3]: σ = 0, μ = 3 → + // burstiness = (0 − 3)/(0 + 3) = −1 (maximally regular), variation 0. + // Tokens: a b c a b c → TTR = 3/6 = 0.5. Trigrams: + // [a b c][b c a][c a b][a b c] → 3 unique of 4 → 0.25. + let stats = DraftStats.compute(body: "a b c. a b c.") + #expect(abs(stats.burstiness - -1.0) < 0.001) + #expect(abs(stats.sentenceVariation - 0.0) < 0.001) + #expect(abs(stats.typeTokenRatio - 0.5) < 0.001) + #expect(abs(stats.trigramRepetition - 0.25) < 0.001) +} + +@Test func `draft stats empty body is all zeros`() { + let stats = DraftStats.compute(body: "") + #expect(stats.burstiness == 0) + #expect(stats.typeTokenRatio == 0) + #expect(stats.sentenceVariation == 0) + #expect(stats.trigramRepetition == 0) +} + +@Test func `draft stats single sentence pins burstiness at minus one`() { + // Derivation: "Only one sentence." → sentences [3]: σ = 0, μ = 3 → + // burstiness −1, variation 0; TTR 3/3 = 1; one trigram, unique → 0. + let stats = DraftStats.compute(body: "Only one sentence.") + #expect(abs(stats.burstiness - -1.0) < 0.001) + #expect(abs(stats.sentenceVariation - 0.0) < 0.001) + #expect(abs(stats.typeTokenRatio - 1.0) < 0.001) + #expect(abs(stats.trigramRepetition - 0.0) < 0.001) +} + +@Test func `draft stats tokens case fold without apostrophe joining`() { + // Derivation: "Dog dog DOG" → dog dog dog → 1 unique of 3 → 1/3. + // No apostrophe joining: "writer's note writer" → writer s note writer + // → 3 unique of 4 → 0.75 (WITH joining it would be 3/3 = 1.0 — this + // pin discriminates the ceiling, the old all-unique body did not). + #expect(abs(DraftStats.compute(body: "Dog dog DOG").typeTokenRatio - 1.0 / 3.0) < 0.001) + #expect(abs(DraftStats.compute(body: "writer's note writer").typeTokenRatio - 3.0 / 4.0) < 0.001) +} diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index 843d59b..5955f68 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -259,3 +259,75 @@ private func textRows(of model: MentorSessionModel) -> [String] { #expect(mentor.activeEntry == mentor.roster.first) #expect(model.lastError == nil) } + +// MARK: First-draft stats capture (#31, S5.1) + +@Test @MainActor func `pass on a writer first draft piece captures stats and still completes`() async throws { + let (model, home, mentor) = try makePassRig() + defer { mentor.shutdown() } + await mentor.openSession() + let post = try PostStore.writeNew(body: "# Stats Piece\n\nOne two three. Four five! Six?", home: home) + model.select(post.id, home: home) + for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + + await model.runPass(.pass1, home: home, mentor: mentor) + + let onDisk = try String( + contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, + ) + // Capture fired at the invocation — the five keys ride post.md… + let matter = Post.frontmatter(of: onDisk) + #expect(matter["stats_captured"] != nil) + #expect(matter["stats_burstiness"] != nil) + #expect(matter["stats_type_token_ratio"] != nil) + #expect(matter["stats_sentence_variation"] != nil) + #expect(matter["stats_trigram_repetition"] != nil) + // …and the pass itself completed untouched. + #expect(onDisk.contains("pass_state: Pass-1 Done")) + #expect(model.lastError == nil) +} + +@Test @MainActor func `cancelled pass still captured stats at invocation`() async throws { + let (model, home, mentor) = try makePassRig(mode: "cancelOnPrompt") + defer { mentor.shutdown() } + await mentor.openSession() + let post = try PostStore.writeNew(body: "# Cancelled Stats\n\nOne two three. Four five!", home: home) + model.select(post.id, home: home) + + await model.runPass(.pass1, home: home, mentor: mentor) + + let onDisk = try String( + contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, + ) + // Stats fire at INVOCATION, not completion — a cancelled pass has them anyway… + let matter = Post.frontmatter(of: onDisk) + #expect(matter["stats_captured"] != nil) + #expect(matter["stats_burstiness"] != nil) + // …while the Pass State never advanced. + #expect(matter["pass_state"] == "First Draft") +} + +@Test @MainActor func `pass on an ai origin piece completes with no stats`() async throws { + let (model, home, mentor) = try makePassRig() + defer { mentor.shutdown() } + await mentor.openSession() + let post = try PostStore.writeNew(body: "# AI Piece\n\nMachine-born prose.", origin: .ai, home: home) + model.select(post.id, home: home) + for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + + await model.runPass(.pass1, home: home, mentor: mentor) + + let onDisk = try String( + contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, + ) + // The pass ran (origin alone decides, never the outcome)… + #expect(onDisk.contains("pass_state: Pass-1 Done")) + // …but nothing was stamped — ai-origin is never stats-eligible. + let matter = Post.frontmatter(of: onDisk) + #expect(matter["stats_captured"] == nil) + #expect(matter["stats_burstiness"] == nil) +} diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 3f2b172..2dbf583 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -879,3 +879,183 @@ private func researchDay() -> String { } #expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty) } + +// MARK: First-draft stats capture (#31, S5.1) + +/// Every `stats_` value is the store-time `%.3f` shape (a period, never a +/// localized comma) — the trend view (S5.2) parses them back as Doubles. +private func threeDecimals(_ value: String) -> Bool { + value.range(of: #"^-?\d+\.\d{3}$"#, options: .regularExpression) != nil +} + +@Test func `capture stamps five stats keys in place and preserves foreign frontmatter`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Draft\n\nOne two three. Four five! Six?", home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false) + // Hand-add a foreign key INSIDE the block before capturing — the + // in-place stamp must keep it byte-identical. + let withForeign = try String(contentsOf: url, encoding: .utf8) + .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") + try withForeign.write(to: url, atomically: true, encoding: .utf8) + let bodyBefore = PostStore.splitFrontmatter(withForeign).body + + let captured = PostStore.captureFirstDraftStats( + id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home, + ) + + #expect(captured) + let after = try String(contentsOf: url, encoding: .utf8) + let matter = Post.frontmatter(of: after) // the trend-view readiness read + #expect(matter["foreign_key"] == "keep-me") + #expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable + #expect(matter["stats_burstiness"].map(threeDecimals) == true) + #expect(matter["stats_type_token_ratio"].map(threeDecimals) == true) + #expect(matter["stats_sentence_variation"].map(threeDecimals) == true) + #expect(matter["stats_trigram_repetition"].map(threeDecimals) == true) + #expect(matter["type"] == "post") + #expect(matter["pass_state"] == "First Draft") + #expect(matter["origin"] == "writer") + // Body byte-identical — the stamp never touches content (#31 in-place proof). + #expect(PostStore.splitFrontmatter(after).body == bodyBefore) +} + +@Test func `capture refuses an ai origin piece untouched`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Machine\n\nAI-born text.", origin: .ai, home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + let before = try String(contentsOf: url, encoding: .utf8) + + #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) + #expect(try String(contentsOf: url, encoding: .utf8) == before) +} + +@Test func `capture refuses a piece past first draft`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Done Once\n\nAlready critiqued.", home: home) + try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + let before = try String(contentsOf: url, encoding: .utf8) + + #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) + #expect(try String(contentsOf: url, encoding: .utf8) == before) +} + +@Test func `capture refuses an outline piece`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "- an outline item", type: .outline, home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + let before = try String(contentsOf: url, encoding: .utf8) + + #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) + #expect(try String(contentsOf: url, encoding: .utf8) == before) +} + +@Test func `recapture while still first draft overwrites latest draft state wins`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Evolving\n\nOne two three. Four five! Six?", home: home) + + #expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home)) + #expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home)) + + let matter = try Post.frontmatter(of: String( + contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, + )) + #expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won + #expect(matter["stats_type_token_ratio"] == "0.500") + #expect(matter["stats_trigram_repetition"] == "0.250") +} + +@Test func `capture qualifies a bare legacy post through the lenient defaults`() throws { + // A bare corpus post (no frontmatter at all) scans writer/First + // Draft/post — the capture gate must reach the same verdict, not + // demand stamps that legacy files never carried. + let home = try storeHome { home in + let dir = home.appendingPathComponent("projects/posts/bare-legacy", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try "# Bare\n\nNo frontmatter here.".write( + to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8, + ) + } + + #expect(PostStore.captureFirstDraftStats(id: "bare-legacy", body: "No frontmatter here.", home: home)) + + let after = try String( + contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8, + ) + let matter = Post.frontmatter(of: after) + #expect(matter["stats_captured"] != nil) + #expect(after.contains("# Bare")) // the body survived the fresh-block prepend +} + +@Test func `advance pass state preserves stats and foreign keys in place`() throws { + // The #31 regression pin: the advance used to rewrite the block from + // its three parsed fields, erasing the stats captured at the pass's + // own invocation (and any foreign frontmatter). The in-place stamp + // keeps every other line byte-identical. + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Kept\n\nBody stays.", home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + let seeded = try String(contentsOf: url, encoding: .utf8) + .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") + try seeded.write(to: url, atomically: true, encoding: .utf8) + #expect(PostStore.captureFirstDraftStats(id: post.id, body: "Body stays.", home: home)) + + let advanced = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) + + #expect(advanced == .pass1Done) + let after = try String(contentsOf: url, encoding: .utf8) + let matter = Post.frontmatter(of: after) + #expect(matter["pass_state"] == "Pass-1 Done") + #expect(matter["stats_captured"] != nil) // survived the advance + #expect(matter["stats_trigram_repetition"] != nil) + #expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss + #expect(matter["origin"] == "writer") + #expect(matter["type"] == "post") + #expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.") +} + +@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws { + // The #31 finish-audit regression pin: an editor save mid-pass used to + // route through the stamped() rewrite and erase the stats captured at + // the invocation (plus foreign frontmatter). The in-place update keeps + // every non-owned key and swaps only the body. + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Draft\n\nFirst words.", home: home) + let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + let seeded = try String(contentsOf: url, encoding: .utf8) + .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") + try seeded.write(to: url, atomically: true, encoding: .utf8) + #expect(PostStore.captureFirstDraftStats(id: post.id, body: "First words.", home: home)) + + try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home) + + let after = try String(contentsOf: url, encoding: .utf8) + let matter = Post.frontmatter(of: after) + #expect(matter["stats_captured"] != nil) // survived the editor save + #expect(matter["foreign_key"] == "keep-me") + #expect(matter["pass_state"] == "First Draft") + #expect(matter["origin"] == "writer") + #expect(matter["type"] == "post") + #expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed +} + +@Test func `overwrite normalizes a bare post with the full stamp`() throws { + // The bare-post branch of the #31 audit fix: no block → the #59 stamp + // shape (type first), exactly as before the fix. + let home = try storeHome { home in + let dir = home.appendingPathComponent("projects/posts/bare-overwrite", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try "Bare body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) + } + + try PostStore.overwrite(id: "bare-overwrite", body: "Bare body, edited.", home: home) + + let after = try String( + contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8, + ) + let matter = Post.frontmatter(of: after) + #expect(matter["type"] == "post") + #expect(matter["pass_state"] == "First Draft") + #expect(matter["origin"] == "writer") + #expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.") +} diff --git a/docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md b/docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md new file mode 100644 index 0000000..5352cc3 --- /dev/null +++ b/docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md @@ -0,0 +1,91 @@ +# M4: First-draft stats capture (S5.1) + +> **Date:** 2026-10-22 +> **Type:** issue +> **Reference:** Gitea issue #31 (AlexKucera/Museion), PRD S5.1 + +## Goal + +Measure the writer, not the text: compute the four style stats (burstiness, +type-token ratio, sentence-length variation, trigram repetition) natively in +Swift at the first pass invocation of any kind — before the engine sees +anything — for `origin: writer` posts still in First Draft Pass State, stored +per post so the S5.2 trend view is a scan of `posts/`. + +## What Was Done + +- `Museion/DraftStats.swift` (new) — pure deterministic model: + `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ), population σ, −1 for + a single sentence), typeTokenRatio, sentenceVariation (σ/μ), + trigramRepetition ((total−unique)/total over consecutive word triples). + Tokens = lowercased `isLetter||isNumber` runs; sentences = chunks between + `.!?` with a token count > 0. +- `Museion/PostStore.swift` — `captureFirstDraftStats(id:body:home:) -> Bool` + (@discardableResult, never throws into the pass): eligibility from the + FILE's own frontmatter via the lenient defaults (writer / First Draft / + post — a bare legacy post qualifies), five flat `stats_*` keys stamped IN + PLACE through `stampingFrontmatter`; `advancePassState` switched from the + `existingStamp→stamped` block rewrite to an in-place `pass_state` key stamp + (bare posts still normalize through `stamped`). +- `Museion/PostsModel.swift` — `runPass` calls the capture after the pre-pass + snapshot, before `beginPassSession`/`sendPrompt` — literally before the + engine sees anything; the Bool is ignored. +- `Museion/LearningDecay.swift` — `stampingFrontmatter` widened + private→internal (its own ponytail comment's third-caller trigger fired). +- `Museion/PostStore.swift` `overwrite` (finish-audit fix) — same in-place + treatment: the `stamped()` round-trip rebuilt the block from three parsed + fields and erased captured stats + foreign frontmatter on every editor + save; now blocked files update the three owned keys in place and swap only + the body. +- Tests: `MuseionTests/DraftStatsTests.swift` (new, 5 pins over hand-derived + expectations, scenario header), PostStoreTests +8 pins (capture gate matrix, + in-place stamp proof, bare-legacy eligibility, recapture overwrite, + advancePassState + overwrite regression pins, bare-post normalization), + PassRunTests +3 wiring pins (full-run capture, cancelled-pass capture at + invocation, ai-origin refusal). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Five flat `stats_*` keys, not a nested `museion:` YAML block | The lenient flat frontmatter parser (`Post.frontmatter`) maps `key: value` lines; a nested block's indented children would be promoted to colliding top-level keys. PRD's "museion: block" reads as "the block Museion owns". | +| In-place key stamps for `advancePassState` + `overwrite` | The `stamped()` full-block rewrite carries only type/pass_state/origin and silently erased everything else. Root-cause fix at the write-path class, not per-symptom. | +| Capture re-fires while still First Draft (latest wins) | A cancelled pass leaves the state at First Draft; the next pass re-captures the current draft. Falls out of the in-place overwrite stamp. | +| Fire at invocation, not completion | PRD S5.1 pins it ("before the engine sees anything"); cancelled/refused passes keep their stats. | +| `.post` type gate | CONTEXT.md vocabulary: Post ≠ Outline; prose metrics on a bullet tree are noise. | +| `now: Date` clock param deleted | Untested seam — ProfileBackup injects a clock because it TESTS one; YAGNI. | +| `stampingFrontmatter` widened, not extracted | The function's own ponytail comment set the trigger ("third caller"); PostStore's enum body is genuinely at its 250-line lint ceiling (347). | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| End-to-end wiring pin failed 3/3 full-suite runs while "passing" in isolation | The isolated runs were VACUOUS: `-only-testing` with a single test name executed 0 tests (free-function Swift Testing tests have no suite; the banner still prints TEST SUCCEEDED). Confirmed via `xcresulttool get test-results summary` → `passedTests: 0`. | Always read the executed count from the xcresult, never the banner. Single-test filtering works only with the backtick-identifier form and is unreliable through wrappers. | +| Stats keys absent after a completed pass (deterministic) | `advancePassState`'s `existingStamp→stamped` rewrite rebuilt the block from three parsed fields. Found by a temporary on-disk diagnostic dump (print() is swallowed by the test harness; write to a scratch file instead). | In-place `pass_state` stamp; regression pin `advance pass state preserves stats and foreign keys in place`. | +| Same erasure class live in `overwrite` (found by the finish-audit security reviewer) | Editor saves mid-pass route through `overwrite` → stats destroyed by ordinary editing; the draft then aged out of eligibility. | In-place key update in `overwrite`; two pins (blocked + bare branch); flip-verified (revert → exactly the new pin fails). | +| Full-suite runs flake on rig pins under machine load (Classis.app at 70% CPU → load 6.4) | Fresh fake-ACP spawn + handshake timeouts under CPU contention — the documented #30 learning, seen again. | Sequential run (`-parallel-testing-enabled NO`) is the honest gate under load; failures verified green in isolation via the executed-count check. | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/DraftStats.swift` | New — the four-metric pure model | +| `Museion/PostStore.swift` | `captureFirstDraftStats`; `advancePassState` + `overwrite` switched to in-place key stamps | +| `Museion/PostsModel.swift` | `runPass` capture call after the snapshot, before engine traffic | +| `Museion/LearningDecay.swift` | `stampingFrontmatter` private→internal (+ comment update) | +| `MuseionTests/DraftStatsTests.swift` | New — 5 metric pins | +| `MuseionTests/PostStoreTests.swift` | +10 capture/advance/overwrite pins incl. 2 regression pins | +| `MuseionTests/PassRunTests.swift` | +3 end-to-end wiring pins | +| `Museion/AGENTS.md` / `MuseionTests/AGENTS.md` | DOX pass: file entries, mechanism corrections, pin inventories | +| `CHANGELOG.md` | Unreleased → added: first-draft stats capture | + +## Open Items & Next Steps + +- [ ] S5.2 trend view — reads the `stats_*` keys via `Post.frontmatter`; consider `stats_captured` date parsing + per-metric charting. +- [ ] Pre-existing SwiftLint ceilings on `PostsModel.swift` (file_length ERROR at HEAD, 1027→1032 lines) and `runPass` body — need their own extraction ticket. +- [ ] `MuseionUITests.testAppLaunches` fails with "Failed to activate application" — environmental, pre-existing, not addressed here. +- [ ] `convert` still uses the `stamped()` rewrite (outline→post only, outlines carry no stats — no live erasure, noted for the record). + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 248a2bc..00c42b0 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -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-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests | | 2026-10-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. | | 2026-10-22 | issue | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) | #29 research rail: submit_research_notes candidates in-session, ask-before keep into research/, resume replay pin, audit fixes — targeted suites green | | 2026-10-22 | issue | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) | #28 Session lifecycle: multi-session model + names-only roster, pane, pass auto-create, finish-audit with 7 fixes — 359 tests green |