feat(mentor): apply/skip fix cards (#25)
CI / ci (push) Canceled after 0s

Fix Cards become actionable. Mechanical cards offer Apply behind a
blocking ask-before sheet showing the exact edit (anchored quote ->
replacement, occurrence + context; empty fix cuts); the sheet is the
only path to a write, one card at a time, no apply-all. The edit
lands through the editing session (pending edits flush first, the
editor re-seeds via adoptText, the card closes applied); Skip and
Done close the card in place, recording nothing; demonstration
cards close Done/Skip only (ADR-0006). Cards arrive ranked
(store-stamped, scan-ordered, open-first palette) and capped at ten
per submit — the app keeps the ranked head and the wire reply
discloses the drop. Stale anchors re-validate at apply: no text
selected or changed, the card flags itself. Includes the
finish-audit round (11 fixes, 2 flip-verified pins); 316 tests
green.

Closes #25
This commit is contained in:
AlexKucera committed 2026-10-20 16:46:43 +02:00
1 parent 5700264628
commit 4d33676a08
15 files changed
+1012 -74

No files matched your search

+3 -4
View File
@@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (3803 symbols, 12077 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (3880 symbols, 12452 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -180,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) |
| 2026-10-20 | [20261020-issue24-pass-guard-matrix_log.md](docs/devlog/20261020-issue24-pass-guard-matrix_log.md) |
| 2026-10-20 | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](docs/devlog/20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) |
| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) |
@@ -188,6 +189,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |
| 2026-10-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) |
| 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) |
| 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) |
| 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) |
| 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) |<!-- write-log: window-end -->
| 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) |<!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added
- **mentor:** Fix Card apply/skip & trust UI (PRD S3.2/S3.3/S2.5) — Fix Cards are actionable: mechanical cards offer Apply behind a blocking ask-before sheet showing the exact edit (anchored quote → replacement, occurrence + context; an empty fix cuts the span) — the only path to a write, one card at a time, no apply-all; the edit lands through the editing session (pending edits flush first, the editor re-seeds, the card closes applied), Skip and Done close the card in place recording nothing, demonstration cards close Done/Skip only (ADR-0006); cards arrive ranked (store-stamped order, `#N` in the meta, open cards first) and capped at ten per submit — the app keeps the ranked head and the wire reply says what dropped; a stale anchor — the Post changed after the card was issued — alerts with no text selected or changed and flags the card (issue #25)
- **mentor:** museion-tools MCP server + Fix Cards (#23, #24 rails) — the app binary grows a headless `--serve-mcp` role speaking NDJSON JSON-RPC on stdio, exposing `query_learnings` (the piece's visible learnings) and `submit_fix_cards` (ADR-0006 cards, anchor-validated against post.md; stale anchors land flagged, never rejected) registered into the museion profile at provisioning; cards persist per-piece under `<piece>/cards/` and surface live in a floating Fix Cards palette (opened from the mentor pass bar, `pass N · lane · emitter` meta when the engine stamps `provenance.pass`); the transcript renders card tool calls as one-line events, the pass verdict references findings by title only (persona v1.3: tools work in silence, the card is the finding's only full statement), and a Debug checkbox (off by default) gates the session/tool chatter writers never wanted
- **skills:** fix-card lanes + card-emitting doctrine (#123, text landings of #118/#119/#121) — every Fix Card declares a lane (mechanical: the whole fix is table-computable and the only lane Apply executes; demonstration: one annotated example, closed Done/Skip) and an emitter (lint | engine; the engine never re-cards a live lint finding); the pass persona emits one ranked `submit_fix_cards` call at pass end, capped at ten, Learnings-resonant first; the Knife floor gains writer-praise immunity; deslop's tables gain the actually/unfortunately filler cuts and the utilize/utilization→use mapping; CONTEXT.md adds the Emitter and Done terms, ADR-0006 the lane/emitter fields, and the sample pass a mechanical-lane exemplar (FC-10)
+5 -5
View File
@@ -26,12 +26,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws).
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing line "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
@@ -63,15 +63,15 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## museion-tools MCP server (S2.4, #23)
- `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 two tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion); `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`.
- `FixCardStore.swift` — `FixCardStore` (nonisolated): the durable card store + tool bodies. `StoredFixCard` (Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (`pass` = the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim. `submit(piecePath:cards:)` — piece resolves to post.md (dir or file path; **audit guard: the file form must BE `post.md` under a `projects/`|`archive/` component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs**), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, **stale → the card still lands flagged** (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes `<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats). `scan(pieceURL:)` newest-first, skips junk. `learnings(piecePath:)` — home = 4 components up (ADR-0012), content type from frontmatter (`Post.frontmatter(of:)`), reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file; decay filtering is pass-through until #26 defines the fields (ponytail note in code).
- `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 two 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); `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`.
- `FixCardStore.swift` — `FixCardStore` (nonisolated): the durable card store + tool bodies. `StoredFixCard` (Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (`pass` = the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim. `submit(piecePath:cards:)` — piece resolves to post.md (dir or file path; **audit guard: the file form must BE `post.md` under a `projects/`|`archive/` component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs**), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, **stale → the card still lands flagged** (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes `<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats). **#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 = 4 components up (ADR-0012), content type from frontmatter (`Post.frontmatter(of:)`), reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file; decay filtering is pass-through until #26 defines the fields (ponytail note in code).
- 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, both tools listed with required arrays, full submit round-trip through the wire, isError path, -32601/-32700).
## 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` (#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.
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, trailing mini **Debug** checkbox — `@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 (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 collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#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). The palette shows the open piece's title + `posts.openPieceCards` (mono-11 "FIX CARDS · N" header, pattern/problem/fix rows, `lane · emitter` mono meta; stale anchors orange + "· stale anchor" — show-only, never acts; Apply is #25; 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).
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, trailing mini **Debug** checkbox — `@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 (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 collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#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). 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).
- 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.
+24
View File
@@ -263,6 +263,30 @@ final class EditorSession {
onError?(nil)
}
/// #25: adopt externally-computed text (Fix Card apply) — Yes-reload's
/// body with a provided text: bumps loadGeneration so both surfaces
/// (the prose coordinator seeds from session.text on a generation move,
/// PostEditorView.swift:405; OutlineEditorView re-parses on the bump)
/// re-seed, then flushes to disk now. Writer-consented explicit action
/// (like ⌘S) — the #67 conflict guard is the CALLER's job.
@discardableResult
func adoptText(_ newText: String) -> Bool {
// A session that never loaded must never write (the flush guard's
// own rule, made explicit here: flush reports success on a clean
// no-op, so a loadFailed session would close cards over a write
// that never landed).
guard !loadFailed else { return false }
// A session that never loaded must never write (the flush guard's
// own rule, made explicit here: flush reports success on a clean
// no-op, so a loadFailed session would close cards over a write
// that never landed).
debounceTask?.cancel()
text = newText
loadText = newText
loadGeneration += 1
return flush()
}
/// #67 No: keep local — the next autosave overwrites disk (the writer's
/// explicit choice). Marks the disk state as seen so the same external
/// content doesn't re-alert on every watcher tick; a new external write
+117 -18
View File
@@ -57,6 +57,14 @@ nonisolated enum FixCardStore {
case valid, stale
}
/// #25 (S3.3): the card's lifecycle state — "open" on submit, one of
/// the CONTEXT.md terminals on close: applied (Apply wrote the edit),
/// skipped (not this instance), done (the writer rewrote the span).
/// A foreign status string on disk fails decode → scan's junk-skip.
enum Status: String, Codable {
case open, applied, skipped, done
}
struct Provenance: Codable, Equatable {
var piece: String
var date: String?
@@ -69,6 +77,10 @@ nonisolated enum FixCardStore {
var id: UUID
var submittedAt: Date
/// #25 (S3.2): the card's rank in its submit — the persona's ranked
/// order, 1-based, stamped by the store like id/submittedAt. Optional:
/// pre-#25 cards on disk carry no rank key.
var rank: Int?
var pattern: String
var problem: String
var diagnosticQuestion: String
@@ -77,8 +89,8 @@ nonisolated enum FixCardStore {
var lane: Lane
var emitter: Emitter
var provenance: Provenance?
/// Always "open" on submit; later states belong to the app slice.
var status: String
/// "open" on submit; a Status terminal once the writer closes it.
var status: Status
var anchorStatus: AnchorStatus
}
@@ -133,18 +145,44 @@ nonisolated enum FixCardStore {
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
}
// MARK: - Apply (pure)
/// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit
/// the card makes in `text`: the anchor's quote occurrence (1-based,
/// non-overlapping — the anchorStatus math) replaced by the fix,
/// everything else untouched. nil = the card must not touch text: a
/// demonstration lane (only a mechanical fix is ever applied,
/// ADR-0006) or an anchor that no longer resolves — edits between
/// 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)
}
// MARK: - Submit
/// Validate every card first, then write one JSON file per card into
/// `<piece>/cards/` named `<yyyyMMdd-HHmmss>-<slug>.json` (collision →
/// -2, -3…). Stale anchors still land, flagged. No dedup — every
/// submission lands (explicit product decision).
/// #25 (S3.2): the pass ceiling — `passCardCeiling` per submit, the
/// ranked head kept (the persona's cap is the primary filter; this is
/// the backstop). Tail cards drop before validation.
static let passCardCeiling = 10
static func submit(piecePath: String, cards: [Input]) throws -> [(card: StoredFixCard, file: String)] {
let postURL = try resolvePostURL(piecePath)
let text = try String(contentsOf: postURL, encoding: .utf8)
// Whole-call semantics: a malformed card errors the call before
// anything is written.
let materialized = try cards.map { try materialize($0, postText: text) }
let materialized = try cards.prefix(passCardCeiling).enumerated().map { index, input in
try materialize(input, postText: text, rank: index + 1)
}
let dir = postURL.deletingLastPathComponent().appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
@@ -169,7 +207,7 @@ nonisolated enum FixCardStore {
}
/// Trust-boundary validation + server stamping.
private static func materialize(_ input: Input, postText: String) throws -> StoredFixCard {
private static func materialize(_ input: Input, postText: String, rank: Int) throws -> StoredFixCard {
guard !input.pattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw CardError(message: "card pattern must not be empty")
}
@@ -185,6 +223,7 @@ nonisolated enum FixCardStore {
return StoredFixCard(
id: UUID(),
submittedAt: Date(),
rank: rank,
pattern: input.pattern,
problem: input.problem,
diagnosticQuestion: input.diagnosticQuestion ?? "",
@@ -193,7 +232,7 @@ nonisolated enum FixCardStore {
lane: input.lane,
emitter: input.emitter,
provenance: input.provenance,
status: "open",
status: .open,
anchorStatus: anchorStatus(
text: postText,
quote: input.anchor.quote,
@@ -255,24 +294,84 @@ nonisolated enum FixCardStore {
// MARK: - Scan
/// Every stored card under `<piece>/cards/`, newest-first (the stamp
/// prefix sorts lexicographically). Undecodable files are skipped
/// silently — a stranger's hand-edit never crashes the reader. A
/// post.md URL is tolerated (app-side call sites hold the file URL).
static func scan(pieceURL: URL) -> [StoredFixCard] {
/// `<piece>/cards/`, tolerating a post.md URL (app-side call sites
/// hold the file URL).
private static func cardsDir(for pieceURL: URL) -> URL {
var dir = pieceURL
if ["md", "markdown"].contains(dir.pathExtension.lowercased()) {
dir.deleteLastPathComponent()
}
let cards = dir.appendingPathComponent("cards", isDirectory: true)
let files = (try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? []
return files
.filter { $0.hasSuffix(".json") }
.sorted(by: >)
.compactMap { name in
guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)) else { return nil }
return try? decoder.decode(StoredFixCard.self, from: data)
return dir.appendingPathComponent("cards", isDirectory: true)
}
/// Every stored card under `<piece>/cards/`, the persona's ranked order:
/// submittedAt DESC (newest submit first), then rank ASC within a
/// submit, pre-#25 cards (rank nil) AFTER ranked ones of the same
/// submit. Undecodable files are skipped silently — a stranger's
/// hand-edit never crashes the reader. A post.md URL is tolerated
/// (app-side call sites hold the file URL).
static func scan(pieceURL: URL) -> [StoredFixCard] {
decoded(in: cardsDir(for: pieceURL)).sorted { lhs, rhs in
if lhs.card.submittedAt != rhs.card.submittedAt {
return lhs.card.submittedAt > rhs.card.submittedAt
}
switch (lhs.card.rank, rhs.card.rank) {
case let (ranked?, other?) where ranked != other:
return ranked < other
case (.some, nil):
return true // ranked cards lead their unranked siblings
case (nil, .some):
return false
default:
return lhs.file > rhs.file
}
}
.map(\.card)
}
/// The shared cards/ walk — decoded cards with their filenames; scan
/// sorts it, close finds in it. Undecodable files are skipped silently
/// (a stranger's hand-edit never crashes the reader). The comparator's
/// filename tiebreak totally orders unique names, so walk order never
/// matters.
private static func decoded(in cards: URL) -> [(file: String, card: StoredFixCard)] {
let files = ((try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? [])
.filter { $0.hasSuffix(".json") }
return files.compactMap { name in
guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)),
let card = try? decoder.decode(StoredFixCard.self, from: data)
else { return nil }
return (name, card)
}
}
// MARK: - Close
/// #25 (S3.3): close a stored card IN PLACE — its JSON file rewritten
/// with the new status, every other field untouched (Skip records
/// nothing beyond the flip). `anchorStatus`, when non-nil, rides the
/// same rewrite (the stale-anchor flag); nil preserves it. Returns
/// the closed card. Throws when no card with the id sits under the
/// piece (the app surface routes the error); undecodable stranger
/// files are skipped, same as scan.
@discardableResult
static func close(
pieceURL: URL,
id: UUID,
status: StoredFixCard.Status,
anchorStatus: StoredFixCard.AnchorStatus? = nil,
) throws -> StoredFixCard {
let cards = cardsDir(for: pieceURL)
for entry in decoded(in: cards) where entry.card.id == id {
var card = entry.card
card.status = status
if let anchorStatus {
card.anchorStatus = anchorStatus
}
try encoder.encode(card).write(to: cards.appendingPathComponent(entry.file), options: .atomic)
return card
}
throw CardError(message: "card not found: \(id)")
}
// MARK: - Learnings
+218 -24
View File
@@ -2,11 +2,10 @@
// FixCardsWindow.swift
// Museion
//
// #23 follow-up (dogfood): the Fix Cards palette — the durable card
// store's own surface, a floating window (scene id "fix-cards") opened
// from the mentor pass bar. The transcript renders card tool calls as
// one-line events; the card DETAIL lives here while the verdict gets
// worked through. Show-only, never acts (Apply is #25).
// #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
// without the ask (S3.3). #23's show-only surface kept its bones.
//
import SwiftUI
@@ -28,9 +27,18 @@ struct FixCardsPalette: View {
.padding(.bottom, 4)
}
if posts.openPieceCards.isEmpty {
emptyState(hasPiece: posts.session?.postID != nil)
EmptyCardsState(hasPiece: posts.session?.postID != nil)
} else {
cardList(posts.openPieceCards)
CardList(cards: ordered(posts.openPieceCards))
// The visible trust posture (S2.5): apply = ask-before, one
// card at a time. Never-do needs no control here — nothing
// auto-applies; the ask is the only path to a write.
Text("apply = ask-before · one card at a time")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.padding(.horizontal, 12)
.padding(.bottom, 10)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
@@ -45,7 +53,19 @@ struct FixCardsPalette: View {
return gate.posts.title(of: id)
}
private func emptyState(hasPiece: Bool) -> some View {
/// Open cards first, closed after — both groups keep the scan's order
/// (newest pass first, rank ascending; #25 S3.2). Live attention stays
/// on open work.
private func ordered(_ cards: [FixCardStore.StoredFixCard]) -> [FixCardStore.StoredFixCard] {
cards.filter { $0.status == .open } + cards.filter { $0.status != .open }
}
}
/// Nothing filed yet — names how cards arrive.
private struct EmptyCardsState: View {
let hasPiece: Bool
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(hasPiece ? "No fix cards yet." : "No piece open.")
.font(.headline)
@@ -58,36 +78,46 @@ struct FixCardsPalette: View {
.padding(12)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
/// The open piece's STORED fix cards (moved from MentorPaneView #23 S2.4
/// — uncapped here, the window owns its scroll).
private func cardList(_ cards: [FixCardStore.StoredFixCard]) -> some View {
// ponytail: eager VStack in the ScrollView — the pass ceiling caps this at
// ~tens of cards; LazyVStack if a piece ever accumulates hundreds.
/// The piece's stored cards, open-first. The header counts OPEN work —
/// closed cards must not read as pending (#25).
private struct CardList: View {
let cards: [FixCardStore.StoredFixCard]
var body: some View {
let openCount = cards.count(where: { $0.status == .open })
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("FIX CARDS · \(cards.count)")
Text(openCount < cards.count ? "FIX CARDS · \(openCount) open" : "FIX CARDS · \(openCount)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
ForEach(cards, id: \.id) { card in
row(card)
CardRow(card: card)
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
/// One card: pattern title, problem + fix body, lane · emitter mono meta
/// (ADR-0006). A stale anchor reads distinct — orange + caption — and is
/// never appliable: v1 shows, never acts.
private func row(_ card: FixCardStore.StoredFixCard) -> some 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).
private struct CardRow: View {
let card: FixCardStore.StoredFixCard
@Environment(AppGateState.self) private var gate
/// The row's own blocking ask; Apply arms it, the sheet answers it.
@State private var asking = false
var body: some View {
let stale = card.anchorStatus == .stale
var meta = "\(card.lane.rawValue) · \(card.emitter.rawValue)"
if let pass = card.provenance?.pass {
meta = "pass \(pass) · " + meta
}
if stale {
meta += " · stale anchor"
}
let open = card.status == .open
return VStack(alignment: .leading, spacing: 6) {
Label(card.pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
.font(.callout.weight(.semibold))
@@ -101,9 +131,173 @@ struct FixCardsPalette: View {
Text(meta)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(stale ? .orange : DesignTokens.muted)
if open {
// The actions this card offers (#25 S3.3): mechanical +
// valid → Apply (opens the blocking ask) and Skip;
// demonstration → Done and Skip (never Apply, ADR-0006);
// stale anchor → Skip only.
HStack(spacing: 8) {
if stale {
SkipButton(card: card)
} else if card.lane == .mechanical {
Button("Apply") { asking = true }
.buttonStyle(.bordered)
.controlSize(.small)
SkipButton(card: card)
} else {
Button("Done") {
gate.posts.doneCard(card, home: gate.museionHome)
}
.buttonStyle(.bordered)
.controlSize(.small)
SkipButton(card: card)
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
.opacity(open ? 1 : 0.45)
// Apply = ask-before, a BLOCKING ask: the sheet is the only path
// from the Apply button to a write.
.sheet(isPresented: $asking) {
ApplyAskSheet(card: card, posts: gate.posts, home: gate.museionHome)
}
}
/// rank · pass · lane · emitter, plus the card's truth markers: the
/// stale anchor, the trust level on appliable mechanical cards (S2.5),
/// and the close status once closed.
private var meta: String {
var value = "\(card.lane.rawValue) · \(card.emitter.rawValue)"
if let pass = card.provenance?.pass {
value = "pass \(pass) · " + value
}
if let rank = card.rank {
value = "#\(rank) · " + value
}
if card.anchorStatus == .stale {
value += " · stale anchor"
}
if card.status == .open, card.lane == .mechanical, card.anchorStatus != .stale {
value += " · apply · ask-before"
}
if card.status != .open {
value += " · \(card.status.rawValue)"
}
return value
}
}
/// Skip — not this instance (CONTEXT.md): closes the card, records
/// nothing beyond the flip.
private struct SkipButton: View {
let card: FixCardStore.StoredFixCard
@Environment(AppGateState.self) private var gate
var body: some View {
Button("Skip") {
gate.posts.skipCard(card, home: gate.museionHome)
}
.buttonStyle(.borderless)
.controlSize(.small)
}
}
/// The blocking ask (#25 S3.3): the exact edit, in full, before any write.
/// No apply-all, no batch, nothing applies without the ask — Apply is the
/// sheet's only write path, Cancel writes nothing. Outcome states: stale
/// swaps the body (no retry — the anchor no longer resolves), a refusal
/// shows its reason with the buttons kept.
private struct ApplyAskSheet: View {
let card: FixCardStore.StoredFixCard
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
@State private var wentStale = false
@State private var refusal: String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
if wentStale {
Text("The text changed since this card was issued — nothing was selected or changed.")
.font(.callout)
Button("Close") { dismiss() }
.frame(maxWidth: .infinity, alignment: .trailing)
} else {
// Untrusted text in bounded chrome: quote/fix are
// client-authored, so the ask scrolls instead of growing
// past the sheet and pushing the buttons out of reach.
ScrollView {
VStack(alignment: .leading, spacing: 12) {
Text(card.pattern)
.font(.headline)
MonoBlock(
label: card.anchor.occurrence > 1
? "Anchored · occurrence \(card.anchor.occurrence)" : "Anchored",
text: card.anchor.quote,
)
if let context = card.anchor.context {
Text(context)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
MonoBlock(label: "Replacement", text: card.fix.isEmpty ? "(cut — the span is removed)" : card.fix)
Text("Apply writes this edit to the piece · ask-before")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let refusal {
Text(refusal)
.font(.callout)
.foregroundStyle(.orange)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack(spacing: 8) {
Button("Apply") { apply() }
.buttonStyle(.borderedProminent)
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.padding(16)
.frame(width: 320, alignment: .leading)
}
private func apply() {
switch posts.applyCard(card, home: home) {
case .applied:
dismiss()
case .stale:
wentStale = true
case let .refused(reason):
refusal = reason
}
}
}
/// One labeled mono text block — the ask's edit halves.
private struct MonoBlock: View {
let label: String
let text: String
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(label)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Text(text)
.font(.system(size: 12, design: DesignTokens.mono))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(8)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 6))
}
}
}
+21 -7
View File
@@ -131,14 +131,20 @@ nonisolated enum MCPServer {
SubmitArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
let written = try FixCardStore.submit(piecePath: args.piecePath, cards: args.cards)
var payload: [String: Any] = [
"cards": written.map {
["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue]
} as [[String: Any]],
]
// The ceiling backstop tells the truth on the wire (#25 S3.2):
// cards beyond the kept ranked head were dropped — say how many.
if args.cards.count > written.count {
payload["dropped_over_ceiling"] = args.cards.count - written.count
}
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString([
"cards": written.map {
["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue]
} as [[String: Any]],
]) ?? "{}",
"text": jsonString(payload) ?? "{}",
]] as [[String: Any]],
])
default:
@@ -181,7 +187,9 @@ nonisolated enum MCPServer {
],
[
"name": "submit_fix_cards",
"description": "Persist fix cards for a piece. Anchor-validated against post.md; stale anchors land flagged.",
"description": "Persist fix cards for a piece. Anchor-validated against post.md; "
+ "stale anchors land flagged. At most 10 cards per call — "
+ "the app keeps the ranked head and drops the rest.",
"inputSchema": [
"type": "object",
"properties": [
@@ -191,13 +199,19 @@ nonisolated enum MCPServer {
],
"cards": [
"type": "array",
"description": "Ranked most-important-first; at most 10 per call — "
+ "the app keeps the ranked head and drops the rest.",
"items": [
"type": "object",
"properties": [
"pattern": ["type": "string"],
"problem": ["type": "string"],
"diagnostic_question": ["type": "string"],
"fix": ["type": "string"],
"fix": [
"type": "string",
"description": "Mechanical cards: the exact replacement for the anchored span "
+ "(empty string = cut). Demonstration cards: the demonstration.",
] as [String: Any],
"anchor": [
"type": "object",
"properties": [
+75
View File
@@ -879,3 +879,78 @@ extension PostsModel {
posts.first(where: { $0.id == id })?.title ?? id
}
}
// MARK: Fix Card apply/skip/done (#25, S3.2/S3.3)
/// #25 (S3.2/S3.3): what Apply did — the edit landed, the anchor went
/// stale (no text touched, card flagged), or the operation refused with
/// a reason for the error strip.
enum FixCardApplyOutcome: Equatable {
case applied
case stale
case refused(String)
}
extension PostsModel {
/// #25 (S3.2/S3.3): Apply a mechanical card — the blocking ask already
/// happened in the UI (ask-before trust level); this lands the edit.
/// Dirty buffer lands first (Apply reads live text); an unanswered #67
/// conflict aborts here with the existing wording. A stale anchor
/// flags the card and touches no text. A failed close after a landed
/// edit is reported via lastError, never silent.
@discardableResult
func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome {
guard card.status == .open else { return .refused("card already closed") }
guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") }
guard let session, let postID = session.postID else {
return .refused("open the piece to work its cards")
}
guard flushOrAbort(postID) else { return .refused(lastError ?? "edits did not land") }
guard let newText = FixCardStore.appliedText(of: card, in: session.text) else {
// Stale anchor — the Post changed after the card was issued:
// persist the honest flag, select and change nothing. A failed
// flag write surfaces like the applied path's — never silent.
do {
_ = try FixCardStore.close(
pieceURL: session.passPieceURL, id: card.id, status: .open, anchorStatus: .stale,
)
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
return .stale
}
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
closeCard(card, status: .applied, home: home)
return .applied
}
/// #25 (S3.3): Skip — not this instance. Closes the card recording
/// NOTHING beyond the status flip (CONTEXT.md).
func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .skipped, home: home)
}
/// #25 (S3.3): Done — the writer rewrote the span themselves. Same
/// flip, different terminal.
func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .done, home: home)
}
private func closeCard(
_ card: FixCardStore.StoredFixCard,
status: FixCardStore.StoredFixCard.Status,
home: URL,
) {
guard let session else {
lastError = "open the piece to work its cards"
return
}
do {
_ = try FixCardStore.close(pieceURL: session.passPieceURL, id: card.id, status: status)
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
}
}
+2 -1
View File
@@ -22,7 +22,8 @@ Owned by the root AGENTS.md contract.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700.
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn through shutdown teardown (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly), 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).
- `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.
+286
View File
@@ -0,0 +1,286 @@
//
// FixCardApplyTests.swift
// MuseionTests
//
// #25 · Slice 2 — Scenario: the writer's hand stays on the wheel
// From issue #25 (S3.2/S3.3): Apply writes the mechanical edit into the
// piece under the ask-before trust level; Skip and Done close the card,
// recording nothing; a stale anchor — the Post changed after the card was
// issued — alerts and touches no text.
// Given an open piece carrying a mechanical fix card,
// when the writer applies, skips, or closes it done, or the anchor went
// stale,
// then the edit lands through the editing session (buffer and disk agree,
// 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.
//
import Foundation
@testable import Museion
import Testing
/// refreshCards hops off MainActor (Task.detached scan) — poll for the
/// hop-back instead of asserting synchronously (PostsModelTests convention).
/// The post-loop expect makes a silent timeout a failure, not a pass.
@MainActor
private func pollUntil(_ condition: @MainActor () -> Bool) async throws {
for _ in 0 ..< 250 where !condition() {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(condition())
}
/// Throwaway piece folder under a throwaway Home — a REAL piece via
/// PostStore.writeNew, so the store's own layout rules apply.
private func makePiece() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("fixcard-apply-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
return try #require(PostStore.folder(of: post.id, home: home))
}
struct FixCardApplyTests {
// MARK: Apply / Skip / Done through the model (#25, S3.2/S3.3)
@Test @MainActor func `apply on a dirty buffer lands the edit buffer and disk agree`() 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(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
let session = try #require(model.session)
let generation = session.loadGeneration
// The writer typed since the last flush — Apply must land the dirty
// buffer first (flush-first, like every op that reads the piece).
session.edit("# Carded\n\nThe anchor sentence.\nPlus a typed line.\n")
#expect(model.applyCard(written[0].card, home: home) == .applied)
// Disk carries the replacement over the flushed buffer...
#expect(PostStore.readBody(id: post.id, home: home) == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n")
// ...and the session re-seeded + saved (the adoptText rail).
#expect(session.text == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n")
#expect(session.saveState == .saved)
#expect(session.loadGeneration == generation + 1)
// The card closed applied on disk.
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .applied)
#expect(model.lastError == nil)
}
@Test @MainActor func `apply with a stale anchor flags the card and touches no text`() 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(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
// The Post changed after the card was issued — the quote is gone.
model.session?.edit("# Carded\n\nThe sentence changed.\n")
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
#expect(model.applyCard(written[0].card, home: home) == .stale)
#expect(try Data(contentsOf: postURL) == before) // nothing selected, nothing changed
let diskCard = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(diskCard.status == .open) // still open — the writer decides
#expect(diskCard.anchorStatus == .stale) // the honest flag persisted
#expect(model.session?.text == "# Carded\n\nThe sentence changed.\n")
}
@Test @MainActor func `apply on a demonstration card refuses and changes 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(pattern: "Demo", fix: "The replaced sentence.", quote: "The anchor sentence.", lane: .demonstration)],
)
model.select(post.id, home: home)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card, home: home)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(why == "demonstration cards close Done or Skip")
#expect(try Data(contentsOf: postURL) == before)
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open)
#expect(model.lastError == nil)
}
@Test @MainActor func `apply under an unanswered conflict refuses and keeps disk untouched`() 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(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
// A foreign write lands on disk underneath the writer (#67) — the
// reload question is up and unanswered.
let postURL = folder.appendingPathComponent("post.md")
try "foreign text on disk".write(to: postURL, atomically: true, encoding: .utf8)
model.session?.diskDidChange(diskText: "foreign text on disk")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card, home: home)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(why.contains("reload question"))
#expect(try Data(contentsOf: postURL) == before) // disk untouched
#expect(model.session?.conflictAlert == true) // the alert stays answerable
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open)
}
@Test @MainActor func `skip and done flip only the card status`() async 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(pattern: "Hedging", quote: "The anchor sentence."),
card(pattern: "Telling", quote: "The anchor sentence."),
],
)
model.select(post.id, home: home)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
model.skipCard(written[0].card, home: home)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.status == .skipped }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[0].card.id })?.status == .skipped)
model.doneCard(written[1].card, home: home)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[1].card.id })?.status == .done }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[1].card.id })?.status == .done)
// Skip records NOTHING beyond the status flip (CONTEXT.md).
#expect(try Data(contentsOf: postURL) == before)
#expect(model.lastError == nil)
}
// MARK: Store addenda (#25 slice 2): scan rank order + close anchorStatus
/// Rank is the persona's ranked order, not the filename's — pattern slugs
/// sort differently than the submit order here, and rank must win.
// ponytail: same-submit cards share a disk timestamp (whole seconds), so
// this pins the microsecond straddle away only probabilistically — a
/// submit-time clock injection if it ever flakes.
@Test func `scan orders a submit by rank regardless of slug order`() throws {
let piece = try makePiece()
_ = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(pattern: "Zebra"), card(pattern: "alpha"), card(pattern: "Mid")],
)
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["Zebra", "alpha", "Mid"])
}
/// Two submits: the newest submission leads. The disk timestamp is
/// whole-second, so the test spans a second boundary deliberately.
@Test func `scan lands the newest submit first`() async throws {
let piece = try makePiece()
_ = try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: "Earlier")])
try await Task.sleep(nanoseconds: 1_100_000_000)
_ = try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: "Later")])
#expect(FixCardStore.scan(pieceURL: piece).first?.pattern == "Later")
}
/// Pre-#25 cards (no rank key) sit AFTER ranked cards of the same submit —
/// filenames here would order them the other way, proving rank decides.
@Test func `scan sorts nil ranks after ranked cards of the same submit`() throws {
let piece = try makePiece()
let dir = piece.appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let stamp = Date(timeIntervalSince1970: 1000)
try FixCardStore.encoder.encode(storedCard(pattern: "Ranked", submittedAt: stamp, rank: 2))
.write(to: dir.appendingPathComponent("a-ranked.json"))
try FixCardStore.encoder.encode(storedCard(pattern: "Old", submittedAt: stamp, rank: nil))
.write(to: dir.appendingPathComponent("b-old.json"))
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["Ranked", "Old"])
}
@Test func `close refreshes anchorStatus when given and preserves it when not`() throws {
let piece = try makePiece()
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let id = written[0].card.id
// A non-nil anchorStatus rides the rewrite — even a status-only close.
let flagged = try FixCardStore.close(pieceURL: piece, id: id, status: .open, anchorStatus: .stale)
#expect(flagged.status == .open) // only the flag flipped
#expect(flagged.anchorStatus == .stale)
// nil preserves it — Skip/Done never touch the anchor verdict.
let skipped = try FixCardStore.close(pieceURL: piece, id: id, status: .skipped)
#expect(skipped.status == .skipped)
#expect(skipped.anchorStatus == .stale)
}
/// A failed stale-flag close surfaces its error — the flag write is
/// honest or loud, never silently skipped (audit: the applied path
/// already reported; this pins the stale sibling).
@Test @MainActor func `stale flag close failure surfaces its error`() 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(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
model.session?.edit("# Carded\n\nThe sentence changed.\n") // stale the anchor
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
// The cards dir goes unreadable — close can't find the card.
let cardsDir = folder.appendingPathComponent("cards", isDirectory: true)
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: cardsDir.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cardsDir.path) }
#expect(model.applyCard(written[0].card, home: home) == .stale) // the primary contract holds…
#expect(model.lastError?.contains("card close failed") == true) // …and the flag failure is loud
#expect(try Data(contentsOf: postURL) == before) // still nothing selected or changed
}
/// A session that never loaded (post.md unreadable/vanished at open)
/// refuses Apply — the card must not close .applied over a write that
/// never landed (audit: flush reports success on a clean no-op).
@Test @MainActor func `apply on a session that never loaded refuses without writing`() 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(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
try FileManager.default.removeItem(at: folder.appendingPathComponent("post.md")) // the read will fail
model.select(post.id, home: home)
#expect(model.session?.loadFailed == true)
// The writer typed the anchor into the empty failed-session buffer.
model.session?.edit("The anchor sentence. typed nowhere durable.")
let outcome = model.applyCard(written[0].card, home: home)
guard case .refused = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
}
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open) // card stays open
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
}
}
+46 -2
View File
@@ -102,14 +102,21 @@ struct MCPServerWireTests {
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
}
@Test func `submit and query round trip through the wire`() throws {
/// One throwaway wire piece: home + `projects/posts/<name>/post.md`
/// (the round-trip test adds its learnings dir on top).
private func seedWirePiece(_ name: String) throws -> (home: URL, piece: URL) {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let piece = home.appendingPathComponent("projects/posts/test-piece", isDirectory: true)
let piece = home.appendingPathComponent("projects/posts/\(name)", isDirectory: true)
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
try "---\ntype: post\n---\nThe repeated anchor line.\n"
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
return (home, piece)
}
@Test func `submit and query round trip through the wire`() throws {
let (home, piece) = try seedWirePiece("test-piece")
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
@@ -180,4 +187,41 @@ struct MCPServerWireTests {
#expect(error["code"] as? Int == -32700)
#expect(replies[0]["id"] is NSNull)
}
/// #25 (S3.2): the ceiling backstop is honest on the wire — 11 valid cards
/// submit, the ranked head (10) lands on disk, the reply says one dropped.
@Test func `submit over the ceiling drops the tail and reports it`() throws {
let (_, piece) = try seedWirePiece("ceiling-piece")
let cards = (1 ... 11).map { index in
[
"pattern": "Pattern \(index)",
"problem": "The problem \(index).",
"anchor": ["quote": "repeated anchor line"],
"lane": "mechanical",
"emitter": "lint",
] as [String: Any]
}
let request: [String: Any] = [
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": ["name": "submit_fix_cards", "arguments": ["piece_path": piece.path, "cards": cards] as [String: Any]],
]
let line = try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8))
let replies = try runWire([line])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["isError"] == nil)
let payload = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any],
)
let landed = try #require(payload["cards"] as? [[String: Any]])
#expect(landed.count == 10)
#expect(payload["dropped_over_ceiling"] as? Int == 1)
let onDisk = ((try? FileManager.default.contentsOfDirectory(
atPath: piece.appendingPathComponent("cards").path,
)) ?? []).filter { $0.hasSuffix(".json") }
#expect(onDisk.count == 10)
}
}
+141 -12
View File
@@ -38,40 +38,55 @@ private func writePiece(
}
/// One wire-shaped card with test-friendly defaults. Internal — shared
/// with PostsModelTests (review: a hand-copy drifted here).
/// with PostsModelTests and FixCardApplyTests (review: a hand-copy drifted
/// here). #25: `fix`/`lane` feed the apply pins.
func card(
pattern: String = "Hedging",
problem: String = "The hedge weakens the claim.",
diagnosticQuestion: String? = nil,
fix: String? = nil,
quote: String = "repeated anchor line",
occurrence: Int = 1,
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
) -> FixCardStore.Input {
FixCardStore.Input(
pattern: pattern,
problem: problem,
diagnosticQuestion: diagnosticQuestion,
fix: nil,
fix: fix,
anchor: .init(quote: quote, occurrence: occurrence),
lane: .mechanical,
lane: lane,
emitter: .lint,
provenance: nil,
)
}
/// A fully-stamped card for hand-written fixtures (scan tests).
private func storedCard(pattern: String) -> FixCardStore.StoredFixCard {
/// A fully-stamped card for hand-written fixtures (scan tests). Defaults
/// match the historical shape; apply tests override anchor/lane, the rank
/// pins override submittedAt/rank. Internal — FixCardApplyTests shares it
/// (the card()/makeModelHome cross-file convention).
func storedCard(
pattern: String = "P",
quote: String = "q",
occurrence: Int = 1,
fix: String = "",
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
submittedAt: Date = Date(timeIntervalSince1970: 0),
rank: Int? = nil,
) -> FixCardStore.StoredFixCard {
FixCardStore.StoredFixCard(
id: UUID(),
submittedAt: Date(timeIntervalSince1970: 0),
submittedAt: submittedAt,
rank: rank,
pattern: pattern,
problem: "p",
diagnosticQuestion: "",
fix: "",
anchor: .init(quote: "q", occurrence: 1),
lane: .mechanical,
fix: fix,
anchor: .init(quote: quote, occurrence: occurrence),
lane: lane,
emitter: .lint,
provenance: nil,
status: "open",
status: .open,
anchorStatus: .valid,
)
}
@@ -103,7 +118,8 @@ struct MCPToolsTests {
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
/// wire; pre-schema cards (no pass key) decode to nil, never error.
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a","pass":2}}"#
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":"#
+ #"{"piece":"posts/a","pass":2}}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
#expect(input.provenance?.pass == 2)
@@ -122,7 +138,7 @@ struct MCPToolsTests {
#expect(written.count == 1)
#expect(written[0].card.anchorStatus == .valid)
#expect(written[0].card.status == "open")
#expect(written[0].card.status == .open)
#expect(written[0].file.hasSuffix("-hedging.json"))
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
@@ -204,6 +220,119 @@ struct MCPToolsTests {
#expect(written[0].file != written[1].file)
}
/// #25 (S3.2): the pass ceiling — an attention budget, not infinite
/// scroll. The backstop keeps the ranked HEAD (submit order = rank,
/// pass-persona doctrine); tail cards drop before validation, so a
/// malformed 12th card never errors an otherwise-fine submit.
@Test func `submit caps at the ten-card pass ceiling keeping the ranked head`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
var cards = (1 ... 11).map { card(pattern: "P\($0)") }
cards.append(card(pattern: " ")) // malformed — and beyond the ceiling
let written = try FixCardStore.submit(piecePath: piece.path, cards: cards)
#expect(written.map(\.card.pattern) == (1 ... 10).map { "P\($0)" })
let files = try FileManager.default.contentsOfDirectory(atPath: piece.appendingPathComponent("cards").path)
.filter { $0.hasSuffix(".json") }
#expect(files.count == 10)
}
/// #25 (S3.2): rank is the submit's array order (the persona's ranked
/// call) — the store stamps it 1-based like id/submittedAt. Optional on
/// decode: pre-#25 cards on disk carry no rank key.
@Test func `submit stamps rank in submit order and old cards decode without it`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(pattern: "Top"), card(pattern: "Mid"), card(pattern: "Tail")],
)
#expect(written.map(\.card.rank) == [1, 2, 3])
// The disk round-trip carries it (snake_case "rank").
let json = try #require(
try JSONSerialization.jsonObject(
with: Data(contentsOf: piece.appendingPathComponent("cards/\(written[0].file)")),
) as? [String: Any],
)
#expect(json["rank"] as? Int == 1)
// A pre-schema card (no rank key) decodes with rank nil, never errors.
let oldData = try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
let stripped = try #require(
try JSONSerialization.jsonObject(with: oldData) as? [String: Any],
).filter { $0.key != "rank" }
let decoded = try FixCardStore.decoder.decode(
FixCardStore.StoredFixCard.self,
from: JSONSerialization.data(withJSONObject: stripped),
)
#expect(decoded.rank == nil)
}
/// #25 (S3.2/S3.3): the pure Apply — the mechanical edit a card makes
/// in a text: the anchored occurrence replaced by the fix, nothing
/// else. nil = the card must not touch text: a demonstration lane
/// (only a mechanical fix is ever applied, ADR-0006) or an anchor that
/// no longer resolves (edits between issue and accept degrade to a
/// loud no-match, never a wrong-span patch).
@Test func `applied text replaces only the anchored occurrence`() {
let text = "alpha anchor beta anchor gamma"
// The nth occurrence, not the first.
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 2, fix: "FIX"), in: text)
== "alpha anchor beta FIX gamma",
)
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX"), in: text)
== "alpha FIX beta anchor gamma",
)
// An empty fix cuts the span.
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor ", occurrence: 2), in: text)
== "alpha anchor beta gamma",
)
// Beyond-count occurrence, vanished quote, empty quote: no edit.
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 3, fix: "FIX"), in: text) == nil)
#expect(FixCardStore.appliedText(of: storedCard(quote: "gone", fix: "FIX"), in: text) == nil)
#expect(FixCardStore.appliedText(of: storedCard(quote: "", fix: "FIX"), in: text) == nil)
// Demonstration lane never applies (ADR-0006).
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX", lane: .demonstration), in: text) == nil)
}
/// #25 (S3.3): the in-place close — Skip/Done/Apply flip the card's
/// status in its own JSON file; every other field travels unchanged
/// (Skip records nothing beyond the flip, CONTEXT.md).
@Test func `close rewrites the card status in place`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let closed = try FixCardStore.close(pieceURL: piece, id: written[0].card.id, status: .skipped)
#expect(closed.status == .skipped)
#expect(closed.rank == 1)
#expect(closed.pattern == "Hedging")
// The SAME single file, status flipped, everything else intact.
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
let files = try FileManager.default.contentsOfDirectory(atPath: cardsDir.path)
.filter { $0.hasSuffix(".json") }
#expect(files == [written[0].file])
let json = try #require(
try JSONSerialization.jsonObject(
with: Data(contentsOf: cardsDir.appendingPathComponent(written[0].file)),
) as? [String: Any],
)
#expect(json["status"] as? String == "skipped")
#expect(json["pattern"] as? String == "Hedging")
#expect(json["rank"] as? Int == 1)
// Scan sees the closed card; a foreign id errors, file untouched.
#expect(FixCardStore.scan(pieceURL: piece).first?.status == .skipped)
#expect(throws: Error.self) {
try FixCardStore.close(pieceURL: piece, id: UUID(), status: .done)
}
}
@Test func `scan returns newest first and skips undecodable`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
@@ -1,3 +1,3 @@
# 0006 — Fix cards travel as typed MCP tool calls
Mentor findings reach the app as typed tool calls — the fix-card schema is the tool's argument schema — rendered from ACP tool-call events, never parsed out of streamed prose. Anchors are quote-based (exact substring + occurrence + context), so edits between issue and accept degrade to a loud no-match, never a wrong-span patch. One schema serves the card UI, the apply-write, and learning promotion; M0's round-trip test exercises exactly this rail. Every fix declares a lane — `mechanical` (the whole fix is a pure function of the anchor plus fixed tables: cut, move, mapping, case) or `demonstration` (any generation) — and only a mechanical fix is ever applied. Every card declares an emitter — `lint` or `engine` — so the engine never re-cards a live lint finding; provenance keeps skill attribution. Rejected: prose parsing (fragile, untyped) and file-watching spools (cards are conversation events, not artifacts).
Mentor findings reach the app as typed tool calls — the fix-card schema is the tool's argument schema — rendered from ACP tool-call events, never parsed out of streamed prose. Anchors are quote-based (exact substring + occurrence + context), so edits between issue and accept degrade to a loud no-match, never a wrong-span patch. One schema serves the card UI, the apply-write, and learning promotion; M0's round-trip test exercises exactly this rail. Every fix declares a lane — `mechanical` (the whole fix is a pure function of the anchor plus fixed tables: cut, move, mapping, case) or `demonstration` (any generation) — and only a mechanical fix is ever applied. Every card declares an emitter — `lint` or `engine` — so the engine never re-cards a live lint finding; provenance keeps skill attribution. Rejected: prose parsing (fragile, untyped) and file-watching spools (cards are conversation events, not artifacts). A mechanical card's fix is the exact replacement for its anchored span (empty = cut) — the only edit Apply ever writes; submits are capped at ten cards, the app keeping the ranked head as backstop.
@@ -0,0 +1,70 @@
# #25 M2: Apply/Skip Fix Cards & trust UI (S3.2–S3.3, S2.5)
> **Date:** 2026-10-20
> **Type:** issue
> **Reference:** [git.babylondreams.de/Museion/issues/25](https://git.babylondreams.de/AlexKucera/Museion/issues/25)
## Goal
Implement #25 over the landed #24 pass substrate: findings as actionable Fix Cards — Apply writes the mechanical edit into the piece under the ask-before trust level (a blocking ask), Skip/Done close the card recording nothing, cards arrive ranked and capped per pass (an attention budget), stale anchors alert without touching text, trust levels visible in the UI. Then run the finish-audit reviewer fanout and fix what it flags.
## What Was Done
- **Dependency check first:** #24 (Run a Pass) closed — the blocked-by edge was satisfied before any work.
- **Three subagent slices at pre-agreed seams** (parent owned scenarios, seams, verification, review aggregation):
- **Store** — `FixCardStore`: `passCardCeiling` = 10 (submit keeps the ranked head, tail drops before validation), `rank` stamped 1-based in submit order, `appliedText(of:in:)` (pure span replacement, nil for demonstration lanes or unresolvable anchors), `close(pieceURL:id:status:anchorStatus:)` in-place status flip, `Status` enum (open|applied|skipped|done), scan sorts submittedAt DESC → rank ASC (nil last) → filename DESC.
- **Model/Session** — `PostsModel.applyCard/skipCard/doneCard` → `FixCardApplyOutcome` (.applied|.stale|.refused); `EditorSession.adoptText` (Yes-reload's body with provided text: loadGeneration bump re-seeds both surfaces, immediate flush).
- **UI/Wire/ADR** — `FixCardsPalette` became the work surface (open-first ordering, per-lane actions, blocking `ApplyAskSheet`, rank + ask-before meta, footer trust line); MCP schema descriptions declare the ranked ≤10 + fix-as-replacement contract; over-ceiling replies carry `dropped_over_ceiling`; ADR-0006 gains the governing sentence.
- **Consolidated DOX pass** — Museion/AGENTS.md (FixCardStore, PostsModel, MCPServer, EditorSession, palette bullets), MuseionTests/AGENTS.md, ADR-0006.
- **finish-audit fanout** (ponytail/security/general, parallel, exclusion-listed): 0 critical/high; **11 accepted fixes** — converged stale-path `try?` → surfaced `lastError`; ask sheet scrolls untrusted text; `adoptText` refuses `loadFailed` sessions; occurrence + context in the ask; `pollUntil` asserts post-loop; 6 ponytail deletions (closeCard dedupe, `storedCard` shared / `fixtureCard` deleted, `makePiece` trim, dead filename pre-sort, `decoded(in:)` shared walk, wire-test seeder). **2 new pins, flip-verified** (both failed with guards deleted in one batch, passed restored).
- **Verification:** full suite **316/316** (299 pre-#25 → +11 slice pins → +2 audit pins), xcresult verdict `Passed`; swiftformat clean; scoped swiftlint unchanged posture; SwiftFairy audits zero findings on changed ranges; GitNexus impact pre-checked per symbol, detect-changes in scope only.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Mechanical `fix` field = the exact replacement for the anchored span (empty = cut) | The only reading where Apply is a pure function without the app owning the tables; ADR-0006 sentence now pins it; sample-pass's "prose stands in for that rail" caveat covers the divergence from FC-10's prose fix |
| Ceiling = keep-the-ranked-head truncation, disclosed on the wire — not a tool error | Slice 1 deviated from the throw-first contract and the parent kept it: a malformed 12th card can't error an otherwise-fine submit, the writer keeps the best findings, and `dropped_over_ceiling` keeps the wire honest |
| Rank stamped store-side from array order (like id/submittedAt) | The persona's ranked call IS the rank; scan's filename order (slug-alphabetical within a shared stamp) loses it — the store preserves arrival order at the boundary |
| Apply routes through the session (`adoptText`), never disk-direct | A disk-direct write would fight the dirty buffer and self-trigger the #67 conflict alert; flush-first + adopt keeps buffer and disk in agreement on both surfaces |
| `adoptText` guards `loadFailed` at the session (audit fix) | `flush()` reports success on a clean no-op, so a never-loaded session would close cards `.applied` over a write that never landed; the guard lives at the write path (root cause), not in `applyCard` |
| Ask-before = the blocking sheet is the ONLY path from Apply to a write | S2.5/S3.3 structurally: no apply-all, no batch, never-do needs no control because nothing auto-applies |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Slice 1's summary claimed done but scan never ordered by rank and `close` couldn't refresh anchorStatus | Child self-reports drift from the contract; rank was stamped but unused | Parent verified the landed diff against the seam contract before wave 2; both gaps folded into slice 2 as store addenda with pins |
| `xcodebuild ... \| grep \| tail` exits 0 regardless of test outcome | Pipe exit status is the LAST command's | Pull the verdict from the xcresult bundle (`xcresulttool get test-results summary`) — the grep filter can also eat the `** TEST SUCCEEDED **` line entirely |
| Prescribed `-only-testing:MuseionTests/PostsModelTests` ran nothing for slice 2 | Suite-name filters don't run free functions (house convention); tests must live inside a `struct` suite | Slice 2 put pins inside `struct FixCardApplyTests` and ran the full unit target instead |
| Parallel sibling builds transiently broke the shared app target | Two agents editing one fs-synced project race the build | Slices used separate `-derivedDataPath` roots; the broken run was re-run once the sibling landed |
| `gitnexus detect-changes` failed with "Multiple repositories indexed" | Global registry holds 11 repos | Always pass `--repo museion` |
| First line-length patch added a pointless `+ ""` concat without shortening the line | Improvised line-break instead of splitting the literal | Split the raw string properly at the JSON boundary |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/FixCardStore.swift` | Ceiling, rank, `appliedText`, `close(anchorStatus:)`, `Status` enum, rank-sorted scan, shared `decoded(in:)` |
| `Museion/PostsModel.swift` | `applyCard`/`skipCard`/`doneCard` + `FixCardApplyOutcome` (guards, stale persistence, surfaced close errors) |
| `Museion/EditorSession.swift` | `adoptText` — programmatic text adoption + immediate flush, `loadFailed` guard |
| `Museion/FixCardsWindow.swift` | Palette work surface: open-first, per-lane actions, blocking ask (scrolling, occurrence + context), trust meta/footer |
| `Museion/MCPServer.swift` | Schema descriptions (ranked ≤10, fix-as-replacement), `dropped_over_ceiling` reply |
| `MuseionTests/FixCardApplyTests.swift` | New — 11 scenario-headed pins incl. 2 flip-verified audit pins |
| `MuseionTests/MCPToolsTests.swift` | Store pins + shared `storedCard` (internal, submittedAt/rank params) |
| `MuseionTests/MCPServerWireTests.swift` | Wire ceiling pin + `seedWirePiece` helper |
| `docs/adr/0006-fix-cards-travel-as-typed-mcp-tool-calls.md` | Mechanical-fix-as-replacement + ten-card ceiling sentence |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass + generated GitNexus counter |
## Open Items & Next Steps
- [ ] `Closes #25` rides the commit — verify the tracker auto-close after push (webhook races a fast read; re-check once).
- [ ] #6 (native deslop lint) is the next domino — it emits the `lane: mechanical` cards that make Apply commonplace; the deferred cumulative `cards/` size cap lands with it or #26.
- [ ] Deferred (security): provenance/emitter self-declared on the wire — ADR-0006 schema-by-design; revisit with a second client surface.
- [ ] Deferred (security Info): card→piece binding relies on `close()`'s foreign-id throw; add an explicit binding check if a non-UI caller ever appears.
- [ ] Deferred (review): outline-piece apply E2E needs a window-hosting harness (none in suite); the `loadGeneration` rail itself is pinned.
- [ ] Deferred from #24: `cancelAck` fake mode for individually discriminating `cancelPass`'s wire effect — still owed to the harness.
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-10-20 | issue | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) | #25 Apply/Skip Fix Cards: ranked ≤10 ceiling, adoptText apply rail, blocking ask, audit fanout with 11 fixes — 316 tests green |
| 2026-10-20 | issue | [20261020-issue24-pass-guard-matrix_log.md](20261020-issue24-pass-guard-matrix_log.md) | #24 close-out: verified against landed #23, pinned the full runPass guard matrix + cancelPass, finish-audit fanout — 299 tests green |
| 2026-10-20 | issue | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) | #23 museion-tools MCP server + fix-card store, Fix Cards palette, dogfood fixes (prompt timeout, persona, debug filter), 3-reviewer audit round — 296 tests green |
| 2026-10-19 | issue | [20261019-issue123-ptacek-fold-text-landings_log.md](20261019-issue123-ptacek-fold-text-landings_log.md) | #123 card-emitting doctrine, lane/emitter terms, FC-10 mechanical exemplar landed across skills, CONTEXT, ADR-0006; deslop gap fixed at source |