diff --git a/AGENTS.md b/AGENTS.md index fc43bab..18da96a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (5820 symbols, 23635 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** (5834 symbols, 24313 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). @@ -197,6 +197,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-03 | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | | 2026-11-03 | [20261103-issue144-library-search-across-titles-and-bodies_log.md](docs/devlog/20261103-issue144-library-search-across-titles-and-bodies_log.md) | | 2026-11-03 | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](docs/devlog/20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | | 2026-11-03 | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](docs/devlog/20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) | @@ -206,5 +207,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](docs/devlog/20261031-issue32-m4-trend-view-s5-2_log.md) | | 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](docs/devlog/20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | | 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](docs/devlog/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](docs/devlog/20261030-issue1-verify-style-constraints-prompt-end_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 16e4c91..dde2294 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -31,7 +31,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `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). - `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue. - `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `![alt](assets/…)` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `![alt]()` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploads (Micro.blog keeps both copies; dedup via `q=source` is v2's call). **`MicropubPublishSheet.swift`** — the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain; `Send Again` re-drafts (the piece changed post-draft) and overwrites the remembered URL; `.onAppear` seeds from the piece's `micropubURL` so a draft from an earlier session still publishes. -- `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; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `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. **#122 Blind Read:** `blindRead(home:mentor:)` (file-scope extension) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#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). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). **#34 (S6.2):** the send first routes through the private `uploadIllustrations` rail (same file) whenever the body carries asset illustration refs — floor + pre-flight + `q=config` + one upload per PNG — then hands `Micropub.sendDraft` the wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** 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; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `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 `extension PostsModel` in PostsModelOutline.swift (#146). 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 the Convert extension (PostsModelOutline.swift, #146). 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 PostsModelPasses.swift (#146): 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. **#122 Blind Read:** `blindRead(home:mentor:)` (PostsModelPasses.swift, #146) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#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). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). **#34 (S6.2):** the send first routes through the private `uploadIllustrations` rail (same file) whenever the body carries asset illustration refs — floor + pre-flight + `q=config` + one upload per PNG — then hands `Micropub.sendDraft` the wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). - `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). diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 6e49b3a..d189f08 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -8,6 +8,10 @@ // the same rescan: one path. // #108: project targeting + the move/archive/restore ops behind the // variant-B library and the Archive pane. +// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in +// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching +// + rescan sit in the file-scope watcher extension below (type-body +// ceiling). // import CoreServices @@ -88,14 +92,17 @@ final class PostsModel { private(set) var posts: [Post] = [] /// The selected Post's id; nil = nothing selected (empty editor). - private(set) var selectedPostID: String? + /// #146: setter internal — the split-out domain extensions set it. + var selectedPostID: String? /// The in-memory draft for New Post (#62): no folder until first save. - private(set) var draft: PostDraft? + /// #146: setter internal — the split-out domain extensions set it. + var draft: PostDraft? /// #19: the open post's editing session; nil while a draft is open or /// nothing is selected. - private(set) var session: EditorSession? + /// #146: setter internal — the split-out domain extensions set it. + var session: EditorSession? /// #92: the external buffer's guest slot — one at a time, transient per /// launch. Takes the editor column; opening a Post or draft dismisses it @@ -109,7 +116,8 @@ final class PostsModel { /// #108: the explicit target for the NEXT new piece — set by New Project /// once the folder exists; outranks selection. Cleared when the draft /// lands (saveDraft) or the ask is canceled. - private(set) var pendingProject: String? + /// #146: setter internal — the split-out domain extensions set it. + var pendingProject: String? /// #108: File ▸ New Project… stages its ask here — commands can't /// present sheets, so the model holds the flag and WorkspaceView @@ -120,40 +128,49 @@ final class PostsModel { /// lags one rescan (the FSEvents window), so the freshly-opened /// session can't read its type from the scan yet and would flash the /// prose editor. True only between saveDraft and the next selection. - private(set) var lastDraftWasOutline = false + /// #146: setter internal — the split-out domain extensions set it. + var lastDraftWasOutline = false /// #111 (S7): a mixed-content outline piece whose open is held for the /// guard ask. Non-nil = the ask is up (no session — the ask presents /// over an empty editor); cleared by any answer. - private(set) var outlineGuardPieceID: String? + /// #146: setter internal — the split-out domain extensions set it. + var outlineGuardPieceID: String? /// #111 (S7): the piece the guard's Prose answer opened in prose mode — /// a routing override with lastDraftWasOutline's exact lifecycle (dies /// on the next open/draft/guest; the rescan lag window is covered). - private(set) var proseOverridePostID: String? + /// #146: setter internal — the split-out domain extensions set it. + var proseOverridePostID: String? /// #114 (S4): the staged Convert to Post ask (row menu → sheet). The /// ask targets a piece id, not the session — it survives background /// selects; the sheet is modal in its window, and the convert itself /// re-derives everything (flush, disk read) at answer time. - private(set) var pendingConversion: PendingConversion? + /// #146: setter internal — the split-out domain extensions set it. + var pendingConversion: PendingConversion? /// #24 (S3.1): the pass currently streaming over the open piece — /// one at a time; nil = idle. Drives the pass bar's Run ↔ Cancel swap. - private(set) var runningPass: PassKind? + /// #146: setter internal — the split-out domain extensions set it. + var runningPass: PassKind? /// #122: the Blind Read currently judging over the open piece — /// one at a time beside runningPass; false = idle. Shares the pass /// bar's Run ↔ Cancel swap. - private(set) var runningBlindRead = false + /// #146: setter internal — the split-out domain extensions set it. + var runningBlindRead = false /// #122: does the OPEN piece have a Pass-start snapshot on disk (the /// Blind Read's comparison base)? Refreshed with the cards at the /// rescan tail and open transitions. - private(set) var openPieceHasSnapshot = false + /// #146: setter internal — the split-out domain extensions set it. + var openPieceHasSnapshot = false /// #23 (M2, slice 3): the OPEN piece's stored fix cards /// (`/cards/*.json`, newest-first) — what any MCP client /// submitted; nil session (draft/guest/nothing) shows none. - private(set) var openPieceCards: [FixCardStore.StoredFixCard] = [] + /// #146: setter internal — the split-out domain extensions set it. + var openPieceCards: [FixCardStore.StoredFixCard] = [] /// Last failed-op message surfaced in the editor (nil = clean). - private(set) var lastError: String? + /// #146: setter internal — the split-out domain extensions set it. + var lastError: String? /// Home the watcher is bound to; also the rescan target. private var watchedHome: URL? private var watcher = PostsWatcher() @@ -173,72 +190,6 @@ final class PostsModel { Task { await rescan() } } - // MARK: Watcher (#61) - - private func startWatching(home: URL) { - guard watchedHome != home else { return } - watchedHome = home - let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) } - for root in roots { - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - } - watcher.onEvent = { [weak self] in Task { await self?.rescan() } } - watcher.start(urls: roots) - } - - /// Off-main scan; keeps selection valid across the fresh refresh. - /// FSEvents already coalesces bursts within its 0.5 s latency window — - /// no second debounce on top. - private func rescan() async { - guard let home = watchedHome else { return } - // Scan + the #67 disk read both run off-main (a synced large post.md - // must never stall the UI on a watcher burst). - let openPostID = session?.postID - // #114 audit: identity, not id — a same-id reopen (convert/restore/ - // move) must not receive the OLD session's stale disk text as a - // spurious #67 conflict. - let openSession = session - let scanMemo = scanCache // detached capture, not a property read - let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { - let posts = Post.scan(home: home, cache: scanMemo) - let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } - return (posts, disk) - }.value - guard !Task.isCancelled else { return } - // #143: @Observable invalidates on assignment regardless of equality — - // skip the no-op so panes don't regroup on our own autosave echoes. - if scanned != posts { - posts = scanned - } - if let id = selectedPostID, !posts.contains(where: { $0.id == id }), - // Stale-scan guard (#137 suite find): the snapshot can PREDATE the - // current selection — bind's initial rescan (detached scan over the - // empty tree) can land its continuation after a select its scan never - // saw, "vanishing" a piece that exists. Disk is the truth for - // vanished; a stale snapshot must not kill a live session (teardown - // cancels the debounce — unflushed edits would die with it). - // #137 audit (finish): a scan that outlived a Home repoint speaks - // for the OLD tree — never let it kill a session selected under - // the NEW home (the id is missing from the old snapshot by - // construction); the next rescan under the new home owns it. - watchedHome == home, PostStore.folder(of: id, home: home) == nil - { - selectedPostID = nil // the post vanished (deleted in Finder or here) - if let open = session, open.postID == id { - open.teardown(flushFirst: false) // post is gone; cancel the debounce - session = nil - } - } - // #67: watcher echo check on the open post — equality against the - // session's lastFlushedText suppresses our own writes exactly. - if openSession === session, let openDiskText { - openSession?.diskDidChange(diskText: openDiskText) - } - // #23: the open piece's stored fix cards ride the same rescan — - // the watcher fires on /cards/ writes too. - refreshCards(home: home) - } - // MARK: Own ops (route through the same rescan, #61) // ponytail: the PostStore calls here run on MainActor — small single-file @@ -300,7 +251,8 @@ final class PostsModel { /// #92: dismiss the external guest slot, flushing pending edits (the /// guest is always leaving for somewhere — same posture as post /// selection change). - private func dismissExternal() { + /// #146: internal — the split-out domain extensions dismiss too. + func dismissExternal() { externalSession?.teardown(flushFirst: true) externalSession = nil externalWatcher.stop() @@ -680,448 +632,77 @@ final class PostsModel { Task { await rescan() } } - private func wireSession() { + /// #146: internal — the split-out domain extensions wire sessions too. + func wireSession() { let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message } session?.onError = route externalSession?.onError = route } } -// MARK: Mixed-content outline guard (#111, S7) +// MARK: Watcher (#61) — #146: file-scope extension (type_body_length) extension PostsModel { - /// A `type: outline` piece that parses with dropped prose — the guard's - /// target. The old session already ended by the time this runs; its - /// flush was prose-mode, so it couldn't drop anything. - /// Type: the scan's word when the list knows it (archive pane opens, - /// app-start selection), the frontmatter's word during the rescan lag - /// (the same window lastDraftWasOutline covers) — ONE disk read derives - /// both. No watched home yet (pre-bind) = post: nothing to guard. - private func isGuardedOutline(_ id: String, home: URL) -> Bool { - guard let dir = PostStore.folder(of: id, home: home), - let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) - else { return false } - let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type { - known - } else { - Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post + private func startWatching(home: URL) { + guard watchedHome != home else { return } + watchedHome = home + let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) } + for root in roots { + try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) } - return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body) + watcher.onEvent = { [weak self] in Task { await self?.rescan() } } + watcher.start(urls: roots) } - /// #111 (S7): guard answers. Prose = safe open in prose mode (the - /// outliner never mounts, nothing drops); Outline = explicit consent, - /// opens the outliner (saves normalize/drop as today). Cancel = back - /// out (no session); the piece stays guarded on the next open. - func openGuardedOutlineInProse(home: URL) { - guard let id = outlineGuardPieceID else { return } - outlineGuardPieceID = nil - proseOverridePostID = id // routing: prose until the next open - openUnguarded(id, home: home) - } - - func openGuardedOutlineAsOutline(home: URL) { - guard let id = outlineGuardPieceID else { return } - outlineGuardPieceID = nil - openUnguarded(id, home: home) - } - - /// #111 (S7): the ask's Cancel — the held open dies (no session opens, - /// nothing stays selected over the empty editor). - func cancelOutlineGuard() { - outlineGuardPieceID = nil - if session == nil { - selectedPostID = nil + /// Off-main scan; keeps selection valid across the fresh refresh. + /// FSEvents already coalesces bursts within its 0.5 s latency window — + /// no second debounce on top. + /// #146: internal — the split-out domain extensions trigger rescans. + func rescan() async { + guard let home = watchedHome else { return } + // Scan + the #67 disk read both run off-main (a synced large post.md + // must never stall the UI on a watcher burst). + let openPostID = session?.postID + // #114 audit: identity, not id — a same-id reopen (convert/restore/ + // move) must not receive the OLD session's stale disk text as a + // spurious #67 conflict. + let openSession = session + let scanMemo = scanCache // detached capture, not a property read + let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { + let posts = Post.scan(home: home, cache: scanMemo) + let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } + return (posts, disk) + }.value + guard !Task.isCancelled else { return } + // #143: @Observable invalidates on assignment regardless of equality — + // skip the no-op so panes don't regroup on our own autosave echoes. + if scanned != posts { + posts = scanned } - } - - /// #111 (S7): the open with the guard passed (either answer or a clean - /// parse) — the plain select body. No re-check: the answer is the - /// explicit choice the ruling requires. - private func openUnguarded(_ id: String, home: URL) { - dismissExternal() - if let session, session.postID != id { - session.teardown(flushFirst: true) - } - session = id == session?.postID ? session : EditorSession(postID: id, home: home) - draft = nil - pendingProject = nil - lastDraftWasOutline = false - outlineGuardPieceID = nil // the open displaces any held ask - selectedPostID = id - wireSession() - refreshCards(home: home) // #23: the newly opened piece's cards, now - } -} - -// MARK: Convert to Post (#114, S4) - -/// The staged ask: which piece, and whether the headings ladder would -/// drop prose lines (mixed content — the sheet warns, verbatim keeps -/// everything). -struct PendingConversion { - let id: String - let lossy: Bool -} - -extension PostsModel { - /// #114 (S4): row-menu entry — stage the ask. Outline pieces only. - /// The open session's text is the truth when the piece is open — disk - /// lags the debounce, and a stale-clean read would drop the warning - /// for prose typed since the last flush (#114 audit). - func stageConversion(_ post: Post, home: URL) { - guard post.type == .outline else { return } - let body: String = if let session, session.postID == post.id { - session.text - } else { - PostStore.readBody(id: post.id, home: home) ?? "" - } - pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body)) - } - - /// #114 (S4): the ask's Cancel (binding dismissal). - func cancelConversion() { - pendingConversion = nil - } - - /// #114 (S4): the answer. Flush-first when the piece is open (the - /// transform reads disk), flip `type` + transform the body once, then - /// reopen the session routed to prose — proseOverridePostID covers the - /// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that - /// isn't open just converts; nothing else moves. One-way in v1. - func convertToPost(headingsLadder: Bool, home: URL) { - guard let pending = pendingConversion else { return } - pendingConversion = nil - guard flushOrAbort(pending.id) else { return } - do { - // The sheet's warning covered the STAGED body. If the - // answer-time body went lossy behind the ask (foreign write, - // late edit) and the writer was never warned, Headings would - // drop unconsented prose — abort, nothing converted (#114 audit). - if headingsLadder, !pending.lossy, - let body = PostStore.readBody(id: pending.id, home: home), - OutlineTree.parsesWithLoss(body) - { - lastError = "The outline changed since the sheet opened — nothing was converted." - return - } - try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home) - if session?.postID == pending.id { - session?.teardown(flushFirst: false) // flushOrAbort already wrote + // Stale-scan guard (#137 suite find): the snapshot can PREDATE the + // current selection — bind's initial rescan (detached scan over the + // empty tree) can land its continuation after a select its scan never + // saw, "vanishing" a piece that exists. Disk is the truth for + // vanished; a stale snapshot must not kill a live session (teardown + // cancels the debounce — unflushed edits would die with it). + // #137 audit (finish): a scan that outlived a Home repoint speaks + // for the OLD tree — never let it kill a session selected under + // the NEW home (the id is missing from the old snapshot by + // construction); the next rescan under the new home owns it. + if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil { + selectedPostID = nil // the post vanished (deleted in Finder or here) + if let open = session, open.postID == id { + open.teardown(flushFirst: false) // post is gone; cancel the debounce session = nil - proseOverridePostID = pending.id - openUnguarded(pending.id, home: home) - } - if outlineGuardPieceID == pending.id { - // Multi-window: the held #111 ask targets an outline that no - // longer is — dismiss it as a cancel (the ask's own teardown). - cancelOutlineGuard() - } - lastError = nil - Task { await rescan() } - } catch { - lastError = error.localizedDescription - } - } -} - -// MARK: Pass orchestration (#24, S3.1) - -extension PostsModel { - /// #24 (S3.1): run one structured critique pass over the OPEN piece. - /// The pre-pass snapshot lands before the engine sees the text; the - /// minimal stub (PassContext) crosses the bridge and the critique - /// streams into the mentor pane. Pass State advances ONLY when the - /// engine's turn ends normally — never on cancel, refusal, or crash, - /// and never when fix cards resolve. Passes run in any order - /// (advancePassState is monotonic). - func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async { - guard runningPass == nil, !runningBlindRead else { - lastError = "A pass is already running." - return - } - guard !mentor.isStreaming else { - lastError = "The mentor is mid-reply — stop it or wait." - return - } - guard mentor.phase.isReady else { - lastError = "The mentor engine isn't ready — wait for it or restart it." - return - } - // #137 (S4): the pass profile's provider has no key — name it and - // point at Settings, BEFORE the open-piece guard so nothing writes - // to disk (not even the pre-pass snapshot). - if case let .missingKey(label) = mentor.readiness(for: kind) { - lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys." - return - } - // The pass targets the open Piece: a never-saved draft has no - // folder, and the external guest and a held #111 guard ask are - // not Pieces. - guard let session, - let id = session.postID, - id == selectedPostID, - draft == nil, - externalSession == nil, - outlineGuardPieceID == nil - else { - lastError = "Open a saved post to run a pass." - return - } - guard flushOrAbort(id) else { return } // the engine reads disk - do { - try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home) - } catch { - lastError = error.localizedDescription - return - } - // #31 (S5.1): unaided-first-draft stats — fires at the invocation, - // before the engine sees anything; eligibility (writer origin, First - // 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/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 - defer { runningPass = nil } - let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch) - // #137: the pass runs on its OWN one-shot engine and streams into the - // transient pass transcript — never rostered (#129, ADR-0014). - let outcome = await mentor.runPass(kind: kind, stub: stub, pieceTitle: title(of: id)) - guard case let .ended(stopReason) = outcome, stopReason != "refusal" else { - return // cancelled / refused / failed — the transcript tells the story - } - do { - _ = try PostStore.advancePassState(id: id, kind: kind, home: home) - lastError = nil - Task { await rescan() } // the library regroups by Pass State - } catch { - lastError = error.localizedDescription - } - } - - /// #24 (S3.1): the pass bar's Cancel — the existing session/cancel - /// rail stops the agent; nothing advances (runPass reads .cancelled). - /// #122: the Blind Read shares the rail — Cancel ends either run. - func cancelPass(mentor: MentorSessionModel) { - guard runningPass != nil || runningBlindRead else { return } - mentor.stopStreaming() - } -} - -// MARK: Blind Read (#122) - -extension PostsModel { - /// #122: run one Blind Read over the OPEN piece — the current document - /// vs the newest Pass-start snapshot, judged blind by a fresh session - /// of the museion profile. Advisory-only (decision #120): no Pass State - /// advance, no cards, no Learnings — the verdict and the reveal live in - /// the transient transcript and die with it. The writer stays judge of - /// record. - func blindRead(home: URL, mentor: MentorSessionModel) async { - guard runningPass == nil else { - lastError = "A pass is already running." - return - } - guard !runningBlindRead else { - lastError = "A Blind Read is already running." - return - } - guard !mentor.isStreaming else { - lastError = "The mentor is mid-reply — stop it or wait." - return - } - guard mentor.phase.isReady else { - lastError = "The mentor engine isn't ready — wait for it or restart it." - return - } - // Same open-piece rule as a pass: the read judges ONE saved piece. - guard let session, - let id = session.postID, - id == selectedPostID, - draft == nil, - externalSession == nil, - outlineGuardPieceID == nil - else { - lastError = "Open a saved post to run a Blind Read." - return - } - guard flushOrAbort(id) else { return } - guard let base = PostStore.latestPassSnapshot(id: id, home: home) else { - lastError = "No Pass snapshot yet — run a Pass first." - return - } - let current = session.text - guard current != base.body else { - lastError = "No edits since the Pass started — the Blind Read judges the current document against the Pass-start snapshot." - return - } - // House posture (runPass's success path): the run is firing — a - // stale guard refusal no longer owns the error strip. - lastError = nil - runningBlindRead = true - defer { runningBlindRead = false } - // Randomized order kills position bias (#120's flagged default); - // the reveal names the mapping only after the verdict. - let snapshotFirst = Bool.random() - _ = await mentor.runBlindRead( - prompt: BlindRead.prompt(snapshot: base.body, current: current, snapshotFirst: snapshotFirst), - pieceTitle: title(of: id), - reveal: BlindRead.reveal(kind: base.kind, snapshotFirst: snapshotFirst), - ) - // Advisory-only: nothing to advance or record — the outcome row in - // the transient transcript IS the deliverable. - } -} - -// MARK: Stored fix cards (#23, M2 slice 3) - -extension PostsModel { - /// #23 (M2, slice 3): re-derive `openPieceCards` from the OPEN piece's - /// `/cards/` (FixCardStore.scan — any MCP client's submissions, - /// newest-first; archive pieces resolve through folder(of:) too). The - /// nil-session rule clears: draft, external guest, held guard ask, - /// nothing open → []. Called at the rescan tail and the open - /// transitions — the piece-roots watcher already fires on cards/ writes. - /// #122: the same pass also derives `openPieceHasSnapshot` (the Blind - /// Read's base) — one detached read of the open piece's disk facts. - func refreshCards(home: URL) { - guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else { - openPieceCards = [] - openPieceHasSnapshot = false - return - } - // Plain disk reads re-run on every watcher burst (typing retriggers - // rescan) — keep the I/O off MainActor, same posture as rescan's - // Post.scan. The id re-check on hop-back drops a scan that raced a - // piece switch. - Task.detached { [weak self] in - let cards = FixCardStore.scan(pieceURL: folder) - let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil - await MainActor.run { [weak self] in - guard let self, session?.postID == id else { return } - openPieceCards = cards - openPieceHasSnapshot = hasSnapshot } } - } - - /// The piece's display title (fallback: id) — runPass, the pass bar, - /// and the Fix Cards palette share this one lookup (review: three - /// hand-copies). - func title(of id: String) -> String { - posts.first(where: { $0.id == id })?.title ?? id - } -} - -// MARK: Fix Card apply/skip/done (#25, S3.2/S3.3) - -/// #25 (S3.2/S3.3): what Apply did — the edit landed, the anchor went -/// stale (no text touched, card flagged), or the operation refused with -/// a reason for the error strip. -enum FixCardApplyOutcome: Equatable { - case applied - case stale - case refused(String) -} - -extension PostsModel { - /// #25 (S3.2/S3.3): Apply a mechanical card — the blocking ask already - /// happened in the UI (ask-before trust level); this lands the edit. - /// Dirty buffer lands first (Apply reads live text); an unanswered #67 - /// conflict aborts here with the existing wording. A stale anchor - /// flags the card and touches no text. A failed close after a landed - /// edit is reported via lastError, never silent. - @discardableResult - func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome { - guard card.status == .open else { return .refused("card already closed") } - guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") } - guard let session, let postID = session.postID else { - return .refused("open the piece to work its cards") - } - guard flushOrAbort(postID) else { return .refused(lastError ?? "edits did not land") } - guard let newText = FixCardStore.appliedText(of: card, in: session.text) else { - // Stale anchor — the Post changed after the card was issued: - // persist the honest flag, select and change nothing. A failed - // flag write surfaces like the applied path's — never silent. - do { - _ = try FixCardStore.close( - pieceURL: session.passPieceURL, id: card.id, status: .open, anchorStatus: .stale, - ) - } catch { - lastError = "card close failed: \(error.localizedDescription)" - } - refreshCards(home: home) - return .stale - } - guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") } - closeCard(card, status: .applied, home: home) - return .applied - } - - /// #25 (S3.3): Skip — not this instance. Closes the card recording - /// NOTHING beyond the status flip (CONTEXT.md). - func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) { - closeCard(card, status: .skipped, home: home) - } - - /// #25 (S3.3): Done — the writer rewrote the span themselves. Same - /// flip, different terminal. - func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) { - closeCard(card, status: .done, home: home) - } - - private func closeCard( - _ card: FixCardStore.StoredFixCard, - status: FixCardStore.StoredFixCard.Status, - home: URL, - ) { - guard let session else { - lastError = "open the piece to work its cards" - return - } - do { - _ = try FixCardStore.close(pieceURL: session.passPieceURL, id: card.id, status: status) - } catch { - lastError = "card close failed: \(error.localizedDescription)" + // #67: watcher echo check on the open post — equality against the + // session's lastFlushedText suppresses our own writes exactly. + if openSession === session, let openDiskText { + openSession?.diskDidChange(diskText: openDiskText) } + // #23: the open piece's stored fix cards ride the same rescan — + // the watcher fires on /cards/ writes too. refreshCards(home: home) } } - -// MARK: Fix Card promote (#26, S4.1/S4.3) - -/// #26 (S4.1): what Promote did — the Learning landed, or the operation -/// refused with a reason (the ask sheet shows it; lastError carries it). -enum FixCardPromoteOutcome: Equatable { - case promoted - case refused(String) -} - -extension PostsModel { - /// #26 (S4.1/S4.3): Promote a card into ONE plain markdown Learning - /// under `/learnings/s/` — the writer's EXPLICIT - /// confirmation only (one confirm = one entry, never a repetition - /// counter; the store guarantees the one-stamp rule). Touches no text - /// and flushes nothing: this writes a Learning, not an edit. - @discardableResult - func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome { - guard card.promotedAt == nil else { return .refused("card already promoted") } - guard let session else { return .refused("open the piece to work its cards") } - do { - _ = try FixCardStore.promote(pieceURL: session.passPieceURL, card: card) - } catch { - lastError = "learning write failed: \(error.localizedDescription)" - return .refused("learning write failed: \(error.localizedDescription)") - } - refreshCards(home: home) - return .promoted - } -} diff --git a/Museion/PostsModelCards.swift b/Museion/PostsModelCards.swift new file mode 100644 index 0000000..586d740 --- /dev/null +++ b/Museion/PostsModelCards.swift @@ -0,0 +1,155 @@ +// +// PostsModelCards.swift +// Museion +// +// #146: the fix-card extensions of PostsModel — stored-card surfacing +// (#23), apply/skip/done (#25, S3.2/S3.3), and promote (#26, S4.1) — +// moved from PostsModel.swift (file-length ceiling), code unchanged. +// + +import Foundation + +// MARK: Stored fix cards (#23, M2 slice 3) + +extension PostsModel { + /// #23 (M2, slice 3): re-derive `openPieceCards` from the OPEN piece's + /// `/cards/` (FixCardStore.scan — any MCP client's submissions, + /// newest-first; archive pieces resolve through folder(of:) too). The + /// nil-session rule clears: draft, external guest, held guard ask, + /// nothing open → []. Called at the rescan tail and the open + /// transitions — the piece-roots watcher already fires on cards/ writes. + /// #122: the same pass also derives `openPieceHasSnapshot` (the Blind + /// Read's base) — one detached read of the open piece's disk facts. + func refreshCards(home: URL) { + guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else { + openPieceCards = [] + openPieceHasSnapshot = false + return + } + // Plain disk reads re-run on every watcher burst (typing retriggers + // rescan) — keep the I/O off MainActor, same posture as rescan's + // Post.scan. The id re-check on hop-back drops a scan that raced a + // piece switch. + Task.detached { [weak self] in + let cards = FixCardStore.scan(pieceURL: folder) + let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil + await MainActor.run { [weak self] in + guard let self, session?.postID == id else { return } + openPieceCards = cards + openPieceHasSnapshot = hasSnapshot + } + } + } + + /// The piece's display title (fallback: id) — runPass, the pass bar, + /// and the Fix Cards palette share this one lookup (review: three + /// hand-copies). + func title(of id: String) -> String { + posts.first(where: { $0.id == id })?.title ?? id + } +} + +// MARK: Fix Card apply/skip/done (#25, S3.2/S3.3) + +/// #25 (S3.2/S3.3): what Apply did — the edit landed, the anchor went +/// stale (no text touched, card flagged), or the operation refused with +/// a reason for the error strip. +enum FixCardApplyOutcome: Equatable { + case applied + case stale + case refused(String) +} + +extension PostsModel { + /// #25 (S3.2/S3.3): Apply a mechanical card — the blocking ask already + /// happened in the UI (ask-before trust level); this lands the edit. + /// Dirty buffer lands first (Apply reads live text); an unanswered #67 + /// conflict aborts here with the existing wording. A stale anchor + /// flags the card and touches no text. A failed close after a landed + /// edit is reported via lastError, never silent. + @discardableResult + func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome { + guard card.status == .open else { return .refused("card already closed") } + guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") } + guard let session, let postID = session.postID else { + return .refused("open the piece to work its cards") + } + guard flushOrAbort(postID) else { return .refused(lastError ?? "edits did not land") } + guard let newText = FixCardStore.appliedText(of: card, in: session.text) else { + // Stale anchor — the Post changed after the card was issued: + // persist the honest flag, select and change nothing. A failed + // flag write surfaces like the applied path's — never silent. + do { + _ = try FixCardStore.close( + pieceURL: session.passPieceURL, id: card.id, status: .open, anchorStatus: .stale, + ) + } catch { + lastError = "card close failed: \(error.localizedDescription)" + } + refreshCards(home: home) + return .stale + } + guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") } + closeCard(card, status: .applied, home: home) + return .applied + } + + /// #25 (S3.3): Skip — not this instance. Closes the card recording + /// NOTHING beyond the status flip (CONTEXT.md). + func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) { + closeCard(card, status: .skipped, home: home) + } + + /// #25 (S3.3): Done — the writer rewrote the span themselves. Same + /// flip, different terminal. + func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) { + closeCard(card, status: .done, home: home) + } + + private func closeCard( + _ card: FixCardStore.StoredFixCard, + status: FixCardStore.StoredFixCard.Status, + home: URL, + ) { + guard let session else { + lastError = "open the piece to work its cards" + return + } + do { + _ = try FixCardStore.close(pieceURL: session.passPieceURL, id: card.id, status: status) + } catch { + lastError = "card close failed: \(error.localizedDescription)" + } + refreshCards(home: home) + } +} + +// MARK: Fix Card promote (#26, S4.1/S4.3) + +/// #26 (S4.1): what Promote did — the Learning landed, or the operation +/// refused with a reason (the ask sheet shows it; lastError carries it). +enum FixCardPromoteOutcome: Equatable { + case promoted + case refused(String) +} + +extension PostsModel { + /// #26 (S4.1/S4.3): Promote a card into ONE plain markdown Learning + /// under `/learnings/s/` — the writer's EXPLICIT + /// confirmation only (one confirm = one entry, never a repetition + /// counter; the store guarantees the one-stamp rule). Touches no text + /// and flushes nothing: this writes a Learning, not an edit. + @discardableResult + func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome { + guard card.promotedAt == nil else { return .refused("card already promoted") } + guard let session else { return .refused("open the piece to work its cards") } + do { + _ = try FixCardStore.promote(pieceURL: session.passPieceURL, card: card) + } catch { + lastError = "learning write failed: \(error.localizedDescription)" + return .refused("learning write failed: \(error.localizedDescription)") + } + refreshCards(home: home) + return .promoted + } +} diff --git a/Museion/PostsModelOutline.swift b/Museion/PostsModelOutline.swift new file mode 100644 index 0000000..fe1074e --- /dev/null +++ b/Museion/PostsModelOutline.swift @@ -0,0 +1,149 @@ +// +// PostsModelOutline.swift +// Museion +// +// #146: the outline-domain extensions of PostsModel — the mixed-content +// guard (#111, S7) and Convert to Post (#114, S4) — moved from +// PostsModel.swift (file-length ceiling), code unchanged save the #114 +// guard unwrap (#142 posture). +// + +import Foundation + +// MARK: Mixed-content outline guard (#111, S7) + +extension PostsModel { + /// A `type: outline` piece that parses with dropped prose — the guard's + /// target. The old session already ended by the time this runs; its + /// flush was prose-mode, so it couldn't drop anything. + /// Type: the scan's word when the list knows it (archive pane opens, + /// app-start selection), the frontmatter's word during the rescan lag + /// (the same window lastDraftWasOutline covers) — ONE disk read derives + /// both. No watched home yet (pre-bind) = post: nothing to guard. + /// #146: internal — `select` (PostsModel.swift) asks the guard. + func isGuardedOutline(_ id: String, home: URL) -> Bool { + guard let dir = PostStore.folder(of: id, home: home), + let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) + else { return false } + let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type { + known + } else { + Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post + } + return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body) + } + + /// #111 (S7): guard answers. Prose = safe open in prose mode (the + /// outliner never mounts, nothing drops); Outline = explicit consent, + /// opens the outliner (saves normalize/drop as today). Cancel = back + /// out (no session); the piece stays guarded on the next open. + func openGuardedOutlineInProse(home: URL) { + guard let id = outlineGuardPieceID else { return } + outlineGuardPieceID = nil + proseOverridePostID = id // routing: prose until the next open + openUnguarded(id, home: home) + } + + func openGuardedOutlineAsOutline(home: URL) { + guard let id = outlineGuardPieceID else { return } + outlineGuardPieceID = nil + openUnguarded(id, home: home) + } + + /// #111 (S7): the ask's Cancel — the held open dies (no session opens, + /// nothing stays selected over the empty editor). + func cancelOutlineGuard() { + outlineGuardPieceID = nil + if session == nil { + selectedPostID = nil + } + } + + /// #111 (S7): the open with the guard passed (either answer or a clean + /// parse) — the plain select body. No re-check: the answer is the + /// explicit choice the ruling requires. + /// #146: internal — `select` (PostsModel.swift) routes its tail through + /// this one open body. + func openUnguarded(_ id: String, home: URL) { + dismissExternal() + if let session, session.postID != id { + session.teardown(flushFirst: true) + } + session = id == session?.postID ? session : EditorSession(postID: id, home: home) + draft = nil + pendingProject = nil + lastDraftWasOutline = false + outlineGuardPieceID = nil // the open displaces any held ask + selectedPostID = id + wireSession() + refreshCards(home: home) // #23: the newly opened piece's cards, now + } +} + +// MARK: Convert to Post (#114, S4) + +/// The staged ask: which piece, and whether the headings ladder would +/// drop prose lines (mixed content — the sheet warns, verbatim keeps +/// everything). +struct PendingConversion { + let id: String + let lossy: Bool +} + +extension PostsModel { + /// #114 (S4): row-menu entry — stage the ask. Outline pieces only. + /// The open session's text is the truth when the piece is open — disk + /// lags the debounce, and a stale-clean read would drop the warning + /// for prose typed since the last flush (#114 audit). + func stageConversion(_ post: Post, home: URL) { + guard post.type == .outline else { return } + let body: String = if let session, session.postID == post.id { + session.text + } else { + PostStore.readBody(id: post.id, home: home) ?? "" + } + pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body)) + } + + /// #114 (S4): the ask's Cancel (binding dismissal). + func cancelConversion() { + pendingConversion = nil + } + + /// #114 (S4): the answer. Flush-first when the piece is open (the + /// transform reads disk), flip `type` + transform the body once, then + /// reopen the session routed to prose — proseOverridePostID covers the + /// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that + /// isn't open just converts; nothing else moves. One-way in v1. + func convertToPost(headingsLadder: Bool, home: URL) { + guard let pending = pendingConversion else { return } + pendingConversion = nil + guard flushOrAbort(pending.id) else { return } + do { + // The sheet's warning covered the STAGED body. If the + // answer-time body went lossy behind the ask (foreign write, + // late edit) and the writer was never warned, Headings would + // drop unconsented prose — abort, nothing converted (#114 audit). + if headingsLadder, !pending.lossy, let body = PostStore.readBody(id: pending.id, home: home), OutlineTree.parsesWithLoss(body) { + lastError = "The outline changed since the sheet opened — nothing was converted." + return + } + try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home) + if session?.postID == pending.id { + session?.teardown(flushFirst: false) // flushOrAbort already wrote + session = nil + proseOverridePostID = pending.id + openUnguarded(pending.id, home: home) + } + if outlineGuardPieceID == pending.id { + // Multi-window: the held #111 ask targets an outline that no + // longer is — dismiss it as a cancel (the ask's own teardown). + cancelOutlineGuard() + } + lastError = nil + Task { await rescan() } + } catch { + lastError = error.localizedDescription + } + } +} diff --git a/Museion/PostsModelPasses.swift b/Museion/PostsModelPasses.swift new file mode 100644 index 0000000..8a3713e --- /dev/null +++ b/Museion/PostsModelPasses.swift @@ -0,0 +1,166 @@ +// +// PostsModelPasses.swift +// Museion +// +// #146: the engine-run extensions of PostsModel — pass orchestration +// (#24, S3.1) and the Blind Read (#122) — moved from PostsModel.swift +// (file-length ceiling), code unchanged. +// + +import Foundation + +// MARK: Pass orchestration (#24, S3.1) + +extension PostsModel { + /// #24 (S3.1): run one structured critique pass over the OPEN piece. + /// The pre-pass snapshot lands before the engine sees the text; the + /// minimal stub (PassContext) crosses the bridge and the critique + /// streams into the mentor pane. Pass State advances ONLY when the + /// engine's turn ends normally — never on cancel, refusal, or crash, + /// and never when fix cards resolve. Passes run in any order + /// (advancePassState is monotonic). + func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async { + guard runningPass == nil, !runningBlindRead else { + lastError = "A pass is already running." + return + } + guard !mentor.isStreaming else { + lastError = "The mentor is mid-reply — stop it or wait." + return + } + guard mentor.phase.isReady else { + lastError = "The mentor engine isn't ready — wait for it or restart it." + return + } + // #137 (S4): the pass profile's provider has no key — name it and + // point at Settings, BEFORE the open-piece guard so nothing writes + // to disk (not even the pre-pass snapshot). + if case let .missingKey(label) = mentor.readiness(for: kind) { + lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys." + return + } + // The pass targets the open Piece: a never-saved draft has no + // folder, and the external guest and a held #111 guard ask are + // not Pieces. + guard let session, + let id = session.postID, + id == selectedPostID, + draft == nil, + externalSession == nil, + outlineGuardPieceID == nil + else { + lastError = "Open a saved post to run a pass." + return + } + guard flushOrAbort(id) else { return } // the engine reads disk + do { + try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home) + } catch { + lastError = error.localizedDescription + return + } + // #31 (S5.1): unaided-first-draft stats — fires at the invocation, + // before the engine sees anything; eligibility (writer origin, First + // 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/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 + defer { runningPass = nil } + let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch) + // #137: the pass runs on its OWN one-shot engine and streams into the + // transient pass transcript — never rostered (#129, ADR-0014). + let outcome = await mentor.runPass(kind: kind, stub: stub, pieceTitle: title(of: id)) + guard case let .ended(stopReason) = outcome, stopReason != "refusal" else { + return // cancelled / refused / failed — the transcript tells the story + } + do { + _ = try PostStore.advancePassState(id: id, kind: kind, home: home) + lastError = nil + Task { await rescan() } // the library regroups by Pass State + } catch { + lastError = error.localizedDescription + } + } + + /// #24 (S3.1): the pass bar's Cancel — the existing session/cancel + /// rail stops the agent; nothing advances (runPass reads .cancelled). + /// #122: the Blind Read shares the rail — Cancel ends either run. + func cancelPass(mentor: MentorSessionModel) { + guard runningPass != nil || runningBlindRead else { return } + mentor.stopStreaming() + } +} + +// MARK: Blind Read (#122) + +extension PostsModel { + /// #122: run one Blind Read over the OPEN piece — the current document + /// vs the newest Pass-start snapshot, judged blind by a fresh session + /// of the museion profile. Advisory-only (decision #120): no Pass State + /// advance, no cards, no Learnings — the verdict and the reveal live in + /// the transient transcript and die with it. The writer stays judge of + /// record. + func blindRead(home: URL, mentor: MentorSessionModel) async { + guard runningPass == nil else { + lastError = "A pass is already running." + return + } + guard !runningBlindRead else { + lastError = "A Blind Read is already running." + return + } + guard !mentor.isStreaming else { + lastError = "The mentor is mid-reply — stop it or wait." + return + } + guard mentor.phase.isReady else { + lastError = "The mentor engine isn't ready — wait for it or restart it." + return + } + // Same open-piece rule as a pass: the read judges ONE saved piece. + guard let session, + let id = session.postID, + id == selectedPostID, + draft == nil, + externalSession == nil, + outlineGuardPieceID == nil + else { + lastError = "Open a saved post to run a Blind Read." + return + } + guard flushOrAbort(id) else { return } + guard let base = PostStore.latestPassSnapshot(id: id, home: home) else { + lastError = "No Pass snapshot yet — run a Pass first." + return + } + let current = session.text + guard current != base.body else { + lastError = "No edits since the Pass started — the Blind Read judges the current document against the Pass-start snapshot." + return + } + // House posture (runPass's success path): the run is firing — a + // stale guard refusal no longer owns the error strip. + lastError = nil + runningBlindRead = true + defer { runningBlindRead = false } + // Randomized order kills position bias (#120's flagged default); + // the reveal names the mapping only after the verdict. + let snapshotFirst = Bool.random() + _ = await mentor.runBlindRead( + prompt: BlindRead.prompt(snapshot: base.body, current: current, snapshotFirst: snapshotFirst), + pieceTitle: title(of: id), + reveal: BlindRead.reveal(kind: base.kind, snapshotFirst: snapshotFirst), + ) + // Advisory-only: nothing to advance or record — the outcome row in + // the transient transcript IS the deliverable. + } +} diff --git a/docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md b/docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md new file mode 100644 index 0000000..94a54a6 --- /dev/null +++ b/docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md @@ -0,0 +1,67 @@ +# #146: PostsModel.swift back under the lint ceilings — extensions split + class-body move + +> **Date:** 2026-11-03 +> **Type:** issue +> **Reference:** [git.babylondreams.de/AlexKucera/museion#146](https://git.babylondreams.de/AlexKucera/museion/issues/146) + +## Goal + +PostsModel.swift back under the swiftlint error ceilings (file 1127→≤1000 lines, class body 361→≤350) with both `opening_brace` warnings gone, as a pure move — zero behavior change, no edits beyond the ticket-sanctioned private→internal widenings. + +## What Was Done + +- Split PostsModel.swift (1127 → 708 lines; class body 361 → 323) into three domain files, all moves verbatim (mechanically verified line-for-line with a `comm` diff against HEAD — every lost line is a declared edit): + - `Museion/PostsModelOutline.swift` — mixed-content outline guard (#111) + Convert to Post (#114) + `PendingConversion` + - `Museion/PostsModelPasses.swift` — pass orchestration (#24) + Blind Read (#122) + - `Museion/PostsModelCards.swift` — stored cards (#23) + apply/skip/done (#25) + promote (#26) + `FixCardApplyOutcome`/`FixCardPromoteOutcome` +- Moved `startWatching` + `rescan` out of the class body into a file-scope `extension PostsModel` in PostsModel.swift (the #111 precedent) — class body 323 < 350; `startWatching` stays private (same-file extension), `posts` stays `private(set)` (rescan writes it same-file). +- 18 widenings private→internal, each doc-noted `#146`: 13 `private(set)` setters → plain internal vars (`selectedPostID`, `draft`, `session`, `pendingProject`, `lastDraftWasOutline`, `outlineGuardPieceID`, `proseOverridePostID`, `pendingConversion`, `runningPass`, `runningBlindRead`, `openPieceHasSnapshot`, `openPieceCards`, `lastError`) + 5 funcs (`rescan`, `dismissExternal`, `wireSession`, `isGuardedOutline`, `openUnguarded`) — every one required by a verified cross-file caller. +- Unwrapped both `opening_brace` guards per #142: rescan's stale-scan guard joined to one 137-char condition line (clause order preserved: `watchedHome == home` still short-circuits before the `PostStore.folder` disk probe); convertToPost's answer-time consent recheck as nested ifs. +- DOX pass: Museion/AGENTS.md PostsModel bullet — #146 lead-in added; all four "file-scope/same-file extension" mentions now name the new files. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Three domain files, not one | Ticket: "domain-grouped at the implementer's discretion"; outline/passes/cards are the natural domains, each ~150 lines, all cross-extension private access stays file-scoped per file | +| "Zero violations" AC read as the four ticket-named violations | swiftlint DEFAULT warning tiers (400 file / 250 type-body) fire at 708/323, but the ticket's own "lands around 700 lines" makes the 400 tier unreachable; 14 repo files carry the same tier, #144's commit records 289 violations repo-wide at HEAD — the house bar is the ERROR tier | +| 573-at-filing vs 574 executed | The scheme runs MuseionTests + the 1 UI smoke test — 573 unit + 1 UI = 574; not a count regression | +| Declined: move `title(of:)` to PostsModel.swift core | Its doc names three consumers spanning passes AND the cards palette — cross-cutting before the split too; reshuffling beyond the ticket breaks the pure-move fence | +| Declined: dedup promoteCard's repeated error string | Pre-existing inside a verbatim-moved body — the fence forbids fixing it here; follow-up | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| swiftlint "zero violations" AC is self-contradictory at filing size | When a value exceeds the ERROR tier, swiftlint reports only the error — the WARNING tiers (400/250) were invisible at 1127/361 and surfaced the moment the errors cleared | Read the AC as the four named violations; flagged the two residual warnings explicitly in the report and to the reviewers (all three audit reviewers ruled it a spec-internal conflict, not a defect) | +| 13 setters silently needed widening beyond the obvious 5 funcs | `private(set)` setter access is same-FILE for extensions — every moved extension that sets model state needs the internal setter | Pre-swept all moved bodies for private/setter writesites before writing (the subagent-delegation skill's move checklist); each widened member carries a `#146` doc note as the tripwire | +| `{PIPESTATUS[0]}` empty in background shell | zsh spells it `pipestatus` | Pinned `-resultBundlePath` and read the xcresult instead of trusting exit banners (house learning #31/#33 anyway) | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostsModel.swift` | 1127→708; watcher section to file-scope extension; 18 widenings; guard #1 unwrapped; header note | +| `Museion/PostsModelOutline.swift` | NEW — guard #111 + Convert #114 extensions + PendingConversion (code unchanged save the #114 guard unwrap) | +| `Museion/PostsModelPasses.swift` | NEW — pass #24 + Blind Read #122 extensions, code unchanged | +| `Museion/PostsModelCards.swift` | NEW — cards #23/#25/#26 extensions + both outcome enums, code unchanged | +| `Museion/AGENTS.md` | DOX: PostsModel bullet — #146 lead-in + four extension-location mentions updated | +| `AGENTS.md` | GitNexus stats-bump line (auto-churn from analyze) | + +## Verification + +- swiftlint on the four Swift files: **0 errors, 0 named-warning violations** (file_length 1127/1000 and type_body 361/350 errors gone; both opening_brace warnings gone). Residual: default warning-tier notices 708/400 + 323/250 — accepted posture (see Decisions). +- swiftformat `. --lint`: **0/113 files require formatting**. +- Build + full suite via pinned xcresult: **574 executed, 574 passed, 0 failed** (573 unit + 1 UI smoke). +- Reviews: implement-close Standards+Spec both Approve (no hard violations); finish-audit ponytail/security/general fanout — 0 deletable code, 0 runtime-exploitable delta, 0 crit/high/medium; one comment-word fix applied (Outline header "code unchanged save the #114 guard unwrap"). +- GitNexus: impact (CRITICAL = fan-out, 113 direct callers — pure-move diff), detect-changes (line-shift noise + docs), analyze re-indexed. + +## Open Items & Next Steps + +- [ ] Follow-up fodder (declined under the pure-move fence): dedup promoteCard's error string; consider `title(of:)`'s home; #137 stale-scan guard has no direct test (pre-existing gap) +- [ ] If literal warning-zero is ever wanted: further split (projects ops + PostsWatcher out) to get under 400/250 — or configure the tiers in .swiftlint.yml +- [ ] Security-review note: `openUnguarded` is now module-callable (latent #111 bypass, zero unsanctioned callers) — re-privatize by folding select's tail into the Outline file if the fence is ever wanted back + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index b80aec5..02a08de 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 | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-03 | issue | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | #146: PostsModel split under lint ceilings — six extensions to three domain files, watcher to file-scope extension; pure move, 574 green | | 2026-11-03 | issue | [20261103-issue144-library-search-across-titles-and-bodies_log.md](20261103-issue144-library-search-across-titles-and-bodies_log.md) | #144: library search — trimmed-id debounce, structured off-main body scan (audit: detached → nonisolated), postRow menu for results | | 2026-11-03 | issue | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | #143: path+mtime+size parse memo — rescans re-read only changed post.md; pre-read stamp closes the overlap race; equality-gated posts assignment | | 2026-11-03 | issue | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) | #142: single-line edits re-key folds in place; chrome becomes per-glyph layers — no more per-keystroke full-document restyle/raster |