feat(mentor): dismiss & decay Learnings (#27)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Dismissed patterns fade instead of haunting. Dismissing a Learning stamps decay state into its own frontmatter (dismissed date, dismiss_count, dismissed_at_pass — every other line preserved verbatim, hand-editable, git-diffable) and hides it from every pass: query_learnings serves only visible learnings. Resurfacing is an output clock, not a calendar — a per-type counter under <home>/learnings/pass-counts.json, ticked by every completed pass (cancels and refusals never advance, so never tick), returns the Learning after 10 subsequent passes of its content type; each re-dismiss doubles the interval (10→20→40…), and a per-Learning resurface_after frontmatter key overrides the base. Hand-edited decay state reads leniently: garbage means visible, absurd values clamp, a hand-edit can never trap the pane or the rail. The Learnings pane rows dismiss (no confirm — low-stakes, self-healing), dim while hidden with a resurfaces-in-N countdown, and foreign unclocked type dirs neither offer Dismiss nor show a verdict — their clock can never advance. Two review waves (two-axis implement review + three-reviewer finish-audit: security clean) produced five fixes, each pinned or noted in the session log. Closes #27
This commit is contained in:
1 parent
0e5c28ad95
commit
78c8844184
15 files changed
+911
-66
No files matched your search
+4
-3
@@ -21,10 +21,10 @@ 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 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).
|
||||
- `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. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). 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).
|
||||
- `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). **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacLine truncated
|
||||
- `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
|
||||
- `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.
|
||||
@@ -64,7 +64,8 @@ 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/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).
|
||||
- `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). **#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). **#27 (S4.2):** `learnings(piecePath:)` filters DECAYED learnings — the consult rail (query_learnings) serves only visible ones: `LearningDecay.passesHidden(Post.frontmatter(of:), currentPass:) == nil`, the clock from `LearningDecay.passCounts(home:)` under `LearningDecay.passKey(type)`; `formatted(_:_:)` is internal (LearningDecay's dismiss date stamp shares it).
|
||||
- `LearningDecay.swift` — #27 (S4.2; own file — FixCardStore sits at its type-body ceiling): Dismiss & Decay, nonisolated. The pass clock is `<home>/learnings/pass-counts.json` (flat {typeDir: completed-pass count}; keys = the LITERAL plural dir names via `passKey(_:)` — one place so writer and readers can't drift): `passCounts(home:)` reads leniently (missing/corrupt → empty, non-integers dropped; values clamp into [0, 1e9] — a hostile hand-edit can't trap the arithmetic), `recordPass(home:type:)` ticks atomically (.sortedKeys; a symlinked `learnings/` refuses — promote's posture, so the per-pass tick can never write outside the Home's tree). `isClocked(_:)` names the dirs that carry a clock — only the content-type plurals (`recordPass` ticks exactly those); a foreign dir (a hand-made `essays/`) is pane-visible but its clock reads 0 forever, so a dismiss there would hide permanently — the store refuses and the pane offers no button. `passesHidden(_:currentPass:)` is the ONE pure visibility verdict the consult rail, the pane rows, and the dismiss stamp ride: nil = visible, positive = passes until resurface; interval = (`resurface_after` ?? `baseInterval` 10) doubled per re-dismiss (doubling capped at 30 — a hand-edited `dismiss_count` 9999 can't overflow Int), garbage `dismiss_count` defaults 1 when an anchor exists, a missing/garbage anchor means VISIBLE (a malformed dismiss never permanently hides a Learning). `dismiss(home:typeDir:file:)` stamps decay state IN the Learning's own frontmatter — `dismissed` (yyyy-MM-dd), `dismiss_count` (+1, clamped first), `dismissed_at_pass` (the type's current clock) — through `stampingFrontmatter` (mergedFrontmatter's line-walk generalized to ordered pairs, ponytail-marked — extraction would grow PostStore at its ceiling; no block → fresh block prepended; every other line verbatim — leading hand-edit lines above the block included, #27-review-pinned), behind write-path guards (traversal/hidden names refuse; symlinked learnings components OR learning file refuse — a planted file link must not become a copy-into-the-consult-tree primitive; a foreign unclocked type dir refuses; a currently-HIDDEN Learning refuses — re-dismiss means AFTER the resurface, CONTEXT.md, which also makes a double-click's second stamp harmless; promote's posture throughout).
|
||||
- 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)
|
||||
|
||||
+12
-10
@@ -282,8 +282,9 @@ nonisolated enum FixCardStore {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// statics (repo convention). stamp(), promote's day stamps, and
|
||||
/// LearningDecay's dismiss stamp (#27) share it.
|
||||
static func formatted(_ date: Date, _ format: String) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = format
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
@@ -393,22 +394,23 @@ nonisolated enum FixCardStore {
|
||||
/// `<home>/learnings/<type>s/` (LITERAL plural — "posts", "outlines"),
|
||||
/// 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.
|
||||
/// #27 (S4.2): dismissed learnings stop feeding passes until their
|
||||
/// decay interval elapses — LearningDecay.passesHidden filters them
|
||||
/// out here. Missing dir → empty (fresh start is the correct v1
|
||||
/// answer); a missing piece still throws.
|
||||
static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] {
|
||||
let postURL = try resolvePostURL(piecePath)
|
||||
let text = try String(contentsOf: postURL, encoding: .utf8)
|
||||
let (home, type) = homeAndType(postURL: postURL, text: text)
|
||||
let dir = learningsDir(home: home, type: type)
|
||||
let currentPass = LearningDecay.passCounts(home: home)[LearningDecay.passKey(type)] ?? 0
|
||||
let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [])
|
||||
.filter { $0.hasSuffix(".md") }
|
||||
.sorted()
|
||||
return files.compactMap { name in
|
||||
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8),
|
||||
LearningDecay.passesHidden(Post.frontmatter(of: markdown), currentPass: currentPass) == nil
|
||||
else { return nil }
|
||||
return (file: name, markdown: markdown)
|
||||
}
|
||||
}
|
||||
@@ -417,7 +419,7 @@ nonisolated enum FixCardStore {
|
||||
/// 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)
|
||||
home.appendingPathComponent("learnings/\(LearningDecay.passKey(type))", isDirectory: true)
|
||||
}
|
||||
|
||||
/// post.md URL + its text → (Home, content type) — the ADR-0012 layout
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//
|
||||
// LearningDecay.swift
|
||||
// Museion
|
||||
//
|
||||
// #27 (M3, S4.2): Dismiss & Decay — a dismissed Learning stops feeding
|
||||
// passes and resurfaces after N completed passes of its content type
|
||||
// (an output clock, not a calendar). Decay state lives in the
|
||||
// Learning's own frontmatter (survives restarts, hand-editable); the
|
||||
// pass clock is one JSON file per Home. Own file — FixCardStore is at
|
||||
// its type-body ceiling.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// #27: Dismiss & Decay. nonisolated (FixCardStore posture) — the
|
||||
/// headless MCP consult rail and off-main pane scans call this.
|
||||
nonisolated enum LearningDecay {
|
||||
/// Base resurface interval: completed passes of the content type.
|
||||
/// Each re-dismiss doubles it; `resurface_after` overrides it
|
||||
/// per-Learning.
|
||||
private static let baseInterval = 10
|
||||
|
||||
/// Hand-editable ints clamp into this band at their parse sites so no
|
||||
/// decay arithmetic can trap (Swift `*`/`+`/`-` crash the process on
|
||||
/// overflow — a hostile or fat-fingered frontmatter value must not take
|
||||
/// down the pane scan or the MCP rail); a billion passes is beyond any
|
||||
/// real Home.
|
||||
private static let valueCeiling = 1_000_000_000
|
||||
|
||||
/// The pass-counts key for a content type — the LITERAL plural dir name
|
||||
/// ("posts"/"outlines"), `learningsDir`'s convention. One place so the
|
||||
/// clock's writer and readers can never drift apart.
|
||||
static func passKey(_ type: Post.ContentType) -> String {
|
||||
"\(type.rawValue)s"
|
||||
}
|
||||
|
||||
/// Whether a learnings/ dir name carries a pass clock — only the
|
||||
/// content-type plurals do (`recordPass` ticks exactly these). A foreign
|
||||
/// dir (a hand-made `essays/`) is pane-visible but never decay-clocked:
|
||||
/// its clock reads 0 forever, so a dismiss there would hide the Learning
|
||||
/// permanently — the store refuses (#27 audit).
|
||||
static func isClocked(_ typeDir: String) -> Bool {
|
||||
Post.ContentType.allCases.contains { passKey($0) == typeDir }
|
||||
}
|
||||
|
||||
// MARK: - Pass clock
|
||||
|
||||
/// `<home>/learnings/pass-counts.json` — a flat {typeDir: count} of
|
||||
/// completed passes (keys "posts"/"outlines"). Missing file/dir,
|
||||
/// undecodable JSON, or non-integer values read as absent: a corrupt
|
||||
/// clock reads as 0 and a lagging clock only delays resurfacing (safe
|
||||
/// direction). Never throws.
|
||||
static func passCounts(home: URL) -> [String: Int] {
|
||||
let url = home.appendingPathComponent("learnings/pass-counts.json")
|
||||
guard let data = try? Data(contentsOf: url),
|
||||
let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
||||
else { return [:] }
|
||||
var counts: [String: Int] = [:]
|
||||
for (key, value) in object {
|
||||
guard let value = value as? Int else { continue }
|
||||
// Hand-editable: clamp into the safe band (negative → 0).
|
||||
counts[key] = min(max(value, 0), valueCeiling)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/// Increment `"<type>s"` by 1, creating learnings/ if missing. The
|
||||
/// decay clock counts COMPLETED passes per content type (#27) —
|
||||
/// advancePassState ticks it after its stamped write.
|
||||
static func recordPass(home: URL, type: Post.ContentType) throws {
|
||||
let learnings = home.appendingPathComponent("learnings", isDirectory: true)
|
||||
// Same symlink posture as dismiss/promote: a pre-planted link must
|
||||
// not turn the per-pass tick into a write outside the Home's tree
|
||||
// (#27 audit).
|
||||
let linkValues = try? learnings.resourceValues(forKeys: [.isSymbolicLinkKey])
|
||||
if linkValues?.isSymbolicLink == true {
|
||||
throw FixCardStore.CardError(message: "learnings path is a symlink: \(learnings.path)")
|
||||
}
|
||||
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
|
||||
var counts = passCounts(home: home)
|
||||
let key = passKey(type)
|
||||
counts[key] = (counts[key] ?? 0) + 1
|
||||
let data = try JSONSerialization.data(withJSONObject: counts, options: [.sortedKeys])
|
||||
try data.write(to: learnings.appendingPathComponent("pass-counts.json"), options: .atomic)
|
||||
}
|
||||
|
||||
// MARK: - Visibility (pure)
|
||||
|
||||
/// nil = visible now; positive = passes still hidden. Pure — the
|
||||
/// pane's rows, the consult rail, and the dismiss stamp all agree
|
||||
/// through this one function. Lenient reads via `Int(_:)`: a garbage
|
||||
/// `dismiss_count` defaults to 1 when an anchor exists (else 0), a
|
||||
/// missing/garbage anchor means visible, and the doubling caps at 30
|
||||
/// iterations so a hand-edited `dismiss_count` can't overflow Int.
|
||||
static func passesHidden(_ frontmatter: [String: String], currentPass: Int) -> Int? {
|
||||
guard let parsedAnchor = frontmatter["dismissed_at_pass"].flatMap({ Int($0) }) else { return nil }
|
||||
let dismissedAt = min(max(parsedAnchor, 0), valueCeiling)
|
||||
let dismissCount = dismissCount(in: frontmatter)
|
||||
guard dismissCount > 0 else { return nil }
|
||||
let override = frontmatter["resurface_after"]
|
||||
.flatMap { Int($0) }
|
||||
.map { min(max($0, 0), valueCeiling) }
|
||||
var interval = override ?? baseInterval
|
||||
for _ in 0 ..< min(dismissCount - 1, 30) {
|
||||
interval *= 2
|
||||
}
|
||||
let elapsed = currentPass - dismissedAt
|
||||
return elapsed >= interval ? nil : interval - elapsed
|
||||
}
|
||||
|
||||
/// The parsed `dismiss_count` — garbage defaults to 1 when an anchor
|
||||
/// exists (a half-done hand-edit still dismisses once), else 0. Negative
|
||||
/// hand-edits clamp at parse (a `-5` must not make Dismiss a silent
|
||||
/// no-op — #27 audit). The ONE parse both the visibility math and the
|
||||
/// dismiss stamp ride; they must agree.
|
||||
private static func dismissCount(in frontmatter: [String: String]) -> Int {
|
||||
if let count = frontmatter["dismiss_count"].flatMap({ Int($0) }) {
|
||||
return max(count, 0)
|
||||
}
|
||||
return frontmatter["dismissed_at_pass"] != nil ? 1 : 0
|
||||
}
|
||||
|
||||
// MARK: - Dismiss
|
||||
|
||||
/// #27: stamp decay state IN the Learning's own file — `dismissed`
|
||||
/// (date), `dismiss_count` (+1), `dismissed_at_pass` (the type's
|
||||
/// current clock) — every other line preserved verbatim. Write-path
|
||||
/// trust boundary (promote's guard posture): hostile names refuse, a
|
||||
/// foreign (unclocked) type dir refuses, a symlinked learnings
|
||||
/// component OR learning file refuses, a missing/unreadable file
|
||||
/// throws, and a currently-hidden Learning refuses (re-dismiss
|
||||
/// lands after the resurface so doubling starts from a fresh
|
||||
/// anchor; this also makes a double-click's second stamp
|
||||
/// harmless) — never a write outside the learnings tree.
|
||||
static func dismiss(home: URL, typeDir: String, file: String, now: Date = Date()) throws {
|
||||
for name in [typeDir, file] {
|
||||
guard !name.isEmpty, !name.contains("/"), !name.contains(".."), !name.hasPrefix(".") else {
|
||||
throw FixCardStore.CardError(message: "invalid learning path: \(typeDir)/\(file)")
|
||||
}
|
||||
}
|
||||
// Decay is defined per pass-clocked content type — a foreign dir's
|
||||
// clock reads 0 forever, so a dismiss there would hide permanently
|
||||
// (#27 audit).
|
||||
guard isClocked(typeDir) else {
|
||||
throw FixCardStore.CardError(message: "not a pass-clocked content type: \(typeDir)")
|
||||
}
|
||||
let learnings = home.appendingPathComponent("learnings", isDirectory: true)
|
||||
let dir = learnings.appendingPathComponent(typeDir, isDirectory: true)
|
||||
let url = dir.appendingPathComponent(file)
|
||||
// The FILE rides the same symlink check as the dirs: reading through
|
||||
// a planted link and writing the stamped copy back would materialize
|
||||
// a foreign file's content into the engine-served tree (#27 audit).
|
||||
for component in [learnings, dir, url] {
|
||||
let values = try? component.resourceValues(forKeys: [.isSymbolicLinkKey])
|
||||
if values?.isSymbolicLink == true {
|
||||
throw FixCardStore.CardError(message: "learnings path is a symlink: \(component.path)")
|
||||
}
|
||||
}
|
||||
guard let text = try? String(contentsOf: url, encoding: .utf8) else {
|
||||
throw FixCardStore.CardError(message: "learning not found: \(file)")
|
||||
}
|
||||
|
||||
let frontmatter = Post.frontmatter(of: text)
|
||||
let clock = passCounts(home: home)[typeDir] ?? 0
|
||||
if let remaining = passesHidden(frontmatter, currentPass: clock) {
|
||||
throw FixCardStore.CardError(message: "already dismissed — resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes")")
|
||||
}
|
||||
// Clamped before +1 — an absurd hand-edited dismiss_count must not
|
||||
// trap the stamp.
|
||||
let count = min(dismissCount(in: frontmatter), valueCeiling)
|
||||
let stamped = stampingFrontmatter(
|
||||
of: text,
|
||||
with: [
|
||||
("dismissed", FixCardStore.formatted(now, "yyyy-MM-dd")),
|
||||
("dismiss_count", "\(count + 1)"),
|
||||
("dismissed_at_pass", "\(clock)"),
|
||||
],
|
||||
)
|
||||
try stamped.write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
/// The surgical frontmatter rewrite (mergedFrontmatter's line-walk,
|
||||
/// generalized to ordered pairs): set-overwrite the keys in place,
|
||||
/// insert absent ones before the closing `---`, preserve every other
|
||||
/// line verbatim (leading hand-edit lines above the opening `---`
|
||||
/// included), keep the block's trailing newline. No frontmatter
|
||||
/// block at all → prepend a fresh one.
|
||||
// ponytail: PostStore.mergedFrontmatter's line-walk duplicated and
|
||||
// generalized — extracting the shared walk would grow PostStore at its
|
||||
// type-body ceiling; do it when a third caller appears.
|
||||
private static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String {
|
||||
let (block, body) = PostStore.splitFrontmatter(text)
|
||||
guard !block.isEmpty else {
|
||||
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
|
||||
}
|
||||
// Lines ABOVE the opening `---` (a hand-edit blank line —
|
||||
// Post.frontmatter tolerates one) fall in neither block nor
|
||||
// body; keep them verbatim so the rewrite loses nothing (#27 review).
|
||||
let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? ""
|
||||
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
// Drop the empty tail the block's final newline produced — re-added below.
|
||||
if let last = lines.last, last.isEmpty {
|
||||
lines.removeLast()
|
||||
}
|
||||
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
|
||||
var seen = Set<String>()
|
||||
for (index, line) in lines.enumerated() {
|
||||
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, trimmed != "---" else { continue }
|
||||
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
|
||||
if let value = oursByKey[key] {
|
||||
lines[index] = "\(key): \(value)"
|
||||
seen.insert(key)
|
||||
}
|
||||
}
|
||||
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
|
||||
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
|
||||
lines.insert(contentsOf: insertions, at: close)
|
||||
}
|
||||
return prefix + lines.joined(separator: "\n") + "\n" + body
|
||||
}
|
||||
}
|
||||
+120
-31
@@ -17,20 +17,27 @@ import SwiftUI
|
||||
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.
|
||||
/// `promoted` omit when the frontmatter key is absent. #27:
|
||||
/// `resurfacesIn` is the decay verdict — nil = visible now,
|
||||
/// positive = passes until resurface. `currentPass: nil` = an
|
||||
/// unclocked (foreign) type dir: never a verdict, so the pane
|
||||
/// cannot show a countdown that could never advance (#27 audit —
|
||||
/// the store refuses to dismiss there for the same reason).
|
||||
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?
|
||||
let resurfacesIn: Int?
|
||||
|
||||
init(file: String, text: String) {
|
||||
init(file: String, text: String, currentPass: Int? = nil) {
|
||||
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 }
|
||||
resurfacesIn = currentPass.flatMap { LearningDecay.passesHidden(frontmatter, currentPass: $0) }
|
||||
}
|
||||
|
||||
/// "20261021-fold-the-ladder.md" → "fold-the-ladder".
|
||||
@@ -60,6 +67,7 @@ nonisolated enum LearningsIndex {
|
||||
/// 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 counts = LearningDecay.passCounts(home: home) // #27: the pass clock feeds the decay verdict
|
||||
let root = home.appendingPathComponent("learnings", isDirectory: true)
|
||||
guard let typeDirs = try? FileManager.default.contentsOfDirectory(
|
||||
at: root,
|
||||
@@ -70,6 +78,11 @@ nonisolated enum LearningsIndex {
|
||||
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix(".") else { continue }
|
||||
guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
|
||||
else { continue }
|
||||
// #27: the pass clock feeds the decay verdict — clocked dirs
|
||||
// carry their count, foreign dirs nil (no verdict; Entry's audit).
|
||||
let currentPass = LearningDecay.isClocked(dir.lastPathComponent)
|
||||
? counts[dir.lastPathComponent] ?? 0
|
||||
: nil
|
||||
let entries = files
|
||||
.filter {
|
||||
!$0.lastPathComponent.hasPrefix(".")
|
||||
@@ -81,7 +94,7 @@ nonisolated enum LearningsIndex {
|
||||
// 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) }
|
||||
.map { Entry(file: file.lastPathComponent, text: $0, currentPass: currentPass) }
|
||||
}
|
||||
guard !entries.isEmpty else { continue }
|
||||
groups.append(Group(
|
||||
@@ -103,22 +116,41 @@ nonisolated enum LearningsIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// #26: the Learnings pane — list-only, like the Archive pane.
|
||||
/// #26: the Learnings pane — list-only, like the Archive pane. #27:
|
||||
/// rows dismiss learnings (decay state stamps into the file's
|
||||
/// frontmatter; the pane re-scans after).
|
||||
struct LearningsPaneView: View {
|
||||
let home: URL
|
||||
@State private var groups: [LearningsIndex.Group] = []
|
||||
@State private var lastError: String?
|
||||
/// The home the LAST-enqueued scan is for — a dismiss Task captures the
|
||||
/// OLD home, and Task.isCancelled cannot reach it, so the assignment
|
||||
/// gates on this instead (#27 audit).
|
||||
@State private var scannedHome: URL?
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
// No New button — learnings arrive by promotion, not creation.
|
||||
PaneHeader(title: "Learnings")
|
||||
if let lastError {
|
||||
Text(lastError)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(.orange)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.bottom, 6)
|
||||
}
|
||||
if groups.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(groups, id: \.type) { group in
|
||||
LearningSection(group: group)
|
||||
LearningSection(group: group) { entry in
|
||||
dismiss(entry, in: group.type)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 12)
|
||||
@@ -135,14 +167,44 @@ struct LearningsPaneView: View {
|
||||
// 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
|
||||
scannedHome = home
|
||||
await rescan(home)
|
||||
}
|
||||
}
|
||||
|
||||
/// The detached scan + cancellation-gated assignment both entries into
|
||||
/// the list share (.task and post-dismiss refresh).
|
||||
private func rescan(_ target: URL) async {
|
||||
let scanned = await Task.detached(priority: .userInitiated) {
|
||||
LearningsIndex.scan(home: target)
|
||||
}.value
|
||||
// A home repoint cancels the awaiting .task, but a detached scan is
|
||||
// not cancellation-aware — and a dismiss Task holds the OLD home
|
||||
// unreached by that cancellation. Either way: a scan that is not for
|
||||
// the Home we last entered must not overwrite its groups.
|
||||
guard !Task.isCancelled, scannedHome == target else { return }
|
||||
groups = scanned
|
||||
lastError = nil // a successful rescan clears the strip
|
||||
}
|
||||
|
||||
/// #27: dismissal is low-stakes and self-healing (it decays back) —
|
||||
/// no confirm sheet. Failures land in the orange strip, never an alert.
|
||||
private func dismiss(_ entry: LearningsIndex.Entry, in typeDir: String) {
|
||||
Task {
|
||||
var failure: String?
|
||||
do {
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
try LearningDecay.dismiss(home: home, typeDir: typeDir, file: entry.id)
|
||||
}.value
|
||||
} catch {
|
||||
failure = error.localizedDescription
|
||||
}
|
||||
await rescan(home)
|
||||
// #27 review: a repointed Home must not inherit the old
|
||||
// Home's failure — the same gate rescan enforces for groups.
|
||||
if scannedHome == home {
|
||||
lastError = failure
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,14 +227,19 @@ struct LearningsPaneView: View {
|
||||
/// own body, not uneven outer-row content).
|
||||
private struct LearningSection: View {
|
||||
let group: LearningsIndex.Group
|
||||
let onDismiss: (LearningsIndex.Entry) -> Void
|
||||
|
||||
var body: some View {
|
||||
SectionHeadView(type: group.type, count: group.entries.count)
|
||||
.padding(.top, 16)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.bottom, 6)
|
||||
// Foreign (unclocked) dirs never offer Dismiss — their clock
|
||||
// reads 0 forever, a dismiss there would hide permanently (the
|
||||
// store refuses too; #27 audit).
|
||||
let dismissable = LearningDecay.isClocked(group.type)
|
||||
ForEach(group.entries) { entry in
|
||||
LearningRow(entry: entry)
|
||||
LearningRow(entry: entry, onDismiss: dismissable ? { onDismiss(entry) } : nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,36 +266,58 @@ private struct SectionHeadView: View {
|
||||
}
|
||||
|
||||
/// One Learning row: pattern as the title, problem as the secondary
|
||||
/// line, promoted date + file name in mono-11.
|
||||
/// line, promoted date + file name in mono-11. #27: visible rows offer
|
||||
/// a mono-11 Dismiss (the Archive pane's Unarchive voice); dismissed
|
||||
/// rows dim (closed-card voice) and count down their resurface.
|
||||
private struct LearningRow: View {
|
||||
let entry: LearningsIndex.Entry
|
||||
/// nil = foreign dir, never decay-clocked (#27 audit).
|
||||
let onDismiss: (() -> Void)?
|
||||
|
||||
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)
|
||||
HStack(alignment: .top) {
|
||||
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(2)
|
||||
.lineLimit(1)
|
||||
.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)
|
||||
if entry.resurfacesIn == nil, let onDismiss {
|
||||
Button("Dismiss", action: onDismiss)
|
||||
.buttonStyle(.plain)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.help("Hide this learning from passes until it resurfaces")
|
||||
.accessibilityLabel("Dismiss \(entry.pattern)")
|
||||
}
|
||||
}
|
||||
.padding(10)
|
||||
.opacity(entry.resurfacesIn == nil ? 1 : 0.45)
|
||||
}
|
||||
|
||||
private var metaLine: String {
|
||||
if let remaining = entry.resurfacesIn {
|
||||
return "dismissed · resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes") · " + metaTail
|
||||
}
|
||||
return metaTail
|
||||
}
|
||||
|
||||
private var metaTail: String {
|
||||
entry.promoted.map { "promoted · \($0) · \(entry.id)" } ?? entry.id
|
||||
}
|
||||
}
|
||||
@@ -173,7 +173,9 @@ nonisolated enum MCPServer {
|
||||
[
|
||||
[
|
||||
"name": "query_learnings",
|
||||
"description": "The piece's visible learnings — raw markdown per file, from <home>/learnings/<type>s/.",
|
||||
"description": "The piece's visible learnings — raw markdown per file, from <home>/learnings/<type>s/. "
|
||||
+ "Dismissed learnings are hidden until their decay interval (base 10 passes, doubling per "
|
||||
+ "re-dismiss; a per-Learning resurface_after frontmatter key overrides) elapses.",
|
||||
"inputSchema": [
|
||||
"type": "object",
|
||||
"properties": [
|
||||
|
||||
@@ -49,7 +49,7 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
case ai
|
||||
}
|
||||
|
||||
nonisolated enum ContentType: String {
|
||||
nonisolated enum ContentType: String, CaseIterable {
|
||||
case post
|
||||
case outline
|
||||
}
|
||||
|
||||
@@ -601,6 +601,10 @@ nonisolated extension PostStore {
|
||||
let advanced = higherState(piece.passState, kind.doneState)
|
||||
try stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
|
||||
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
// The decay clock counts completed passes per content type (#27).
|
||||
// try?: a failed clock bump must never fail a completed pass, and
|
||||
// a lagging clock only delays resurfacing (safe direction).
|
||||
try? LearningDecay.recordPass(home: home, type: piece.type)
|
||||
return advanced
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user