Files
museion/Museion/AGENTS.md
T
AlexKucera f2953ee07e
CI / ci (push) Canceled after 0s
feat(editor): land editor core — open, edit, autosave (S1.2)
Posts open into the TextKit2 surface (ADR-0010 mode B) lifted from
the proven spike: styled source, scaled headings, dimmed syntax,
native undo/IME. One EditorSession per open post drives a ~1 s
debounced autosave (flush on selection change, window close, app
quit; ⌘S immediate), the Saved/Saving/Failed dot, and the per-post
.museion-state.json cursor sidecar that dies with the folder.
External edits raise an explicit Reload/Keep-Local alert — the
debounce never answers it for the writer, and drafts keep the
lazy-folder first-⌘S rule (#62).

Reviewer fanout fixes folded in: session teardown at every lifecycle
exit (rename flushes before the folder move; trash cancels the
debounce), draft ⌘S continues in place, conflict holds the debounce,
rescan's disk read off-main, ~35 lines of dead code out.

Closes #19
2026-10-05 10:56:33 +02:00

76 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Museion (app target)
## Purpose
The Museion application target: the native SwiftUI macOS app shell of the Agentic Writing Environment. Everything user-visible lives here.
## 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).
## Local Contracts
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state).
- `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 26.5; 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. Exception: the engine gate's `state.json` (see below).
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
## Workspace shell (M1, #17 + #18 / S1.1)
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. Light-only — the export defines one palette.
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border.
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`).
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on `posts/`, rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `posts/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — the lifted spike presenter: line-kind → attributes map (Iowan Old Style 17 body, 26/20 bold headings, quote spacing, `***`-rule syntaxOnly), dimmed syntax (marker prefixes + inline marks, mono 13 at 0.55 white), pure functions; full-doc `attribute` on load, per-paragraph `reattribute` on edit. `EditorSession.swift` — @MainActor @Observable session per open post: `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` writes `PostStore.overwrite` + the cursor sidecar, tracks `saveState` Saved→Saving…→Saved (+ Save failed in accent, #65, routed to `lastError` too); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local; `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads the sidecar; `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in `posts/<id>/.museion-state.json` — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI.
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). 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.
## Engine gate (launch gate, tickets #35–#41)
- `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): phases for the UI, `onPass` seam (fires provisioning, #47), `currentBinaryPath` handed to provisioning. `execute(_:timeout:)`/`ProcessOutput` are internal — shared child-process machinery.
- `EngineGateView.swift` — blocking sheet card: checking / pass (version + Start Writing) / fail (two install steps per #40, Re-check, Technical details disclosure). `interactiveDismissDisabled`; sheet never closes itself.
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check; fail records carry no `engineVersion`. Gate renders in-memory; About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` fires provisioning (#47) in parallel on pass.
- Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
## Profile provisioning (S2.1, tickets #43–#48)
- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: <name> <version>, … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate.
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning writes nothing to the profile config — never an `mcp_servers` entry (#44 negative invariant, test-pinned).
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.
## Profile backup (S2.6, #15 map / #50)
- `ProfileBackup.swift` — `ProfileBackup` (nonisolated): one pass per launch, fired on gate pass **after** the provisioning pass finishes (await chain in `ContentView.onEnginePass` — a failed provision doesn't skip the backup). Liveness gate first: `gateway.pid` (JSON line: `pid`, `hermes_home`) pid-liveness via `kill(pid, 0)` + `ps ax -o command=` scan for `profiles/museion` / `-p museion` (`psScan` injectable for tests); either live → `.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: recursive enumerator 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. Directories are `createDirectory`d, files `copyItem`d (the enumerator re-yields children — whole-subtree copyItem would collide); a file vanishing mid-copy is skipped. Install: copy into `.<stamp>-<UUID>` temp dir, rename into `~/Library/Application Support/Museion/Backups/<stamp>/`, prune past 7 after a successful rename. `RESTORE.md` (manual Finder copy-back instructions) written once into the Backups root. Failure = one os_log line, never an alert (contrast #45's provisioning card); 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: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept).
## ACP bridge (S2.2, #14 map)
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (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): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), 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) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. 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.
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note), transcript (text rows, FixCardRow cards, RawUpdateRow disclosure), freeform input 1…4 lines + send + Stop while streaming, crash card (Restart, last prompt, stderr tail behind Technical details).
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — 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.
## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeMirror/ProseMirror-class dependencies.
## Verification
- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build`
- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test`
## Child DOX Index
- None yet — add child docs when subdirectories with distinct responsibilities appear (e.g. editor, library, agent integration).