docs: shrink AGENTS.md rails 206KB to 36KB
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Museion/AGENTS.md 147KB -> 30KB, MuseionTests/AGENTS.md 60KB -> 5.4KB. Contracts, rulings, and trust gates kept; per-issue narratives, UI round histories, and pin inventories dropped (the test files carry their own scenario headers). Serif skill payload deliberately untouched (mentor payload, own governance). closes #183
This commit is contained in:
1 parent
efbde25cdd
commit
c2eb9573db
5 files changed
+139
-103
No files matched your search
@@ -201,6 +201,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) |
|
||||
| 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_log.md) |
|
||||
| 2026-11-05 | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](docs/devlog/20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) |
|
||||
| 2026-11-04 | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](docs/devlog/20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) |
|
||||
@@ -210,5 +211,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
| 2026-11-04 | [20261104-issue162-cold-turkey-writing-lock-integration_log.md](docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md) |
|
||||
| 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) |
|
||||
| 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_log.md) |
|
||||
| 2026-11-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](docs/devlog/20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) |
|
||||
<!-- write-log: window-end -->
|
||||
+55
-65
@@ -6,85 +6,75 @@ The Museion application target: the native SwiftUI macOS app shell of the Agenti
|
||||
|
||||
## Ownership
|
||||
|
||||
Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchronized groups** — files on disk are the truth; add/move/delete sources here and Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values and the one sanctioned exception: the `ref/writing skills` **folder reference** into the Resources phase (#46 map decision — a folder reference can't be expressed through fs-sync groups).
|
||||
Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchronized groups** — disk is truth; Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values and the one sanctioned exception: the `ref/writing skills` **folder reference** into the Resources phase (#46 — a folder reference can't be expressed through fs-sync groups).
|
||||
|
||||
## Local Contracts
|
||||
|
||||
- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped state; #151 gateless — `ContentView.task` fires `startLaunchCheck`, the async engine check + auto-fire chain). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) ride the same `CommandGroup(replacing: .newItem)` — `replacing` is load-bearing (single-window dogfood ruling 2026-11-05): with `after`, the stock File ▸ New Window item the WindowGroup owns kept its ⌘N and BOTH fired — a new window AND a new post; replacing kills the stock item, so ⌘N is New Post alone and a second Museion window cannot open from the menu. One shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#162 (Cold Turkey S2):** `WritingLockAppDelegate` rides `@NSApplicationDelegateAdaptor` (quit refused while a block holds); the View group gains Start Cold Turkey… (focus-gated, disabled on outline/no piece — the #160 second path behind the dot) and the lock refusals — Toggle Focus Mode, Toggle Reading Mode, and every File entry that would swap the editor surface (New Post/Outline/Project, Open…, Import…) disable while locked; ⌘W is swallowed by the kiosk's key monitor (WritingLockState.swift). **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; the stock New Window item is REPLACED — ⌘N is New Post alone, no second window).
|
||||
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
|
||||
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
||||
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exceptions (both app metadata, never content): the engine gate's `state.json` and the session roster's `sessions.json` (#28 — names/ids only; transcripts stay engine-owned per ADR-0007).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||
- App icon: `Assets.xcassets/AppIcon.appiconset` — single-size 1024×1024 PNG (`Museion-Logo_1024.png`); Xcode derives all sizes. The built icns tops out at 256 px entries — that matches Apple's own apps on this macOS; larger sizes come from the catalog.
|
||||
- Entry: `MuseionApp.swift` (`WindowGroup` + `about` window; `AppGateState` holds app-scoped state). No `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless museion-tools MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). `WritingLockAppDelegate` rides `@NSApplicationDelegateAdaptor` — quit asks once while a Cold Turkey block holds, unlocked passes straight through.
|
||||
- File ▸ Open… (⌘O) + Import… (⇧⌘O) ride `CommandGroup(replacing: .newItem)` — **`replacing` is load-bearing** (single-window ruling 2026-11-05: with `after`, the stock New Window item kept ⌘N and BOTH fired; replacing makes ⌘N New Post alone and a second window unopenable from the menu). Shared `pickMarkdown` NSOpenPanel helper; never `CommandMenu("File")`. New Post ⌘N · New Outline ⇧⌘N · New Project ⌥⌘N (commands can't present sheets — WorkspaceView presents via pending-state). Cold Turkey: Start is focus-gated; focus/reading toggles and every surface-swapping File entry disable while locked.
|
||||
- `AppMetadata` is the single source for displayed name/tagline; members `nonisolated`.
|
||||
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
||||
- App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no `.entitlements` file.
|
||||
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
|
||||
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
## Workspace shell
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs, and — 2026-11-05 owner ruling — the chat's three face constructors `valkyrie`/`concourse`/`ubuntuMono` (Valkyrie OT B / Concourse OT Book / UbuntuMono NFM, PostScript names mirroring ProseTypography; Font.custom falls back to system when absent). **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette, with the single semantic exception `readyGreen` (#153/#156: the mentor header's ready dot; a meaning, never a style color).
|
||||
- `WorkspaceView.swift` — the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane. `RailButton` (44×44, muted icon, hover wash, surface tile + hairline border when current, icon in fg ink — **ui-polish r2 re-ruling:** NO visible edge bar; the export's `::before` selection bar paints BEHIND the app border in the export's own render, so contract-faithful is tile + border + fg-ink icon alone). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`; **owner ruling 2026-11-07 — scoped hosting:** the Mentor pane hosts the open piece's matching roster session (`SessionRoster.hostedSessionId` — exact pieceTitle match, newest first; `MentorPaneView` scopes at mount/remount and on every piece change via `scopeHostedSession`), shows its honest empty presentation when none matches, and never interrupts an in-flight pass transcript, streaming turn, or another session's in-flight replay — the switch defers to turn/replay end and the replay's completion re-fires the pending scope; an automatic action never leaks a refusal row), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s card language, ui-polish r6: selected strip = vertically-inset 2pt rounded accent capsule — part of the card, never a full-height pasted strip; titles truncation-seamed `WordBoundaryTruncation.fit(maxWidth:lines:)`, GLYPH-MEASURED (NSFont serif-13 semibold vs the row's 192pt width, pinned in WordBoundaryTruncationTests) so the seam's output is what renders and lineLimit(2) is a no-op safety net — ui-polish r7 (argon#14/sol#32/47): an overflowing title MIDDLE-elides — **ui-polish r8 (sol#3) HEAD-BIASED ~60/40: the head keeps the "Pass N ·" label + leading words grown into ~60% of the glyph budget (`headShare`), then the longest fitting word SUFFIX — more of the unique topic, less of the shared tail ("Pass 2 · Museion Handoff — … apex) vs. Hand-rolled TextKit"); r7's label-only head + maximal suffix let the topic die at the same elision point**: 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, ui-polish r8 mercury#17: the engine-version mono badge sits BESIDE the trailing button group — title | spacer | badge | buttons, never beside the title; **#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 `NewPostFromSessionSheet` (own file, ui-polish r1 — extracted past the 400-line ceiling; internal) 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 sLine truncated
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + origin-only meta — the pass state rides the group label; the row's a11y label still states it), 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 (11px mono at full muted ink; **r6 indent ladder** — chevron slot x14 / head text x30 / group labels + row CARDS x44 with title text x56, so every level starts at or right of the one above it and the search field's box shares the row card's insets exactly), 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. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). **#162:** the focused branch mounts the Cold Turkey chrome as overlays (`ColdTurkeySeat` bottom-center, `ColdTurkeyDot` bottom-right) and suppresses the mentor hover reveal while a block holds; leaving focus drops a stale arm-bar (`onDisappear`).
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
|
||||
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). **#161:** internal `words(in:)` (`tokens(in:).count`) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift.
|
||||
- `WritingGoal.swift` — #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock): `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun` (the armed block: goal + `armedAt` + baseline/current word counts via `DraftStats.words`). `update(text:)` takes whole-document text — typing/deleting/pasting/undo all land the same way, `netNewWords` falls out of the delta (deleting costs; a big paste counts). `now` is INJECTED (`isMet(now:)`, `secondsRemaining(now:)`, `progress(now:)` 0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary; `isMet` is live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2's `WritingLockState` owns the ticker and calls this.
|
||||
- `WritingLockState.swift` — #162 (Cold Turkey S2, map #158) the writing lock machine + kiosk: `WritingLockState` (@Observable, app-scoped as `gate.writingLock`; `static weak active` is the app-delegate's quit-refusal handle) — `start(goal:body:at:)` arms (refuses a second block while locked), a 1 s ticker + the per-keystroke `feed(text:)` (ProseTextView.onTextChange, both editor modes) drive `WritingGoalRun`, `tick(at:)` completes on the first met tick (internal seam — tests inject the decisive moments), `complete()` exits the kiosk and leaves `completionNote` fading ~6 s. `WritingLockKiosk` — the #159 recipe verbatim (6-option combo + `.disableScreenCornerInteractions`), enter = activate→options→toggle (returns whether WE toggled fullscreen — an already-fullscreen window is entered in place; exit replays only what entry toggled), exit = options-clear-FIRST then toggle (never churn mid-transition); ⌘W + ⌃⌘F + ⌘N refusals = a local keyDown monitor (matched by KEY CODE with the exact modifier set plus a lowercased character net — audit 2026-11-04: charactersIgnoringModifiers is layout- and Caps-Lock-dependent, a Cyrillic/caps ⌘W slipped past while the stock Close still fired; ⌘N covers the stock New Window item SwiftUI owns, which stays enabled mid-lock) swallowing all three while locked (⌃⌘F added 2026-11-04: the kiosk holds even windowed, so a user-initiated fullscreen exit mid-block left a windowed kiosk — menu bar gone, quit refused — the dogfood trap; fullscreen now leaves only via completion) (SwiftUI owns the stock window delegate and `.closeItem` has no CommandGroupPlacement — the OutlineDrag monitor pattern, installed/removed with the lock); hosted-test guard = full no-op (never kiosk the test machine). `WritingLockAppDelegate` (`@NSApplicationDelegateAdaptor` in MuseionApp) — `applicationShouldTerminate` while locked asks ONCE (#163 ruling 2026-11-04: "Walk away from the block?" — Walk Away clears the kiosk and quits, the block dying quietly with the process; Keep Writing cancels; unlocked quits pass straight through, all quit paths route here). Nothing persists — the block dies with the session.
|
||||
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, symmetric 2×2 equal-cell grid — top-aligned rows, fixed two-line explain frames; **ui-polish r2:** y-value labels OUTSIDE the plot in a dedicated trailing axis gutter, vertically centered on their gridlines — one tick convention everywhere = domain bounds + midpoint (the zero line reads on 0…1 cards); x labels capture-aligned, one centered "Oct 5" (POSIX `MMM d`) under each capture date, never weekly ticks that miss the points). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` in neutral foreground ink (r2: no arrow glyph, no per-verdict tint — polarity rides the card-header badge (↑/↓ better) alone; the old orange slipping died with the ui-polish round, the arrows with r2); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
|
||||
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
|
||||
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
|
||||
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
|
||||
- `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploadsLine truncated
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** 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; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `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 `extension PostsModel` in PostsModelOutline.swift (#146). 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`, opeLine truncated
|
||||
- `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 (#ui-r2: marker by DEPTH — every top-level row the same 10pt filled disc, every nested level the single 7pt dot, parent-vs-leaf never changes the glyph, ink foreground-0.8 not muted; fold toggle stays on child-bearing rows; 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) (ui-polish r1: outline bullet glyphs render at ONE size — parent-vs-leaf stays the fill distinction, never size), 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).
|
||||
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **#142 paragraph-scoped fold maintenance:** a `shouldChangeText` override records the last accepted single-line edit (range + UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes it to the in-place re-key (`rekey` — pure, `RekeyOutcome`: survivors shifted by delta, marker-line edits kill the fold and return the scope for un-hiding, scope-interior edits grow/shrink it and flag the edited line for re-hide + caret park) — no parents rescan, no `setAttributedString` swap. The single-line gate is `\.isNewline`, never a literal `"\n"`/`"\r"` compare — `"\r\n"` is ONE grapheme equal to neither, and a CRLF-carrying edit must reach the full pass (finish-audit pin); `apply()` nulls `pendingPlainEdit` outright — structural edits reshape blocks even when the replacement is single-line (a childless unterminated block's outdent; finish-audit pin, `performOutdent` internal for it). A font probe at each survivor's scope head guards the path: hidden styling still present, else fall back to the full pass (wholesale restyles like the fence-flip self-heal this way); dead-scope un-hides are bounds-hardened at the sink. Full pass stays for structural edits, wholesale loads, and toggleFold. `Fold` carries the hidden `scope` (shift-maintained; the full pass re-derives it). **Chrome rendering (#115 field findings, #142 rework):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render as one TINY per-glyph CALayer (contents = a small flipped NSImage raster, `isGeometryFlipped` on the overlay layer so sublayer frames speak lineRect's top-left y) in the click-through `ProseChromeView` overlay (deferred one main-queue tick past textDidChange) — NEVER a document-sized bitmap (~35M pixels per keystroke on a tall doc, #142/F2); glyph rasters are cached by string (`chromeGlyphImages` — 50k parents share a handful of images; layers stay unculled because scroll fires no refresh, ponytail-noted); an edit at/after every parent line skips the rebuild outright (`parentsUnmoved`), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting. **#141 illustration ingest:** window-level SwiftUI `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'s #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (`allSatisfy` — a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the dLine truncated
|
||||
- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "SESSIONS" in the P1/P2 uppercase-badge voice; selected row = fg-ink 0.10 wash (one step over the 0.06 hover) + accent bar inset from the highlight edge; header title inset 18 shares the sidebar labels' edge; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded; ui-polish r2: the MUSEION HOME row is ONE bounded field-group (surface fill + 1pt #E8E5DF hairline) — the path expands to fill the available width before eliding (r6: `ElidedPathText` — glyph-measured slash-boundary ladder, full path first then dropping middle components down to `/first/…/last`, each candidate measured in the real mono face against the actual row width, longest fit renders, character-middle only if even the shortest overflows; full-strength hairline on Choose… inside the group — the softBorder param died with it), Choose… adjacent at 8pt in the `BorderedSecondaryButtonStyle` (WorkspaceView.swift — mono-11 on surface + hairline, 36pt hit target by default, 28 in compact rows); all detail forms are LEFT-anchored per wf130 `.vC .detail` padding 18/26/48, never HORIZONTALLY centered in the pane; r6: every page pins a serif-15 header at top 17 — baseline-aligned with the sidebar's 'Settings' across the divider — and TOP-ALIGNS its form stack ~24pt under the intro with NO ScrollView - ui-polish r8 owner-reported fix: the r6 vertical-centering left a ~320px dead gap and a phantom scrollbar; one leading control column, every control label-above at the page title's x). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship; **#175:** the nous block carries the Portal note — chats ride the hermes Portal login, a pasted key bills the same account credits, `hermes auth add nous` signs in). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models (**#175 adds `nous` — Nous Portal: endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, switch flagship `anthropic/claude-sonnet-5` keeping the app's sonnet posture — the portal's catalog is the vendor-prefixed router list, live-probed; ladder = the 5-level OpenAI-compatible set hermes clamps nous to; engine auth rides the hermes Portal login, API key and subscription bill the same account credits), `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending wrLine truncated
|
||||
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. **#162 (Cold Turkey S2, map #158):** the chrome lineage grows the lock — `ColdTurkeySeat` (one bottom-center seat: the arm-bar before Start, the live readout while locked, the completion note fading ~6 s; the arm-bar carries a chip that BLENDS into the focus ground — 2026-11-04 dogfood amendment: the ground's own color + the faintest token hairline, no shadow, because the bare seat let the document text show through; readout + note stay bare mono; readout = numerals + 2px hairline, terracotta numerals inside the last 20 %, piece title absent; the arm value is directly typeable — parsed and clamped at every read — with ± steppers for coarse moves; defaults 250 words / 5 min, ranges 1…1000 words / 1…60 min — what's typed is what arms, the 2026-11-04 dogfood amendments; the readout and completion note carry the same blending chip) and `ColdTurkeyDot` (the persistent muted pip bottom-right, label on hover, click opens the arm-bar — hidden while the bar is up, a block runs, or nothing prose is open). The arm-bar's Esc = a hidden `.cancelAction` button (the PostEditorView ⌘S rail — `.onExitCommand` never fires behind the hosting view, the #109 probe). Both mount as overlays on PostsPaneView's focused ZStack only, so lock transitions never restructure the editor column (the #87 remount hazard / typing-continuity AC). `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
|
||||
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView` (ui-polish r1: the document title — first non-blank body line — renders at the 22pt title rung in the SERIF body face (#ui-r2: face change only, Valkyrie not the sans heading face; after-space measured so the title→body ink gap is 24–28pt, editor top padding 40pt), list lines hang at their marker-prefix width MEASURED IN THE EXACT RENDER ATTRIBUTES (#ui-r2: markers render in the body face at foreground-0.8 ink — the r1 mono-render/body-measure drift put continuations ~4pt left), and programmatic caret landings hop past leading blank lines via `caretPastLeadingBlanks` — the r1 stray-caret artifact was the caret parked in an invisible leading blank fragment), toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
|
||||
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`; non-file URLs read back as nil — the Home is always a folder). **#171:** fresh installs (no stored override) resolve once and PIN the winner, so the Home never silently moves: (2) legacy `~/Documents/Museion` exists as a directory (`existingDirectory` gate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3) `<CloudDocs>/Museion` when iCloud Drive is present (CloudDocs resolved dynamically at the unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path — never a hard-coded `iCloud~` form; plain FileManager probing, no ubiquity entitlements per ADR-0009), (4) else the silent Documents fallback — no dialog, no rail pill. The ladder + probes live in `HomeResolution.swift` (`resolvedInitialHome`/`liveCloudDocsDir`/`existingDirectory`); init takes injectable probes + defaults — hosted tests drive the ladder without touching the machine's real iCloud state, and the DEFAULT construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched. Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
|
||||
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
|
||||
The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in `docs/devlog/`.
|
||||
|
||||
## Engine check (gateless launch, #35–#41 + #151, map #148)
|
||||
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
|
||||
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
|
||||
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
|
||||
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the immutable pair (origin writer, type post — never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
|
||||
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via `stampingFrontmatter` — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility read from the file's own frontmatter (writer/First Draft/post); failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `` builder.
|
||||
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
|
||||
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
|
||||
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session.
|
||||
- `TrendsPaneView.swift` — per-metric line charts over first-draft captures; only pieces with `firstDraftStats` appear (the view answers "am I getting better", never "is this draft good"); one capture shows a value, no verdict. `TrendMetric` (pure): fixed y-domains (burstiness −1…1, TTR + trigram 0…1, sentenceVariation scaled to 1.2× peak, floor 1), verdict at ±0.01 (trigram inverted), one explain line per metric.
|
||||
- `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `<home>/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress).
|
||||
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
|
||||
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
|
||||
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
|
||||
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal". `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
|
||||
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
|
||||
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
|
||||
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
|
||||
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
|
||||
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
|
||||
- Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage).
|
||||
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — `ModelProvider` slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship `anthropic/claude-sonnet-5`, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions); 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot).
|
||||
- Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only.
|
||||
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
|
||||
- `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `<CloudDocs>/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.
|
||||
|
||||
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phase machine (idle/checking/pass/fail) — **#151: the pill's state source**, unchanged; `onPass` seam (fires the auto-fire chain), `currentBinaryPath` handed to provisioning. `execute(_:timeout:)`/`ProcessOutput` are internal — shared child-process machinery.
|
||||
- **#151 — the gateless flip:** `AppGateState.startLaunchCheck()` (called from `ContentView.task`) arms the auto-fire chain (`wireAutoFire` — provisioning `runPass(hermesBinary:)` then `backup.runPass()`, the gate era's exact `onEnginePass` body) and awaits `beginAutomaticCheck()`; `hasStarted` preserves #41's once-per-app-launch, first-window-only rule (⌘N no-ops). No-ops under hosted tests (`XCTestConfigurationFilePath` — the panes' guard pattern; never probe or auto-provision there). ContentView renders `WorkspaceView` unconditionally — the posts scan starts at first frame, concurrent with the check; nothing library-side waits on the gate. The blocking sheet, placeholder logo screen, `gateRaised`/`gateDismissed`, and `EngineGateView`/`ProvisioningFailureCard` are deleted.
|
||||
- `EngineStatusView.swift` — the status surfaces (#149 variant A, prototype `prototypes/GatelessStatusPrototype.swift`): `EngineStatusSurface.visibility(phase:provisioningFailed:)` (pure, test-pinned — the mapping: idle/pass+healthy → hidden, checking → pulse, fail/pass+provisioning-failed → failed), `EngineStatusPill` (44×44 rail slot above Archive: 8pt pulsing accent dot while checking, `exclamationmark.triangle.fill` on an accent-12% wash when failed, nothing when healthy — the slot collapses and rail spacing closes), `EngineStatusCard` (the anchored fail card: 340pt, bottom-leading at railWidth+12/bottom 14, surface bg, accent-0.5 border, radius 12, shadow — floats, never blocks, never pushes layout; auto-expands on each failure arrival via WorkspaceView's `.onChange(of: visibility)`, chevron collapses, slot click re-opens; WorkspaceView hosts slot + card overlay — focus mode recesses the CARD with the rail, the expanded state surviving for exit-focus). Engine-fail content = #40 copy with the gateless subtitle ("Passes and Sessions need it — the editor keeps working"), the two install steps + Copy + Installation guide link, Re-check (accent, disabled-while-checking, label "Checking…"), Technical details (stderr excerpt + "Probed: <path>"; bare Probed line when stderr is empty). Provisioning failure rides the same card: title "Setup failed", phase rawValue + failing profile mono (#134), the safe-to-retry body, Retry inline (re-runs provisioning; success nils `lastFailure` and the surface disappears — live-read, no snapshot).
|
||||
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check (Re-check included); fail records carry no `engineVersion`. About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
|
||||
- Panes spawn the engine the moment the check lands: `MentorPaneView`/`SessionsPaneView` seed `.task(id: binaryPath)` (nil→value arrival re-fires; a nil binary never calls `openSession` — that path lands the crash card, so the gate's fail state owns the interim). The mentor pane header carries mono-10 engine states beside the serif "Mentor" title (checking… muted + mini spinner / engine missing accent / setup failed accent / #156: ready = the semantic green dot + lowercase `ready` — the BASE version rides the tooltip, handshake answer first, gate's derived string `+`-stripped meanwhile; drift note keeps its orange text + help). The session chip renders only once ready; status text wins layout priority. Both panes' idle branches show the honest missing-engine notice when the gate failed (never an eternal "Starting…" spinner — SessionsPaneView takes `gate` for it). The header's state derivation is `MentorEngineStatus.state(phase:provisioningFailed:)` — pure, test-pinned (the outrank rule: engine failure wins over a lingering provisioning failure).
|
||||
- Tests: `MuseionTests/EngineGateTests.swift` (untouched — probe order, first-stderr reporting, timeout kill, state records, onPass-fires-per-passing-check, once-per-model) + `MuseionTests/GatelessLaunchTests.swift` (#151: startLaunchCheck hosted-test no-op, wireAutoFire arms the chain, the pill visibility mapping incl. provisioning-failure-under-passed-gate, the mentor header mapping).
|
||||
## Engine check (gateless launch)
|
||||
|
||||
## Profile provisioning (S2.1 #43–#48; #134 Profiles S1)
|
||||
- `EngineGate.swift` — `EngineProbe` (six-path probe order, `acp --check` health, 5 s timeout) + `EngineGateModel` (idle/checking/pass/fail; `onPass` seam; `currentBinaryPath` handed to provisioning). Gateless flip (#151): `AppGateState.startLaunchCheck()` from `ContentView.task` arms the auto-fire chain (provisioning pass → backup pass) and awaits the check async; `hasStarted` = once per launch, first window only; no-op under hosted tests. No blocking UI — `WorkspaceView` renders unconditionally, the posts scan starts at first frame.
|
||||
- `EngineStatusView.swift` — `visibility` mapping (idle/pass+healthy → hidden, checking → pulse, fail AND pass+provisioning-failed → failed — pure, test-pinned), the 44×44 rail pill, and the floating anchored fail card (never blocks layout): install steps + Re-check; provisioning failures ride the same card naming the failing profile in mono. Failure content keeps the "Passes and Sessions need it — the editor keeps working" posture.
|
||||
- `state.json` at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check (Re-check included); About reads it and never triggers a check.
|
||||
- Panes spawn the engine on the nil→value `binaryPath` arrival (`.task(id:)`; a nil binary never calls `openSession`).
|
||||
|
||||
- `ProfileProvisioner.swift` — the #134 surface registry + the provisioner. **`ProfileSurface`** (nonisolated enum, chat/pass1/pass2; declaration order = provision order — chat first so the resident surface is healthy before any pass-profile failure stops the loop): `profileName` (museion adopted in place / museion-pass1 / museion-pass2, Sessions rides Chat per #126), `allocatedSkills` (#133 table: P1 10 · P2 9 · Chat 11 — #58 adds owned-insight on all three; persona pair never co-occurring), `init?(passKind:)` (the PassKind→profile seam), and the #132 fresh-seed defaults as constants (`defaultModelProvider` anthropic, `defaultModelID` claude-sonnet-5-5, `outputBudgetTokens` 24000 — reasoning_effort never written). **`ProfileProvisioner.perform`** (nonisolated): one idempotent pass = master-seed + per-surface phases. Phase 0 master: every manifest skill seeded additively as REAL dirs into the ONE master copy at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable) — `seed-manifest.txt` is still the shipped-set list (kebab-validated at the trust boundary); temp+rename per skill, never touch present ones, orphaned `.`-temps swept, `.DS_Store` purged. Then per surface (first failure wins; the next pass heals): **create** — dir-check first, `hermes profile create <name> --no-alias --no-skills` only when missing (#43 already-exists semantics); `museion` is adopted, never re-created (ADR-0014). **configure** — the #132 defaults written through the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.extra_body.max_tokens 24000 --force`, provider first — switching providers clears a stale inherited base_url, live-probed; #128: never rely on create-time inheritance); success is WIRE-VERIFIED (`exit 0` + `✓ Set <key>` on stdout — not exit code alone, finish-audit) and a marker write that fails surfaces as a configure-phase failure (an unrecorded configure must not count as done). MARKER-GATED by `.museion-provisioned` in the profile dir so a re-pass is a no-op and a user's later Settings change survives: runs for fresh creates and for an unconfigured PASS profile (interrupted before its marker landed — Retry heals); the adopted museion is NEVER configured (its glm-5.3-max is the user's until Settings switches it). **skills** — per profile, symlink each manifest name into the master: an existing link (live or dangling) is never retargeted; a copy-era REAL dir swaps to a symlink only on `treesByteMatch` against the MASTER (the link's target — identical to the payload on first seed; `.DS_Store` filtered from both listings so a Finder-browsed dir still migrates) with move-aside → link → delete-aside, restored on failure; a diverged dir stays a copy, untracked/user skills never touched (G3a); a missing skill links only when the surface ALLOCATES it (curation). **register** — museion-tools per profile (ADR-0008 amendment): `-p <profile> mcp list` skip / `mcp add` with repeated-y stdin, both binaries required (nil = test seam). `Outcome.seeded(copied:present:)` aggregates master copies + links; `.failed(profile:phase:excerpt:)` names the profile (nil for payload-level failures) — phases create/copy/register/configure. `ProvisioningModel` unchanged in shape; `runPass` gained `masterRoot`.
|
||||
- Provisioning failure UX (#48, reborn #151): rides the rail fail card (`EngineStatusCard`'s setup branch — `EngineStatusView.swift`) — the blocking-sheet `ProvisioningFailureCard` is deleted; phase rawValue + failing profile name in mono (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; Retry re-runs the whole idempotent pass (a success nils `lastFailure` and the surface disappears; Not-Now defer died with the sheet and the dead `deferFailure` method is deleted with its test — collapse is view-state, the orange pill stays until a pass succeeds, #38's no-silent-degradation carried by the pill). Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's own `hermes` CLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written by `config set` — byte-identity now holds only for adopted/engine-owned configs, test-pinned).
|
||||
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 12 mentor skills ship (#58 added owned-insight); the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
|
||||
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profiles at `<binaryDir>/profiles/<name>`, speaks `-p <any-profile> mcp list`/`mcp add` with per-profile marker/invocation files and `config set` with a per-profile argv log + `config-set-fails`/`mcp-add-fails` knobs, logs every `profile create`), injected profile/payload/master dirs, manifest ↔ payload correspondence. **#134:** `ProfileSurfaceTests.swift` (own file) pins the registry (names/order, PassKind mapping, allocation counts + persona split, defaults, allocation ⊆ bundled manifest), ×3 provisioning with exact config-set command lines, master-once + per-allocation symlinks, re-pass no-op (config-set log byte-stable, no re-creates), adopted-museion untouched, marker heal/no-stomp, failing provision names the profile, configure-phase failure. `ProfileSkillMigrationTests.swift` (own file) pins the byte-match migration (browsed dir with `.DS_Store` still migrates, content identical through the swap; diverged stays a copy; untracked untouched; a symlinked entry inside a copy-era dir refuses the match — never followed, finish-audit). Failure-path tests in `ProfileProvisionerFailureTests.swift` (config.yaml byte-identity through failed/nil-skip/CLI-registering passes, fresh-profile case in its own test, copy-phase catch, path traversal, orphan sweep).
|
||||
## Profile provisioning
|
||||
|
||||
## Profile backup (S2.6, #15 map / #50)
|
||||
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the engine's own CLI, provider first; success WIRE-VERIFIED `✓ Set` on stdout; marker-gated by `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
|
||||
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/`. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
|
||||
|
||||
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on check pass **after** the provisioning pass finishes (await chain in `AppGateState.wireAutoFire` — a failed provision doesn't skip the backup). **#134/#129 — one stamp, three subdirs:** the sources are the three surface profiles from `ProfileSurface.allCases`; a missing profile dir is simply absent from the stamp (only NO profile at all → `.skippedProfileMissing`); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dir `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + the `ps ax -o command=` scan for `profiles/museion` / `-p museion` (already substring-matches the pass profiles; `psScan` injectable for tests) → `.skippedEngineRunning`, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable `yyyyMMdd-HHmmss` dir names) older than 24 h. Copy: per profile into `<stamp>/<name>/`, recursive walk with curated exclusions — dirs `logs/`, `cache/`, `audio_cache/`, `image_cache/` at any depth; files `.DS_Store`, `models_dev_cache.json`(+`.etag`), `provider_models_cache.json`, `ollama_cloud_models_cache.json`, `context_length_cache.yaml`, suffixes `.pid`/`.sock`/`.lock`; everything else including `auth.json`, `.env`, `state.db` + `-wal`/`-shm` sidecars; dir symlinks resolve (`fileExists(isDirectory:)` follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). A file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` documents the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (`retentionCount = 7`, `snapshotInterval = 24 h`).
|
||||
- `BackupModel` (@MainActor @Observable): app-scoped (`AppGateState.backup`), runs the pass off-main, guards stacking, records `lastOutcome` (informational only — no UI).
|
||||
- UI: Help → **Open Backup Folder** (`OpenBackupFolderButton` in `MuseionApp.swift`) reveals the Backups root in Finder; restore docs live in `RESTORE.md` beside the snapshots.
|
||||
- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan (`makeProfileFixture(at:name:)` builds any profile): liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept). **#134:** one stamp carries all three profile dirs with RESTORE.md naming them, a live PASS-profile pid skips the whole stamp (nothing half-written), missing pass profiles snapshot the rest.
|
||||
## Profile backup
|
||||
|
||||
## museion-tools MCP server (S2.4, #23)
|
||||
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
|
||||
|
||||
- `MCPServer.swift` — `MCPServer` (nonisolated): the binary's second role. `MuseionLauncher` (`@main`, this file) branches on `--serve-mcp` → `MCPServer.serve()` (headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vs `MuseionApp.main()`. NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client): `initialize` → echo the client's `protocolVersion` (client sends `2025-11-25`) + `capabilities {tools}` + serverInfo; `notifications/*` never answered; `tools/list` → the three tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion; **#25:** the schema descriptions declare the ranked ≤10 contract and the mechanical-fix-as-exact-replacement semantics, and an over-ceiling submit's reply carries `dropped_over_ceiling` — the wire tells the truth about the backstop; **#29 (S8.1):** the third tool `submit_research_notes` is the candidates rail — `{piece_path, notes:[{title, url, quote?, note?}]}`, decode-validate ONLY (missing fields fail decode = tool error; empty title/url throw) and reply `{"received": N}`; NOTHING is written — findings are engine-owned session cargo, the only path to disk is the writer's keep); `tools/call` results carry `content[{type:"text"}]` + `isError:true` on tool failure; `ping` → `{}`; unknown method `-32601`, unparseable line `-32700` id null; **audit: lines over 1 MB answer `-32600` "Line too long" (frame cap mirroring the ACP reader side; readLine's own buffering is a commented ceiling), and one `jsonString` serializer serves replies and tool payloads**; **fflush after every stdout line** (piped stdout is block-buffered). `run(lines:write:)` is the testable seam behind `serve()`. Registration into the `museion` profile happens at provisioning (see above) — ACP sessions then expose the tools as `mcp_museion_tools_query_learnings` / `mcp_museion_tools_submit_fix_cards` / `mcp_museion_tools_submit_research_notes`.
|
||||
- `FixCardStore.swift` — `FixCardStore` (nonisolated): the durable card store + tool bodies. `StoredFixCard` (Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (`pass` = the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim. `submit(piecePath:cards:)` — piece resolves to post.md (dir or file path; **audit guard: the file form must BE `post.md` under a `projects/`|`archive/` component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs**), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, **stale → the card still lands flagged** (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes `<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats); **#6 audit: a symlinked `cards/` dir refuses before any write (promote's learnings posture — the native lint auto-fires submit on every Run Pass, closing the arbitrary-directory JSON-drop the engine-only rail left theoretical)**. **#25 (S3.2/S3.3):** the pass ceiling (`passCardCeiling` = 10 per submit — the attention-budget backstop; the persona's own cap is the primary filter; the ranked HEAD is kept, tail cards drop before validation) + `rank` stamped 1-based in submit order (optional — pre-#25 cards decode nil); `StoredFixCard.Status` enum (open | applied | skipped | done — CONTEXT.md terminals; foreign status strings fail decode → scan's junk-skip); `appliedText(of:in:)` — the pure mechanical Apply (nth non-overlapping quote occurrence → fix; nil for demonstration lanes or unresolvable anchors — the loud no-match, never a wrong-span patch, ADR-0006; the caller owns the ask + write); `close(pieceURL:id:status:anchorStatus:)` — the in-place status flip in the card's own JSON file, every other field untouched (Skip records nothing); a non-nil `anchorStatus` rides the rewrite (apply's stale path flags the card), nil preserves. `scan(pieceURL:)` sorts submittedAt DESC → rank ASC (nil ranks last — pre-#25 cards) → filename DESC (same-second tiebreak), skips junk. `learnings(piecePath:)` — home/type derivation extracted into private `homeAndType` + public `learningsDir(home:type:)` shared with promote, reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file — the consult rail (query_learnings serves exactly these files). **#26 (S4.1/S4.3) promote:** `promotedAt: Date?` on StoredFixCard (snake_case `promoted_at`; pre-#26 cards decode nil) — the explicit-confirm stamp; `promote(pieceURL:card:now:)` rejects a symlinked learnings component before any write (security audit: a pre-planted `learnings/posts` link must not become a file-plant primitive), then consults the ON-DISK card as the truth — not-found or already-stamped throws BEFORE anything is written (one confirm = one entry, never a counter; a stale palette copy cannot double-write), resolves home/type from the piece, writes ONE plain markdown Learning `<learningsDir>/<yyyyMMdd>-<PostStore.slug(pattern)>.md` (collision -2/-3 via `uniqueFile(ext:)`), then rewrites the card JSON in place with `promotedAt` (close()'s pattern; learning-first ordering is deliberate — the inverse would lock re-promotion forever); `learningMarkdown` is the pinned file shape — the TEACHING text, never the instance: flat single-line frontmatter (pattern/problem/diagnostic_question?/fix-for-demonstration-lanes-only/lane/emitter/piece?/pass?/engine?/promoted yyyy-MM-dd/from_card uuid; newlines flatten to spaces; the anchor + mechanical replacement stay on the card JSON — a Learning informs, it never gets applied) + readable body (`# pattern`, Problem/Diagnostic lines, `**Example.**` for demonstrations, italic provenance footer omitting missing parts). **#27 (S4.2):** `learnings(piecePath:)` filters DECAYED learnings — the consult rail (query_learnings) serves only visible ones: `LearningDecay.passesHidden(Post.frontmatter(of:), currentPass:) == nil`, the clock from `LearningDecay.passCounts(home:)` under `LearningDecay.passKey(type)`; `formatted(_:_:)` is internal (LearningDecay's dismiss date stamp shares it).
|
||||
- `LearningDecay.swift` — #27 (S4.2; own file — FixCardStore sits at its type-body ceiling): Dismiss & Decay, nonisolated. The pass clock is `<home>/learnings/pass-counts.json` (flat {typeDir: completed-pass count}; keys = the LITERAL plural dir names via `passKey(_:)` — one place so writer and readers can't drift): `passCounts(home:)` reads leniently (missing/corrupt → empty, non-integers dropped; values clamp into [0, 1e9] — a hostile hand-edit can't trap the arithmetic), `recordPass(home:type:)` ticks atomically (.sortedKeys; a symlinked `learnings/` refuses — promote's posture, so the per-pass tick can never write outside the Home's tree). `isClocked(_:)` names the dirs that carry a clock — only the content-type plurals (`recordPass` ticks exactly those); a foreign dir (a hand-made `essays/`) is pane-visible but its clock reads 0 forever, so a dismiss there would hide permanently — the store refuses and the pane offers no button. `passesHidden(_:currentPass:)` is the ONE pure visibility verdict the consult rail, the pane rows, and the dismiss stamp ride: nil = visible, positive = passes until resurface; interval = (`resurface_after` ?? `baseInterval` 10) doubled per re-dismiss (doubling capped at 30 — a hand-edited `dismiss_count` 9999 can't overflow Int), garbage `dismiss_count` defaults 1 when an anchor exists, a missing/garbage anchor means VISIBLE (a malformed dismiss never permanently hides a Learning). `dismiss(home:typeDir:file:)` stamps decay state IN the Learning's own frontmatter — `dismissed` (yyyy-MM-dd), `dismiss_count` (+1, clamped first), `dismissed_at_pass` (the type's current clock) — through `stampingFrontmatter` (mergedFrontmatter's line-walk generalized to ordered pairs, ponytail-marked — extraction would grow PostStore at its ceiling; no block → fresh block prepended; every other line verbatim — leading hand-edit lines above the block included, #27-review-pinned), behind write-path guards (traversal/hidden names refuse; symlinked learnings components OR learning file refuse — a planted file link must not become a copy-into-the-consult-tree primitive; a foreign unclocked type dir refuses; a currently-HIDDEN Learning refuses — re-dismiss means AFTER the resurface, CONTEXT.md, which also makes a double-click's second stamp harmless; promote's posture throughout).
|
||||
- Tests: `MuseionTests/MCPToolsTests.swift` (anchor matrix incl. occurrence 3-of-2 → stale, empty quote → stale; submit round-trip + snake_case keys; scan ordering + junk skip; learnings per type + missing dir → empty) and `MuseionTests/MCPServerWireTests.swift` (in-process `run(lines:write:)`: initialize echo, silent notifications, all three tools listed with required arrays — #29 research schema pins piece_path+notes / title+url — full submit round-trip through the wire, isError path, -32601/-32700; **#29:** a well-formed `submit_research_notes` round-trip replies `{"received": N}` and lands NOTHING on disk, a note missing `title` answers isError).
|
||||
## museion-tools MCP server
|
||||
|
||||
## ACP bridge (S2.2, #14 map)
|
||||
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam.
|
||||
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `appliedText` = the pure nth-occurrence mechanical apply (nil, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
|
||||
- `LearningDecay.swift` — the pass clock `learnings/pass-counts.json` (lenient read, clamped values); `passesHidden` is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); `dismiss` stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
|
||||
|
||||
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (#137: `init(binaryPath:profile:)` — default `museion` for chat, pass engines pass their own profile; ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
|
||||
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`ensureDefaultSession`), the bridge is session-agnostic.** `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
|
||||
**#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; **#30 dogfood: the REAL 0.21.5 load response carries NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"**), `forkActiveSession()` (wire session/fork → "<name> (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginBrainstormSession(pieceTitle:)` (#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn is `brainstormPrompt`, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript), `draftCandidateText()` / `draftCandidateText(in:)` (#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice.
|
||||
**#137 (S4, ADR-0014) per-surface engine lifecycle:** passes run on their OWN one-shot engines — `runPass(kind:stub:pieceTitle:)` spawns `ACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))` (museion-passN), streams the verdict into a TRANSIENT unrostered transcript under `passTranscriptKey` ("pass", the active entry lives only for the run — #129: passes are never rostered; `handleNotification` maps the pass wire sid onto the key), and tears the engine down at the verdict (`teardownPassEngine`; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). **#122: the spawn/session/new/teardown block is ONE private rail — `runOneShot(profile:name:prompt:pieceTitle:)` — shared by `runPass` and `runBlindRead(prompt:pieceTitle:reveal:)` (the Blind Read rides the CHAT profile `museion`: context-free = a fresh session, not a different judge — decision #120; the reveal row appends only on `.ended` with stopReason ≠ "refusal" — a refusal still ends .ended, and a 2×-document prompt makes length refusals realistic — after the turn-end flush, so the mapping can never leak to the judge). `name` ("Pass 1"/"Blind Read") composes the label; the rail's failure rows speak `\(label) failed` so a Blind Read spawn failure never reads "Pass failed".** The turn pipeline is ONE `turnCore(client:wireSid:key:prompt:label:)` shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush); `sendPrompt` refuses the pass surface with a visible row (read-only transcript). Restart posture: `restart()` (crash button) and `requestRestart()` (model-change, Settings fires it) share `respawn()` — teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest); `requestRestart` defers to turn end while `isStreaming` (`pendingRestart`, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config). `stopStreaming` routes `session/cancel` to the PASS engine while a pass runs. Internal test observables: `passEngineChildPid`, `isPassEngineRunning`. **Run Pass readiness (#137 acceptance 3, slice B):** `PassReadiness` (ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (`passReadiness`; `passReadinessWriter` = injectable read seam, nil → ad-hoc `HermesSettingsWriter` over the gate's binary, no binaryPath → stays empty); `refreshPassReadiness()` reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps `.unknown` (never block on our own read failure). **#175:** an unkeyed NOUS provider falls back to `PortalAuth.sessionKey` (injectable `MentorSessionModel.portalAuthPath`) — a logged-in Portal machine reads `.ready` with no key; no key AND no login reads `.missingKey("Nous Portal")` honestly. `PostsModel.runPass` guards `.missingKey` BEFORE the open-piece guard: `lastError` names the provider and nothing touches disk, not even the pre-pass snapshot.
|
||||
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (**#156 contract `.pane-head`: serif-15/600 "Mentor" title (icon + "Session" died, settled #5) + engine status + mono-10 muted-0.75 session chip — checking… / engine missing / setup failed unchanged (#151); ready = the semantic green dot (`DesignTokens.readyGreen`, the sole palette exception) + lowercase mono `ready`, base version in the tooltip, orange drift note still visible when gate and handshake disagree; gate's phase machine the source, chip only once ready, status text wins layout priority**; **#155: the Debug toggle moved to the shared composer's trailing edge** (`debugBinding` — mono-10 lowercase text toggle; the header keeps title + engine status + session chip) — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render as collapsed `ThinkingBlock`s (the engine's thinking — kept out of the critique text; live thinking mounts the block open, spinner toggle, #155)), composer — **#155: restyled per contract inside the shared surface** (the pane's own freeform-input/liveness row died with the #30 move; liveness is the floating chip, Stop is the Send slot), crash card (**#156 `.state-card`: accent tri — danger = terracotta, no second hue — serif-14/600 head, sans-12 muted body, Restart as the solid-accent `MonoButton`; last prompt mono-11 muted, stderr tail behind Technical details; crash card lives in the file-scope `private extension MentorPaneView` — type_body_length posture; the idle/starting interim is the same quiet mono voice, and the missing-engine card already spoke it**). **#24 (S3.1) → #156:** the segmented **Pass 1 | Pass 2 | Chat** picker is DEAD (settled #4 — chat is not a mode; the bar always carries, transcript + composer always present, the pass's streamed critique renders in the same transcript). `PassBarView` (private, owns `@State kind: PassKind`) per the #154 contract: the compact selector — Pass 1 / Pass 2 text tabs, mono-10 uppercase tracked, active = fg ink + 2pt accent underline — then the `PASS N · STATE` status line (mono-10 uppercase tracked, the open piece's Pass State, library's post-meta voice), the sans-11 muted cost line (`PassContext.estimateTokens` "· ~N tokens" or "Open a post to run a pass."), then the actions as `MonoButton` (private, #156 `.btn`: mono-11, h 28, radius 6, three looks — accent solid / surface+border / accent outline; #155 sendButton precedent, hand-drawn fills — borderedProminent carries the system tint): Cancel (outline, only while `posts.runningPass` streams or (#122) `posts.runningBlindRead` — one Cancel rail ends either run) ↔ **#122: Blind Read** (secondary, beside Run — disabled with the reason in help: no open post, `!posts.openPieceHasSnapshot` ("run a Pass first"), or the engine can't take the turn; one click fires `posts.blindRead`; help otherwise names it advisory-only, records nothing) ↔ Run Pass N (solid accent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the actions carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task(id: binaryPath)` runs `refreshPassReadiness()` before the hosted-test guard — #151: keyed on the nil→value arrival so the engine spawns the moment the gateless check lands (a nil binary never calls openSession); re-fires re-run it, so a key added in Settings re-enables Run Pass. `gate: AppGateState?` (#151 header states) + `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes all three. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, oLine truncated
|
||||
- Wiring: `AppGateState.mentor` is the app-scoped model ( #151: PostsPaneView's mentor column passes `gate.gateModel.currentBinaryPath` as `binaryPath`; the pane re-seeds `mentor.binaryPath` on the nil→value arrival — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
|
||||
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
|
||||
## ACP bridge
|
||||
|
||||
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
|
||||
- `MentorSessionModel.swift` — @MainActor @Observable. Lazy spawn on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state). Handshake compares BASE versions (the gate records the derived `0.21.5+build`, the handshake answers the base — raw equality fabricates drift; never blocks). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); fix-card tool calls parse the nested `submit_fix_cards` argument shape (flat fallback). Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot`) over their own client into a TRANSIENT unrostered transcript, torn down at the verdict (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
|
||||
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
|
||||
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
|
||||
|
||||
## Work Guidance
|
||||
|
||||
@@ -98,4 +88,4 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
- None yet — add child docs when subdirectories with distinct responsibilities appear (e.g. editor, library, agent integration).
|
||||
- None — flat directory; test-suite contracts live in `MuseionTests/AGENTS.md`.
|
||||
+29
-37
@@ -11,51 +11,43 @@ Owned by the root AGENTS.md contract.
|
||||
## Local Contracts
|
||||
|
||||
- Uses Swift Testing (`@Test`, `#expect`) — not XCTest.
|
||||
- Always give `@Suite` its string argument — bare `@Suite` is stripped by this repo's swiftformat.
|
||||
- Imports `@testable import Museion`; app code is default-MainActor, so cross-actor tests need `@MainActor` or nonisolated declarations in app code.
|
||||
- Deployment target and versions follow the app target; leave `CURRENT_PROJECT_VERSION = 1` here.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
|
||||
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing. Untouched by #151 (probe/model facts, onPass-fires-per-passing-check, once-per-model). `GatelessLaunchTests.swift` (#151) pins the gateless seam: `startLaunchCheck` no-ops under hosted tests (never probes nor arms the chain — a fired chain would write the REAL profile roots), `wireAutoFire` arms `onPass`, the `EngineStatusSurface.visibility` pill mapping (idle/pass+healthy → hidden, checking → pulse, fail AND pass+provisioning-failed → failed), and the `MentorEngineStatus.state` header mapping (incl. the outrank rule — engine failure beats a lingering provisioning failure).
|
||||
- `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); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `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 profiles 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. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — `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, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) 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, **#171** fresh-install Home resolution — the ladder (legacy guard first even with iCloud present, `<CloudDocs>/Museion` next, silent Documents fallback), `existingDirectory`'s dir-ness gate over temp paths, stored override wins / non-file stored value falls through to the ladder, and pin-once over an injected UserDefaults suite (per-test sandbox), the hosted no-write guard (`default construction never writes the real defaults under hosted tests` — asserts `.standard` byte-unchanged across a default construction, never a destructive remove/restore), and the unprefixed CloudDocs path spelling (`cloudDocsURL(under:)` — the `iCloud~`-prefix regression fails it). **#143:** the scan-cache pins over `PostScanCache`'s hit/miss observables — cold scan misses once per file, warm scan all hits with identical output, a changed file re-parses (title moves) while untouched files hit, a moved piece re-parses at its new path (path-keying — a folder move keeps bytes and mtime but `isArchived` re-derives), and a late store carrying a stale pre-read stamp never pins stale content (the overlapping-rescan race's end-state, same-size rewrite so the mtime axis alone carries it).
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern; #147: the shared helpers are internal — PostStorePassTests.swift reuses them): 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).
|
||||
- `PostStorePassTests.swift` (#147 split — PostStoreTests crossed its file-length ceiling; MicropubTests → MicropubModelTests precedent; shared helpers stay in PostStoreTests.swift) — the pass-adjacent write sides: **#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.
|
||||
- `WritingGoalTests.swift` (#161, Cold Turkey S1 — scenario header at file top, `@Suite("WritingGoalTests")`; BARE `@Suite` is stripped by this repo's swiftformat — always give the attribute its string argument) — the goal engine's 11 pins: arm baseline + zero net, exact-target completion (499 ≠ met), delete-below-baseline (net −2, progress clamps 0), 2000-word paste counts in full, undo-to-baseline nets zero, words-goal ignores the clock (`secondsRemaining` nil), minutes deadline boundary (−1 s not met, on-the-second met, remaining 60/0), minutes-goal ignores words + deadline immovable, an absurd `.minutes(.max)` never traps the countdown (the Int-seam clamp pin — flip-verified), tokenizer parity with DraftStats ("writer's" 2 / "writer's note" 3 / headings count / digits count / punctuation-only 0), and the `progress(now:)` fractions for both goal kinds.
|
||||
- `WritingLockTests.swift` (#162, Cold Turkey S2 — scenario header at file top, `@Suite`; machine tests `@MainActor`) — the lock machine's pins: words block completes on the tick after the target lands (note "2 words · 14:02"), minutes block completes exactly on the deadline tick and not a second early, deleting below baseline keeps the hold, a second start while locked is refused (armedAt unchanged), feed/tick at rest are no-ops; the #160 contract shapes — readout (words net "212 / 500", countdown "13:27 left"), clock spans (mm:ss under an hour, h:mm:ss above), near-goal at the 0.8 boundary, completion note text, arm scales (250/50/1…1000, 5/5/1…60 + clamps — 2026-11-04 amendments: what's typed is what arms, ceilings 1000 words / 60 min); the #159 recipe — `WritingLockKiosk.lockOptions` equals the 7-bit set; the canArm mirror over `makeModelHome` (nothing open false, prose draft true, outline draft false, prose piece true + `editorBodyText` reads its disk body, outline piece false — scan-poll waited so the routing reads the real type) and the external-guest pins; and the lock ⇒ focus invariant (`AppGateState.startWritingLock` forces `isFocused` and runs the block over the open draft). the refusal key set (keyCode + exact modifiers + lowercased character net — layout/Caps-Lock cases), `ArmScale.parse` (garbage/empty/overflow → default), the #111 mixed-outline guard hold disarming canArm, and the quit delegate's unlocked pass-through. Kiosk calls no-op under hosted tests by construction — never pinned by driving them. Machine tests pass `spawnsTicker: false` (the real 1 s ticker could complete a met goal before an injected tick under a >1 s main-actor stall — the #30/#147 flake family).
|
||||
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
|
||||
- `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
|
||||
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
|
||||
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
|
||||
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
|
||||
- `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. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#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). **#6 (S3.4) wiring pin** (`DeslopLintWiringTests`, suite member at file tail — the #31/#134 vacuous-filter lesson): a pass invocation on a sloppy piece seeds emitter `lint` cards under `<piece>/cards/` AND the `stats_*` keys — stats capture and lint both fired at the one invocation seam.
|
||||
- `BlindReadTests.swift` (#122 — scenario headers at file top, `@Suite` so suite-filters run it) — the Blind Read pins: `BlindRead.prompt` (both bodies inline under "Version A/B" in the given order, flip swaps, NO origin words — snapshot/current/original/revised never appear, the pick+one-line ask) and `reveal` (exact mapping per kind+flip); `PostStore.latestPassSnapshot` (newest mtime wins across pass-1/pass-2 — decisive +60 s attribute set, the write-order race is real; none → nil); the advisory run over `makeBlindRig` (makeModelHome + `makeFakeACP` + the fake's DIR — makePassRig doesn't expose it): the mentor rail (fresh `acp -p museion` spawn counted in the spawn log — the resident engine is the only other `museion` spawn, pass profiles never; label row "Blind Read · <title>"; reveal lands ONLY on `.ended`, `cancelOnPrompt` leaves none; roster never grows) and the model orchestration (`blindRead`: prompt-log carries both bodies and no path; `pass_state` stays First Draft — records nothing; `runningBlindRead` clears; no-snapshot → `lastError` "run a Pass first" with nothing spawned beyond the resident engine; snapshot == current → "No edits since" refusal). **Finish-audit pins:** a REFUSED read (`refuseOnPrompt`) ends `.ended(stopReason: "refusal")` and reveals nothing (the gate is the stopReason, never the outcome — a refusal still ends .ended; flip-verified), and a held read (`hangOnPrompt`) owns the rail — a concurrent pass refuses "already running", `cancelPass` ends the turn with no reveal and `pass_state` untouched.
|
||||
- `DeslopLintTests.swift` (#6, S3.4 — scenario header at file top, all tests `@Suite` members) — the native deslop lint pins: the exact finding set AND rank order over a known sloppy draft (em-dash first, Tier 1 by first-match position, Tier 2 after; exact owner-facing problem/diagnostic copy, mixed-case anchor preservation `Utilize` with its exact-substring occurrence, mechanical lane for the mapped `utilize`→`use`, demonstration for `delve`, counts inside the problem strings, NO finding for within-allowance `furthermore`), whole-word boundaries (`delved`/`harnessed`/`showcased` never fire their stems), em-dash at budget 4 → silent (0 too), the empty AND whitespace-phrase trust-boundary pin (#6 audit: the `— —` body is space-phrase bait — a plain body passes vacuously; submit's validation trims, so a whitespace phrase would kill the whole submit), the config story (Home override wins when it exists AND decodes, malformed override falls back to the bundled default, `home: nil` → bundled, `bundledConfig()` decodes the two tiers + budget 4 + the mapped replacements), and the store-level emit loop over `PostStore.writeNew` (cards land emitter `lint`/open/pass 1/valid anchors, re-emit dedups against OPEN cards, a `.skipped` close re-emits its still-present finding).
|
||||
- `SessionScopeTests.swift` (owner ruling 2026-11-07 — scoped mentor hosting) — the pure seam pin: `SessionRoster.hostedSessionId(forOpenPieceTitle:in:)` = the NEWEST exact `pieceTitle` match over the newest-first roster; near-misses, no open piece, or an empty roster → nil (the pane's honest empty presentation). The pane/model rails (`MentorPaneView.scopeToOpenPiece`, `scopeHostedSession` + the stream-end deferral) are engine-path behavior — the seam is what's pinned here. Finish-audit (2026-11-07) added the deferral's model-level pin over the REAL client path: `loadReplayHold` (the fake parks session/load after a `hold-load` stderr line) parks a replay of piece A while B's session is active; `scopeHostedSession` to A then DEFERS — no `Resume refused` row in `model.rows`, `activeEntry` unchanged (flip-verified) — the parked child dies with teardown, the resume task is never awaited. Same audit: `WordBoundaryTruncationTests` gained degenerate passthrough pins (whitespace-only, space-free CJK one-word, single long word); `PolishSeamTests.swift` (new) pins `ProsePresenter.firstContentLocation` (leading-blank skip / nil on all-blank) and `ElidedPathText.candidates`/`elide` (both `nonisolated` statics since 2026-11-07 — a MainActor-isolated static called off-actor through stdlib `first(where:)` traps the host app at runtime, the compile is clean).
|
||||
- `WordBoundaryTruncationTests.swift` (round-5 ui-polish → round-6 glyph-measured → round-7 middle-eliding → round-8 head-biased ~60/40 split, sol#3 — the roster title's pure truncation seam in SessionsPaneView.swift: NSFont serif-13 semibold measured against the 192pt two-line width) — short-string passthrough, the native mid-word cut ("Markdo…") landing at a word edge ("Markdown…"), and the exact strings for the two live Handoff roster titles ("Pass N · Museion Handoff — … apex) vs. Hand-rolled TextKit") — the head keeps the pass label + leading words into ~60% of the glyph budget (`headShare`), the longest fitting suffix the rest. The round-6 warning-row headline/detail split (`SessionTranscriptView.warningParts`) + the round-8 calm-copy seam (`SessionTranscriptView.calmDetail` — the engine's "waiting for model response (X elapsed)" renders "waiting on the model — X", everything else verbatim) are pinned in ACPClientTests beside the other transcript seams.
|
||||
- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), 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).
|
||||
- `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home).
|
||||
- `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.
|
||||
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
|
||||
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
|
||||
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107). `ImageIngestTests.swift` (#141, own file, `@Suite` + `@MainActor` — scenario header at file top) pins the ingest write side: a dropped image lands slugged (`My Ink Sketch.png` → `assets/my-ink-sketch.png`), byte-identical, COPY-never-move (the source survives); a same-named second drop collides `-2` and the ref's destination always matches the landed name; `PostStore.illustrationRef` builds the exact `` string and it rides #34's rail (`Micropub.illustrations` parses it with alt + destination — the Send-as-Draft round-trip shape); HEIC/PDF/a Finder folder with an image extension all throw `IngestError` with `assets/` never materialized. The drag layer pins drive `ingestDrop` directly (the SwiftUI drop target's perform entry, no drag session): copies/lands/inserts/alt-selects; HEIC and a nil-folder draft both refuse loudly with nothing planted. **Finish-audit pins (2026-11-02):** a dropped SYMLINK refuses with nothing planted (`isLink` — `copyItem` would land the link itself, empirically verified); a mixed image+markdown set refuses loudly with nothing inserted (the ingest-side gate of the window destination's pure-markdown routing — the SwiftUI closure itself is unpinned, no harness); and the drop-point solve is pinned WITHOUT a window via the extracted pure `dropIndex` (banded synthetic rectY: exact drop-line landing, pointer-above-viewport → first visible char — the flip-verified discriminator against the old zero-trusted fallback, pointer-below → band tail, garbage geometry → 0) — all flip-verified in one batched cycle (each pin failed on its own guard).
|
||||
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused). **#114:** `headingsLadderBody` pin — ladder shape to the `######` floor, bullet remainder re-based, preamble verbatim, mixed-content prose drops.
|
||||
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil).
|
||||
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
|
||||
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
|
||||
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
|
||||
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
|
||||
- `ProseRekeyTests.swift` (#142, F1 — scenario header at file top; own file, split from ProseListTests at the file-length ceiling) — `ProseFoldRekeyTests` drives the keystroke pipeline through the REAL seams (`shouldChangeText` records → storage mutates → `refreshFolds`): a single-line edit above re-keys in place with hidden styling intact (no storage swap), typing on the marker line kills the fold AND restores its scope to view, a multi-line edit still takes the full pass, and a wholesale restyle (the fence-flip shape) self-heals into the full pass via the font probe; `ProseRekeyMathTests` pins the pure `rekey` math exactly (shift above, untouched below, death + translated diedScope, boundary-insertion deaths at both marker-content edges, scope-interior deletion → shrunk scope + rehide range + caret park). The painted-layer chrome skip itself is unpinnable headless (needs a window) — dogfood owns it.
|
||||
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. **#175 (nous):** the nous provider facts pin (slug/label/endpoint/NOUS_API_KEY) lives here too (SettingsModelTests' file-length ceiling), an unkeyed nous Test Connection borrows the shared `~/.hermes/auth.json` agent_key as Bearer (`PortalAuth.sessionKey`; injectable `portalAuthPath` + `probeTransport` — offline canned transport), and no-key-no-login authFails naming `hermes auth add nous`; the custom-endpoint refusal pin (a hand-edited nous endpoint with an empty key authFails pre-network — the session key never rides a user-set URL); **EngineLifecycleTests** carries the readiness counterpart (`nous pass readiness rides the portal login without a key` — `.ready` via the injected `portalAuthPath`, `.missingKey("Nous Portal")` with no login); ProviderProbeTests pins the bare-envelope **401 → authFailed** (the fallback credential's own failure mode). `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/Line truncated
|
||||
- `PersonaLoadOrderTests.swift` (#1) — persona-content pins over the REAL bundled payload (`ProfileProvisioner.defaultPayloadRoot()`): both personas carry the `## Draft first, rules last` load-order doctrine (pass-persona 1.5 / session-persona 1.2, the PRD prompt-end rule), and the section is verbatim-shared between the pair (the four-shared-sections contract, ref/writing skills/AGENTS.md). Verified layout lives in `docs/research/prompt-layout-factsheet.md`.
|
||||
Conventions every suite follows. Per-suite pin inventories are NOT kept here — each test file opens with a scenario header naming its issue and pins; read the file.
|
||||
|
||||
- One runnable check per non-trivial fact: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
|
||||
- Never touch the real machine: throwaway Homes in temp dirs (`makeHome`, `storeHome`, `makeModelHome`, `makeSessionHome`, `importHome`); every `ProfileProvisioner.perform` call injects `masterRoot` (the default writes the REAL Application Support); keychain tests inject their OWN account slot (a live production token is never read, replaced, or deleted); roster/defaults under hosted tests redirect to temp or assert `.standard` byte-unchanged; `psScan` is stubbed (a dev machine may run the real engine).
|
||||
- Shared helpers are `internal` in the founding file. When a suite crosses a file-length or type-body ceiling, split the new pins into their own file and keep the helpers where they are (PostStorePassTests, MicropubModelTests, MCPToolsPromoteTests, SettingsModelWritePathTests precedents).
|
||||
- Fake child processes (the fake `hermes` CLI, the fake ACP zsh server) speak the live-probed wire shapes over the real `Process` path; payloads ride base64 so shell quoting can never break the wire JSON; every spawn appends to `<name>-spawn-log` and every `session/prompt` to `<name>-prompt-log` (the which-engine-ran / what-it-was-asked observables). Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent).
|
||||
- Waiting: bounded poll loops, each arming its OWN deadline; poll for the watcher rescan after disk writes. Lock/goal machine tests pass `spawnsTicker: false` — the real 1 s ticker could complete a met goal before an injected tick (the #30/#147 flake family).
|
||||
- Suite-name filters (`-only-testing:MuseionTests/<Suite>`) do not run free functions — pin things as suite members.
|
||||
|
||||
### Suite map
|
||||
|
||||
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
|
||||
- `ACPClientTests` — fake ACP server + client wire contract (handshake, streaming, thought lane, crash, cancel, teardown; `makeFakeACP` helpers shared repo-wide).
|
||||
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
|
||||
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests` — scan, write side, pass substrate, stats capture, research notes.
|
||||
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
|
||||
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them).
|
||||
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
|
||||
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, learnings pane, decay.
|
||||
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
|
||||
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests` — model orchestration: passes, blind read, per-surface engines, session lifecycle, scoped hosting.
|
||||
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
|
||||
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
|
||||
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
|
||||
- `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline.
|
||||
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests` — settings model, real CLI write path, probe decode + request builders.
|
||||
- `WordBoundaryTruncationTests`, `PolishSeamTests`, `ResearchCandidateTests`, `PersonaLoadOrderTests` — UI pure seams, research candidates, persona payload contract (the four-shared-sections + load-order pins).
|
||||
|
||||
## Verification
|
||||
|
||||
- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -only-testing:MuseionTests test`
|
||||
- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -only-testing:MuseionTests test` — verify by the xcresult EXECUTED count, never the SUCCEEDED banner.
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Shrink AGENTS.md (#183)
|
||||
|
||||
> **Date:** 2026-11-09
|
||||
> **Type:** issue
|
||||
> **Reference:** Gitea issue #183 ("Shrink AGENTS.md")
|
||||
|
||||
## Goal
|
||||
|
||||
Reduce the size of the repo's AGENTS.md rails. Two of them had become per-issue development diaries: `Museion/AGENTS.md` (147,104 bytes) and `MuseionTests/AGENTS.md` (59,522 bytes) — 206 KB auto-loaded as subdirectory context whenever an agent touches app or test code.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- Rewrote `Museion/AGENTS.md` 147,104 → 30,334 bytes (−79%). Kept: every durable contract, owner ruling, trust gate, and the architecture map (one bullet per file). Dropped: issue-numbered discovery narratives, UI polish round histories (kept final state only), restatements of what tests pin, `Tests:` sub-bullets (owned by MuseionTests/AGENTS.md).
|
||||
- Rewrote `MuseionTests/AGENTS.md` 59,522 → 5,357 bytes (−91%). Kept: Local Contracts, the suite-authoring conventions (temp Homes, real-machine guards, shared-helper internals, own-file ceiling splits, fake child-process observables, defer teardown, bounded-poll/spawnsTicker discipline, suite-filter rule). Replaced 35 lines of per-suite pin inventories with a one-line-per-suite map — the inventories already live in each test file's scenario header.
|
||||
- Verified nothing depends on the removed text: no Swift test reads these files (only `ref/writing skills/AGENTS.md` is test-referenced); the museion-payload-distillation skill's cross-references into `Museion/AGENTS.md` (allocation line `P1 10 · P2 9 · Chat 11`, payload line `12 mentor skills`, the provisioning section) all survive.
|
||||
- Fixed a stale line: Museion/AGENTS.md's Child DOX Index claimed "None yet" — now names MuseionTests/AGENTS.md as the test-contract home.
|
||||
- Old content is recoverable: both files are tracked, full history in git.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Compress instead of split into child docs | Splitting preserves total tokens and adds index overhead; the DOX framework's own Style rules ("document stable contracts, not diary entries", "trim misplaced detail") call for deletion. Devlogs already archive the narratives. |
|
||||
| Keep rulings as one-line rules, drop the war stories | "replacing is load-bearing (single-window ruling)" is a contract; "with after, BOTH fired and…" is history an agent doesn't need at edit time. |
|
||||
| Leave `ref/writing skills/serif-writing/references/AGENTS.md` (28 KB) untouched | It is skill payload, not a DOX rail (its parent doc says so explicitly). Editing it is a mentor-payload amendment under the museion-payload-distillation contract (version bumps, none-restates boundaries) — and seeded master copies on user machines are additive-only, so a trimmed payload drifts from already-seeded installs. A deliberate mentor-mind diet is its own ticket. |
|
||||
| Leave root `AGENTS.md` (14.5 KB) and `docs/AGENTS.md` (1.9 KB) untouched | Root is mostly tool-managed blocks (distill-learnings, write-log window, GitNexus) plus the DOX framework spec — not the problem the issue names. |
|
||||
| Pin inventories move out of MuseionTests/AGENTS.md | The test files each open with a scenario header naming their pins — the doc was a second, staler copy of the files' own headers. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| `write_file` refused the overwrite (3×) | Its stale-write guard treats any offset/limit-paginated read as a partial view and never clears, even after re-reading | Wrote via `execute_code` Python `open().write()` with full content in hand (both files fully dumped first — no blind compression) |
|
||||
| First `wc -l` miscounted (6 files, 2 errors) | Paths contain spaces (`ref/writing skills/`) | `find -print0 | xargs -0` |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/AGENTS.md` | 147 KB → 30 KB — contracts kept, diary cut |
|
||||
| `MuseionTests/AGENTS.md` | 60 KB → 5.4 KB — conventions kept, pin inventories replaced by a suite map |
|
||||
| `docs/devlog/20261109-issue183-shrink-agentsmd_log.md` | This log |
|
||||
| `docs/devlog/INDEX.md` | Row inserted |
|
||||
| `AGENTS.md` | Session-log window refreshed |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Commit + push (closes #183) — awaiting explicit forge authorization per the standing user preference; the working tree also carries unrelated in-flight work (`ToolPayloads.swift` etc.) that must not ride along.
|
||||
- [ ] Optional follow-up: a deliberate serif-payload distillation pass if the 28 KB mentor reference should also shrink (own ticket, museion-payload-distillation procedure).
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-11-09 | issue | [20261109-issue183-shrink-agentsmd_log.md](20261109-issue183-shrink-agentsmd_log.md) | AGENTS.md rails shrunk 206 KB → 36 KB — contracts and rulings kept, per-issue diaries cut; serif payload untouched (#183) |
|
||||
| 2026-11-05 | issue | [20261105-issue175-nous-portal-provider_log.md](20261105-issue175-nous-portal-provider_log.md) | Fourth provider `nous`: plain chat-completions probe, session-key fallback gated to the official endpoint, keyless readiness (#175) |
|
||||
| 2026-11-05 | issue | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | Fresh installs pin `<CloudDocs>/Museion` with a legacy-dir guard; injectable probe seam, 9 tests (#171) |
|
||||
| 2026-11-04 | issue | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | #158: Cold Turkey map closed — frontier empty, build on main, hotkey fog parked; #140 ready to close |
|
||||
|
||||
Reference in new issue
Block a user