feat(mentor): promote & consult Learnings (#26)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
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 <home>/learnings/<type>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
This commit is contained in:
1 parent
154bb8a114
commit
0e5c28ad95
18 files changed
+1133
-82
No files matched your search
+4
-4
@@ -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 `<project>` + 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 `<home>/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 `<project>` + 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/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws).
|
||||
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing line "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
|
||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
|
||||
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
@@ -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.
|
||||
|
||||
|
||||
+170
-20
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user