feat(library): search by title and body (#144)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
The library offered only project/pass-state browsing — no way to find a
piece by content ("which piece was it that talked about X", FEAT-004).
The library column gains a plain-text search field under the Posts
header: a 250 ms-debounced title+body filter over the non-archived
pieces, flat results with title matches first (both halves keep the
scan's Finder order), a mono match count, and the full row context menu
(Rename/Convert/Move/Archive/Trash) on result rows — extracted into one
postRow helper shared with the sections. Body matches go through
PostStore.readBody, so frontmatter never matches (machinery, not
prose). Clearing returns the project sections; state is view-local, so
both render sites (unfocused layout + focus-mode reveal) get the field.
The scan runs as a nonisolated static async helper awaited from
.task(id: trimmedQuery): off MainActor (a nonisolated async function
doesn't inherit the caller's actor) while staying INSIDE the structured
task, so a superseding keystroke or clear actually cancels the sweep
between pieces — the spec's Task.detached shape never received
cancellation (two-reviewer convergence in the finish-audit caught it,
plus the code comment claiming it did), and trimming the task id stops
whitespace-only edits from re-running identical scans.
Deliberately deferred: re-filter on a watcher rescan while a query sits
unchanged (any keystroke refreshes), and a PostScanCache-style body
memo (full-body re-read per sweep — same unbounded-read ceiling as
Post.scan; upgrade path noted in the helper's ponytail comment).
Known pre-existing (unchanged by this diff, proven by stash control):
repo-wide swiftlint exits 2 with 289 violations / 72 serious at HEAD;
this diff adds zero error-severity violations.
Suite 574/574 (xcresult executed count).
Closes #144
This commit is contained in:
1 parent
a2f6dc1653
commit
53c314d4e1
6 files changed
+219
-19
No files matched your search
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
|
|||||||
<!-- gitnexus:start -->
|
<!-- gitnexus:start -->
|
||||||
# GitNexus — Code Intelligence
|
# GitNexus — Code Intelligence
|
||||||
|
|
||||||
This project is indexed by GitNexus as **museion** (5791 symbols, 23577 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** (5820 symbols, 23635 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).
|
> 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
|
|||||||
<!-- write-log: window-start -->
|
<!-- write-log: window-start -->
|
||||||
| Date | Log |
|
| Date | Log |
|
||||||
|------|-----|
|
|------|-----|
|
||||||
|
| 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-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) |
|
| 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) |
|
||||||
| 2026-11-02 | [20261102-issue141-image-drop-illustration-ingest_log.md](docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md) |
|
| 2026-11-02 | [20261102-issue141-image-drop-illustration-ingest_log.md](docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md) |
|
||||||
@@ -206,6 +207,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
|||||||
| 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-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-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) |
|
| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](docs/devlog/20261030-issue1-verify-style-constraints-prompt-end_log.md) |
|
||||||
| 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) |
|
|
||||||
| 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](docs/devlog/20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) |
|
|
||||||
<!-- write-log: window-end -->
|
<!-- write-log: window-end -->
|
||||||
@@ -10,6 +10,8 @@ All notable changes to this project will be documented in this file. The format
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- **library:** Search across titles and bodies (#144, FEAT-004) — the library column gains a plain-text search field under the Posts header: a debounced (250 ms) title+body filter over the non-archived pieces, body scan off MainActor through `PostStore.readBody` (frontmatter never searched), flat results with title matches first (Finder order preserved), match count, and the full context menu on result rows. Clearing returns the project sections. Suite 574 (issue #144)
|
||||||
|
|
||||||
- **editor:** Drop an image into the prose (#141) — dragging an image file onto a saved post's prose editor COPIES it (never moves) into the piece's `assets/` under a parser-clean slugged name (collision `-2` via the shared uniqueFile helper) and inserts `` at the drop point with `alt` selected for immediate type-over; one edit step = one undo. The type gate is exactly the publish rail's set (#34's `Micropub.mimeType` — PNG/JPEG/GIF/WebP/SVG: nothing enters `assets/` that can't ship), a Finder folder or a dropped SYMLINK refuses (`copyItem` would land the link itself and the publish rail would refuse the whole send), and drafts/outline/guest surfaces refuse loudly with a transient strip. Routing rides the window-level SwiftUI drop destination — field-verified to starve every deeper drag destination (nested SwiftUI targets never fire, AppKit NSDraggingDestination never fires) — pure-markdown sets keep the open-as-guest behavior, mixed md+image sets refuse loudly instead of silently dropping the images. The drop-point mapping inverts the one geometry source that answers under SwiftUI hosting (`firstRect`, bottom-up screen coords): a viewport-banded sample→bracket→binary-search over it — non-contiguous layout returns garbage rects for off-screen characters, so only in-band rects are trusted — then a whitespace-gap slide so a landing never splices inside a word or an existing ref; the solve is a pure function pinned by windowless tests, and the typewriter inset re-syncs after the edit so scrolling never freezes. Eleven tests incl. a flip-verified finish-audit cycle; suite 557 (issue #141)
|
- **editor:** Drop an image into the prose (#141) — dragging an image file onto a saved post's prose editor COPIES it (never moves) into the piece's `assets/` under a parser-clean slugged name (collision `-2` via the shared uniqueFile helper) and inserts `` at the drop point with `alt` selected for immediate type-over; one edit step = one undo. The type gate is exactly the publish rail's set (#34's `Micropub.mimeType` — PNG/JPEG/GIF/WebP/SVG: nothing enters `assets/` that can't ship), a Finder folder or a dropped SYMLINK refuses (`copyItem` would land the link itself and the publish rail would refuse the whole send), and drafts/outline/guest surfaces refuse loudly with a transient strip. Routing rides the window-level SwiftUI drop destination — field-verified to starve every deeper drag destination (nested SwiftUI targets never fire, AppKit NSDraggingDestination never fires) — pure-markdown sets keep the open-as-guest behavior, mixed md+image sets refuse loudly instead of silently dropping the images. The drop-point mapping inverts the one geometry source that answers under SwiftUI hosting (`firstRect`, bottom-up screen coords): a viewport-banded sample→bracket→binary-search over it — non-contiguous layout returns garbage rects for off-screen characters, so only in-band rects are trusted — then a whitespace-gap slide so a landing never splices inside a word or an existing ref; the solve is a pure function pinned by windowless tests, and the typewriter inset re-syncs after the edit so scrolling never freezes. Eleven tests incl. a flip-verified finish-audit cycle; suite 557 (issue #141)
|
||||||
- **publish:** Illustrations travel with it (PRD S6.2, G12) — a piece's `assets/` ink-sketch images now publish: Send as Draft first uploads every referenced image to Micro.blog's media endpoint (discovered per send via `GET ?q=config`, one multipart `file` POST per FILE — duplicate refs share an upload — decoding Location/body-url behind the trust gate), then each `` ref REWRITES IN PLACE with its uploaded URL in the wire content, so the image renders exactly where the writer placed it and the alt rides the markdown (live dogfood killed the first shape: a Micropub `photo` property renders wherever the theme decides — the bottom — losing position; no property ships at all now). The piece on disk never changes. The floor (G12): a photo without alt text never ships — the send refuses naming the illustration BEFORE anything touches the wire, and a parsed body ref is the only way an image ships. Pre-flight gates every payload: the endpoint's exact formats only (PNG/JPEG/GIF/WebP/SVG — nothing enters `assets/` that can't ship), path containment resolved through symlinks (a planted link never uploads outside-file bytes under the writer's token), all-or-nothing uploads. A URL carrying markdown-active characters rides the angle form `` — a plain-paren destination would close at the first `)` and smuggle a live link into the published post (the frontmatter trust gate doesn't cover markdown's grammar). The mentor is consulted for nothing — style judgment stays with the author. Seventeen tests incl. a flip-verified audit cycle; suite 546 (issue #34)
|
- **publish:** Illustrations travel with it (PRD S6.2, G12) — a piece's `assets/` ink-sketch images now publish: Send as Draft first uploads every referenced image to Micro.blog's media endpoint (discovered per send via `GET ?q=config`, one multipart `file` POST per FILE — duplicate refs share an upload — decoding Location/body-url behind the trust gate), then each `` ref REWRITES IN PLACE with its uploaded URL in the wire content, so the image renders exactly where the writer placed it and the alt rides the markdown (live dogfood killed the first shape: a Micropub `photo` property renders wherever the theme decides — the bottom — losing position; no property ships at all now). The piece on disk never changes. The floor (G12): a photo without alt text never ships — the send refuses naming the illustration BEFORE anything touches the wire, and a parsed body ref is the only way an image ships. Pre-flight gates every payload: the endpoint's exact formats only (PNG/JPEG/GIF/WebP/SVG — nothing enters `assets/` that can't ship), path containment resolved through symlinks (a planted link never uploads outside-file bytes under the writer's token), all-or-nothing uploads. A URL carrying markdown-active characters rides the angle form `` — a plain-paren destination would close at the first `)` and smuggle a live link into the published post (the frontmatter trust gate doesn't cover markdown's grammar). The mentor is consulted for nothing — style judgment stays with the author. Seventeen tests incl. a flip-verified audit cycle; suite 546 (issue #34)
|
||||||
- **publish:** Micropub draft → publish to Micro.blog (PRD S6.1, G2/G11) — a Publish button in the editor toolbar opens the two-step ask: Send as Draft (JSON Micropub `h=entry` create — name = the piece's Title, markdown content verbatim, `post-status: draft`; the piece's frontmatter `category:` is accepted but never travels), review via the Micro.blog preview link, then Publish (the `action=update` post-status flip against the piece's remembered `micropub_url` — persisted in frontmatter so a draft survives a reopen; Send Again re-drafts after edits). The Micro.blog app token lives in the Keychain (login keychain, entered once in the sheet, re-offered only on an auth failure — rotation replaces). Every draft URL passes a format gate at both the decode and the scan read-back: the URL is trust-boundary data landing in frontmatter, and a newline-`---` rider would close the block and reparse as attacker markdown in the writer's piece; the preview URL is display-only, never the publish target. Frontmatter-only stamps keep the body and foreign keys byte-identical (issue #33)
|
- **publish:** Micropub draft → publish to Micro.blog (PRD S6.1, G2/G11) — a Publish button in the editor toolbar opens the two-step ask: Send as Draft (JSON Micropub `h=entry` create — name = the piece's Title, markdown content verbatim, `post-status: draft`; the piece's frontmatter `category:` is accepted but never travels), review via the Micro.blog preview link, then Publish (the `action=update` post-status flip against the piece's remembered `micropub_url` — persisted in frontmatter so a draft survives a reopen; Send Again re-drafts after edits). The Micro.blog app token lives in the Keychain (login keychain, entered once in the sheet, re-offered only on an auth failure — rotation replaces). Every draft URL passes a format gate at both the decode and the scan read-back: the URL is trust-boundary data landing in frontmatter, and a newline-`---` rider would close the block and reparse as attacker markdown in the writer's piece; the preview URL is display-only, never the publish target. Frontmatter-only stamps keep the body and foreign keys byte-identical (issue #33)
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
|||||||
|
|
||||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media querieLine truncated
|
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media querieLine truncated
|
||||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
|
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
|
||||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
|
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
|
||||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
|
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
|
||||||
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
|
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
|
||||||
|
|||||||
+156
-15
@@ -181,6 +181,18 @@ struct PostsLibraryColumn: View {
|
|||||||
/// #108: collapsed project sections — per-view state, not persisted (a
|
/// #108: collapsed project sections — per-view state, not persisted (a
|
||||||
/// fresh open shows everything; the prototype behaved the same).
|
/// fresh open shows everything; the prototype behaved the same).
|
||||||
@State private var collapsed: Set<String> = []
|
@State private var collapsed: Set<String> = []
|
||||||
|
/// #144: the library search — live title+body filter over the
|
||||||
|
/// non-archived pieces. nil = not searching (sections render).
|
||||||
|
@State private var query = ""
|
||||||
|
@State private var matches: [Post]?
|
||||||
|
|
||||||
|
private var trimmedQuery: String {
|
||||||
|
query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var isSearching: Bool {
|
||||||
|
!trimmedQuery.isEmpty
|
||||||
|
}
|
||||||
|
|
||||||
/// Non-archived pieces keyed by project (scan order = title order holds
|
/// Non-archived pieces keyed by project (scan order = title order holds
|
||||||
/// inside each group — filter preserves it).
|
/// inside each group — filter preserves it).
|
||||||
@@ -201,7 +213,19 @@ struct PostsLibraryColumn: View {
|
|||||||
.help("New Post")
|
.help("New Post")
|
||||||
.accessibilityLabel("New Post")
|
.accessibilityLabel("New Post")
|
||||||
}
|
}
|
||||||
if activeByProject.isEmpty {
|
searchField
|
||||||
|
if isSearching {
|
||||||
|
if let matches {
|
||||||
|
if matches.isEmpty {
|
||||||
|
searchEmptyState
|
||||||
|
} else {
|
||||||
|
searchResults(matches)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ProgressView()
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
} else if activeByProject.isEmpty {
|
||||||
emptyState
|
emptyState
|
||||||
} else {
|
} else {
|
||||||
ScrollView {
|
ScrollView {
|
||||||
@@ -268,22 +292,62 @@ struct PostsLibraryColumn: View {
|
|||||||
model.moveToProject(post, project: project, home: home)
|
model.moveToProject(post, project: project, home: home)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// #144: keystroke-debounced (250 ms), structured body scan —
|
||||||
|
// nonisolated search() runs the disk reads off MainActor while
|
||||||
|
// staying inside this task, so a superseding keystroke or clear
|
||||||
|
// cancels the sweep between pieces (the in-flight file read
|
||||||
|
// always finishes — readBody is synchronous).
|
||||||
|
.task(id: trimmedQuery) {
|
||||||
|
guard !trimmedQuery.isEmpty else {
|
||||||
|
matches = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try? await Task.sleep(for: .milliseconds(250))
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
let found = await Self.search(
|
||||||
|
candidates: model.posts.filter { !$0.isArchived },
|
||||||
|
matching: trimmedQuery,
|
||||||
|
home: home,
|
||||||
|
)
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
matches = found
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
|
/// #144: the title+body scan — title matches first (stable partition,
|
||||||
/// softer, indented under the section head).
|
/// both halves keep the scan's Finder order), body via readBody
|
||||||
private func passStateGroups(_ pieces: [Post]) -> some View {
|
/// (frontmatter never searched); the per-piece cancellation check stops
|
||||||
ForEach(Post.PassState.allCases, id: \.self) { state in
|
/// a superseded sweep between files.
|
||||||
let grouped = pieces.filter { $0.passState == state }
|
///
|
||||||
if !grouped.isEmpty {
|
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
|
||||||
Text(state.rawValue.uppercased())
|
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
|
||||||
.font(.system(size: 10, design: DesignTokens.mono))
|
/// posture); a PostScanCache-style body memo if it ever measures hot.
|
||||||
.kerning(0.6)
|
private nonisolated static func search(
|
||||||
.foregroundStyle(DesignTokens.muted.opacity(0.8))
|
candidates: [Post],
|
||||||
.padding(.horizontal, 22)
|
matching trimmed: String,
|
||||||
.padding(.top, 8)
|
home: URL,
|
||||||
.padding(.bottom, 5)
|
) async -> [Post] {
|
||||||
ForEach(grouped) { post in
|
var byTitle: [Post] = []
|
||||||
|
var byBody: [Post] = []
|
||||||
|
for post in candidates {
|
||||||
|
if Task.isCancelled {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if post.title.localizedCaseInsensitiveContains(trimmed) {
|
||||||
|
byTitle.append(post)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let body = PostStore.readBody(id: post.id, home: home) ?? ""
|
||||||
|
if body.localizedCaseInsensitiveContains(trimmed) {
|
||||||
|
byBody.append(post)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return byTitle + byBody
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One piece row + its context menu — sections and search results
|
||||||
|
/// render the same row (#144: results carry the full menu too).
|
||||||
|
private func postRow(_ post: Post) -> some View {
|
||||||
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
|
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
|
||||||
model.select(post.id, home: home)
|
model.select(post.id, home: home)
|
||||||
}
|
}
|
||||||
@@ -305,9 +369,86 @@ struct PostsLibraryColumn: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
|
||||||
|
/// softer, indented under the section head).
|
||||||
|
private func passStateGroups(_ pieces: [Post]) -> some View {
|
||||||
|
ForEach(Post.PassState.allCases, id: \.self) { state in
|
||||||
|
let grouped = pieces.filter { $0.passState == state }
|
||||||
|
if !grouped.isEmpty {
|
||||||
|
Text(state.rawValue.uppercased())
|
||||||
|
.font(.system(size: 10, design: DesignTokens.mono))
|
||||||
|
.kerning(0.6)
|
||||||
|
.foregroundStyle(DesignTokens.muted.opacity(0.8))
|
||||||
|
.padding(.horizontal, 22)
|
||||||
|
.padding(.top, 8)
|
||||||
|
.padding(.bottom, 5)
|
||||||
|
ForEach(grouped) { post in
|
||||||
|
postRow(post)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #144: the field row + bottom hairline (the pane-head voice).
|
||||||
|
private var searchField: some View {
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
Image(systemName: "magnifyingglass")
|
||||||
|
.font(.system(size: 11))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
TextField("Search posts", text: $query)
|
||||||
|
.textFieldStyle(.plain)
|
||||||
|
.font(.system(size: 12))
|
||||||
|
if isSearching {
|
||||||
|
Button {
|
||||||
|
query = ""
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "xmark.circle.fill")
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
.accessibilityLabel("Clear search")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.padding(.vertical, 7)
|
||||||
|
.overlay(alignment: .bottom) {
|
||||||
|
Rectangle().fill(DesignTokens.border).frame(height: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flat results, title matches first (stable partition — both halves
|
||||||
|
/// keep the scan's Finder order). Same row the sections render.
|
||||||
|
private func searchResults(_ found: [Post]) -> some View {
|
||||||
|
ScrollView {
|
||||||
|
LazyVStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("\(found.count) \(found.count == 1 ? "match" : "matches")")
|
||||||
|
.font(.system(size: 10, design: DesignTokens.mono))
|
||||||
|
.kerning(0.6)
|
||||||
|
.foregroundStyle(DesignTokens.muted.opacity(0.8))
|
||||||
|
.padding(.horizontal, 14)
|
||||||
|
.padding(.top, 12)
|
||||||
|
.padding(.bottom, 5)
|
||||||
|
ForEach(found) { post in
|
||||||
|
postRow(post)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.bottom, 12)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var searchEmptyState: some View {
|
||||||
|
VStack(spacing: 8) {
|
||||||
|
Text("No matches")
|
||||||
|
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||||
|
Text("No piece's title or body contains “\(trimmedQuery)”.")
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
.multilineTextAlignment(.center)
|
||||||
|
}
|
||||||
|
.padding(38)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
|
||||||
private var emptyState: some View {
|
private var emptyState: some View {
|
||||||
VStack(spacing: 8) {
|
VStack(spacing: 8) {
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Library search across titles and bodies (#144)
|
||||||
|
|
||||||
|
> **Date:** 2026-11-03
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [museion-#144](https://git.babylondreams.de/AlexKucera/museion/issues/144) — [museion-FEAT-004] Library search across titles and bodies
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Ship FEAT-004 (Argus cycle-1 smallest-win, effort S): search across post titles and bodies over the whole library. Fix direction pinned in the ticket: in-memory title filter + body scan scoped to the library roots, debounce, no new persistence. Full spec (UI sketch, code, constraints) in `~/argus-audits/audit/2026-11-02/museion-features.md` §FEAT-004.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- `PostsLibraryColumn` (Museion/PostsPaneView.swift) gains the search: `query`/`matches` view state below `collapsed`, `isSearching`/`trimmedQuery` computed, the plain-text `searchField` row under the Posts header (magnifyingglass + clear ✕, bottom hairline), `searchResults(_:)` (flat list, mono count line, title matches first) and `searchEmptyState`.
|
||||||
|
- The scan: `.task(id: trimmedQuery)` → 250 ms debounce → `await Self.search(...)` — a `nonisolated static func` running the disk reads off MainActor but *inside* the structured task, with a per-piece `Task.isCancelled` check.
|
||||||
|
- `postRow(_:)` extracted (`LibraryPostRow` + full context menu) — sections and search results render the same row; results carry Rename/Convert/Move/Archive/Trash too.
|
||||||
|
- DOX closeout: `Museion/AGENTS.md` PostsPaneView entry gains the `**#144:**` line (field, debounce, off-main posture, frontmatter exclusion, ordering, both render surfaces).
|
||||||
|
- Verification: build SUCCEEDED; suite 574/574 (xcresult executed count); swiftformat idempotent; swiftlint adds zero error-severity violations.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| `nonisolated static` async helper instead of the spec's `Task.detached` | Finish-audit converged finding (security + general): `Task.detached` is unstructured — `.task(id:)` cancellation never reaches it, and the spec's comment claimed it did. A nonisolated async func awaited from the `.task` runs off MainActor (doesn't inherit the actor) while staying on the same *task*, so SwiftUI's cancellation actually lands; per-piece check stops superseded sweeps between files. Single pass also killed the double title-predicate. |
|
||||||
|
| `.task(id: trimmedQuery)` not `query` | Whitespace-only edits ("foo"→"foo ") must not restart the debounce+scan for identical trimmed input; the id now agrees with the render gate's source of truth. |
|
||||||
|
| `postRow(_:)` extraction | Search results lacked the context menu (Rename/Move/etc. unreachable from results); one row+menu source for both sites beats duplicating the menu block. |
|
||||||
|
| Stale-while-revalidate during debounce (`matches` nils only on clear) | Spec's exact code: later keystrokes keep showing prior results through the 250 ms window instead of a spinner flicker; ProgressView is the first-search state. |
|
||||||
|
| No `readBody` size gate | `Post.scan` already reads every post.md unbounded at startup — search adds no new exposure class; a gate would change shared-function behavior beyond this diff. Ceiling documented as a `ponytail:` note with the `PostScanCache`-style memo upgrade path (LearningsIndex posture). |
|
||||||
|
| No unit test for the filter | View-local state, no pure logic added — the spec's verification is manual smoke; the repo has no component-render harness (named unpinned delta in the audit report). |
|
||||||
|
| Two `PostsLibraryColumn` instances (unfocused layout + focus reveal) keep separate query state | Matches #108's documented per-view `collapsed` posture; only one is alive at a time; AGENTS.md row promises availability, not shared state. Reviewer confirmed fine. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| swiftlint `opening_brace` violation after formatting | swiftformat pushed a wrapped `else if` condition's brace to its own line (#142's known trap) | Hoisted the body read into a local (`let body = …`) so the condition never wraps — don't fight the formatter |
|
||||||
|
| Test-run exit 1 with all tests passing | My xcresult-summary one-liner ran while the bundle was still finalizing (#33's race, live again — a piped wait isn't enough) | Read the bundle in a separate later call: 574/574, 0 failed |
|
||||||
|
| swiftlint gate exits 2 repo-wide | Pre-existing: 289 violations / 72 serious at HEAD, identical with the diff; earlier chained runs piped through `tail` masked the exit code | Proven pre-existing via stash control (same 289/72); named here and in the commit; my file adds zero errors |
|
||||||
|
| GitNexus `detect-changes` said "No changes detected" despite a dirty tree | Stale index after an earlier incremental analyze | Re-ran `analyze` (full, 5,820 nodes) → detect-changes then reported the true scope (`PostsLibraryColumn` + docs) |
|
||||||
|
| Review flag: comment claimed `.task(id:)` cancels the in-flight scan | `Task.detached` never receives parent cancellation — the prose promised an invariant the code didn't have | Structured-concurrency fix above; the comment is now true |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/PostsPaneView.swift` | +164/−23: search state, field, results, empty state, structured scan, `postRow(_:)` extraction |
|
||||||
|
| `Museion/AGENTS.md` | `**#144:**` line on the PostsPaneView entry (DOX closeout) |
|
||||||
|
| `AGENTS.md` | write-log window refresh + gitnexus index-stats churn |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Deferred: re-filter when a watcher rescan lands while a query sits unchanged (any keystroke refreshes; a later slice if it bites)
|
||||||
|
- [ ] Deferred: `folder(of:)` re-walk per piece per sweep — `PostScanCache`-style body memo if it ever measures hot (named in `search()`'s ponytail note; see the `local-store-caching` skill)
|
||||||
|
- [ ] Manual smoke: type a known word into Search posts → flat match list; clear → sections return; right-click a result → full menu
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
|||||||
<!-- write-log: full-index -->
|
<!-- write-log: full-index -->
|
||||||
| Date | Type | File | Summary |
|
| Date | Type | File | Summary |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
| 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-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 |
|
| 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 |
|
||||||
| 2026-11-02 | issue | [20261102-issue141-image-drop-illustration-ingest_log.md](20261102-issue141-image-drop-illustration-ingest_log.md) | Image drop → assets/ ingest at drop point; window-destination routing, firstRect viewport-band solve, finish-audit fixes |
|
| 2026-11-02 | issue | [20261102-issue141-image-drop-illustration-ingest_log.md](20261102-issue141-image-drop-illustration-ingest_log.md) | Image drop → assets/ ingest at drop point; window-destination routing, firstRect viewport-band solve, finish-audit fixes |
|
||||||
|
|||||||
Reference in new issue
Block a user