diff --git a/AGENTS.md b/AGENTS.md index 533aae6..300eef3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (5211 symbols, 19643 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** (5285 symbols, 20153 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,13 +180,17 @@ This project is indexed by GitNexus as **museion** (5211 symbols, 19643 relation - Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) - When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift ` check of the pure logic still verify honestly (#134) +### Trust boundaries +- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6) + ## Session Logs -Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent: +Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](INDEX.md). The 10 most recent: | Date | Log | |------|-----| +| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | | 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) | | 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | | 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index e4c632a..e848949 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **mentor:** Native deslop lint at pass invocation (PRD S3.4) — running a pass now computes the deslop skill's deterministic findings (banned-vocab tiers + em-dash density) natively in Swift at the invocation — after first-draft stats capture, before the engine turn, no engine round-trip — and each finding lands as a real fix card (emitter `lint`) under `/cards/`, rendered by the existing Fix Cards palette with ask-before Apply on mechanical mapping cards (mapped phrases like `utilize`→`use` carry the replacement; unmapped ones land demonstration for judgment). One card per phrase over its tier allowance, case-insensitive whole-word matching (`delved` never fires `delve`), anchor = the first match with case preserved, em-dash density card first when over budget, tiers ranked by first match. The tier data ships as `Resources/deslop-lint.json` mirroring the deslop doctrine verbatim (`key`/`landscape`/`highlight`/bare `underscore` deliberately omitted as POS-ambiguous — add via `/deslop-lint.json`, which wins whenever it exists and decodes); emit dedups against OPEN cards before submit so re-runs make progress (closed cards never block) and the engine never re-cards a live lint finding. A failed lint never blocks the pass (the stats-capture posture). Suite 487 (issue #6) + - **mentor:** Prompt-end constraint ordering verified + pinned (#1) — the PRD's cross-cutting rule audited on the app's REAL wire: an ACP probe (initialize → session/new → session/prompt against the provisioned museion-pass1) plus the engine's own state.db read-back show constraint bodies never ride the system prompt — they enter as `skill_view` results, so "assembly order" is the mentor's tool-call order, and the baseline already loaded deslop AFTER the piece but by model choice. Both personas (pass 1.5 / session 1.2) gain the verbatim-shared "Draft first, rules last" pin converting observed-once into instructed-always; `PersonaLoadOrderTests` guards presence + parity over the bundled payload; the verified layout, the `hermes -z` trap (one-shot swaps the skills directive — a `-z` probe loads ZERO skills and assembles a different prompt), and the additive-only propagation cost (content edits need a hand-copy to master/profile copies; byte-match then migrates) live in `docs/research/prompt-layout-factsheet.md` with the probe script in-repo. Suite 479 + 1 load-flake cleared in isolation (issue #1) - **mentor:** Profiles S4 — per-surface engine lifecycle + model-switch UX (#137) — passes run on their OWN one-shot engines (`hermes acp -p museion-passN` spawned per pass run, torn down at the verdict — a model switch costs nothing, the next spawn reads fresh config) streaming into transient unrostered transcripts (#129: one Sessions surface over the chat engine); the Chat engine stays resident and a Chat model change in Settings restarts it in place, deferred to turn end while a reply streams; Run Pass names the missing provider key and disables with an Open Settings link until the key lands (pane re-entry re-checks). Finish-audit (3 reviewers) fixed a post-await activation steal that could flip the surface mid-pass and lose the Cancel (one `claimActive` gate), plus a PRE-EXISTING `rescan` bug where a stale scan snapshot "vanished" a just-opened piece and killed its session with unflushed edits. Suite 477 (issue #137) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 86012c0..77074ef 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -26,8 +26,9 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). - `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; 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 resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. - `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). +- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`. - `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 contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. 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), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `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; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). +- `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; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). - `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here. - `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions. - `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam). @@ -65,7 +66,7 @@ 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 three 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; **#29 (S8.1):** the third tool `submit_research_notes` is the candidates rail — `{piece_path, notes:[{title, url, quote?, note?}]}`, decode-validate ONLY (missing fields fail decode = tool error; empty title/url throw) and reply `{"received": N}`; NOTHING is written — findings are engine-owned session cargo, the only path to disk is the writer's keep); `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` / `mcp_museion_tools_submit_research_notes`. -- `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 `/cards/-.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 `/learnings/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 `/-.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). +- `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 `/cards/-.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats); **#6 audit: a symlinked `cards/` dir refuses before any write (promote's learnings posture — the native lint auto-fires submit on every Run Pass, closing the arbitrary-directory JSON-drop the engine-only rail left theoretical)**. **#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 `/learnings/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 `/-.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 `/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, all three tools listed with required arrays — #29 research schema pins piece_path+notes / title+url — full submit round-trip through the wire, isError path, -32601/-32700; **#29:** a well-formed `submit_research_notes` round-trip replies `{"received": N}` and lands NOTHING on disk, a note missing `title` answers isError). diff --git a/Museion/DeslopLint.swift b/Museion/DeslopLint.swift new file mode 100644 index 0000000..16245e6 --- /dev/null +++ b/Museion/DeslopLint.swift @@ -0,0 +1,224 @@ +// +// DeslopLint.swift +// Museion +// +// #6 (PRD S3.4): the native deslop lint — the SAME deterministic findings +// the engine's deslop skill doctrine defines (banned-vocab tiers + em-dash +// density), computed in Swift at pass invocation. No engine round-trip: +// the same invocation posture as the #31 stats capture — pure Foundation, +// deterministic, and a failed lint never blocks the pass. Findings land +// as real fix cards (emitter `lint`, ADR-0006) through FixCardStore; the +// GLOSSARY emitter contract keeps the engine from re-carding a live lint +// finding, which is why emit() dedups against OPEN cards before submit. +// +// Data: `Resources/deslop-lint.json` is the bundled default, mirroring +// the deslop SKILL.md tier doctrine verbatim (owner-facing — copy +// exactly, never regenerate). `key`, `landscape`, `highlight`, and bare +// `underscore` are deliberately omitted from the tiers: POS-ambiguous +// (a regex can't tell the noun `key` from the adjective) and the phrase +// `underscore` collides with the character name. A writer who wants +// them adds them via `/deslop-lint.json` — the Home override wins +// whenever it exists AND decodes (trivially editable without a recompile). +// + +import Foundation + +/// #6 (S3.4): the native deslop lint. nonisolated like FixCardStore — +/// pure compute plus one disk-touching emit the pass flow calls. +nonisolated enum DeslopLint { + /// The lint's editable data shape (`deslop-lint.json`, camelCase keys). + struct Config: Codable, Equatable { + struct Tier: Codable, Equatable { + struct Phrase: Codable, Equatable { + var phrase: String + /// The plain word a mechanical-lane card can Apply directly; + /// nil = demonstration (the rewrite needs judgment). + var replacement: String? + } + + var name: String + var note: String + /// How many occurrences this tier tolerates (0 = never; + /// 1 = suspicious in density). + var maxAllowed: Int + var phrases: [Phrase] + } + + var tiers: [Tier] + var emDashBudget: Int + } + + /// One deterministic finding — the card body before it becomes a card. + /// (No `count` field: the occurrence count lives verbatim in the + /// owner-facing `problem` string — "Appears 2×" — audit-deleted as + /// write-only.) + struct Finding: Equatable { + var pattern: String + var problem: String + var diagnosticQuestion: String + var fix: String + var lane: FixCardStore.StoredFixCard.Lane + var anchor: FixCardStore.StoredFixCard.Anchor + } + + /// Created per access; no non-Sendable statics (repo convention, + /// FixCardStore.codec). The config JSON is camelCase — a plain decoder. + private static var decoder: JSONDecoder { + JSONDecoder() + } + + // MARK: - Config + + /// The bundled doctrine. Missing/undecodable → the no-op config: the + /// lint stays silent, never crashes (the stats-capture posture). + static func bundledConfig() -> Config { + guard let url = Bundle.main.url(forResource: "deslop-lint", withExtension: "json"), + let data = try? Data(contentsOf: url), + let config = try? decoder.decode(Config.self, from: data) + else { return Config(tiers: [], emDashBudget: .max) } + return config + } + + /// `/deslop-lint.json` wins when it exists AND decodes; any + /// read/decode failure falls back to the bundled default (lenient, + /// never fatal). `home: nil` → bundled (test-injectable). + // ponytail: no bound on override size or values — a hostile 5000-phrase + // override self-freezes the pass (same-privilege local file), a + // negative emDashBudget junk-cards dash-free text; reject >500 phrases + // / clamp negatives if a hand-edit ever bites. + static func config(home: URL?) -> Config { + guard let home, + let data = try? Data(contentsOf: home.appendingPathComponent("deslop-lint.json")), + let override = try? decoder.decode(Config.self, from: data) + else { return bundledConfig() } + return override + } + + // MARK: - Compute (pure) + + /// The deterministic findings over `body`: the em-dash density finding + /// first when over budget, then each tier's over-allowance phrases + /// ordered by first-match position. ONE finding per phrase — never one + /// per occurrence. Same body in, same findings out. + // ponytail: lints the raw body as given — no fence/heading stripping; + // the engine's pass does the context judgment (code fences, quotes) a + // table lint can't. Strip contexts if false positives ever bite. + static func compute(body: String, config: Config) -> [Finding] { + var findings: [Finding] = [] + let dashes = body.ranges(of: "—").count + if dashes > config.emDashBudget { + findings.append(Finding( + pattern: "em-dash density", + problem: "\(dashes) em-dashes in this piece — the budget is \(config.emDashBudget). " + + "Most separation wants a comma or a period; 1-2 earned dashes are plenty. " + + "The em-dash habit is the prompt-resistant AI tell.", + diagnosticQuestion: "Does this aside need an em-dash, or would a comma or a period carry it?", + fix: "", + lane: .demonstration, + anchor: .init(quote: "—", occurrence: 1), + )) + } + for tier in config.tiers { + var ranked: [(position: String.Index, finding: Finding)] = [] + for entry in tier.phrases { + guard let hit = scan(entry.phrase, in: body), hit.count > tier.maxAllowed else { continue } + ranked.append((hit.first.lowerBound, vocabFinding(body: body, tier: tier, entry: entry, hit: hit))) + } + findings.append(contentsOf: ranked.sorted { $0.position < $1.position }.map(\.finding)) + } + return findings + } + + /// Case-insensitive whole-word matches of `phrase` in `body`: ICU regex + /// `(? (first: Range, count: Int)? { + // Trust boundary (a hand-edited override): an empty or + // whitespace-only phrase (submit's validation TRIMS) would match + // everywhere, build a junk anchor, and fail submit's whole-call + // validation — silently killing the entire lint. + guard !phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } + let pattern = "(?i)(?, count: Int), + ) -> Finding { + let quote = String(body[hit.first]) + let fix = entry.replacement.map { replacement -> String in + guard let quoteFirst = quote.first, quoteFirst.isUppercase, + let fixFirst = replacement.first + else { return replacement } + return fixFirst.uppercased() + replacement.dropFirst() + } ?? "" + return Finding( + pattern: entry.phrase, + problem: "\(tier.name) AI vocabulary — \(tier.note). Appears \(hit.count)× in this piece. " + + "Replace with the plain word.", + diagnosticQuestion: "What plain word says this instead?", + fix: fix, + lane: entry.replacement == nil ? .demonstration : .mechanical, + anchor: .init( + quote: quote, + occurrence: (body.ranges(of: quote).firstIndex(of: hit.first) ?? 0) + 1, + ), + ) + } + + // MARK: - Emit + + /// Load config, compute, dedup, submit — the pass-flow hook (#6). + /// Swallows every error: a failed lint must never fail the pass (the + /// `captureFirstDraftStats` posture). `pieceURL` is the piece's + /// post.md URL (already flushed at the call site). + static func emit(body: String, pieceID: String, pieceURL: URL, kind: PassKind, home: URL?) { + let findings = compute(body: body, config: config(home: home)) + guard !findings.isEmpty else { return } + // Dedup BEFORE submit: an OPEN card with the same pattern AND + // anchor already covers the finding. Closed cards (applied/ + // skipped/done) do NOT block — a still-present finding after the + // writer closed a card re-emits (re-runs make progress). + let open = FixCardStore.scan(pieceURL: pieceURL) + .filter { $0.status == .open } + let inputs = findings.compactMap { finding -> FixCardStore.Input? in + let duplicate = open.contains { + $0.pattern == finding.pattern + && $0.anchor.quote == finding.anchor.quote + && $0.anchor.occurrence == finding.anchor.occurrence + } + guard !duplicate else { return nil } + return FixCardStore.Input( + pattern: finding.pattern, + problem: finding.problem, + diagnosticQuestion: finding.diagnosticQuestion, + fix: finding.fix, + anchor: finding.anchor, + lane: finding.lane, + emitter: .lint, + provenance: .init(piece: pieceID, date: nil, engine: nil, pass: kind == .pass1 ? 1 : 2), + ) + } + guard !inputs.isEmpty else { return } + // submit validates anchors against post.md on disk, stamps + // id/date/rank, enforces the 10-card ceiling (the ranked head + // survives), and writes the JSON files. Any failure → silence. + try? FixCardStore.submit(piecePath: pieceURL.path, cards: inputs) + } +} diff --git a/Museion/FixCardStore.swift b/Museion/FixCardStore.swift index 2e1232c..43216dd 100644 --- a/Museion/FixCardStore.swift +++ b/Museion/FixCardStore.swift @@ -190,6 +190,14 @@ nonisolated enum FixCardStore { } let dir = postURL.deletingLastPathComponent().appendingPathComponent("cards", isDirectory: true) + // Security (audit): a pre-planted symlink under the piece must not + // turn a card submit into an arbitrary-directory JSON drop — + // promote's learnings posture, now covering the rail the native + // lint auto-fires on every Run Pass. + let values = try? dir.resourceValues(forKeys: [.isSymbolicLinkKey]) + if values?.isSymbolicLink == true { + throw CardError(message: "cards path is a symlink: \(dir.path)") + } try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) let stamp = Self.stamp(Date()) diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index eec2b82..33aa6a3 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -862,8 +862,13 @@ extension PostsModel { // Draft, post type) is read from disk. A failed capture must never // fail the pass (decay-clock posture), so the Bool is ignored. PostStore.captureFirstDraftStats(id: id, body: session.text, home: home) + // #6 (S3.4): the native deslop lint — same invocation posture as the + // stats capture: pure Swift, no engine round-trip, a failure never + // blocks the pass. Cards land in /cards/ and the palette's + // watcher-driven rescan surfaces them (the #23 path). + DeslopLint.emit(body: session.text, pieceID: id, pieceURL: session.passPieceURL, kind: kind, home: home) // #137 (S4): runningPass goes live BEFORE the mentor awaits — - // flush/snapshot/capture above are synchronous, so nothing can slip + // flush/snapshot/capture/lint above are synchronous, so nothing can slip // between the guards and the flag: the #124 Cancel-visibility // invariant now holds for the WHOLE run, pass-engine spawn included. runningPass = kind diff --git a/Museion/Resources/deslop-lint.json b/Museion/Resources/deslop-lint.json new file mode 100644 index 0000000..aa59cc7 --- /dev/null +++ b/Museion/Resources/deslop-lint.json @@ -0,0 +1,93 @@ +{ + "tiers": [ + { + "name": "Tier 1", + "note": "dead giveaway, never use", + "maxAllowed": 0, + "phrases": [ + { "phrase": "additionally" }, + { "phrase": "align with" }, + { "phrase": "bolster" }, + { "phrase": "bolsters", "replacement": "supports" }, + { "phrase": "catalyst" }, + { "phrase": "catalyzes", "replacement": "starts" }, + { "phrase": "cornerstone" }, + { "phrase": "comprehensive" }, + { "phrase": "crucial" }, + { "phrase": "delve" }, + { "phrase": "emphasize" }, + { "phrase": "emphasizing" }, + { "phrase": "embark" }, + { "phrase": "empower" }, + { "phrase": "encompass" }, + { "phrase": "encompassing" }, + { "phrase": "encompasses", "replacement": "includes" }, + { "phrase": "elucidate" }, + { "phrase": "endure" }, + { "phrase": "enduring" }, + { "phrase": "enhance" }, + { "phrase": "enhanced" }, + { "phrase": "facilitate", "replacement": "help" }, + { "phrase": "facilitated", "replacement": "helped" }, + { "phrase": "foster" }, + { "phrase": "fostering" }, + { "phrase": "garner" }, + { "phrase": "garnered" }, + { "phrase": "garners", "replacement": "gets" }, + { "phrase": "groundbreaking" }, + { "phrase": "harness" }, + { "phrase": "holistic" }, + { "phrase": "invaluable" }, + { "phrase": "interplay" }, + { "phrase": "intricate" }, + { "phrase": "intricacies" }, + { "phrase": "leverage", "replacement": "use" }, + { "phrase": "leveraging", "replacement": "using" }, + { "phrase": "meticulous" }, + { "phrase": "multifaceted" }, + { "phrase": "myriad" }, + { "phrase": "nuanced" }, + { "phrase": "paramount" }, + { "phrase": "paradigm" }, + { "phrase": "pivotal" }, + { "phrase": "poised" }, + { "phrase": "realm" }, + { "phrase": "reimagine" }, + { "phrase": "robust" }, + { "phrase": "seamless" }, + { "phrase": "showcase" }, + { "phrase": "showcasing" }, + { "phrase": "spearhead" }, + { "phrase": "spearheading" }, + { "phrase": "spearheads", "replacement": "leads" }, + { "phrase": "streamline" }, + { "phrase": "streamlined" }, + { "phrase": "synergy" }, + { "phrase": "tapestry" }, + { "phrase": "testament" }, + { "phrase": "transformative" }, + { "phrase": "underscored" }, + { "phrase": "underscores", "replacement": "shows" }, + { "phrase": "utilize", "replacement": "use" }, + { "phrase": "utilizing", "replacement": "using" }, + { "phrase": "utilization", "replacement": "use" }, + { "phrase": "valuable" }, + { "phrase": "vibrant" } + ] + }, + { + "name": "Tier 2", + "note": "suspicious in density, use sparingly", + "maxAllowed": 1, + "phrases": [ + { "phrase": "furthermore" }, + { "phrase": "moreover" }, + { "phrase": "notably" }, + { "phrase": "quintessential" }, + { "phrase": "ubiquitous" }, + { "phrase": "proactive" } + ] + } + ], + "emDashBudget": 4 +} diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 391eb6f..900808f 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -23,10 +23,11 @@ Owned by the root AGENTS.md contract. - `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///` + `archive///` (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///` + #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///post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#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 in-place `pass_state` stamp since #31, formerly the block rewrite; 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 — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`. - `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts. -- `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 `/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. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#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. +- `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 `/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), 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. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#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 · " 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. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). +- `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. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). **#6 (S3.4) wiring pin** (`DeslopLintWiringTests`, suite member at file tail — the #31/#134 vacuous-filter lesson): a pass invocation on a sloppy piece seeds emitter `lint` cards under `<piece>/cards/` AND the `stats_*` keys — stats capture and lint both fired at the one invocation seam. +- `DeslopLintTests.swift` (#6, S3.4 — scenario header at file top, all tests `@Suite` members) — the native deslop lint pins: the exact finding set AND rank order over a known sloppy draft (em-dash first, Tier 1 by first-match position, Tier 2 after; exact owner-facing problem/diagnostic copy, mixed-case anchor preservation `Utilize` with its exact-substring occurrence, mechanical lane for the mapped `utilize`→`use`, demonstration for `delve`, counts inside the problem strings, NO finding for within-allowance `furthermore`), whole-word boundaries (`delved`/`harnessed`/`showcased` never fire their stems), em-dash at budget 4 → silent (0 too), the empty AND whitespace-phrase trust-boundary pin (#6 audit: the `— —` body is space-phrase bait — a plain body passes vacuously; submit's validation trims, so a whitespace phrase would kill the whole submit), the config story (Home override wins when it exists AND decodes, malformed override falls back to the bundled default, `home: nil` → bundled, `bundledConfig()` decodes the two tiers + budget 4 + the mapped replacements), and the store-level emit loop over `PostStore.writeNew` (cards land emitter `lint`/open/pass 1/valid anchors, re-emit dedups against OPEN cards, a `.skipped` close re-emits its still-present finding). - `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key). - `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home). - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. diff --git a/MuseionTests/DeslopLintTests.swift b/MuseionTests/DeslopLintTests.swift new file mode 100644 index 0000000..6f80bda --- /dev/null +++ b/MuseionTests/DeslopLintTests.swift @@ -0,0 +1,228 @@ +// +// DeslopLintTests.swift +// MuseionTests +// +// #6 (S3.4): the native deslop lint — banned-vocab tiers + em-dash +// density computed in Swift, findings as real fix cards. Expectations +// are derived here from the doctrine data, not copied from the +// implementation (DraftStatsTests convention). +// +// ## Scenario: Native deslop cards at pass invocation +// From issue #6 / PRD S3.4 +// +// Given a saved piece whose draft contains Tier-1 banned words, a Tier-2 +// word above its allowance, and more em-dashes than the budget +// When the writer invokes a pass (Run Pass 1) +// Then the lint computes findings in Swift at invocation — after +// First-Draft stats capture, before the engine turn, no engine +// round-trip — and each finding lands as a real fix card (emitter +// `lint`) under <piece>/cards/, rendered by the existing Fix Cards +// palette with ask-before Apply on mechanical mapping cards. +// + +import Foundation +@testable import Museion +import Testing + +@Suite("DeslopLintTests") +struct DeslopLintTests { + /// The AC #4 fixture: mixed-case `Utilize` twice, `delve`, `notably` ×2 + /// (over the Tier-2 allowance), `furthermore` ×1 (within it), 5 em-dashes + /// (over budget 4), plus words that merely CONTAIN tier phrases. + private static let sloppy = """ + # Sloppy Draft + + Delve into it. Utilize the tool — and utilize it twice — notably here — notably there — \ + a fifth dash — plain words carry the rest. Furthermore stays within allowance. \ + Delved, harnessed, showcased stay quiet. + """ + + private func anchor(_ quote: String, _ occurrence: Int) -> FixCardStore.StoredFixCard.Anchor { + .init(quote: quote, occurrence: occurrence) + } + + @Test func `known sloppy draft produces the expected findings`() { + let findings = DeslopLint.compute(body: Self.sloppy, config: DeslopLint.bundledConfig()) + + let expected: [DeslopLint.Finding] = [ + .init( + pattern: "em-dash density", + problem: "5 em-dashes in this piece — the budget is 4. Most separation wants a comma " + + "or a period; 1-2 earned dashes are plenty. The em-dash habit is the " + + "prompt-resistant AI tell.", + diagnosticQuestion: "Does this aside need an em-dash, or would a comma or a period carry it?", + fix: "", + lane: .demonstration, + anchor: anchor("—", 1), + ), + .init( + pattern: "delve", + problem: "Tier 1 AI vocabulary — dead giveaway, never use. Appears 1× in this piece. " + + "Replace with the plain word.", + diagnosticQuestion: "What plain word says this instead?", + fix: "", + lane: .demonstration, + anchor: anchor("Delve", 1), + ), + .init( + pattern: "utilize", + problem: "Tier 1 AI vocabulary — dead giveaway, never use. Appears 2× in this piece. " + + "Replace with the plain word.", + diagnosticQuestion: "What plain word says this instead?", + fix: "Use", // case-matched: the anchor quotes sentence-initial `Utilize` + lane: .mechanical, + anchor: anchor("Utilize", 1), + ), + .init( + pattern: "notably", + problem: "Tier 2 AI vocabulary — suspicious in density, use sparingly. Appears 2× in " + + "this piece. Replace with the plain word.", + diagnosticQuestion: "What plain word says this instead?", + fix: "", + lane: .demonstration, + anchor: anchor("notably", 1), + ), + ] + // Exact set AND rank order: em-dash first, then Tier 1 by first-match + // position (delve precedes utilize in the text), then Tier 2. The + // within-allowance `furthermore` and the containing words + // (Delved/harnessed/showcased) contribute nothing. + #expect(findings == expected) + } + + @Test func `word boundaries exclude inflected containing words`() { + // `delved`/`harnessed`/`showcased` must NOT match `delve`/`harness`/ + // `showcase` — whole-word boundaries, not substring. + let findings = DeslopLint.compute( + body: "Delved deep. Harnessed it. Showcased the work.", + config: DeslopLint.bundledConfig(), + ) + #expect(findings.isEmpty) + } + + @Test func `em dash at budget or zero stays quiet`() { + let atBudget = "One — two — three — four." // exactly the budget of 4 + #expect(DeslopLint.compute(body: atBudget, config: DeslopLint.bundledConfig()).isEmpty) + let none = "No dashes at all here." + #expect(DeslopLint.compute(body: none, config: DeslopLint.bundledConfig()).isEmpty) + } + + @Test func `home override wins and a malformed one falls back`() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("deslop-config-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + + // An override that exists AND decodes wins over the bundled default. + try """ + {"tiers":[{"name":"Home Tier","note":"local","maxAllowed":0,"phrases":[{"phrase":"dig"}]}],"emDashBudget":0} + """.write(to: home.appendingPathComponent("deslop-lint.json"), atomically: true, encoding: .utf8) + let overridden = DeslopLint.config(home: home) + #expect(overridden.tiers.map(\.name) == ["Home Tier"]) + #expect(overridden.tiers.first?.phrases.map(\.phrase) == ["dig"]) + #expect(overridden.emDashBudget == 0) + + // Malformed override JSON → the bundled default (lenient, never fatal). + try "{not json".write(to: home.appendingPathComponent("deslop-lint.json"), atomically: true, encoding: .utf8) + let fallenBack = DeslopLint.config(home: home) + #expect(fallenBack.tiers.count == 2) + #expect(fallenBack.emDashBudget == 4) + + // No home at all → the bundled default. + let bundled = DeslopLint.config(home: nil) + #expect(bundled.tiers.count == 2) + #expect(bundled.emDashBudget == 4) + } + + @Test func `bundled config decodes the doctrine`() { + let config = DeslopLint.bundledConfig() + #expect(config.tiers.map(\.name) == ["Tier 1", "Tier 2"]) + #expect(config.emDashBudget == 4) + // The mapped phrases carry their replacements (mechanical lanes). + let tier1 = config.tiers[0].phrases + #expect(tier1.first(where: { $0.phrase == "utilize" })?.replacement == "use") + #expect(tier1.first(where: { $0.phrase == "bolsters" })?.replacement == "supports") + #expect(tier1.first(where: { $0.phrase == "facilitate" })?.replacement == "help") + #expect(tier1.first(where: { $0.phrase == "facilitated" })?.replacement == "helped") + #expect(tier1.first(where: { $0.phrase == "delve" })?.replacement == nil) + // The tiers mirror the doctrine's allowances. + #expect(config.tiers[0].maxAllowed == 0) + #expect(config.tiers[1].maxAllowed == 1) + #expect(!config.tiers[1].phrases.isEmpty) + } + + @Test func `empty and whitespace phrases in hand-edited data are ignored`() { + // Trust boundary: an empty or whitespace-only phrase in a Home + // override must not match everywhere and kill the whole submit + // (whole-call validation) — they contribute nothing, the rest + // still lints. The "— —" in the body is the space-phrase bait + // (a bare space flanked by non-letters DOES match without the + // trimmed guard — a plain body would pass vacuously); budget 10 + // keeps the dashes out of the assertion. + let config = DeslopLint.Config(tiers: [ + .init(name: "T", note: "n", maxAllowed: 0, phrases: [ + .init(phrase: "", replacement: "x"), + .init(phrase: " ", replacement: "x"), + .init(phrase: "dig", replacement: nil), + ]), + ], emDashBudget: 10) + let findings = DeslopLint.compute( + body: "Dig it. Over — the — budget — of — dashes — — end.", + config: config, + ) + #expect(findings.map(\.pattern) == ["dig"]) + } + + @Test func `emit lands lint cards dedups and re-emits after close`() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("deslop-emit-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + + let body = "Utilize this. Delve deep. Utilize it again." + let post = try PostStore.writeNew(body: body, home: home) + let pieceURL = home.appendingPathComponent("projects/posts/\(post.id)/post.md") + + DeslopLint.emit(body: body, pieceID: post.id, pieceURL: pieceURL, kind: .pass1, home: home) + + let first = FixCardStore.scan(pieceURL: pieceURL) + #expect(first.count == 2) // delve + utilize — one finding per phrase + #expect(first.allSatisfy { $0.emitter == .lint }) + #expect(first.allSatisfy { $0.status == .open }) + #expect(first.allSatisfy { $0.anchorStatus == .valid }) + #expect(first.allSatisfy { $0.provenance?.pass == 1 }) + #expect(first.allSatisfy { $0.provenance?.piece == post.id }) + + // Emit again over unchanged text: every finding already has an OPEN + // card with the same pattern + anchor — nothing duplicates. + DeslopLint.emit(body: body, pieceID: post.id, pieceURL: pieceURL, kind: .pass1, home: home) + #expect(FixCardStore.scan(pieceURL: pieceURL).count == 2) + + // Close one card: a closed card does NOT block — the still-present + // finding re-emits (re-runs make progress). + let closed = try FixCardStore.close( + pieceURL: pieceURL, + id: #require(first.first { $0.pattern == "delve" }?.id), + status: .skipped, + ) + #expect(closed.status == .skipped) + DeslopLint.emit(body: body, pieceID: post.id, pieceURL: pieceURL, kind: .pass1, home: home) + let after = FixCardStore.scan(pieceURL: pieceURL) + #expect(after.count == 3) + #expect(after.filter { $0.pattern == "delve" && $0.status == .open }.count == 1) + #expect(after.filter { $0.pattern == "utilize" }.count == 1) // still deduped + + // Pass 2 stamps its own provenance on a fresh finding — the + // ternary's other branch, ASSERTED (close → re-emit → pass == 2), + // not just deduped silence. + try FixCardStore.close( + pieceURL: pieceURL, + id: #require(after.first { $0.pattern == "delve" && $0.status == .open }?.id), + status: .done, + ) + DeslopLint.emit(body: body, pieceID: post.id, pieceURL: pieceURL, kind: .pass2, home: home) + let passTwo = FixCardStore.scan(pieceURL: pieceURL) + #expect(passTwo.count == 4) + #expect(passTwo.first { $0.pattern == "delve" && $0.status == .open }?.provenance?.pass == 2) + } +} diff --git a/MuseionTests/MCPToolsTests.swift b/MuseionTests/MCPToolsTests.swift index c19c38d..73c8593 100644 --- a/MuseionTests/MCPToolsTests.swift +++ b/MuseionTests/MCPToolsTests.swift @@ -149,6 +149,19 @@ struct MCPToolsTests { ) } + @Test func `submit refuses a symlinked cards dir`() throws { + let home = try toolsHome() + let piece = try writePiece(home) + let target = home.appendingPathComponent("drop-target", isDirectory: true) + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: piece.appendingPathComponent("cards"), + withDestinationURL: target, + ) + #expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card()]) } + #expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty) + } + @Test func `submit throws on missing piece`() throws { let home = try toolsHome() // A lazy piece folder without post.md is not a piece. diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index bdf46c3..e951f17 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -312,3 +312,35 @@ func textRows(of model: MentorSessionModel) -> [String] { #expect(matter["stats_captured"] == nil) #expect(matter["stats_burstiness"] == nil) } + +// MARK: Native deslop lint (#6, S3.4) + +@Suite("DeslopLintWiringTests") +struct DeslopLintWiringTests { + /// #6 (S3.4): the lint fires AT the invocation — stats capture and lint + /// cards both land before the engine turn, no engine round-trip. + @Test @MainActor func `a pass invocation seeds lint cards`() async throws { + let (model, home, mentor) = try makePassRig() + defer { mentor.shutdown() } + await mentor.openSession() + let body = "# Lint Piece\n\nUtilize the index — and delve twice — notably once, and again — " + + "and again — and once more — to clear the dash budget. Utilize it twice." + let post = try PostStore.writeNew(body: body, home: home) + model.select(post.id, home: home) + for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + + await model.runPass(.pass1, home: home, mentor: mentor) + + let piece = home.appendingPathComponent("projects/posts/\(post.id)") + let cards = FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md")) + #expect(cards.contains { $0.emitter == .lint && $0.status == .open }) + #expect(cards.contains { $0.pattern == "utilize" && $0.lane == .mechanical }) + // Stats capture fired at the same invocation — both hooks, one seam. + let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8) + let matter = Post.frontmatter(of: onDisk) + #expect(matter["stats_captured"] != nil) + #expect(onDisk.contains("pass_state: Pass-1 Done")) + } +} diff --git a/docs/devlog/20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md b/docs/devlog/20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md new file mode 100644 index 0000000..c2bf06d --- /dev/null +++ b/docs/devlog/20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md @@ -0,0 +1,68 @@ +# Issue #6 — Native deslop lint in Swift (banned vocab + em-dash density as fix cards) + +> **Date:** 2026-10-30 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/6 (PRD S3.4, ships with M2) + +## Goal + +Deterministic style findings as fix cards without an engine round-trip: banned-vocab tiers and em-dash density computed in Swift at pass invocation, after First-Draft stats capture (S5.1); findings use the fix-card schema (ADR-0006) and render/play like any card (ask-before apply); the vocab tiers and em-dash budget ship as data, trivially editable without a recompile. + +## What Was Done + +- `Museion/DeslopLint.swift` (new, nonisolated): `Config`/`Tier`/`Phrase` Codable shape, `bundledConfig()` (bundled `Resources/deslop-lint.json`, missing/undecodable → silent no-op), `config(home:)` (`<home>/deslop-lint.json` wins when it exists AND decodes), `compute(body:config:)` (pure: one finding per phrase over its tier allowance, case-insensitive whole-word ICU match, anchor = first match case-preserved with exact-substring occurrence, em-dash density finding first when over budget, tiers by first-match position; mechanical lane for mapped replacements — case-matched to the anchor per ADR-0006 — demonstration otherwise), `emit(...)` (dedup vs OPEN cards → `FixCardStore.submit`, swallows every error — the stats-capture posture). +- `Museion/Resources/deslop-lint.json` (new): the deslop doctrine as data — Tier 1 ×68 / Tier 2 ×6 / budget 4, 13 mechanical mappings (the skill's verb swaps + #31). `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted (POS-ambiguous / character-name collision; add via Home override). +- `Museion/PostsModel.swift`: one hook in `runPass`, immediately after `captureFirstDraftStats`, before `runningPass = kind`. +- `MuseionTests/DeslopLintTests.swift` (new, @Suite, scenario header): exact finding set/order/copy over a known-sloppy draft, word boundaries, em-dash budget edges, config override/fallback/bundled-decode, store-level emit→dedup→close→re-emit loop incl. asserted pass-2 provenance, empty AND whitespace-phrase trust-boundary pin (the `— —` body is space-phrase bait — a plain body passes vacuously). +- `MuseionTests/PassRunTests.swift`: `DeslopLintWiringTests` — a pass invocation seeds lint cards AND `stats_*` keys at the one seam. +- `Museion/FixCardStore.swift` (audit fix): `submit` refuses a symlinked `cards/` dir before any write (promote's learnings posture; the lint auto-fires submit every Run Pass); pin in `MCPToolsTests`. +- DOX: `Museion/AGENTS.md` (DeslopLint entry, runPass seam, submit symlink guard), `MuseionTests/AGENTS.md` (test entries), `CHANGELOG.md`. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Bundled default + `<home>/deslop-lint.json` override (override REPLACES, no merge) | PRD: "trivially editable without a recompile". Replace-not-merge is predictable; a malformed override falls back to bundled, never fatal (lenient config posture). | +| One finding per phrase (not per occurrence), anchored at first match | N cards for N instances of the same word is palette noise; the count rides the problem string; re-runs re-card remaining instances after Apply/Skip closes the prior card. | +| Dedup vs OPEN cards only (pattern + quote + occurrence) | GLOSSARY Emitter contract (engine never re-cards a live lint finding); closed cards don't block → re-runs make progress. | +| Mapped replacements → mechanical lane (fix case-matches the anchor); unmapped → demonstration | ADR-0006: mechanical = pure function of anchor + fixed tables (mappings are the skill's own verb swaps/#31); case named among mechanical transforms. | +| Em-dash budget 4, anchor = first `—`, demonstration lane | Skill: "3-4 per article is plenty, 1-2 fine"; density is judgment (comma vs period vs restructure), never auto-applied. | +| Rank order: em-dash density, then Tier 1, then Tier 2 (by first-match position) | The em-dash habit is the issue's flagship prompt-resistant tell; deterministic order under the 10-card submit ceiling keeps the ranked head. | +| Lint the raw body (no fence/heading stripping) | ponytail-marked: the engine does context judgment; strip contexts if false positives bite. | +| Omitted `key`/`landscape`/`highlight`/bare `underscore` from default data | POS-ambiguous / collides with the character name — a word-boundary regex false-positives; engine-side judgment, add via override. | +| Deferred: >500-phrase override bound, negative-budget clamp | Same-privilege self-inflicted lows; `ponytail:` ceiling comment on `config(home:)` names the fix if a hand-edit ever bites. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| A hand-edited `{"phrase": ""}` override would kill the ENTIRE lint silently | Empty regex matches everywhere → empty-quote anchor → submit's whole-call validation throws → `try?` swallows → zero cards every pass | Empty-phrase guard in `scan()` (first review round) | +| Whitespace-only phrase (`" "`) still killed the whole lint | My guard checked `isEmpty`; submit's validation TRIMS — the two definitions of "empty" disagreed | Guard widened to trimmed-emptiness; pin's body carries `— —` so the space-phrase actually matches (a plain body passes vacuously) | +| `Utilize` at sentence start would Apply to lowercase `use` | Mechanical fix was the raw replacement; ADR-0006 names case among mechanical transforms | Fix case-matches the anchor's first letter | +| Pre-planted `cards/` symlink = arbitrary-directory JSON drop, auto-triggered every Run Pass | `submit` created/wrote through `cards/` without a symlink check — theoretical when only the engine's MCP call reached it, practical once the lint auto-fired it | Promote's 5-line symlink refusal copied onto submit; pinned | +| Flip-cycle restore dropped the `pass:` argument label | Python restore anchored on the ternary expression, marker check matched the expression without the label | One-label patch; caught by the suite's compile error (never a silent green) | +| One full-suite run failed `EditorSessionTests/debounce flushes after idle` | Documented #30 load flake — passes in isolation, passes on the idle definitive run, zero diff overlap | No fix needed; re-ran per the learning's protocol | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/DeslopLint.swift` | new — the lint (config load, compute, dedup+emit) | +| `Museion/Resources/deslop-lint.json` | new — the tier/budget data (bundled default) | +| `Museion/PostsModel.swift` | +6 — the runPass hook after stats capture | +| `Museion/FixCardStore.swift` | +8 — submit refuses a symlinked cards/ dir | +| `MuseionTests/DeslopLintTests.swift` | new — 7 pins (compute, config, emit loop) | +| `MuseionTests/PassRunTests.swift` | +32 — the invocation wiring pin | +| `MuseionTests/MCPToolsTests.swift` | +14 — the symlinked-cards submit pin | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `CHANGELOG.md` | DOX pass | + +## Open Items & Next Steps + +- [ ] Deferred visibly: >500-phrase override bound + negative `emDashBudget` clamp (`ponytail:` comment on `config(home:)`) — add if a hand-edit ever bites +- [ ] Accepted-cosmetic: intra-batch duplicate phrases in one hand-edited tier yield duplicate cards from one emit (next re-run dedups) +- [ ] Accepted-cosmetic: em-dash card anchors the first `—` — a still-over-budget re-run is deduped while that card stays open (demonstration lane, no apply risk) +- [ ] S3.4 is complete; M2 continues with the remaining map items + +--- + +*Log written by write-log skill. Verification cited: full suite 489/489 passed (xcresult-verified), swiftformat 0/98, swiftlint no new violation class.* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index e1ccc86..a922907 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa <!-- write-log: full-index --> | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-30 | issue | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | #6 native deslop lint: banned-vocab tiers + em-dash budget as data, emitter-lint cards at pass invocation; audit fixes — 489 tests | | 2026-10-30 | issue | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) | #1 prompt-end constraints: ACP audit, draft-first-rules-last persona pin, layout factsheet, real-run verify | | 2026-10-28 | issue | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | Pass engines on-demand per profile, transient transcripts, chat restart deferred mid-turn, missing-key Run Pass — 2 race fixes | | 2026-10-27 | issue | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | Profiles S3: settings write path (config set + .env), Test Connection probe, three dogfood rounds, three-reviewer audit |