From 0e5c28ad95c2202cf1c54e8c038baf6c37eaabe0 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 21 Oct 2026 12:13:24 +0200 Subject: [PATCH] feat(mentor): promote & consult Learnings (#26) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only the writer's explicit confirmation promotes a Fix Card into a Learning — one confirm, one entry, never a repetition counter. The Learning is a plain markdown file under /learnings/s/ carrying the card's teaching fields (pattern, problem, diagnostic question, the demonstration example) plus promotion provenance; the instance-bound anchor and mechanical replacement stay on the card. Every pass consults these files via query_learnings; the Learnings pane replaces its placeholder. Promote consults the on-disk card as the truth and rejects symlinked learnings paths before any write (finish-audit round). Dismiss/decay follows in #27. Closes #26 --- AGENTS.md | 6 +- CHANGELOG.md | 2 + CONTEXT.md | 2 +- Museion/AGENTS.md | 8 +- Museion/FixCardStore.swift | 190 ++++++++++-- Museion/FixCardsWindow.swift | 48 ++- Museion/LearningsPaneView.swift | 234 ++++++++++++++ Museion/PostsModel.swift | 30 ++ Museion/PromoteAskSheet.swift | 118 +++++++ Museion/WorkspaceView.swift | 4 +- MuseionTests/AGENTS.md | 2 +- MuseionTests/FixCardApplyTests.swift | 37 +++ MuseionTests/LearningsPaneTests.swift | 126 ++++++++ MuseionTests/MCPToolsPromoteTests.swift | 289 ++++++++++++++++++ MuseionTests/MCPToolsTests.swift | 46 +-- PRD.md | 3 +- ...1-issue26-promote-consult-learnings_log.md | 69 +++++ docs/devlog/INDEX.md | 1 + 18 files changed, 1133 insertions(+), 82 deletions(-) create mode 100644 Museion/LearningsPaneView.swift create mode 100644 Museion/PromoteAskSheet.swift create mode 100644 MuseionTests/LearningsPaneTests.swift create mode 100644 MuseionTests/MCPToolsPromoteTests.swift create mode 100644 docs/devlog/20261021-issue26-promote-consult-learnings_log.md diff --git a/AGENTS.md b/AGENTS.md index 22adfe7..1b72b33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (3889 symbols, 12468 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** (4003 symbols, 13313 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 | Date | Log | |------|-----| +| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) | | 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | | 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) | @@ -188,5 +189,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) | | 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) | | 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-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 6302908..5cdbfb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **mentor:** Promote & consult Learnings (PRD S4.1/S4.3/S4.4, ADR-0005) — only the writer's explicit confirmation promotes a Fix Card into a Learning: one confirm = one entry, never a repetition counter (the store refuses a second promote of a stamped card). The promote ask on every card row (open or closed — the Learning outlives the card) matches the design contract's dialog (pattern/problem/provenance preview, Cancel/Promote); confirming writes ONE plain markdown file `/learnings/s/YYYYMMDD-.md` carrying the card's teaching fields — pattern, problem, diagnostic question, the demonstration example (demonstration lanes only) — plus promotion provenance (flat frontmatter + readable body, `from_card` traceability, collision -2; the instance-bound anchor and mechanical replacement stay on the card — the Learning teaches the symptom/fix, never re-quotes the originating text) and stamps the card `promoted_at` (pre-#26 cards decode nil); every pass consults exactly these files through `query_learnings`, so recurring weaknesses surface as fix cards; the Learnings pane replaces its placeholder — list-only, grouped by content type, newest first, lenient to hand-edits; learnings are hand-editable, git-diffable, per-writer portable files in the Home (dismiss/decay is #27) (issue #26) + - **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 `/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 diff --git a/CONTEXT.md b/CONTEXT.md index 4db11df..bec7d0b 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -100,7 +100,7 @@ The per-writer, per-content-type store of promoted critique patterns (`learnings _Avoid_: critique memory, memory (unqualified), .learnings **Learning**: -One promoted pattern in Learnings: a Fix Card's fields plus the provenance of its promotion, with decay state in frontmatter. One file per Learning, named `YYYYMMDD-.md`. +One promoted pattern in Learnings: the card's teaching fields (pattern, problem, diagnostic question, the demonstration example when the lane is one) plus the provenance of its promotion, with decay state in frontmatter. The instance-bound evidence — the anchor quote, a mechanical replacement — stays on the card; the Learning teaches the symptom and the fix, it never re-quotes the text it came from. One file per Learning, named `YYYYMMDD-.md`. _Avoid_: rule, note **Skip**: diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 3ae8ca9..7d4a798 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Workspace shell (M1, #17 + #18 / S1.1) - `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette. -- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). +- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions stays an honest placeholder until #28; **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). - `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. - `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///post.md` AND `archive///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//` — 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 disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — 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//`), 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 `/passes/pass-.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 session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · ")` (the label renders, the wire stub never lands) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). +- `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 session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → stub over the bridge via `mentor.sendPrompt(stub, label: "Pass N · <title>")` (the label renders, the wire stub never lands) → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). - `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). @@ -64,14 +64,14 @@ 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; **#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). +- `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/type derivation extracted into private `homeAndType` + public `learningsDir(home:type:)` shared with promote, reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file — the consult rail (query_learnings serves exactly these files); decay filtering is pass-through until #27 defines the decay keys on this frontmatter (ponytail note in code). **#26 (S4.1/S4.3) promote:** `promotedAt: Date?` on StoredFixCard (snake_case `promoted_at`; pre-#26 cards decode nil) — the explicit-confirm stamp; `promote(pieceURL:card:now:)` rejects a symlinked learnings component before any write (security audit: a pre-planted `learnings/posts` link must not become a file-plant primitive), then consults the ON-DISK card as the truth — not-found or already-stamped throws BEFORE anything is written (one confirm = one entry, never a counter; a stale palette copy cannot double-write), resolves home/type from the piece, writes ONE plain markdown Learning `<learningsDir>/<yyyyMMdd>-<PostStore.slug(pattern)>.md` (collision -2/-3 via `uniqueFile(ext:)`), then rewrites the card JSON in place with `promotedAt` (close()'s pattern; learning-first ordering is deliberate — the inverse would lock re-promotion forever); `learningMarkdown` is the pinned file shape — the TEACHING text, never the instance: flat single-line frontmatter (pattern/problem/diagnostic_question?/fix-for-demonstration-lanes-only/lane/emitter/piece?/pass?/engine?/promoted yyyy-MM-dd/from_card uuid; newlines flatten to spaces; the anchor + mechanical replacement stay on the card JSON — a Learning informs, it never gets applied) + readable body (`# pattern`, Problem/Diagnostic lines, `**Example.**` for demonstrations, italic provenance footer omitting missing parts). - 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` — **#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). +- `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). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture). - 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. diff --git a/Museion/FixCardStore.swift b/Museion/FixCardStore.swift index d69e0b8..3f71176 100644 --- a/Museion/FixCardStore.swift +++ b/Museion/FixCardStore.swift @@ -92,6 +92,11 @@ nonisolated enum FixCardStore { /// "open" on submit; a Status terminal once the writer closes it. var status: Status var anchorStatus: AnchorStatus + /// #26 (S4.1): when the writer promoted this card into a Learning — + /// the EXPLICIT confirm only; nil until then. Optional: pre-#26 card + /// JSON decodes nil (a missing key never errors), and one stamp per + /// card is enforced at promote. + var promotedAt: Date? } /// The wire shape of one submitted card (ADR-0006 input fields only — @@ -238,6 +243,7 @@ nonisolated enum FixCardStore { quote: input.anchor.quote, occurrence: input.anchor.occurrence, ), + promotedAt: nil, ) } @@ -272,21 +278,28 @@ nonisolated enum FixCardStore { /// Timestamped card filename prefix, lexicographically sortable /// (ProfileBackup convention). private static func stamp(_ date: Date) -> String { + formatted(date, "yyyyMMdd-HHmmss") + } + + /// en_US_POSIX date formatting, created per access — no non-Sendable + /// statics (repo convention). stamp() and promote's day stamps share it. + private static func formatted(_ date: Date, _ format: String) -> String { let formatter = DateFormatter() - formatter.dateFormat = "yyyyMMdd-HHmmss" + formatter.dateFormat = format formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.string(from: date) } - /// First free filename for `base` (no extension): base, base-2, base-3… + /// First free filename for `base`: base, base-2, base-3… (#26: `ext` — + /// cards are .json, Learnings .md.) // ponytail: exists-then-write race needs two concurrent same-second - // same-pattern submits to matter (atomic rename = replace, not corrupt); - // O_EXCL retry if a second writer ever appears. - private static func uniqueFile(_ dir: URL, base: String) -> String { - var name = "\(base).json" + // same-pattern writers to matter (atomic rename = replace, not + // corrupt); O_EXCL retry if a second writer ever appears. + private static func uniqueFile(_ dir: URL, base: String, ext: String = "json") -> String { + var name = "\(base).\(ext)" var suffix = 2 while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) { - name = "\(base)-\(suffix).json" + name = "\(base)-\(suffix).\(ext)" suffix += 1 } return name @@ -378,22 +391,17 @@ nonisolated enum FixCardStore { /// The piece's visible learnings: raw markdown per file under /// `<home>/learnings/<type>s/` (LITERAL plural — "posts", "outlines"), - /// name-sorted. Raw contents, no parsing — promotion stays a later - /// decision (#26). Missing dir → empty (fresh start is the correct - /// v1 answer); a missing piece still throws. - // ponytail: decay filtering is pass-through until issue #26 defines - // the frontmatter fields. + /// name-sorted. Raw contents, no parsing — the pass rail consults + /// exactly these files (query_learnings; #26 promote writes them). + /// Missing dir → empty (fresh start is the correct v1 answer); a + /// missing piece still throws. + // ponytail: decay filtering is pass-through until a decay policy is + // defined on the #26 frontmatter fields. static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] { let postURL = try resolvePostURL(piecePath) let text = try String(contentsOf: postURL, encoding: .utf8) - // ADR-0012 layout: <home>/<projects|archive>/<project>/<id>/post.md — - // the Home is four components up from the file. - var home = postURL - for _ in 0 ..< 4 { - home.deleteLastPathComponent() - } - let type = Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post - let dir = home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true) + let (home, type) = homeAndType(postURL: postURL, text: text) + let dir = learningsDir(home: home, type: type) let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []) .filter { $0.hasSuffix(".md") } .sorted() @@ -404,4 +412,146 @@ nonisolated enum FixCardStore { return (file: name, markdown: markdown) } } + + /// #26: the Learnings directory for a content type under a Home — + /// LITERAL plural ("posts", "outlines"). ADR-0005: Museion owns these + /// files, the engine profile never does. + static func learningsDir(home: URL, type: Post.ContentType) -> URL { + home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true) + } + + /// post.md URL + its text → (Home, content type) — the ADR-0012 layout + /// walk learnings(piecePath:) and promote(pieceURL:) share: the Home is + /// four components up from the file, the type from the frontmatter + /// (default post). + private static func homeAndType(postURL: URL, text: String) -> (home: URL, type: Post.ContentType) { + var home = postURL + for _ in 0 ..< 4 { + home.deleteLastPathComponent() + } + return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post) + } + + // MARK: - Promote (#26, S4.1/S4.3) + + /// #26 (S4.1/S4.3): promote a card into ONE plain markdown Learning + /// under `<home>/learnings/<type>s/` — the writer's EXPLICIT + /// confirmation only: one confirm = one entry, never a repetition + /// counter (an already-promoted card throws before anything is + /// written). The Learning is Museion's file (ADR-0005): plain + /// markdown, hand-editable, git-diffable; `learnings(piecePath:)` + /// serves it to the next pass. Returns the card with `promotedAt` + /// stamped — its JSON rewritten in place (close()'s pattern), every + /// other field untouched. A missing/unreadable piece throws (trust + /// boundary, resolvePostURL). + @discardableResult + static func promote(pieceURL: URL, card: StoredFixCard, now: Date = Date()) throws -> StoredFixCard { + let postURL = try resolvePostURL(pieceURL.path) + let text = try String(contentsOf: postURL, encoding: .utf8) + let (home, type) = homeAndType(postURL: postURL, text: text) + let dir = learningsDir(home: home, type: type) + + // Security (audit): a pre-planted symlink under the Home must not + // turn promote into a file-plant primitive — reject before any + // write when an existing learnings component is a symlink (the + // read side skips symlinked dirs, Post.scan posture). + for component in [home.appendingPathComponent("learnings"), dir] { + let values = try? component.resourceValues(forKeys: [.isSymbolicLinkKey]) + if values?.isSymbolicLink == true { + throw CardError(message: "learnings path is a symlink: \(component.path)") + } + } + + // The on-disk card is the truth, not the caller's copy: a stale + // palette copy (promotedAt nil while disk is stamped) or a + // vanished/undecodable card JSON must refuse BEFORE anything is + // written — one confirm = one entry, no duplicate Learnings. + let cards = cardsDir(for: postURL) + guard let entry = decoded(in: cards).first(where: { $0.card.id == card.id }) else { + throw CardError(message: "card not found: \(card.id)") + } + guard entry.card.promotedAt == nil else { + throw CardError(message: "card already promoted") + } + + // ONE file: <yyyyMMdd>-<pattern slug>.md, collision -2/-3 (submit's + // uniqueFile, .md edition) — written from the on-disk card. + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let base = "\(formatted(now, "yyyyMMdd"))-\(PostStore.slug(from: entry.card.pattern))" + try learningMarkdown(card: entry.card, now: now).write( + to: dir.appendingPathComponent(uniqueFile(dir, base: base, ext: "md")), + atomically: true, + encoding: .utf8, + ) + + // Stamp the card in place (close()'s rewrite): promotedAt on, + // everything else untouched — the on-disk one-stamp guarantee. + // (Learning-first ordering is deliberate — the inverse would lock + // re-promotion forever after a mid-promote crash.) + var stamped = entry.card + stamped.promotedAt = now + try encoder.encode(stamped).write(to: cards.appendingPathComponent(entry.file), options: .atomic) + return stamped + } + + /// The Learning file's exact shape (tests pin it): the TEACHING text — + /// pattern, problem, diagnostic question, and the demonstration + /// example when the lane is one — never the instance-bound evidence + /// (the anchor quote and a mechanical fix are apply-machinery from the + /// originating piece; the card JSON keeps them, `from_card` traces + /// back). Single-line frontmatter values (newlines flatten to a + /// space), then a human-readable body with an italic provenance + /// footer that omits missing parts — never a dangling separator. + private static func learningMarkdown(card: StoredFixCard, now: Date) -> String { + func flat(_ value: String) -> String { + value.components(separatedBy: .newlines).joined(separator: " ") + } + var keys = [ + "pattern: \(flat(card.pattern))", + "problem: \(flat(card.problem))", + ] + if !card.diagnosticQuestion.isEmpty { + keys.append("diagnostic_question: \(flat(card.diagnosticQuestion))") + } + // Demonstration lanes: the fix IS the example rewrite — teaching + // material, it travels. Mechanical lanes: the fix is a literal + // replacement string from one instance — it teaches nothing + // general and would mislead as "the fix". + let example = card.lane == .demonstration ? card.fix : "" + if !example.isEmpty { + keys.append("fix: \(flat(example))") + } + keys.append("lane: \(card.lane.rawValue)") + keys.append("emitter: \(card.emitter.rawValue)") + if let piece = card.provenance?.piece { + keys.append("piece: \(flat(piece))") + } + if let pass = card.provenance?.pass { + keys.append("pass: \(pass)") + } + if let engine = card.provenance?.engine { + keys.append("engine: \(flat(engine))") + } + keys.append("promoted: \(formatted(now, "yyyy-MM-dd"))") + keys.append("from_card: \(card.id.uuidString)") + + var body = [ + "# \(flat(card.pattern))", + "**Problem.** \(flat(card.problem))", + ] + if !card.diagnosticQuestion.isEmpty { + body.append("**Diagnostic.** \(flat(card.diagnosticQuestion))") + } + if !example.isEmpty { + body.append("**Example.** \(flat(example))") + } + var footer = [(card.provenance?.piece).map(flat) ?? "a fix card"] + if let pass = card.provenance?.pass { + footer.append("Pass \(pass)") + } + footer.append(formatted(now, "yyyy-MM-dd")) + body.append("*Promoted from \(footer.joined(separator: " · ")).*") + + return "---\n\(keys.joined(separator: "\n"))\n---\n\n\(body.joined(separator: "\n\n"))\n" + } } diff --git a/Museion/FixCardsWindow.swift b/Museion/FixCardsWindow.swift index e81e517..a6f4b2e 100644 --- a/Museion/FixCardsWindow.swift +++ b/Museion/FixCardsWindow.swift @@ -114,6 +114,8 @@ private struct CardRow: View { @Environment(AppGateState.self) private var gate /// The row's own blocking ask; Apply arms it, the sheet answers it. @State private var asking = false + /// #26: the promotion ask — Promote arms it, its sheet answers it. + @State private var promoting = false var body: some View { let stale = card.anchorStatus == .stale @@ -131,25 +133,34 @@ private struct CardRow: 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; + if open || card.promotedAt == nil { + // The actions this card offers (#25 S3.3, #26 S4.1): + // mechanical + valid → Apply (the blocking ask) and Skip; // demonstration → Done and Skip (never Apply, ADR-0006); - // stale anchor → Skip only. + // stale anchor → Skip only. Promote (its own ask) sits + // between the primary action and Skip, and outlives the + // card — closed cards keep it until promoted (#26: the + // Learning is the durable artifact). HStack(spacing: 8) { - if stale { - SkipButton(card: card) - } else if card.lane == .mechanical { - Button("Apply") { asking = true } + if open, !stale { + if card.lane == .mechanical { + Button("Apply") { asking = true } + .buttonStyle(.bordered) + .controlSize(.small) + } else { + Button("Done") { + gate.posts.doneCard(card, home: gate.museionHome) + } .buttonStyle(.bordered) .controlSize(.small) - SkipButton(card: card) - } else { - Button("Done") { - gate.posts.doneCard(card, home: gate.museionHome) } - .buttonStyle(.bordered) - .controlSize(.small) + } + if card.promotedAt == nil { + Button("Promote") { promoting = true } + .buttonStyle(.bordered) + .controlSize(.small) + } + if open { SkipButton(card: card) } } @@ -165,11 +176,15 @@ private struct CardRow: View { .sheet(isPresented: $asking) { ApplyAskSheet(card: card, posts: gate.posts, home: gate.museionHome) } + // #26: Promote is its own blocking ask — one confirm, one Learning. + .sheet(isPresented: $promoting) { + PromoteAskSheet(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. + /// the close status, and the promotion stamp (#26). private var meta: String { var value = "\(card.lane.rawValue) · \(card.emitter.rawValue)" if let pass = card.provenance?.pass { @@ -187,6 +202,9 @@ private struct CardRow: View { if card.status != .open { value += " · \(card.status.rawValue)" } + if card.promotedAt != nil { + value += " · promoted" + } return value } } diff --git a/Museion/LearningsPaneView.swift b/Museion/LearningsPaneView.swift new file mode 100644 index 0000000..7c35f12 --- /dev/null +++ b/Museion/LearningsPaneView.swift @@ -0,0 +1,234 @@ +// +// LearningsPaneView.swift +// Museion +// +// #26 (S4.4, ADR-0005): the Learnings pane — the writer's per-writer +// portable critique memory as plain files. List-only (Archive pane +// precedent): read side; promotion (the fix-card rail) writes the files. +// + +import SwiftUI + +/// The pane's disk reader. One markdown file per Learning under +/// `<home>/learnings/<type-plural>/` (literal plurals: "posts", +/// "outlines"), named `YYYYMMDD-<pattern-slug>.md` — hand-editable, +/// git-diffable, surviving restarts. Every read is lenient: a +/// stranger's hand-edit never crashes the pane. +nonisolated enum LearningsIndex { + /// One Learning on disk. `pattern` falls back to the filename + /// (extension and leading date + hyphen stripped); `problem`/ + /// `promoted` omit when the frontmatter key is absent. + nonisolated struct Entry: Identifiable { + /// The file name (with extension) — unique within its group. + let id: String + let pattern: String + var problem: String? + var promoted: String? + + init(file: String, text: String) { + let frontmatter = Post.frontmatter(of: text) + id = file + pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file) + problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 } + promoted = frontmatter["promoted"].flatMap { $0.isEmpty ? nil : $0 } + } + + /// "20261021-fold-the-ladder.md" → "fold-the-ladder". + static func pattern(fromFilename file: String) -> String { + let stem = (file as NSString).deletingPathExtension + guard Self.isDated(file) else { return stem } + return String(stem.dropFirst(9)) + } + + /// The filename contract: a `YYYYMMDD-` prefix (8 digits + hyphen). + static func isDated(_ file: String) -> Bool { + let stem = (file as NSString).deletingPathExtension + let digits = stem.prefix(8) + return digits.count == 8 && digits.allSatisfy(\.isNumber) && stem.dropFirst(8).first == "-" + } + } + + /// One content-type section, keyed by the directory name. + nonisolated struct Group { + let type: String + var entries: [Entry] + } + + /// Scans `<home>/learnings/*/` — groups keyed by directory name + /// (type-sorted), entries newest-first (the YYYYMMDD prefix sorts + /// lexicographically desc; undated files last). Missing learnings/ → + /// empty; hidden dirs/files, non-.md, loose files, and unreadable + /// files never surface. Same skip posture as `Post.scan`. + static func scan(home: URL) -> [Group] { + let root = home.appendingPathComponent("learnings", isDirectory: true) + guard let typeDirs = try? FileManager.default.contentsOfDirectory( + at: root, + includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], + ) else { return [] } + var groups: [Group] = [] + for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { + guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix(".") else { continue } + guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) + else { continue } + let entries = files + .filter { + !$0.lastPathComponent.hasPrefix(".") + && $0.pathExtension.caseInsensitiveCompare("md") == .orderedSame + } + .compactMap { file in + // ponytail: unbounded read, file symlinks followed — same + // ceiling as Post.scan/FixCardStore.learnings (systemic, + // local-Home threat only); isSymbolicLink + size cap if a + // hostile Home ever matters. + (try? String(contentsOf: file, encoding: .utf8)) + .map { Entry(file: file.lastPathComponent, text: $0) } + } + guard !entries.isEmpty else { continue } + groups.append(Group( + type: dir.lastPathComponent, + // Dated files first (newest first — lexicographic desc on + // the name), undated hand-edits last. + entries: entries.sorted { lhs, rhs in + let (lhsDated, rhsDated) = (Entry.isDated(lhs.id), Entry.isDated(rhs.id)) + return lhsDated == rhsDated ? lhs.id > rhs.id : lhsDated + }, + )) + } + return groups + } + + private static func isPlainDirectory(_ url: URL) -> Bool { + let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false) + } +} + +/// #26: the Learnings pane — list-only, like the Archive pane. +struct LearningsPaneView: View { + let home: URL + @State private var groups: [LearningsIndex.Group] = [] + + var body: some View { + VStack(spacing: 0) { + // No New button — learnings arrive by promotion, not creation. + PaneHeader(title: "Learnings") + if groups.isEmpty { + emptyState + } else { + ScrollView { + LazyVStack(alignment: .leading, spacing: 4) { + ForEach(groups, id: \.type) { group in + LearningSection(group: group) + } + } + .padding(.bottom, 12) + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(DesignTokens.background) + // Disk I/O stays off MainActor (rescan posture, PostsModel) — the + // .task body is MainActor, so the scan hops to a detached task and + // the assignment lands back on the main actor. + // ponytail: no FSEvents watcher — the pane re-scans on .task(id: home) + // each time it appears; a promote landing while the pane stays open + // goes stale until the pane is re-entered. Add a watcher if that + // ever annoys. + .task(id: home) { + let scanned = await Task.detached(priority: .userInitiated) { + LearningsIndex.scan(home: home) + }.value + // A home repoint cancels the awaiting task, but a detached + // scan is not cancellation-aware — a slow OLD scan must not + // overwrite the new Home's groups after it resumes. + guard !Task.isCancelled else { return } + groups = scanned + } + } + + private var emptyState: some View { + VStack(spacing: 8) { + Text("No learnings yet.") + .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) + Text("Promoting a fix card writes one plain markdown Learning here.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + .multilineTextAlignment(.center) + } + .padding(38) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +/// One content-type section: the head + its rows. A child view so the +/// lazy stack sees one view per group (its inner ForEach is the view's +/// own body, not uneven outer-row content). +private struct LearningSection: View { + let group: LearningsIndex.Group + + var body: some View { + SectionHeadView(type: group.type, count: group.entries.count) + .padding(.top, 16) + .padding(.horizontal, 14) + .padding(.bottom, 6) + ForEach(group.entries) { entry in + LearningRow(entry: entry) + } + } +} + +/// The library's section-head voice: serif-15 semibold name +/// (display-lowercased) + mono-11 `· N` count. +private struct SectionHeadView: View { + let type: String + let count: Int + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(type) + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + .textCase(.lowercase) // display-only — the dir name keeps its case + .lineLimit(1) + .truncationMode(.tail) + Text("· \(count)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + Spacer(minLength: 0) + } + } +} + +/// One Learning row: pattern as the title, problem as the secondary +/// line, promoted date + file name in mono-11. +private struct LearningRow: View { + let entry: LearningsIndex.Entry + + var body: some View { + VStack(alignment: .leading, spacing: 5) { + Text(entry.pattern) + .font(.callout.weight(.semibold)) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + if let problem = entry.problem { + Text(problem) + .font(.callout) + .foregroundStyle(DesignTokens.muted) + .lineLimit(2) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + Text(metaLine) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(10) + } + + private var metaLine: String { + entry.promoted.map { "promoted · \($0) · \(entry.id)" } ?? entry.id + } +} diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 52aeed3..40bb758 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -954,3 +954,33 @@ extension PostsModel { refreshCards(home: home) } } + +// MARK: Fix Card promote (#26, S4.1/S4.3) + +/// #26 (S4.1): what Promote did — the Learning landed, or the operation +/// refused with a reason (the ask sheet shows it; lastError carries it). +enum FixCardPromoteOutcome: Equatable { + case promoted + case refused(String) +} + +extension PostsModel { + /// #26 (S4.1/S4.3): Promote a card into ONE plain markdown Learning + /// under `<home>/learnings/<type>s/` — the writer's EXPLICIT + /// confirmation only (one confirm = one entry, never a repetition + /// counter; the store guarantees the one-stamp rule). Touches no text + /// and flushes nothing: this writes a Learning, not an edit. + @discardableResult + func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome { + guard card.promotedAt == nil else { return .refused("card already promoted") } + guard let session else { return .refused("open the piece to work its cards") } + do { + _ = try FixCardStore.promote(pieceURL: session.passPieceURL, card: card) + } catch { + lastError = "learning write failed: \(error.localizedDescription)" + return .refused("learning write failed: \(error.localizedDescription)") + } + refreshCards(home: home) + return .promoted + } +} diff --git a/Museion/PromoteAskSheet.swift b/Museion/PromoteAskSheet.swift new file mode 100644 index 0000000..7ac3fb0 --- /dev/null +++ b/Museion/PromoteAskSheet.swift @@ -0,0 +1,118 @@ +// +// PromoteAskSheet.swift +// Museion +// +// #26 (S4.1): the promotion ask, extracted from FixCardsWindow.swift +// (file was past its length ceiling; OutlineRowTextView precedent). +// + +import SwiftUI + +/// #26 (S4.1): the promotion ask — ONE explicit confirmation writes ONE +/// plain markdown Learning (never a repetition counter; the store refuses +/// the second). The design contract's #promoteDialog: title, the consulted- +/// on-future-Passes body, a learning preview, Cancel/Promote. Promote is +/// the sheet's only write path; Cancel writes nothing; a refusal shows its +/// reason with the buttons kept (ApplyAskSheet posture). +struct PromoteAskSheet: View { + let card: FixCardStore.StoredFixCard + let posts: PostsModel + let home: URL + @Environment(\.dismiss) private var dismiss + + @State private var refusal: String? + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + Text("Promote to Learnings?") + .font(.headline) + Text( + "This pattern will be consulted on future Passes for \(typePlural). " + + "Museion will write one plain markdown Learning.", + ) + .font(.callout) + // The Learning preview: pattern, problem, provenance — + // the file the confirm writes. + VStack(alignment: .leading, spacing: 6) { + Text(card.pattern) + .font(.callout.weight(.semibold)) + if !card.problem.isEmpty { + Text(card.problem).font(.callout) + } + // The preview shows what lands: the diagnostic + // and, on demonstration lanes, the example the + // Learning will carry. + if !card.diagnosticQuestion.isEmpty { + Text(card.diagnosticQuestion).font(.callout) + } + if card.lane == .demonstration, !card.fix.isEmpty { + Text("Example: \(card.fix)").font(.callout) + } + if !provenanceLine.isEmpty { + Text(provenanceLine) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + } + } + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 6)) + if let refusal { + Text(refusal) + .font(.callout) + .foregroundStyle(.orange) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + HStack(spacing: 8) { + Button("Promote") { promote() } + .buttonStyle(.borderedProminent) + Button("Cancel") { dismiss() } + .buttonStyle(.bordered) + } + .frame(maxWidth: .infinity, alignment: .trailing) + } + .padding(16) + .frame(width: 320, alignment: .leading) + } + + /// The open piece's content type, pluralized; "pieces" when unknown. + private var typePlural: String { + guard let id = posts.session?.postID, + let type = posts.posts.first(where: { $0.id == id })?.type + else { return "pieces" } + return type == .post ? "Posts" : "Outlines" + } + + /// "<piece title> · Pass N · <engine> · <date>" — provenance.piece is + /// the piece id, resolved through the model's title lookup (fallback: + /// the id); missing parts drop out, date falls back to promotedAt. + private var provenanceLine: String { + var parts: [String] = [] + if let pieceID = card.provenance?.piece { + parts.append(posts.title(of: pieceID)) + } + if let pass = card.provenance?.pass { + parts.append("Pass \(pass)") + } + if let engine = card.provenance?.engine { + parts.append(engine) + } + if let date = card.provenance?.date { + parts.append(date) + } + return parts.joined(separator: " · ") + } + + private func promote() { + switch posts.promoteCard(card, home: home) { + case .promoted: + dismiss() + case let .refused(reason): + refusal = reason + } + } +} diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index 88de16a..15bb294 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -198,7 +198,9 @@ struct WorkspaceView: View { case .sessions: PlaceholderPane(title: "Sessions", detail: "Session lifecycle arrives with S2.3 (#28).") case .learnings: - PlaceholderPane(title: "Learnings", detail: "Promote, consult, and decay arrive with S4 (#26, #27).") + // #26: list-only pane over <home>/learnings/ — read side; + // promoting a fix card (the fix-card rail) writes the files. + LearningsPaneView(home: gate.museionHome) case .archive: // #108: list-only pane — clicking a row selects the piece and // hops to Posts where its editor lives. diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index e4e37da..d060a7f 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -22,7 +22,7 @@ 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. **#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. +- `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. **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses. - `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve). - `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered. - `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. diff --git a/MuseionTests/FixCardApplyTests.swift b/MuseionTests/FixCardApplyTests.swift index 08a2863..5efc81d 100644 --- a/MuseionTests/FixCardApplyTests.swift +++ b/MuseionTests/FixCardApplyTests.swift @@ -283,4 +283,41 @@ struct FixCardApplyTests { #expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open) // card stays open #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written } + + // MARK: Promote (#26, S4.1) + + /// Scenario: the mentor remembers — promoting through the model writes + /// the Learning under the open piece's Home, refreshes the palette's + /// cards (promotedAt visible), and refuses a second confirm; with no + /// open piece it refuses before touching anything. + @Test @MainActor func `promote through the model writes one learning and refuses repeats`() 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()]) + model.select(post.id, home: home) + + #expect(model.promoteCard(written[0].card, home: home) == .promoted) + + let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true) + #expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1) + try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.promotedAt != nil } + #expect(model.lastError == nil) + + // Already promoted → refused, no second file (one confirm = one entry). + let scanned = try #require(FixCardStore.scan(pieceURL: folder).first) + #expect(model.promoteCard(scanned, home: home) == .refused("card already promoted")) + #expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1) + } + + @Test @MainActor func `promote without an open piece refuses and writes nothing`() throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home) + let folder = try #require(PostStore.folder(of: post.id, home: home)) + let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()]) + + #expect(model.promoteCard(written[0].card, home: home) == .refused("open the piece to work its cards")) + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path)) + #expect(model.lastError == nil) + } } diff --git a/MuseionTests/LearningsPaneTests.swift b/MuseionTests/LearningsPaneTests.swift new file mode 100644 index 0000000..4c3c542 --- /dev/null +++ b/MuseionTests/LearningsPaneTests.swift @@ -0,0 +1,126 @@ +// +// LearningsPaneTests.swift +// MuseionTests +// +// #26 (S4.4, ADR-0005): the Learnings pane's disk reader — one plain +// markdown file per Learning under <home>/learnings/<type-plural>/, +// frontmatter read leniently (a stranger's hand-edit never surfaces +// wrong or crashes the pane). +// + +import Foundation +@testable import Museion +import Testing + +/// Throwaway Homes with hand-written .md Learning fixtures — the format +/// contract the promote rail writes: frontmatter pattern/problem/promoted +/// (all optional, quoted or bare), file named YYYYMMDD-<slug>.md, +/// dir = the content-type plural. +private func makeHome(_ write: (URL) throws -> Void) throws -> URL { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("learnings-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + try write(home) + return home +} + +/// Seeds <home>/learnings/<type>/<file> with raw markdown. +private func writeLearning(_ home: URL, _ type: String, _ file: String, _ markdown: String) throws { + let dir = home.appendingPathComponent("learnings/\(type)", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try markdown.write(to: dir.appendingPathComponent(file), atomically: true, encoding: .utf8) +} + +struct LearningsPaneTests { + @Test func `scan groups by type dir and orders entries newest first`() throws { + // Scenario: two content-type dirs; within posts three files — the + // YYYYMMDD prefix orders newest-first and an undated file sorts last. + let home = try makeHome { home in + try writeLearning(home, "posts", "20261020-late-scene-reveal.md", """ + --- + pattern: "Open on the reveal" + problem: "Scenes opened after the reveal" + promoted: 2026-10-20 + --- + """) + try writeLearning(home, "posts", "20261021-fold-the-ladder.md", """ + --- + pattern: Fold the ladder + problem: Ladders left standing + promoted: "2026-10-21" + --- + """) + try writeLearning(home, "posts", "undated-note.md", "# just a hand edit\n") + try writeLearning(home, "outlines", "20261019-parallel-arcs.md", """ + --- + pattern: Parallel arcs + promoted: 2026-10-19 + --- + """) + } + let groups = LearningsIndex.scan(home: home) + #expect(groups.map(\.type) == ["outlines", "posts"]) + let posts = try #require(groups.first { $0.type == "posts" }) + #expect(posts.entries.map(\.id) == [ + "20261021-fold-the-ladder.md", + "20261020-late-scene-reveal.md", + "undated-note.md", + ]) + let newest = try #require(posts.entries.first) + #expect(newest.pattern == "Fold the ladder") // bare value, not just the quoted form + #expect(newest.problem == "Ladders left standing") + #expect(newest.promoted == "2026-10-21") + let outlines = try #require(groups.first { $0.type == "outlines" }) + #expect(outlines.entries.count == 1) + #expect(outlines.entries.first?.problem == nil) // absent key omits the line + } + + @Test func `scan reads leniently - noise never surfaces or crashes`() throws { + // Scenario: a stranger hand-edits the vault — a dated file with no + // frontmatter (pattern derives from the filename), non-md and hidden + // files, a hidden dir, a loose file directly under learnings/. + let home = try makeHome { home in + try writeLearning(home, "posts", "20261018-dated-without-frontmatter.md", "# note\n") + try writeLearning(home, "posts", ".DS_Store", "junk") + try writeLearning(home, "posts", "draft.txt", "not markdown") + try writeLearning(home, ".git", "20260101-x.md", "---\npattern: hidden\n---\n") + // A symlinked type-dir with FULL payload (a real .md behind the + // link) never surfaces — Post.scan posture, pinned. + let linkedTo = home.appendingPathComponent("real-drafts", isDirectory: true) + try FileManager.default.createDirectory(at: linkedTo, withIntermediateDirectories: true) + try "---\npattern: behind the link\n---\n".write( + to: linkedTo.appendingPathComponent("20261016-linked.md"), + atomically: true, + encoding: .utf8, + ) + try FileManager.default.createSymbolicLink( + at: home.appendingPathComponent("learnings/linked-posts"), + withDestinationURL: linkedTo, + ) + try writeLearning(home, "outlines", "20261017-outline-edge.md", """ + --- + promoted: 2026-10-17 + --- + """) + try "stray".write( + to: home.appendingPathComponent("learnings/loose.md"), + atomically: true, + encoding: .utf8, + ) + } + let groups = LearningsIndex.scan(home: home) + #expect(groups.map(\.type) == ["outlines", "posts"]) // hidden dir + loose file: no group + let posts = try #require(groups.first { $0.type == "posts" }) + #expect(posts.entries.map(\.pattern) == ["dated-without-frontmatter"]) // date+hyphen stripped, ext gone + #expect(posts.entries.first?.promoted == nil) + let outlines = try #require(groups.first { $0.type == "outlines" }) + #expect(outlines.entries.first?.pattern == "outline-edge") // no pattern key → filename, date+hyphen stripped + } + + @Test func `missing learnings dir scans empty`() throws { + // Scenario: a fresh Home before the first promotion — nothing to + // read, no crash. + let home = try makeHome { _ in } + #expect(LearningsIndex.scan(home: home).isEmpty) + } +} diff --git a/MuseionTests/MCPToolsPromoteTests.swift b/MuseionTests/MCPToolsPromoteTests.swift new file mode 100644 index 0000000..7cbdacd --- /dev/null +++ b/MuseionTests/MCPToolsPromoteTests.swift @@ -0,0 +1,289 @@ +// +// MCPToolsPromoteTests.swift +// MuseionTests +// +// #26 (M3, S4.1/S4.3/S4.4): the promote rail's store pins — one confirm +// writes ONE plain markdown Learning under <home>/learnings/<type>s/, +// the consult rail reads it back, and pre-#26 card JSON stays readable. +// Own file (MCPToolsTests was past its type-body ceiling): the +// temp-home/piece/card helpers stay in MCPToolsTests (cross-file +// convention). +// + +import Foundation +@testable import Museion +import Testing + +/// The store's stamp conventions (en_US_POSIX, per access) — expected +/// learning filenames/dates in the #26 promote pins. +private func stamped(_ date: Date, _ format: String) -> String { + let formatter = DateFormatter() + formatter.dateFormat = format + formatter.locale = Locale(identifier: "en_US_POSIX") + return formatter.string(from: date) +} + +/// 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: submittedAt, + rank: rank, + pattern: pattern, + problem: "p", + diagnosticQuestion: "", + fix: fix, + anchor: .init(quote: quote, occurrence: occurrence), + lane: lane, + emitter: .lint, + provenance: nil, + status: .open, + anchorStatus: .valid, + promotedAt: nil, + ) +} + +struct MCPToolsPromoteTests { + // MARK: Promote (#26, S4.1/S4.3/S4.4) + + /// Scenario: one confirm writes one learning — given a submitted card + /// on a piece under a temp Home, when the writer confirms promotion, + /// then exactly ONE plain markdown Learning exists under + /// `<home>/learnings/posts/<yyyyMMdd>-<slug>.md` with the pinned + /// frontmatter shape and a `# <pattern>` body, the card carries + /// promotedAt, and a second confirm is refused with no second file — + /// never a repetition counter. + @Test func `promote writes one learning and stamps the card`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit( + piecePath: piece.path, + cards: [ + card( + diagnosticQuestion: "Is the hedge load-bearing?", + fix: "Cut the hedge.", + provenance: .init(piece: "test-piece", date: "2026-08-27", engine: "hermes", pass: 1), + ), + ], + ) + let now = Date(timeIntervalSince1970: 1_800_000_000) + + let promoted = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now) + + // ONE file, the pinned name shape. + let dir = home.appendingPathComponent("learnings/posts", isDirectory: true) + let name = "\(stamped(now, "yyyyMMdd"))-hedging.md" + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") } == [name]) + + let markdown = try String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8) + #expect(markdown.contains("pattern: Hedging\n")) + #expect(markdown.contains("problem: The hedge weakens the claim.\n")) + #expect(markdown.contains("diagnostic_question: Is the hedge load-bearing?\n")) + #expect(markdown.contains("lane: mechanical\n")) + #expect(markdown.contains("emitter: lint\n")) + #expect(markdown.contains("piece: test-piece\n")) + #expect(markdown.contains("pass: 1\n")) + #expect(markdown.contains("engine: hermes\n")) + #expect(markdown.contains("promoted: \(stamped(now, "yyyy-MM-dd"))\n")) + #expect(markdown.contains("from_card: \(written[0].card.id.uuidString)\n")) + // The Learning teaches, it never re-quotes the instance: a + // mechanical fix is a literal replacement string from one piece + // and the anchor is apply-machinery — both stay on the card JSON. + #expect(!markdown.contains("fix:")) + #expect(!markdown.contains("anchor")) + #expect(!markdown.contains("repeated anchor line")) + #expect(!markdown.contains("Cut the hedge.")) + #expect(markdown.contains("\n# Hedging\n")) + #expect(markdown.contains("**Problem.** The hedge weakens the claim.")) + #expect(markdown.contains("*Promoted from test-piece · Pass 1 · \(stamped(now, "yyyy-MM-dd")).*")) + + // The returned card carries promotedAt; so does the re-scan. + #expect(promoted.promotedAt == now) + #expect(FixCardStore.scan(pieceURL: piece).first?.promotedAt == now) + + // A second confirm is refused at the store level — no second file. + #expect(throws: FixCardStore.CardError(message: "card already promoted")) { + try FixCardStore.promote(pieceURL: piece, card: promoted, now: now) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1) + + // A missing piece is a thrown error, never a silent no-op. + #expect(throws: Error.self) { + try FixCardStore.promote(pieceURL: home.appendingPathComponent("gone"), card: storedCard()) + } + } + + /// Scenario: the mentor remembers — after promotion, + /// learnings(piecePath:) returns the Learning's raw markdown: the pass + /// rail consults exactly these files (S4.3/S4.4 — the engine reads + /// them via query_learnings, unchanged). + @Test func `promoted learnings are consultable`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()]) + _ = try FixCardStore.promote(pieceURL: piece, card: written[0].card) + + let learned = try FixCardStore.learnings(piecePath: piece.path) + #expect(learned.count == 1) + #expect(learned[0].file.hasSuffix("-hedging.md")) + #expect(learned[0].markdown.contains("# Hedging")) + } + + /// An outline-typed piece promotes into learnings/outlines/ — the + /// Learning lands with the piece's own content type (learningsDir). + @Test func `promote follows the piece content type`() throws { + let home = try toolsHome() + let piece = try writePiece(home, id: "outline-piece", type: "outline") + let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()]) + _ = try FixCardStore.promote(pieceURL: piece, card: written[0].card) + + #expect(FixCardStore.learningsDir(home: home, type: .post).lastPathComponent == "posts") + let dir = FixCardStore.learningsDir(home: home, type: .outline) + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1) + #expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) + } + + /// Same-day, same-pattern: the second Learning takes the -2 suffix + /// (uniqueFile's collision pattern, .md edition). + @Test func `promote suffixes same-day same-pattern collisions`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit( + piecePath: piece.path, + cards: [card(), card(problem: "A different problem.")], + ) + let now = Date() + _ = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now) + _ = try FixCardStore.promote(pieceURL: piece, card: written[1].card, now: now) + + let dir = home.appendingPathComponent("learnings/posts", isDirectory: true) + let base = "\(stamped(now, "yyyyMMdd"))-hedging" + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).sorted() == ["\(base)-2.md", "\(base).md"]) + } + + /// Frontmatter values are single-line: any newline in a pattern, problem, + /// or example flattens to a space — the file stays parseable. Demonstration + /// lanes keep their fix (the example rewrite teaches); it lands as `fix:` + /// frontmatter and an `**Example.**` body line. + @Test func `promote flattens newlines and keeps the demonstration example`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit( + piecePath: piece.path, + cards: [ + card( + pattern: "Hedging\nacross lines", + problem: "Two-line\nproblem.", + fix: "Rewritten\nas the master would pace it.", + lane: .demonstration, + ), + ], + ) + let now = Date() + _ = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now) + + let dir = home.appendingPathComponent("learnings/posts", isDirectory: true) + let files = try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") } + let markdown = try String(contentsOf: dir.appendingPathComponent(files[0]), encoding: .utf8) + #expect(markdown.contains("pattern: Hedging across lines\n")) + #expect(markdown.contains("problem: Two-line problem.\n")) + #expect(markdown.contains("lane: demonstration\n")) + #expect(markdown.contains("fix: Rewritten as the master would pace it.\n")) + #expect(markdown.contains("**Example.** Rewritten as the master would pace it.")) + #expect(markdown.contains("# Hedging across lines\n")) + // No provenance → the footer's piece falls back to "a fix card". + #expect(markdown.contains("*Promoted from a fix card · \(stamped(now, "yyyy-MM-dd")).*")) + } + + /// Pre-#26 card JSON (no promoted_at key) decodes promotedAt nil; a + /// promoted card round-trips the stamp (snake_case promoted_at). + @Test func `old card json decodes promoted at nil`() throws { + let legacy = try FixCardStore.decoder.decode( + FixCardStore.StoredFixCard.self, + from: FixCardStore.encoder.encode(storedCard()), + ) + #expect(legacy.promotedAt == nil) + + var promotedCard = storedCard() + promotedCard.promotedAt = Date(timeIntervalSince1970: 1_800_000_000) + let data = try FixCardStore.encoder.encode(promotedCard) + let json = try #require( + try JSONSerialization.jsonObject(with: data) as? [String: Any], + ) + #expect(json["promoted_at"] is String) + #expect( + try FixCardStore.decoder.decode(FixCardStore.StoredFixCard.self, from: data).promotedAt + == promotedCard.promotedAt, + ) + } + + /// Scenario: the on-disk card is the truth — a STALE palette copy + /// (promotedAt nil while disk is already stamped, the async refresh + /// gap) must refuse with no second Learning (audit: the double-write + /// window, closed at the store seam). + @Test func `a stale unstamped copy cannot double-promote`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()]) + _ = try FixCardStore.promote(pieceURL: piece, card: written[0].card) + + // The caller's copy is the pre-promote one — the disk check must refuse. + #expect(throws: FixCardStore.CardError(message: "card already promoted")) { + try FixCardStore.promote(pieceURL: piece, card: written[0].card) + } + let dir = home.appendingPathComponent("learnings/posts", isDirectory: true) + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1) + } + + /// Scenario: a vanished (or undecodable) card JSON refuses BEFORE the + /// Learning is written — a retry can never accumulate orphan files. + @Test func `a vanished card refuses before writing anything`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()]) + let cardsDir = piece.appendingPathComponent("cards", isDirectory: true) + let json = try #require(try FileManager.default.contentsOfDirectory(atPath: cardsDir.path).first) + try FileManager.default.removeItem(at: cardsDir.appendingPathComponent(json)) + + #expect(throws: FixCardStore.CardError(message: "card not found: \(written[0].card.id)")) { + try FixCardStore.promote(pieceURL: piece, card: written[0].card) + } + #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path)) + } + + /// Scenario: a pre-planted symlinked learnings component must not turn + /// promote into a file-plant primitive (security audit) — refuse + /// before any write, nothing lands in the link's target. + @Test func `a symlinked learnings dir refuses to promote`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()]) + let target = home.appendingPathComponent("elsewhere", isDirectory: true) + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: home.appendingPathComponent("learnings", isDirectory: true), + withIntermediateDirectories: true, + ) + try FileManager.default.createSymbolicLink( + at: home.appendingPathComponent("learnings/posts"), + withDestinationURL: target, + ) + + let planted = home.appendingPathComponent("learnings/posts").path + #expect(throws: FixCardStore.CardError(message: "learnings path is a symlink: \(planted)")) { + try FixCardStore.promote(pieceURL: piece, card: written[0].card) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty) + } +} diff --git a/MuseionTests/MCPToolsTests.swift b/MuseionTests/MCPToolsTests.swift index b663cc5..c19c38d 100644 --- a/MuseionTests/MCPToolsTests.swift +++ b/MuseionTests/MCPToolsTests.swift @@ -12,8 +12,9 @@ import Foundation @testable import Museion import Testing -/// Throwaway Home in a temp dir (PostStoreTests convention). -private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL { +/// Throwaway Home in a temp dir (PostStoreTests convention). Internal — +/// MCPToolsPromoteTests shares it (cross-file convention). +func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL { let home = FileManager.default.temporaryDirectory .appendingPathComponent("mcp-tools-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) @@ -22,9 +23,10 @@ private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL { } /// One piece under projects/posts/<id>/post.md; returns the piece folder. -/// `type: nil` writes no frontmatter block at all. +/// `type: nil` writes no frontmatter block at all. Internal — +/// MCPToolsPromoteTests shares it (cross-file convention). @discardableResult -private func writePiece( +func writePiece( _ home: URL, id: String = "test-piece", type: String? = "post", @@ -39,7 +41,8 @@ private func writePiece( /// One wire-shaped card with test-friendly defaults. Internal — shared /// with PostsModelTests and FixCardApplyTests (review: a hand-copy drifted -/// here). #25: `fix`/`lane` feed the apply pins. +/// here). #25: `fix`/`lane` feed the apply pins; #26: `provenance` feeds +/// the promote pins. func card( pattern: String = "Hedging", problem: String = "The hedge weakens the claim.", @@ -48,6 +51,7 @@ func card( quote: String = "repeated anchor line", occurrence: Int = 1, lane: FixCardStore.StoredFixCard.Lane = .mechanical, + provenance: FixCardStore.StoredFixCard.Provenance? = nil, ) -> FixCardStore.Input { FixCardStore.Input( pattern: pattern, @@ -57,37 +61,7 @@ func card( anchor: .init(quote: quote, occurrence: occurrence), lane: lane, emitter: .lint, - provenance: nil, - ) -} - -/// 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: submittedAt, - rank: rank, - pattern: pattern, - problem: "p", - diagnosticQuestion: "", - fix: fix, - anchor: .init(quote: quote, occurrence: occurrence), - lane: lane, - emitter: .lint, - provenance: nil, - status: .open, - anchorStatus: .valid, + provenance: provenance, ) } diff --git a/PRD.md b/PRD.md index 4bc38fd..ffa1505 100644 --- a/PRD.md +++ b/PRD.md @@ -76,6 +76,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of - **Reader-simulation session flavor** — three simulated readers: what landed, where they stopped. Fills the reader-psych shelf with a prompt pack. - **Demonstrator-model audition (optional)** — Claude Fable 5 (human-judged #1 on the Hemingway bench; GLM-5.3's nearest register neighbor, stronger emotional depth) and Muse Glimmer 30B (Apache-2.0 open weights, one 24 GB GPU; credible community prose reputation, unlisted on EQ-Bench — audition-tier) vs the `zai/glm-5.3` pin: same draft, same skills, one session each; actors, not authors — the winner executes the doctrine best. Glimmer doubles as a local-engine candidate for the ADR-0007 swap seam (fully-on-device critique story). - **Dedicated lint repair model** (GPT-5.6-line) if the lint ever grows a repair loop — curiosity only. +- **LLM-authored Learning text** (considered at #26, 2026-10-21): generate the promoted Learning via an engine call instead of the deterministic transform. Parked — the card fields are already persona-authored generalizations (promote is format conversion, not thinking), the ask's preview must equal what lands, promote stays a local atomic op (works engine-down), and deterministic output is what makes learnings git-diffable. Revisit only if card fields prove to generalize badly in practice — the first fix is pass-persona doctrine, not a generation hop. The interesting variant — one living Learning per pattern, synthesized across promotions — fights one-confirm-one-entry; separate idea. - **Writer-issued placeholders** — inline flag + note, panel, research-pass resolver (Neo learnings, 2026-10-08): a Neo-style placeholder is a writer-issued anchor — the same quote-anchored span machinery Fix Cards use (#25/M2), issued by the writer instead of the mentor; the M5 research pass is its natural resolver. Revisit when anchors (#25) and research (M5) both exist; until then markdown itself is the placeholder (`[[TODO:]]`). ## User stories @@ -105,7 +106,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of ### Persistent critique memory — the load-bearing feature (M3) -- **S4.1 — Promote by confirmation.** As the writer, only my explicit confirmation promotes a fix card into persistent critique memory — never a raw repetition counter. *AC:* one confirm = one entry, carrying the fix-card fields plus provenance. +- **S4.1 — Promote by confirmation.** As the writer, only my explicit confirmation promotes a fix card into persistent critique memory — never a raw repetition counter. *AC:* one confirm = one entry, carrying the card's teaching fields (pattern, problem, diagnostic question, demonstration example) plus provenance — instance-bound evidence (anchor, mechanical replacement) stays on the card (revised 2026-10-21: the Learning teaches the symptom/fix, never re-quotes the originating text). - **S4.2 — Dismiss with decay.** As the writer, dismissed patterns fade instead of haunting me. *AC:* a dismissed learning resurfaces after 10 subsequent passes of that content type (output-clock, not calendar); each re-dismiss doubles the interval (10→20→40…); per-learning `resurface_after` frontmatter overrides the base. - **S4.3 — The mentor remembers.** As the writer, every future pass consults my critique memory, so recurring weaknesses surface as fix cards. *AC:* stored as plain markdown in the Home's `learnings/posts/` (ADR-0005) — one file per learning (`YYYYMMDD-<pattern-slug>.md`), human-readable, diffable and exportable. - **S4.4 — Mine alone.** As the writer, my memory is per-writer and portable. *AC:* lives in the Museion Home as plain files; fresh start in v1 — no legacy import (verified: the hand-maintained MEMORY.md carries agent-tooling notes, no writing learnings). diff --git a/docs/devlog/20261021-issue26-promote-consult-learnings_log.md b/docs/devlog/20261021-issue26-promote-consult-learnings_log.md new file mode 100644 index 0000000..996e377 --- /dev/null +++ b/docs/devlog/20261021-issue26-promote-consult-learnings_log.md @@ -0,0 +1,69 @@ +# M3: Promote & consult Learnings (S4.1, S4.3, S4.4) + +> **Date:** 2026-10-21 +> **Type:** issue +> **Reference:** AlexKucera/Museion#26 (blocked-by #25 verified closed before start) + +## Goal + +Ship #26: only the writer's explicit confirmation promotes a Fix Card into a Learning — one confirm, one entry, never a repetition counter — carrying the card's teaching fields plus promotion provenance into plain markdown files under the Home's `learnings/<type>s/`, consulted by every pass via `query_learnings`, plus the Learnings pane replacing its M1 placeholder. Dismiss/decay stays #27. + +## What Was Done + +- `FixCardStore.promote(pieceURL:card:now:)` — rejects a symlinked learnings component before any write, consults the ON-DISK card as the truth (not-found / already-stamped throw before anything is written), writes ONE Learning `<learningsDir>/<yyyyMMdd>-<slug(pattern)>.md` (collision -2/-3), then restamps the card JSON in place with `promotedAt` (close()'s rewrite pattern; learning-first ordering deliberate — the inverse would lock re-promotion after a crash). +- `StoredFixCard.promotedAt: Date?` (snake_case `promoted_at`; pre-#26 cards decode nil); `learningsDir(home:type:)` public seam + private `homeAndType` shared with `learnings(piecePath:)`. +- `learningMarkdown` — the pinned file shape: flat single-line frontmatter (pattern/problem/diagnostic_question?/demonstration-fix?/lane/emitter/piece?/pass?/engine?/promoted/from_card; newlines flatten) + readable body (`# pattern`, Problem/Diagnostic lines, `**Example.**` for demonstrations, italic provenance footer). +- `PostsModel.promoteCard` → `FixCardPromoteOutcome` (.promoted | .refused) — guards already-promoted + open session, failure → `lastError`, success → `refreshCards`; touches no text. +- `FixCardsWindow.CardRow` — Promote button (open cards between primary action and Skip; closed unpromoted cards alone; `· promoted` in meta, never re-offers) + per-row sheet. +- `PromoteAskSheet.swift` (new) — the design contract's `#promoteDialog`: "Promote to Learnings?", type-pluralized body line, preview showing exactly what lands (pattern, problem, diagnostic, demonstration example, provenance), Cancel/Promote, refusal inline orange. +- `LearningsPaneView.swift` (new) — list-only pane (Archive posture): `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased section heads) → entries newest-first (YYYYMMDD desc, undated last), lenient `Post.frontmatter` reads, scan detached off MainActor with a `Task.isCancelled` gate; WorkspaceView placeholder swapped. +- Tests: `MCPToolsPromoteTests.swift` (9 store pins incl. the audit pins), `LearningsPaneTests.swift` (4 pins incl. symlinked type-dir fixture), 2 model pins in `FixCardApplyTests`. +- Docs: Museion/AGENTS.md ×4 bullets, MuseionTests/AGENTS.md, CHANGELOG (Unreleased), CONTEXT.md Learning definition, PRD S4.1 AC + v2 parking-lot entries. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Learning carries TEACHING fields only — anchor + mechanical fix stay on the card JSON | Anchor is apply-machinery (a Learning informs, never gets applied); a mechanical fix is a literal replacement string from one instance that teaches nothing; demonstration fix IS the example and travels. User-approved mid-session revision (CONTEXT.md/PRD updated). | +| Deterministic generation, no LLM call | Card fields are already persona-authored generalizations (promote is format conversion, not thinking); the ask's preview must equal what lands; promote stays local/atomic (works engine-down); deterministic output is what keeps learnings git-diffable. Parked in PRD v2 lot with revisit trigger: if card fields generalize badly, fix pass-persona doctrine first. | +| On-disk card as truth in promote (finish-audit Medium) | A stale palette copy (async refresh gap) or vanished card JSON could double-write Learnings; the disk check before any write is the only real one-confirm-one-entry guarantee. | +| Symlink guard on the learnings path (finish-audit security LOW) | Reviewer empirically verified a pre-planted `learnings/posts` symlink turned promote into a file-plant primitive; one guard at the single write site, read side already skipped links. | +| Promote button outlives the card (offered on closed cards) | The design contract's promote-resolved buttons; the Learning is the durable artifact. | +| Button order Promote-left/Cancel-right | House `ApplyAskSheet` precedent (repo overrides the HTML order). | +| Pane without FSEvents watcher | Re-scans on pane re-entry; ponytail ceiling, commented. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Subagent hand-off patches mangled ("No valid patches in input") | The terminal backend collapses `git diff` output — even through redirects — into a stat+context summary | Byte-copied the changed files from the worktrees instead; later diffs taken with `git diff --output=<file>` + read_file | +| Ponytail reviewer claimed `??`/`&&` precedence made `isPlainDirectory`'s symlink check dead | Misread of NilCoalescing vs LogicalConjunction precedence (2 of 3 reviewers + a scratch probe confirmed it parses correctly) | No change; probe settled it; the unpinned behavior got a symlink fixture instead | +| Audit-flip first attempt duplicated the pane's scan | Patch added the guard AFTER an assignment instead of between await and assign | Rewrote the task body to `let scanned = await …; guard !Task.isCancelled; groups = scanned` | +| Full-suite grep counted "failed" hits | Test NAMES containing "failed" match `grep "Test case .* failed"` | Parsed with python regex over the log instead | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/FixCardStore.swift` | promote + promotedAt + learningsDir + learningMarkdown (teaching shape) | +| `Museion/PostsModel.swift` | promoteCard + FixCardPromoteOutcome | +| `Museion/FixCardsWindow.swift` | Promote button + promoted meta in CardRow | +| `Museion/PromoteAskSheet.swift` | new — the blocking promote ask | +| `Museion/LearningsPaneView.swift` | new — LearningsIndex + list-only pane | +| `Museion/WorkspaceView.swift` | placeholder → LearningsPaneView | +| `MuseionTests/MCPToolsPromoteTests.swift` | new — 9 store pins | +| `MuseionTests/LearningsPaneTests.swift` | new — 4 pane pins | +| `MuseionTests/FixCardApplyTests.swift` | +2 model pins | +| `MuseionTests/MCPToolsTests.swift` | helpers widened internal, card(provenance:) | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass | +| `CHANGELOG.md`, `CONTEXT.md`, `PRD.md` | entry, Learning definition, S4.1 AC + parking lot | + +## Open Items & Next Steps + +- [ ] #27 Dismiss & Decay (S4.2) — now unblocked; decay keys land on the #26 frontmatter +- [ ] FixCardStore at 532 lines / 335-line type body — warning-level lint only (error gates 1000/350); split when the next slice forces it +- [ ] Dogfood: run a real pass, promote a card, verify the engine's critique of the NEXT piece reflects the learning + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index f581082..26f7cb2 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa <!-- write-log: full-index --> | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-21 | issue | [20261021-issue26-promote-consult-learnings_log.md](20261021-issue26-promote-consult-learnings_log.md) | #26 promote/consult Learnings: teaching-shape files, on-disk-truth promote, symlink guard, Learnings pane — 329 tests green | | 2026-10-20 | issue | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | #124 cancel-acknowledging hangOnPrompt fake, Cancel-rail pin (RED→GREEN), defer-at-rig-creation teardown ×27 rigs — 316 tests green | | 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 |