diff --git a/CHANGELOG.md b/CHANGELOG.md index d6fd61b..a4b0922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format ## [Unreleased] +### Added + +- **fix cards:** **Jump** on a Fix Card selects the anchor's span in the piece's editor and makes the main window key (#204) — the borderless button sits in every non-stale card's action row (closed cards keep it; a stale anchor has nothing to land on); the span is the card's quote at its 1-based occurrence, resolved against the LIVE session text so a dirty buffer still lands, and it rides the reading flip-back's caret rail (one token counter; a zero-length hint stays a bare caret, a non-zero range selects). A jump leaves reading mode first, writes nothing, and re-fires on every click. Two review rounds closed the view-layer gaps the pure pins could not see: a jump dropped in reading mode, a main window that never became key (`NSApp.activate` is a no-op once the palette's click activated the app), a leading-blank caret hop that moved a span onto the title, and a cursor record taken before the scroll. +3 tests (`anchorRange` occurrence math with a UTF-16 fixture, the model's reveal stamp, the editor's `landingSpan`), all flip-verified. Suite 732 + ## [0.1.2] - 2026-12-03 Human-readable notes: [docs/releases/0.1.2.md](docs/releases/0.1.2.md). diff --git a/GLOSSARY.md b/GLOSSARY.md index d81401a..c4da5ee 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -123,6 +123,10 @@ _Avoid_: reject, dismiss Accepting a mechanical Fix Card so its edit lands in the file. Demonstration cards never offer it — they close Done or Skip. _Avoid_: accept, fix (verb) +**Jump**: +Selecting a Fix Card's anchor span in the piece's editor — the span the card points at, revealed and selected, the editor made key. A view act: records nothing, writes nothing. A stale anchor offers none. +_Avoid_: go to, scroll to, reveal + **Done**: Closing a Fix Card because the writer rewrote the span — the demonstration lane's terminal, beside Apply and Skip. Records nothing. _Avoid_: applied, complete diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index c17391c..c7b3ad1 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -41,7 +41,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `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 `![alt](assets/…)` 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`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). 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. 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 through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; 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). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register. +- `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`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). 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. 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 through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; 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; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register. - `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `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), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail. - `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through `sessionMayDepart`/`departOpenDocuments` — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25). - `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal` (`-> Bool` — false holds the departure)/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`). @@ -78,7 +78,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te ## museion-tools MCP server - `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. #177: both submit tools decode through `ToolPayloads` (below) — the strict entry throws named `CardError`s (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias). -- `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). +- `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. `anchorRange` = the nth-occurrence span (nil = stale, empty quote, or occurrence below 1 — never a wrong span; the lane never gates it); `appliedText` = the mechanical apply over that span (lane-gated, nil on a stale anchor, 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). - `ToolPayloads.swift` — #177: THE tool-payload decoder, one home for the `submit_fix_cards`/`submit_research_notes` wire shapes; the MCP server (strict — required fields throw `CardError`) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in `ToolPayloadsTests` — a shape change fails one suite. @@ -87,7 +87,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit. - `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p `; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). 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. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown. - `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open 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); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `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); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. 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` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (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; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable). -- `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). +- `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; #204 **Jump** on every non-stale card that still shows an action row (a closed-and-promoted card has none) — leaves reading mode, selects the anchor span in the editor, reveals it, and makes the main window key (the coordinator owns `tv.window`; `NSApp.activate` is a no-op once the palette's click already activated the app)), 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). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop). ## Work Guidance diff --git a/Museion/FixCardStore.swift b/Museion/FixCardStore.swift index ffd5b8b..7734342 100644 --- a/Museion/FixCardStore.swift +++ b/Museion/FixCardStore.swift @@ -153,6 +153,20 @@ nonisolated enum FixCardStore { return text.ranges(of: quote).count >= occurrence ? .valid : .stale } + /// #204: the anchor's exact span in `text` — the appliedText math WITHOUT + /// the edit: the quote's 1-based non-overlapping occurrence as an NSRange + /// a jump can select. nil for every case that must never land: a stale + /// anchor (quote gone or occurrence short) or an empty quote. The lane + /// never gates here — a demonstration card's anchor is still a real + /// place in the text; the palette decides what to offer. + static func anchorRange(of card: StoredFixCard, in text: String) -> NSRange? { + guard card.anchor.occurrence >= 1, !card.anchor.quote.isEmpty else { return nil } + return text.ranges(of: card.anchor.quote) + .dropFirst(card.anchor.occurrence - 1) + .first + .map { NSRange($0, in: text) } + } + // MARK: - Apply (pure) /// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit @@ -164,12 +178,8 @@ nonisolated enum FixCardStore { /// issue and accept degrade to a loud no-match, never a wrong-span /// patch. The caller owns the ask and the file write. static func appliedText(of card: StoredFixCard, in text: String) -> String? { - guard card.lane == .mechanical, - card.anchor.occurrence >= 1, - !card.anchor.quote.isEmpty, - let range = text.ranges(of: card.anchor.quote).dropFirst(card.anchor.occurrence - 1).first - else { return nil } - return text.replacingCharacters(in: range, with: card.fix) + guard card.lane == .mechanical, let range = anchorRange(of: card, in: text) else { return nil } + return (text as NSString).replacingCharacters(in: range, with: card.fix) } // MARK: - Submit diff --git a/Museion/FixCardsWindow.swift b/Museion/FixCardsWindow.swift index 1f2f7f7..a259956 100644 --- a/Museion/FixCardsWindow.swift +++ b/Museion/FixCardsWindow.swift @@ -3,8 +3,8 @@ // Museion // // #25 (S3.3): the Fix Cards palette becomes the card work surface. Open -// cards lead with their actions — Apply (a blocking ask), Skip, Done — -// closed cards dim behind them. No apply-all, no batch, nothing applies +// cards lead with their actions — Apply (a blocking ask), Skip, Done, +// Promote (#26), Jump (#204) — closed cards dim behind them. No apply-all, no batch, nothing applies // without the ask (S3.3). #23's show-only surface kept its bones. // @@ -106,9 +106,10 @@ private struct CardList: View { /// One card: pattern title, problem + fix body, rank · pass · lane · /// emitter mono meta (ADR-0006). A stale anchor reads distinct — orange — -/// and never offers Apply. Closed cards dim, record their status in the -/// meta, and offer no actions. The blocking Apply ask is the ROW's own -/// sheet: one card asks at a time, by construction (S3.3). +/// and never offers Apply or Jump (#204). Closed cards dim, record their +/// status in the meta, and keep only Promote and Jump — a closed card that +/// is already promoted keeps neither (its row is gone). The blocking Apply +/// ask is the ROW's own sheet: one card asks at a time (S3.3). private struct CardRow: View { let card: FixCardStore.StoredFixCard @Environment(AppGateState.self) private var gate @@ -134,14 +135,22 @@ private struct CardRow: View { .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(stale ? .orange : DesignTokens.muted) if open || card.promotedAt == nil { - // The actions this card offers (#25 S3.3, #26 S4.1): - // mechanical + valid → Apply (the blocking ask) and Skip; - // demonstration → Done and Skip (never Apply, ADR-0006); - // stale anchor → Skip only. Promote (its own ask) sits - // between the primary action and Skip, and outlives the - // card — closed cards keep it until promoted (#26: the + // The actions this card offers (#25 S3.3, #26 S4.1, #204): + // Jump on every card whose anchor still resolves (closed cards + // included — the span is still a real place; stale anchors offer + // none — nothing to land on); mechanical + valid → Apply (the + // blocking ask) and Skip; demonstration → Done and Skip (never + // Apply, ADR-0006); stale anchor → Skip only. Promote (its own + // ask) sits between the primary action and Skip, and outlives + // the card — closed cards keep it until promoted (#26: the // Learning is the durable artifact). HStack(spacing: 8) { + if !stale { + Button("Jump") { gate.posts.revealCard(card) } + .buttonStyle(.borderless) + .controlSize(.small) + .help("Select the anchored span in the piece") + } if open, !stale { if card.lane == .mechanical { Button("Apply") { asking = true } diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index 14ce782..0be04ad 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -47,9 +47,10 @@ struct PostEditorView: View { /// #68: reading is a transient act of inspection — no persistence; a /// fresh open always lands in editing. @State private var reading = false - /// Flip-back caret (#68): source location + a token so repeated flips to - /// the same location re-apply. Consumed by ProseTextView's coordinator. - @State private var flipBackCaret: (location: Int, token: Int)? + /// Flip-back caret (#68) and #204 jump span: a zero-length range is a + /// bare caret landing, a non-zero range selects the anchor; the token + /// re-applies repeats. Consumed by ProseTextView's coordinator. + @State private var flipBackCaret: FixCardRevealRequest? @State private var flipToken = 0 /// Reading scroll state (#68 mapping): entry caret + live top block. @State private var readingState = ReadingStateBox() @@ -108,6 +109,22 @@ struct PostEditorView: View { } } } + // #204: a Fix Card jump (the palette's Jump) lands here — the model's + // reveal request rides the SAME caret rail as the reading flip-back, + // through the ONE token counter (two counters could collide and a + // jump would silently never land): the span selected, revealed, and + // the main window made key so the writer can type where the card + // pointed (the coordinator does that — it owns tv.window). A jump + // while READING leaves reading first — plain `reading = false`, not + // exitReading (which would stamp its own zero-length hint over the + // jump); the remounted coordinator applies the jump after the load. + // Outline pieces have no prose surface — the request is dropped. + .onChange(of: gate.posts.revealRequest) { _, request in + guard let request, !outline else { return } + flipToken += 1 + flipBackCaret = FixCardRevealRequest(range: request.range, token: flipToken) + reading = false + } .onAppear { if draftMirror.isEmpty { draftMirror = draftText ?? "" @@ -220,7 +237,7 @@ struct PostEditorView: View { flipToken += 1 // Toggle-back maps the reading scroll back (top visible block); // click-to-edit lands at the clicked paragraph (survives always). - flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken) + flipBackCaret = FixCardRevealRequest(range: NSRange(location: caret ?? readingState.topSourceLocation ?? 0, length: 0), token: flipToken) reading = false } @@ -350,8 +367,9 @@ final class ProseDropBridge { /// NSTextView in a scroll view; attributes are presentation-only over a plain /// store. Session mode: edits → session.edit (debounce), cursor → session, /// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit. -/// #71: `caretHint` (location + token) lands the caret after a flip back -/// from reading — applied once per token, after any generation load. +/// #71/#204: `caretHint` (range + token) lands a bare caret after a flip +/// back from reading or SELECTS a card's anchor span after a Jump — applied +/// once per token, after any generation load. struct ProseTextView: NSViewRepresentable { var session: EditorSession? var draft: String? @@ -363,7 +381,7 @@ struct ProseTextView: NSViewRepresentable { var spellChecking = false /// #21: focus mode — the text ground joins the workspace background. var focused = false - var caretHint: (location: Int, token: Int)? + var caretHint: FixCardRevealRequest? /// #141: the piece folder dropped images ingest into — saved posts /// only (drafts have no folder until first save; the external guest /// isn't a piece). Nil = image drags refuse loudly. @@ -378,7 +396,7 @@ struct ProseTextView: NSViewRepresentable { session: EditorSession, spellChecking: Bool = false, focused: Bool = false, - caretHint: (location: Int, token: Int)? = nil, + caretHint: FixCardRevealRequest? = nil, dropBridge: ProseDropBridge, routeDrop: @escaping ([URL]) -> Bool, onTextChange: ((String) -> Void)? = nil, @@ -398,7 +416,7 @@ struct ProseTextView: NSViewRepresentable { spellChecking: Bool = false, focused: Bool = false, onEdit: @escaping (String) -> Void, - caretHint: (location: Int, token: Int)? = nil, + caretHint: FixCardRevealRequest? = nil, dropBridge: ProseDropBridge, routeDrop: @escaping ([URL]) -> Bool, onTextChange: ((String) -> Void)? = nil, @@ -428,12 +446,25 @@ struct ProseTextView: NSViewRepresentable { /// location 0 then rests inside the invisible 9pt blank fragment ABOVE /// the title, rendering as a detached terracotta stroke at the canvas /// top. Programmatic landings (cursor restore, reading flip-back) hop - /// over leading blanks to the first content line; interactive - /// placements (click, drag, typing) never route through here. + /// over leading blanks to the first content line — zero-length landings + /// only, a #204 span never hops (`landingSpan`); interactive placements + /// (click, drag, typing) never route through here. static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int { max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location) } + /// Where a caret-hint lands, clamped to the text: a zero-length range + /// (#71 flip-back) is a bare caret and hops past leading blanks; a + /// non-zero range (#204 jump) SELECTS the anchor exactly where it + /// resolved — a quote that IS the leading blanks selects those blanks, + /// never the title (the load restore gates its hop the same way). + static func landingSpan(for hint: FixCardRevealRequest, in text: String) -> NSRange { + let length = (text as NSString).length + let start = hint.range.length == 0 ? caretPastLeadingBlanks(max(0, hint.range.location), in: text) : max(0, hint.range.location) + let loc = min(start, length) + return NSRange(location: loc, length: min(max(0, hint.range.length), length - loc)) + } + func makeNSView(context: Context) -> NSScrollView { let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests) @@ -541,25 +572,9 @@ struct ProseTextView: NSViewRepresentable { tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft)) tv.refreshFolds() // #115: re-key folds over the swapped content } - // #71: flip-back caret — apply once per token, after any load above. + // #71 flip-back caret / #204 jump span — apply once per token, after any load above. if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token { - context.coordinator.appliedCaretToken = hint.token - let length = (tv.string as NSString).length - // #ui-r1: same leading-blank hop as the load restore — a reading - // flip-back must never park the caret above the first content line. - let loc = min(Self.caretPastLeadingBlanks(max(0, hint.location), in: tv.string), length) - tv.setSelectedRange(NSRange(location: loc, length: 0)) - // ponytail: same layout race as the cursor-restore scroll above — - // this was the click-to-edit "always lands at top" defect: the sync - // scrollRangeToVisible fired before the target region was laid out. - // One runloop hop fixes it (offscreen-verified, 3000-para doc). - DispatchQueue.main.async { [weak tv] in - tv?.scrollRangeToVisible(NSRange(location: loc, length: 0)) - tv?.window?.makeFirstResponder(tv) - } - if let session { - session.cursorUpdate(ProseTextView.cursorState(of: tv)) - } + context.coordinator.applyCaretHint(hint, tv: tv, session: session) } } @@ -585,6 +600,33 @@ struct ProseTextView: NSViewRepresentable { onTextChange = representable.onTextChange } + /// The caret rail's landing (#71 flip-back, #204 jump). Called by the + /// representable once per token. + func applyCaretHint(_ hint: FixCardRevealRequest, tv: NSTextView, session: EditorSession?) { + appliedCaretToken = hint.token + let landing = ProseTextView.landingSpan(for: hint, in: tv.string) + tv.setSelectedRange(landing) + // ponytail: same layout race as the cursor-restore scroll — this was + // the click-to-edit "always lands at top" defect: the sync + // scrollRangeToVisible fired before the target region was laid out. + // One runloop hop fixes it (offscreen-verified, 3000-para doc). + DispatchQueue.main.async { [weak tv] in + guard let tv else { return } + // #204: a jump (span > 0) comes from the palette window, which + // holds key after the click — make the main window key or the + // first responder never sees keystrokes. The #71 flip-back + // (span 0) is already in the key window; untouched. + if landing.length > 0 { + tv.window?.makeKeyAndOrderFront(nil) + } + tv.scrollRangeToVisible(landing) + tv.window?.makeFirstResponder(tv) + // Recorded AFTER the scroll: the sidecar's scrollOffset must be + // the landed one, or a reopen restores an off-screen selection. + session?.cursorUpdate(ProseTextView.cursorState(of: tv)) + } + } + func textDidChange(_ notification: Notification) { guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return } let sel = tv.selectedRange() diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 0b8fb76..3a1050d 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -140,6 +140,12 @@ final class PostsModel { /// submitted; nil session (draft/guest/nothing) shows none. /// #146: setter internal — the split-out domain extensions set it. var openPieceCards: [FixCardStore.StoredFixCard] = [] + /// #204: one jump-to-the-anchor request from the Fix Cards palette — + /// the anchor's span in the LIVE session text plus a token that + /// advances per jump (the editor column applies once per token, the + /// #71 flip-back caret pattern). Set by `revealCard`; never written + /// to disk — a jump is a view act. + var revealRequest: FixCardRevealRequest? /// Last failed-op message surfaced in the editor (nil = clean). /// #146: setter internal — the split-out domain extensions set it. var lastError: String? diff --git a/Museion/PostsModelCards.swift b/Museion/PostsModelCards.swift index c7e6a80..280d82f 100644 --- a/Museion/PostsModelCards.swift +++ b/Museion/PostsModelCards.swift @@ -4,7 +4,8 @@ // // #146: the fix-card extensions of PostsModel — stored-card surfacing // (#23), apply/skip/done (#25, S3.2/S3.3), and promote (#26, S4.1) — -// moved from PostsModel.swift (file-length ceiling), code unchanged. +// moved from PostsModel.swift (file-length ceiling), code unchanged; +// #204: the jump-to-the-anchor reveal (`revealCard`, `FixCardRevealRequest`). // import Foundation @@ -133,6 +134,31 @@ extension PostsModel { } } +// MARK: Jump to the anchor (#204) + +/// #204: one jump-to-the-anchor request — the anchor's span in the live +/// session text plus a token that advances per jump so the editor column +/// (which applies once per token) re-fires on a repeated jump. Ephemeral +/// view state: nothing here ever reaches disk. +struct FixCardRevealRequest: Equatable { + var range: NSRange + var token: Int +} + +extension PostsModel { + /// #204: jump to a card's anchor — the palette's Jump. Resolves the + /// anchor against the LIVE session text (a dirty buffer still lands + /// where the writer sees it) and stamps one reveal request; the editor + /// column observes it and selects + reveals the span. A stale anchor + /// (quote gone, occurrence short) stamps nothing — the previous + /// request stands. Touches no text, no card, no disk: a jump is a view + /// act, the writer's hands stay on the wheel. + func revealCard(_ card: FixCardStore.StoredFixCard) { + guard let session, let range = FixCardStore.anchorRange(of: card, in: session.text) else { return } + revealRequest = FixCardRevealRequest(range: range, token: (revealRequest?.token ?? 0) + 1) + } +} + // MARK: Fix Card promote (#26, S4.1/S4.3) /// #26 (S4.1): what Promote did — the Learning landed, or the operation diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 2869299..87f6261 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -41,7 +41,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap). - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. - `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay. -- `FixCardApplyTests` — fix-card apply/skip/done lifecycle. +- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does). - `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load). - `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 + the 27.2 drag-routing seam (`DragInfoStub`, the suite's NSDraggingInfo mock: a Finder-shaped drag routes through the text view and never pastes the path; text-only drags keep the stock drop; outline rows bounce; the probe follows `changeCount`; web URLs and vanished files refuse with the right notice) + the one router's pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal). diff --git a/MuseionTests/FixCardApplyTests.swift b/MuseionTests/FixCardApplyTests.swift index bb77c80..4937b7a 100644 --- a/MuseionTests/FixCardApplyTests.swift +++ b/MuseionTests/FixCardApplyTests.swift @@ -14,6 +14,16 @@ // card closes applied), skip and done flip only the status, and the stale // anchor selects and changes no text while the card flags itself stale. // +// #204 — Scenario: the card points, the editor lands +// From issue #204: a Fix Card should let the writer jump to the relevant +// paragraph — the palette's Jump hands the editor the anchor's exact span. +// Given an open piece carrying a fix card whose anchor is valid, +// when the writer clicks Jump on that card, +// then the model stamps one reveal request carrying the anchor's NSRange +// resolved against the LIVE session text (a dirty buffer still lands), +// the request's token advances so repeated jumps re-fire, nothing is +// written (not text, not the card), and a stale anchor stamps nothing. +// import Foundation @testable import Museion @@ -284,7 +294,103 @@ struct FixCardApplyTests { #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written } - // MARK: Promote (#26, S4.1) + // MARK: Jump to the anchor (#204) + + /// #204: the pure anchor-span math — the appliedText occurrence rule + /// (1-based, non-overlapping) answered as a range, with every + /// must-never-land case nil. + @Test func `anchorRange resolves the nth occurrence and nils every unlandable case`() throws { + let piece = try makePiece() + let written = try FixCardStore.submit( + piecePath: piece.path, + cards: [ + card(quote: "anchor sentence"), + card(quote: "anchor sentence", occurrence: 2), + card(quote: "vanished quote", occurrence: 1), + card(quote: "anchor sentence", lane: .demonstration), + ], + ) + // submit refuses an empty quote and occurrence 0 at the trust + // boundary — the unlandable-input cases are pinned through the + // stored shape directly. + let emptyQuote = FixCardStore.StoredFixCard( + id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p", + diagnosticQuestion: "", fix: "", anchor: .init(quote: "", occurrence: 1), + lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil, + ) + let zeroOccurrence = FixCardStore.StoredFixCard( + id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p", + diagnosticQuestion: "", fix: "", anchor: .init(quote: "anchor", occurrence: 0), + lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil, + ) + let text = "The anchor sentence. And the anchor sentence again." + + let first = try #require(FixCardStore.anchorRange(of: written[0].card, in: text)) + #expect((text as NSString).substring(with: first) == "anchor sentence") + #expect(first.location == 4) // 1-based, the FIRST match + let second = try #require(FixCardStore.anchorRange(of: written[1].card, in: text)) + #expect(second.location == 29) // occurrence 2 — not the first + #expect(FixCardStore.anchorRange(of: written[2].card, in: text) == nil) // stale + // A demonstration card's anchor is still a real place in the text. + #expect(FixCardStore.anchorRange(of: written[3].card, in: text) != nil) + #expect(FixCardStore.anchorRange(of: emptyQuote, in: text) == nil) + #expect(FixCardStore.anchorRange(of: zeroOccurrence, in: text) == nil) + // The range is UTF-16 (NSTextView's unit), not Characters — a grapheme + // before the anchor is 2 units here; a Character-counted location would say 6. + let wide = FixCardStore.anchorRange(of: written[0].card, in: "✍️ The anchor sentence.") + #expect(wide?.location == 7) + } + + /// #204: a jump selects the anchor exactly where it resolved; only a bare + /// caret (the #71 flip-back) hops past leading blanks — a quote that IS + /// the leading blanks must select those blanks, never the title. Both + /// shapes clamp to the text. + @Test @MainActor func `landingSpan hops only a bare caret and clamps both shapes to the text`() { + let text = "\n\n\nTitle line." + let jump = FixCardRevealRequest(range: NSRange(location: 0, length: 3), token: 1) + #expect(ProseTextView.landingSpan(for: jump, in: text) == NSRange(location: 0, length: 3)) // the blank run itself + let caret = FixCardRevealRequest(range: NSRange(location: 0, length: 0), token: 2) + #expect(ProseTextView.landingSpan(for: caret, in: text) == NSRange(location: 3, length: 0)) // hops to the title + let over = FixCardRevealRequest(range: NSRange(location: 10, length: 50), token: 3) + #expect(ProseTextView.landingSpan(for: over, in: text) == NSRange(location: 10, length: 4)) // clamped + } + + /// #204: the model stamps ONE reveal request per jump — the range + /// resolved against the LIVE session text (dirty buffer included), the + /// token advancing so a repeated jump re-fires; a stale anchor stamps + /// nothing. No write of any kind. + @Test @MainActor func `revealCard stamps a reveal request against the live text and writes nothing`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) + let folder = try #require(PostStore.folder(of: post.id, home: home)) + let written = try FixCardStore.submit( + piecePath: folder.path, + cards: [card(quote: "anchor sentence"), card(quote: "vanished quote")], + ) + model.select(post.id) + let session = try #require(model.session) + // The writer typed since the last flush — the jump must resolve + // against the buffer, not disk (the range would otherwise drift). + session.edit("# Carded\n\nIntro line.\nThe anchor sentence.\n") + let before = try Data(contentsOf: folder.appendingPathComponent("post.md")) + + model.revealCard(written[0].card) + + let request = try #require(model.revealRequest) + #expect(request.range.location == (session.text as NSString).range(of: "anchor sentence").location) + #expect(request.range.length == ("anchor sentence" as NSString).length) // UTF-16 units — what NSTextView selects + let token = request.token + #expect(try Data(contentsOf: folder.appendingPathComponent("post.md")) == before) // no write + #expect(try FixCardStore.scan(pieceURL: folder).allSatisfy { $0.status == .open }) // card untouched + + // A repeated jump re-fires (the editor applies once per token). + model.revealCard(written[0].card) + #expect(model.revealRequest?.token == token + 1) + + // A stale anchor stamps nothing — the previous request stands. + model.revealCard(written[1].card) + #expect(model.revealRequest?.token == token + 1) + } /// Scenario: the mentor remembers — promoting through the model writes /// the Learning under the open piece's Home, refreshes the palette's