diff --git a/AGENTS.md b/AGENTS.md index 0e85048..773a77b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,6 +201,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 2c89efa..a47da0c 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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 \
` (#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) `/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/ / /post.md` AND `archive/ / /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- .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; ` /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); `` 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) → ` /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: "; 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 --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 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 ` 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 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 ` /profiles/ `, speaks `-p 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 ` / /`, 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 `. - ` temp dir, rename into `~/Library/Application Support/Museion/Backups/ /`, 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 ` /cards/ - .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 ` /learnings/ 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 ` / - .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 ` /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 → " (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 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, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist; **#156 ruling: a plain mono row — no card, no hairline of its own, a link not content**). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture). **#29 (S8.3):** the transcript renders `.researchNote` as full candidate cards (NOT one-line events — a handful of notes curates in place, no palette): serif-13 title, mono-11 muted url, selectable note, muted-italic quote; pending offers Keep + Reject (mono-11 bordered; hidden when the pane's `home` is nil — previews), kept/rejected dim 0.45 (closed-card voice) with meta `kept · research/ ` / `rejected`; the Mentor pane passes its `home`, the Sessions pane gains `home: URL?` (WorkspaceView hands `gate.museionHome`). Keep = ask-before (G9): `ResearchKeepSheet` (own file, PromoteAskSheet posture — "Keep this research note?", the nothing-saves-until-you-keep line, note preview, Cancel/Keep; ONE confirm → `PostStore.writeResearchNote` → disposition flips, refusal inline orange with buttons kept). Reject = no confirm (Dismiss-button voice — vanishes, nothing recorded). The sheet state lives in SessionTranscriptView (`pendingKeep`, `.sheet(item:)` over the transcript — never inside a lazy row). -- 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 `; 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`. diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 33847ea..7caaef3 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -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 ` -spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to ` -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- ` 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 ` /profiles/ ` (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 mcp list`/`mcp add` (per-profile marker `mcp-registered- ` = already registered, invocation log `mcp-add-invocation- ` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p config set` (argv log `config-set- `, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store- ` map (dedup per key), and the fake speaks `config get ` (store value, or the not-set line on stderr exit 1) and `config unset ` (argv log `config-unset- `, 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/ / /` + `archive/ / /` (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, ` /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/ / /` + #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/ / /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 ` /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 · " 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 ` /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 · "; 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 · \ "), 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 (" (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 ` `, 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/
/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 ` ` 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/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed, **#175 nous chat-completions** + the portal's bare `{status, message}` envelope decoding requestFailed with the message — the error-object-less shape) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the Responses dialect** — `input` + `max_output_tokens` + `gpt-6.1-sol`, messages/max_completion_tokens/max_tokens asserted ABSENT, URL `/v1/responses`; trailing-slash + garbage-endpoint nil-safety via the http(s)-scheme check) and `probe()` over canned transports — no-key fail-fast, end-to-end works with model count + reply, a /models auth failure short-circuits the chat step, transport errors → unreachable. `SettingsModelTests`' switch-default pin rides the gpt-6.1-sol flagship; **#175:** the nous switch lands on `anthropic/claude-sonnet-5` (the router-catalog flagship, registry-known via the fixture's `.nous` row) and the ladder pin covers nous. **#137 B2 (scenario header in `SettingsModelWritePathTests.swift`):** the chat-restart hook — a successful chat-surface write fires `onChatSurfaceWrite` after `awaitPendingWrites()`, pass-surface edits and key writes never do, and a failed chat write (`failSurfaceWrites`) never does either. -- `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 `
-spawn-log` and every `session/prompt` to ` -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/ `) 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 diff --git a/docs/devlog/20261109-issue183-shrink-agentsmd_log.md b/docs/devlog/20261109-issue183-shrink-agentsmd_log.md new file mode 100644 index 0000000..82468fc --- /dev/null +++ b/docs/devlog/20261109-issue183-shrink-agentsmd_log.md @@ -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* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 2d77d89..6661568 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | 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 ` /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 |