feat(mentor): dismiss & decay Learnings (#27)
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:
AlexKucera committed 2026-10-21 14:19:43 +02:00
1 parent 0e5c28ad95
commit 78c8844184
15 files changed
+911 -66

No files matched your search

+3 -3
View File
@@ -132,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (4003 symbols, 13313 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (4079 symbols, 13825 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -180,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](docs/devlog/20261021-issue27-dismiss-decay-learnings_log.md) |
| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) |
| 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) |
| 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) |
@@ -188,5 +189,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) |
| 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) |
| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) |
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |
| 2026-10-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) |<!-- write-log: window-end -->
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |<!-- write-log: window-end -->
+3 -1
View File
@@ -6,7 +6,9 @@ All notable changes to this project will be documented in this file. The format
### Added
- **mentor:** Promote & consult Learnings (PRD S4.1/S4.3/S4.4, ADR-0005) — only the writer's explicit confirmation promotes a Fix Card into a Learning: one confirm = one entry, never a repetition counter (the store refuses a second promote of a stamped card). The promote ask on every card row (open or closed — the Learning outlives the card) matches the design contract's dialog (pattern/problem/provenance preview, Cancel/Promote); confirming writes ONE plain markdown file `<home>/learnings/<type>s/YYYYMMDD-<pattern-slug>.md` carrying the card's teaching fields — pattern, problem, diagnostic question, the demonstration example (demonstration lanes only) — plus promotion provenance (flat frontmatter + readable body, `from_card` traceability, collision -2; the instance-bound anchor and mechanical replacement stay on the card — the Learning teaches the symptom/fix, never re-quotes the originating text) and stamps the card `promoted_at` (pre-#26 cards decode nil); every pass consults exactly these files through `query_learnings`, so recurring weaknesses surface as fix cards; the Learnings pane replaces its placeholder — list-only, grouped by content type, newest first, lenient to hand-edits; learnings are hand-editable, git-diffable, per-writer portable files in the Home (dismiss/decay is #27) (issue #26)
- **mentor:** Dismiss & decay for Learnings (PRD S4.2, G8) — dismissed patterns fade instead of haunting: a Dismiss button on every visible Learning in the Learnings pane stamps decay state into the Learning's own frontmatter (`dismissed`, `dismiss_count`, `dismissed_at_pass` — every other line preserved verbatim; hand-editable, git-diffable, survives restarts) and hides it from every pass: `query_learnings` serves only visible learnings. Resurfacing is an output clock, not a calendar — a dismissed Learning returns after 10 subsequent completed passes of its content type (a per-type counter under `<home>/learnings/pass-counts.json`, ticked by every completed pass, re-runs included), each re-dismiss doubles the interval (10 → 20 → 40…), and a per-Learning `resurface_after` frontmatter key overrides the base 10. Dismissed rows dim with a "resurfaces in N passes" countdown and no button until they return; hand-edited decay state reads leniently — garbage means visible, absurd numbers clamp, a hand-edit can never crash the pane or the rail (issue #27)
- **mentor:** Promote & consult Learnings (PRD S4.1/S4.3/S4.4, ADR-0005) — only the writer's explicit confirmation promotes a Fix Card into a Learning: one confirm = one entry, never a repetition counter (the store refuses a second promote of a stamped card). The promote ask on every card row (open or closed — the Learning outlives the card) matches the design contract's dialog (pattern/problem/provenance preview, Cancel/Promote); confirming writes ONE plain markdown file `<home>/learnings/<type>s/YYYYMMDD-<pattern-slug>.md` carrying the card's teaching fields — pattern, problem, diagnostic question, the demonstration example (demonstration lanes only) — plus promotion provenance (flat frontmatter + readable body, `from_card` traceability, collision -2; the instance-bound anchor and mechanical replacement stay on the card — the Learning teaches the symptom/fix, never re-quotes the originating text) and stamps the card `promoted_at` (pre-#26 cards decode nil); every pass consults exactly these files through `query_learnings`, so recurring weaknesses surface as fix cards; the Learnings pane replaces its placeholder — list-only, grouped by content type, newest first, lenient to hand-edits; learnings are hand-editable, git-diffable, per-writer portable files in the Home (dismiss/decay landed in #27) (issue #26)
- **mentor:** Fix Card apply/skip & trust UI (PRD S3.2/S3.3/S2.5) — Fix Cards are actionable: mechanical cards offer Apply behind a blocking ask-before sheet showing the exact edit (anchored quote → replacement, occurrence + context; an empty fix cuts the span) — the only path to a write, one card at a time, no apply-all; the edit lands through the editing session (pending edits flush first, the editor re-seeds, the card closes applied), Skip and Done close the card in place recording nothing, demonstration cards close Done/Skip only (ADR-0006); cards arrive ranked (store-stamped order, `#N` in the meta, open cards first) and capped at ten per submit — the app keeps the ranked head and the wire reply says what dropped; a stale anchor — the Post changed after the card was issued — alerts with no text selected or changed and flags the card (issue #25)
+4 -3
View File
@@ -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
View File
@@ -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
+222
View File
@@ -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
View File
@@ -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
}
}
+3 -1
View File
@@ -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": [
+1 -1
View File
@@ -49,7 +49,7 @@ nonisolated struct Post: Identifiable, Equatable {
case ai
}
nonisolated enum ContentType: String {
nonisolated enum ContentType: String, CaseIterable {
case post
case outline
}
+4
View File
@@ -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
}
+1 -1
View File
@@ -22,7 +22,7 @@ Owned by the root AGENTS.md contract.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation.
+400
View File
@@ -0,0 +1,400 @@
//
// LearningDecayTests.swift
// MuseionTests
//
// #27 (M3, S4.2): Dismiss & Decay — the pass clock, the dismiss stamp,
// and the resurface math. Temp homes via toolsHome/writePiece (the
// MCPToolsTests cross-file convention).
//
import Foundation
@testable import Museion
import Testing
/// A promote-shaped Learning (the #26 format contract) for hand-written
/// fixtures — frontmatter + a human-readable body. Seeding uses
/// LearningsPaneTests' `writeLearning`, internal (cross-file convention);
/// date-stamp expectations call the prod `FixCardStore.formatted` — the
/// format literals stay pinned (#27 audit: no test-side formatter copy).
private let learning = """
---
pattern: Hedging
problem: The hedge weakens the claim.
lane: mechanical
promoted: 2026-10-21
from_card: 6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0
---
# Hedging
**Problem.** The hedge weakens the claim.
*Promoted from test-piece · Pass 1 · 2026-10-21.*
"""
/// Reads the decay-stamped Learning back.
private func readLearning(_ home: URL, _ file: String) throws -> String {
try String(contentsOf: home.appendingPathComponent("learnings/posts/\(file)"), encoding: .utf8)
}
struct LearningDecayTests {
// MARK: Pass clock (#27 S4.2)
/// Scenario: the clock counts COMPLETED passes per content type —
/// every advancePassState ticks its type's counter (re-runs included),
/// types are independent, and a fresh Home reads empty.
@Test func `completed passes tick the per-type clock`() throws {
let home = try toolsHome()
_ = try writePiece(home)
_ = try writePiece(home, id: "outline-piece", type: "outline")
try PostStore.advancePassState(id: "test-piece", kind: .pass1, home: home)
try PostStore.advancePassState(id: "test-piece", kind: .pass2, home: home) // re-run counts
try PostStore.advancePassState(id: "outline-piece", kind: .pass1, home: home)
#expect(LearningDecay.passCounts(home: home) == ["posts": 2, "outlines": 1])
#expect(try LearningDecay.passCounts(home: toolsHome()) == [:])
}
// MARK: Dismiss (#27 S4.2)
/// Scenario: dismiss stamps decay state IN the Learning's own
/// frontmatter — dismissed date, dismiss_count, dismissed_at_pass
/// matching the clock — while every other frontmatter key and the
/// body stay byte-identical; the consult rail stops returning it.
@Test func `dismiss stamps decay frontmatter in place and hides the learning`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try PostStore.advancePassState(id: "test-piece", kind: .pass1, home: home) // clock: posts = 1
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible before
let now = Date(timeIntervalSince1970: 1_800_000_000)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file, now: now)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismissed"] == FixCardStore.formatted(now, "yyyy-MM-dd"))
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "1")
// Other keys untouched, still in place.
#expect(frontmatter["pattern"] == "Hedging")
#expect(frontmatter["problem"] == "The hedge weakens the claim.")
#expect(frontmatter["lane"] == "mechanical")
#expect(frontmatter["promoted"] == "2026-10-21")
#expect(frontmatter["from_card"] == "6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0")
// The body is byte-identical.
#expect(PostStore.splitFrontmatter(stampedText).body == PostStore.splitFrontmatter(learning).body)
// Hidden from the pass rail.
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
}
// MARK: Resurface (#27 S4.2)
/// Scenario: a dismissed learning (anchor P) stays hidden through
/// P+9 completed passes of its content type and resurfaces at P+10 —
/// an output clock, not a calendar.
@Test func `a dismissed learning resurfaces after ten passes of its type`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try writeLearning(home, "posts", "20261021-hedging.md", learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-hedging.md") // anchor 0
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden at P
for _ in 0 ..< 9 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden through P+9
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at P+10
}
/// Scenario: each re-dismiss doubles the interval — after the first
/// resurface a second dismiss stamps dismiss_count: 2 (anchor P) and
/// the learning stays hidden for 20 more passes, surfacing at P+20.
@Test func `re-dismissing doubles the interval`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file) // count 1, anchor 0
for _ in 0 ..< 10 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // resurfaced
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let frontmatter = try Post.frontmatter(of: readLearning(home, file))
#expect(frontmatter["dismiss_count"] == "2")
#expect(frontmatter["dismissed_at_pass"] == "10") // re-anchored at the current clock
for _ in 0 ..< 19 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden through 19
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at 20
}
/// Scenario: a per-Learning `resurface_after` frontmatter key
/// overrides the base 10 — hand-editable decay (#27 S4.2).
@Test func `resurface_after overrides the base interval`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try writeLearning(home, "posts", "20261021-hedging.md", """
---
pattern: Hedging
dismiss_count: 1
dismissed_at_pass: 0
resurface_after: 3
---
# Hedging
""")
for _ in 0 ..< 2 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden at 2
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at 3
}
// MARK: Lenient reads (#27 S4.2)
/// Scenario: hand-edited decay state never traps or surfaces wrong —
/// garbage ints default per contract, a missing anchor means visible,
/// an absurd dismiss_count stays hidden without overflow, and a
/// corrupt clock reads as 0 / partial.
@Test func `lenient reads never trap or surface wrong`() throws {
// Garbage dismiss_count with an anchor present → default 1 → 10-pass interval.
#expect(LearningDecay.passesHidden(
["dismiss_count": "ten", "dismissed_at_pass": "4"],
currentPass: 5,
) == 9)
// Missing anchor → visible, whatever the count says.
#expect(LearningDecay.passesHidden(["dismiss_count": "3"], currentPass: 100) == nil)
// No decay state at all → visible.
#expect(LearningDecay.passesHidden(["pattern": "Hedging"], currentPass: 0) == nil)
// Garbage anchor → visible.
#expect(LearningDecay.passesHidden(["dismiss_count": "1", "dismissed_at_pass": "ten"], currentPass: 5) == nil)
// Hand-edited dismiss_count 9999 — no Int overflow trap, stays hidden.
#expect(LearningDecay.passesHidden(
["dismiss_count": "9999", "dismissed_at_pass": "0"],
currentPass: 1000,
) != nil)
// Huge hand-edited ints clamp at parse — no arithmetic trap anywhere.
#expect(LearningDecay.passesHidden(
["resurface_after": String(Int.max), "dismiss_count": "5", "dismissed_at_pass": "0"],
currentPass: 3,
) != nil)
// A negative anchor clamps to 0 — the interval counts from zero
// (unclamped, elapsed 45 would already have resurfaced it).
#expect(LearningDecay.passesHidden(
["dismiss_count": "1", "dismissed_at_pass": "-40"],
currentPass: 5,
) != nil)
// A corrupt clock reads empty; non-integer values read partial —
// never throws (a lagging clock only delays resurfacing).
let home = try toolsHome()
try FileManager.default.createDirectory(at: home.appendingPathComponent("learnings"), withIntermediateDirectories: true)
let counts = home.appendingPathComponent("learnings/pass-counts.json")
try "not json at all".write(to: counts, atomically: true, encoding: .utf8)
#expect(LearningDecay.passCounts(home: home) == [:])
try "{\"posts\": 2, \"outlines\": \"later\"}".write(to: counts, atomically: true, encoding: .utf8)
#expect(LearningDecay.passCounts(home: home) == ["posts": 2])
// A huge hand-edited dismiss_count is permanently hidden (the
// 30-doubling cap turns ANY base into ≥ 2^30) and dismiss REFUSES
// it — the count+1 stamp can never see an absurd value, so no
// arithmetic in the stamp path can trap; the file stays untouched.
let hugeHome = try toolsHome()
try writeLearning(hugeHome, "posts", "20261021-huge.md", """
---
pattern: Huge
dismiss_count: \(Int.max)
dismissed_at_pass: 0
---
""")
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: hugeHome, typeDir: "posts", file: "20261021-huge.md")
}
#expect(try Post.frontmatter(of: readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
}
/// Scenario: dismiss is a write-path trust boundary — traversal-shaped
/// or hidden names refuse, a missing file refuses, and nothing lands
/// outside the learnings tree.
@Test func `dismiss refuses hostile paths and missing files`() throws {
let home = try toolsHome()
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "../x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "../learnings", file: "x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "", file: "x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: ".hidden.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20260101-gone.md")
}
// Nothing escaped the learnings tree; the real learning is untouched.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("x.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings/x.md").path))
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == nil)
}
/// Scenario: a pre-planted symlinked learnings component must not
/// turn dismiss into a file-plant primitive (promote's guard posture).
@Test func `a symlinked learnings dir refuses to dismiss`() throws {
let home = try toolsHome()
try writeLearning(home, "posts", "20261021-hedging.md", learning)
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
try FileManager.default.removeItem(at: home.appendingPathComponent("learnings/posts"))
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings/posts"),
withDestinationURL: target,
)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-hedging.md")
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
/// Scenario: a symlinked learning FILE must not become a copy-into-the-
/// consult-tree primitive — dismiss reads through a planted link and
/// the stamped write would materialize the target's content as a real
/// file the engine then serves. It refuses; the link and its target
/// stay untouched (#27 audit).
@Test func `a symlinked learning file refuses to dismiss`() throws {
let home = try toolsHome()
let secret = home.appendingPathComponent("secret.txt")
try "private stuff".write(to: secret, atomically: true, encoding: .utf8)
let posts = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: posts, withIntermediateDirectories: true)
let link = posts.appendingPathComponent("20261021-link.md")
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: secret)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-link.md")
}
let values = try link.resourceValues(forKeys: [.isSymbolicLinkKey])
#expect(values.isSymbolicLink == true) // still a link, not a copied file
#expect(try String(contentsOf: secret, encoding: .utf8) == "private stuff")
}
/// Scenario: the per-pass tick writes through a pre-planted symlinked
/// learnings dir if nothing guards it — recordPass refuses (promote's
/// posture), and the target dir stays empty (#27 audit).
@Test func `a symlinked learnings dir refuses to record a pass`() throws {
let home = try toolsHome()
let elsewhere = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings"),
withDestinationURL: elsewhere,
)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(!FileManager.default.fileExists(atPath: elsewhere.appendingPathComponent("pass-counts.json").path))
}
/// Scenario: re-dismiss means AFTER the resurface (CONTEXT.md) — a
/// second dismiss while hidden (double-click, impatient tap) refuses
/// and changes nothing; a negative hand-edited dismiss_count clamps at
/// parse so the stamp still lands (#27 audit).
@Test func `re-dismiss refuses while hidden and negative counts clamp`() throws {
let home = try toolsHome()
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
}
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == "1")
// A negative hand-edited count clamps to 0 at parse → stamp writes 1.
let negHome = try toolsHome()
try writeLearning(negHome, "posts", file, """
---
pattern: Neg
dismiss_count: -5
dismissed_at_pass: 0
---
""")
try LearningDecay.dismiss(home: negHome, typeDir: "posts", file: file)
#expect(try Post.frontmatter(of: readLearning(negHome, file))["dismiss_count"] == "1")
}
/// Scenario: decay is defined per pass-clocked content type — a foreign
/// learnings dir (a hand-made `essays/`) is pane-visible but never
/// clocked; dismissing there would hide the Learning forever behind a
/// lying countdown, so the store refuses (#27 audit).
@Test func `a foreign type dir refuses to dismiss`() throws {
#expect(LearningDecay.isClocked("posts"))
#expect(LearningDecay.isClocked("outlines"))
#expect(!LearningDecay.isClocked("essays"))
let home = try toolsHome()
let file = "20261021-musing.md"
try writeLearning(home, "essays", file, learning)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "essays", file: file)
}
let text = try String(
contentsOf: home.appendingPathComponent("learnings/essays/\(file)"),
encoding: .utf8,
)
#expect(Post.frontmatter(of: text)["dismiss_count"] == nil)
}
/// Scenario: a Learning with NO frontmatter (a hand-made file) still
/// dismisses — stampingFrontmatter prepends a fresh block and the body
/// rides verbatim below it (#27 audit: the prepend branch pinned).
@Test func `dismiss prepends a fresh block on a frontmatter-less file`() throws {
let home = try toolsHome()
let file = "20261021-bare.md"
let body = "# Just a hand edit\n\nSome prose.\n"
try writeLearning(home, "posts", file, body)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "0")
#expect(PostStore.splitFrontmatter(stampedText).body == body)
}
/// Scenario: lines ABOVE the opening `---` (a hand-edit blank —
/// Post.frontmatter tolerates one) belong to neither block nor body;
/// the stamp keeps them — the "every other line verbatim" contract
/// (#27 review pin).
@Test func `dismiss preserves lines above the frontmatter block`() throws {
let home = try toolsHome()
let file = "20261021-blank.md"
try writeLearning(home, "posts", file, "\n---\npattern: Blank\n---\n\n# Blank\n")
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
#expect(stampedText.hasPrefix("\n---\n")) // the leading blank survived
#expect(Post.frontmatter(of: stampedText)["dismiss_count"] == "1")
#expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched
}
}
+64 -1
View File
@@ -25,7 +25,7 @@ private func makeHome(_ write: (URL) throws -> Void) throws -> URL {
}
/// Seeds <home>/learnings/<type>/<file> with raw markdown.
private func writeLearning(_ home: URL, _ type: String, _ file: String, _ markdown: String) throws {
func writeLearning(_ home: URL, _ type: String, _ file: String, _ markdown: String) throws {
let dir = home.appendingPathComponent("learnings/\(type)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try markdown.write(to: dir.appendingPathComponent(file), atomically: true, encoding: .utf8)
@@ -123,4 +123,67 @@ struct LearningsPaneTests {
let home = try makeHome { _ in }
#expect(LearningsIndex.scan(home: home).isEmpty)
}
// MARK: Decay surface (#27, S4.2)
/// Scenario: Entry carries the decay verdict — visible learnings read
/// resurfacesIn nil; a dismissed one (anchor 2, once-dismissed =
/// interval 10) at pass 5 has 7 passes left; a twice-dismissed one
/// (interval 20) has 17.
@Test func `entry resurfacesIn pins the remaining-pass math`() {
#expect(LearningsIndex.Entry(
file: "20261021-fold-the-ladder.md",
text: "---\npattern: Fold the ladder\n---\n",
).resurfacesIn == nil)
#expect(LearningsIndex.Entry(
file: "20261020-hedging.md",
text: "---\npattern: Hedging\ndismiss_count: 1\ndismissed_at_pass: 2\n---\n",
currentPass: 5,
).resurfacesIn == 7)
#expect(LearningsIndex.Entry(
file: "20261020-hedging.md",
text: "---\npattern: Hedging\ndismiss_count: 2\ndismissed_at_pass: 2\n---\n",
currentPass: 5,
).resurfacesIn == 17)
}
/// Scenario: scan feeds the pass clock from pass-counts.json — the
/// dismissed fixture computes against the Home's counts, not zero.
/// Foreign (unclocked) dirs carry NO verdict even when hand-edited
/// decay state sits in the file — their clock never advances, a
/// countdown would lie (the store refuses to dismiss there; #27 audit).
@Test func `scan carries the pass clock into entries`() throws {
let home = try makeHome { home in
try writeLearning(home, "posts", "20261020-hedging.md", """
---
pattern: Hedging
dismiss_count: 1
dismissed_at_pass: 2
---
# Hedging
""")
try writeLearning(home, "posts", "20261021-fold.md", "---\npattern: Fold\n---\n")
try writeLearning(home, "essays", "20261019-musing.md", """
---
pattern: Musing
dismiss_count: 1
dismissed_at_pass: 2
---
""")
}
try "{\"outlines\": 99, \"posts\": 5}".write(
to: home.appendingPathComponent("learnings/pass-counts.json"),
atomically: true,
encoding: .utf8,
)
let posts = try #require(LearningsIndex.scan(home: home).first { $0.type == "posts" })
#expect(posts.entries.first { $0.id == "20261020-hedging.md" }?.resurfacesIn == 7)
#expect(posts.entries.first { $0.id == "20261021-fold.md" }?.resurfacesIn == nil)
let essays = try #require(LearningsIndex.scan(home: home).first { $0.type == "essays" })
#expect(essays.entries.first?.resurfacesIn == nil) // foreign: no verdict, no lying countdown
}
}
+5 -14
View File
@@ -14,15 +14,6 @@ import Foundation
@testable import Museion
import Testing
/// The store's stamp conventions (en_US_POSIX, per access) — expected
/// learning filenames/dates in the #26 promote pins.
private func stamped(_ date: Date, _ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: date)
}
/// A fully-stamped card for hand-written fixtures (scan tests). Defaults
/// match the historical shape; apply tests override anchor/lane, the rank
/// pins override submittedAt/rank. Internal — FixCardApplyTests shares it
@@ -83,7 +74,7 @@ struct MCPToolsPromoteTests {
// ONE file, the pinned name shape.
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let name = "\(stamped(now, "yyyyMMdd"))-hedging.md"
let name = "\(FixCardStore.formatted(now, "yyyyMMdd"))-hedging.md"
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") } == [name])
let markdown = try String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8)
@@ -95,7 +86,7 @@ struct MCPToolsPromoteTests {
#expect(markdown.contains("piece: test-piece\n"))
#expect(markdown.contains("pass: 1\n"))
#expect(markdown.contains("engine: hermes\n"))
#expect(markdown.contains("promoted: \(stamped(now, "yyyy-MM-dd"))\n"))
#expect(markdown.contains("promoted: \(FixCardStore.formatted(now, "yyyy-MM-dd"))\n"))
#expect(markdown.contains("from_card: \(written[0].card.id.uuidString)\n"))
// The Learning teaches, it never re-quotes the instance: a
// mechanical fix is a literal replacement string from one piece
@@ -106,7 +97,7 @@ struct MCPToolsPromoteTests {
#expect(!markdown.contains("Cut the hedge."))
#expect(markdown.contains("\n# Hedging\n"))
#expect(markdown.contains("**Problem.** The hedge weakens the claim."))
#expect(markdown.contains("*Promoted from test-piece · Pass 1 · \(stamped(now, "yyyy-MM-dd")).*"))
#expect(markdown.contains("*Promoted from test-piece · Pass 1 · \(FixCardStore.formatted(now, "yyyy-MM-dd")).*"))
// The returned card carries promotedAt; so does the re-scan.
#expect(promoted.promotedAt == now)
@@ -168,7 +159,7 @@ struct MCPToolsPromoteTests {
_ = try FixCardStore.promote(pieceURL: piece, card: written[1].card, now: now)
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let base = "\(stamped(now, "yyyyMMdd"))-hedging"
let base = "\(FixCardStore.formatted(now, "yyyyMMdd"))-hedging"
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).sorted() == ["\(base)-2.md", "\(base).md"])
}
@@ -203,7 +194,7 @@ struct MCPToolsPromoteTests {
#expect(markdown.contains("**Example.** Rewritten as the master would pace it."))
#expect(markdown.contains("# Hedging across lines\n"))
// No provenance → the footer's piece falls back to "a fix card".
#expect(markdown.contains("*Promoted from a fix card · \(stamped(now, "yyyy-MM-dd")).*"))
#expect(markdown.contains("*Promoted from a fix card · \(FixCardStore.formatted(now, "yyyy-MM-dd")).*"))
}
/// Pre-#26 card JSON (no promoted_at key) decodes promotedAt nil; a
@@ -0,0 +1,68 @@
# M3: Dismiss & Decay (S4.2) — issue #27
> **Date:** 2026-10-21
> **Type:** issue
> **Reference:** AlexKucera/museion#27 (M3 milestone)
## Goal
Ship #27: dismissed Learnings fade instead of haunting — a dismissed Learning stops feeding passes and resurfaces after 10 subsequent completed passes of its content type (an output clock, not a calendar), each re-dismiss doubles the interval (10→20→40…), a per-Learning `resurface_after` frontmatter key overrides the base, and decay state lives in frontmatter — surviving restarts, hand-editable (PRD S4.2, G8; ADR-0005 file home).
## What Was Done
- `Museion/LearningDecay.swift` (new, own file — FixCardStore sits at its type-body ceiling): the decay engine, nonisolated. Pass clock `<home>/learnings/pass-counts.json` (flat {typeDir: count}, keys via `passKey`); `recordPass(home:type:)` ticks it (symlink-guarded); `passesHidden(_:currentPass:)` is the ONE pure visibility verdict (nil = visible, positive = passes remaining) shared by the consult rail, the pane rows, and the dismiss stamp; `dismiss(home:typeDir:file:)` stamps `dismissed`/`dismiss_count`/`dismissed_at_pass` into the Learning's own frontmatter via `stampingFrontmatter` (mergedFrontmatter's line-walk generalized; set-overwrite in place, insert before closing `---`, no block → fresh prepend, every other line verbatim — leading hand-edit lines above the block included).
- `FixCardStore.learnings(piecePath:)` — the `query_learnings` consult rail — now filters hidden learnings through the same verdict (replacing the #26 ponytail pass-through note); `learningsDir` keys through `passKey`; `formatted` widened internal (dismiss's date stamp shares it).
- `PostStore.advancePassState` ticks the type's clock after its stamped write — `try?`, because a failed tick must never fail a completed pass and a lagging clock only delays resurfacing (safe direction). Cancelled/refused passes never advance, so never tick.
- `LearningsPaneView` — `Entry.resurfacesIn` (currentPass param, nil = foreign dir → never a verdict); visible rows in clocked dirs carry a mono-11 Dismiss (no confirm — low-stakes, self-healing); dismissed rows dim 0.45 with "dismissed · resurfaces in N passes"; scan refactored into `rescan()` reused post-dismiss; orange lastError strip; `scannedHome` gate so a stale dismiss task can't overwrite a repointed Home's groups or error state.
- `Post.ContentType` → CaseIterable (drives `isClocked`); `MCPServer` query_learnings description documents the decay contract.
- Tests: `LearningDecayTests` (new) — clock ticking (re-runs included, per-type, fresh home), stamp shape (frontmatter keys + anchor pinned, other keys + body byte-identical, rail exclusion), resurface boundary (hidden through +9, visible at +10), doubling to 20 with re-anchoring, `resurface_after` override, lenient edges (garbage ints, clamps so no arithmetic can trap, corrupt clock), every refusal guard (hostile paths, missing file, symlinked dir AND file, foreign dir, re-while-hidden), fresh-block prepend, leading-blank preservation. `LearningsPaneTests` — resurfacesIn math pins + scan carrying the clock + foreign-dir no-verdict.
- Docs: Museion/AGENTS.md, MuseionTests/AGENTS.md, CHANGELOG entry.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Output clock = one JSON file per Home (`pass-counts.json`), not per-Learning counting | One counter per content type is the honest unit ("passes of that content type"); ticking every Learning's frontmatter per pass would be O(n) writes per pass. Flat JSON is hand-editable and reads leniently (corrupt → 0, only delays resurfacing). |
| Tick lives in `advancePassState`, every completed pass counts (re-runs included) | One call site, monotonic with the existing completed-pass record; a re-run IS a pass that consulted the learnings. `try?` — the clock must never fail a pass. |
| Re-dismiss only after resurface (store refuses while hidden) | Doubling needs a fresh anchor at the current clock; also makes a double-click's second stamp harmless. |
| Foreign (unclocked) type dirs: store refuses dismiss AND pane shows no verdict/button | Their clock reads 0 forever — a dismiss or a displayed countdown there could never advance (permanent hide / lying UI). |
| Interval = (resurface_after ?? 10) « min(dismiss_count−1, 30); values clamp to [0, 1e9] | Override replaces the base, doubling compounds from it; caps keep every hand-edit from trapping Int arithmetic (max ~1.07e18 < Int.max). |
| Decay keys in the Learning's own frontmatter (`dismissed_at_pass` anchor + `dismiss_count` + `resurface_after`) | AC4: hand-editable, git-diffable, survives restarts; deleting the anchor re-activates the Learning. |
| No-confirm dismiss in the pane | Low-stakes and self-healing (it decays back); CONTEXT.md's Dismiss is not a trust-gated action (unlike Apply/Promote). |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Pane rendered a decay countdown in foreign dirs that could never advance | Scan fed every entry a clock; foreign dirs are never ticked | `Entry.currentPass: Int?` — nil = unclocked = never a verdict, mirroring the store's refusal (review finding; pinned) |
| `stampingFrontmatter` dropped lines above the opening `---`, contradicting its "verbatim" contract | `splitFrontmatter` starts at the first non-empty `---` line; leading hand-edit blanks fall in neither block nor body | Prefix recovered via exact `range(of: block)` and re-prepended; pin added and flip-verified (fails with fix off) |
| Stale `lastError` could leak from an old Home after repoint | Failure assignment ran outside `scannedHome` gate rescan enforces | Gated on `scannedHome == home` (no pin — race window, no view-state harness) |
| "resurfaces in 1 passes" copy bug | No pluralization at pane meta + store refusal | Ternary at both sites |
| Test-side `stamped()` DateFormatter helper duplicated prod `FixCardStore.formatted` | Reinvention the same diff internalized | Helper deleted; 6 call sites call the prod function (format literals still pinned) |
| `LearningDecayTests` crossed file/type-body ceilings by one line | New pin pushed it over | Trimmed a redundant assert + comment line |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/LearningDecay.swift` | New — decay engine: clock, verdict, dismiss, frontmatter rewrite |
| `Museion/FixCardStore.swift` | Consult rail filters hidden learnings; `learningsDir` via `passKey`; `formatted` internal |
| `Museion/PostStore.swift` | `advancePassState` ticks the decay clock (`try?`) |
| `Museion/LearningsPaneView.swift` | Dismiss button, dimmed countdown rows, rescan, error strip, scannedHome gate, foreign-dir gating |
| `Museion/PostLibrary.swift` | `ContentType` CaseIterable |
| `Museion/MCPServer.swift` | query_learnings description documents decay |
| `MuseionTests/LearningDecayTests.swift` | New — 15 decay pins |
| `MuseionTests/LearningsPaneTests.swift` | resurfacesIn + clock-carrying scan + foreign-dir pins |
| `MuseionTests/MCPToolsPromoteTests.swift` | `stamped` helper deleted (prod `formatted` direct) |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `CHANGELOG.md` | DOX + changelog |
## Open Items & Next Steps
- [ ] None for #27 — all four acceptance criteria met and pinned.
- M3 (critique memory) is now fully shipped (S4.1–S4.4 across #26 + #27); the Sessions rail placeholder is #28's.
---
*Implementation landed in an interrupted working session; this session resumed it, verified the full suite, and ran two review waves (two-axis implement review + three-reviewer finish-audit: ponytail/security/general — security clean, five findings fixed, all documented above). Verified green on the final tree: `xcodebuild test` (unit + UI) TEST SUCCEEDED, swiftformat 0/75, swiftlint 0 violations in touched files; GitNexus detect-changes symbol set = intended scope, graph re-analyzed (4,079 nodes).*
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-10-21 | issue | [20261021-issue27-dismiss-decay-learnings_log.md](20261021-issue27-dismiss-decay-learnings_log.md) | #27 dismiss & decay Learnings: per-type pass clock, frontmatter decay state, consult filtering, two review waves with 5 fixes |
| 2026-10-21 | issue | [20261021-issue26-promote-consult-learnings_log.md](20261021-issue26-promote-consult-learnings_log.md) | #26 promote/consult Learnings: teaching-shape files, on-disk-truth promote, symlink guard, Learnings pane — 329 tests green |
| 2026-10-20 | issue | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) | #124 cancel-acknowledging hangOnPrompt fake, Cancel-rail pin (RED→GREEN), defer-at-rig-creation teardown ×27 rigs — 316 tests green |
| 2026-10-20 | issue | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) | #25 Apply/Skip Fix Cards: ranked ≤10 ceiling, adoptText apply rail, blocking ask, audit fanout with 11 fixes — 316 tests green |