perf(library): memoize scan parses per save (#143)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Every FSEvents change — each 1 s autosave echo — ran Post.scan over the whole library: read + frontmatter parse + title per post.md, O(library bytes) per save cycle while writing, and the posts array was replaced unconditionally, so every observing pane regrouped and re-rendered even when nothing changed. Post.scan now takes an optional PostScanCache (path+mtime+size-keyed parse memo, nil default — every other caller unchanged): the readdir walk stays the truth, only changed files are read and re-parsed. The stamp is captured BEFORE the read and keys the store, so a mid-scan rewrite can never be pinned as fresh — a late overlapping store keys its own pre-read stamp and the next scan misses (review-caught race, pinned by a same-size-rewrite test). rescan skips the posts assignment when the scan equals the current list; @Observable invalidates on assignment regardless of equality, so panes stop re-rendering on the app's own autosave echoes. Deliberately skipped (measured cold): folder(of:) caching (stat-only walk) and refreshCards throttling (O(open piece), card surfacing depends on it). Closes #143
This commit is contained in:
1 parent
cc317b65b9
commit
a2f6dc1653
9 files changed
+287
-39
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 — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (5755 symbols, 23498 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** (5791 symbols, 23577 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).
|
||||
|
||||
@@ -183,6 +183,8 @@ This project is indexed by GitNexus as **museion** (5755 symbols, 23498 relation
|
||||
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
|
||||
|
||||
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — avoid the wrap (nested ifs / a hoisted helper), don't fight the formatter (#142)
|
||||
- swiftformat's self-remove strips a load-bearing `self.` when a local hoists a property for a detached capture (`let x = self.x` becomes the self-referential `let x = x`) — rename the local so nothing shadows (#143)
|
||||
- A `//` note sitting between a `///` doc block and its declaration detaches the doc (swiftlint orphaned_doc_comment) — fold such notes into the `///` block (#143)
|
||||
### Trust boundaries
|
||||
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
|
||||
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
|
||||
@@ -195,6 +197,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 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-02 | [20261102-issue141-image-drop-illustration-ingest_log.md](docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md) |
|
||||
| 2026-11-01 | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) |
|
||||
|
||||
@@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **library:** Incremental rescan (#143, OPT-F3) — every save/watcher cycle re-read and re-parsed EVERY post.md in the library (O(library bytes) per autosave echo, forever while writing) and replaced the posts array unconditionally, regrouping/re-rendering every observing pane even when nothing changed. `Post.scan` now takes an optional parse memo (`PostScanCache`, keyed on path+mtime+size — the readdir walk stays the truth, only changed files are read and re-parsed; the stamp is captured BEFORE the read so a mid-scan rewrite can never be pinned as fresh — an overlapping-rescan race the review caught, pinned), and the rescan skips the posts assignment when the scan equals the current list, so panes stop re-rendering on the app's own autosave echoes. Deliberately skipped (measured cold): `folder(of:)` caching (stat-only walk) and refreshCards throttling (O(open piece), card surfacing depends on it). Suite 573 (issue #143)
|
||||
|
||||
### Added
|
||||
|
||||
- **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)
|
||||
|
||||
+2
-2
@@ -23,7 +23,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.
|
||||
- `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)`).
|
||||
- `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. **#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
|
||||
- `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`).
|
||||
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
|
||||
@@ -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 `` 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 `` — 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-uploadsLine truncated
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
|
||||
- `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-archivLine truncated
|
||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
|
||||
- `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).
|
||||
|
||||
+134
-33
@@ -117,7 +117,10 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
/// Same skip rules at both levels: symlinks, hidden dirs, loose files;
|
||||
/// folders without `post.md` (lazy) aren't Posts; a malformed folder
|
||||
/// can't crash the list. Read-only for #17.
|
||||
static func scan(home: URL) -> [Post] {
|
||||
/// #143: pass a `cache` to reuse parses of files whose path, mtime,
|
||||
/// and size are unchanged (nil, the default, reads everything —
|
||||
/// every existing caller's behavior).
|
||||
static func scan(home: URL, cache: PostScanCache? = nil) -> [Post] {
|
||||
var posts: [Post] = []
|
||||
// #107 audit: duplicate ids can appear on disk (Finder copy across
|
||||
// projects, partial restore) — first-wins dedupe, in the SAME
|
||||
@@ -145,45 +148,69 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
guard pieceValues?.isDirectory ?? false, !(pieceValues?.isSymbolicLink ?? false),
|
||||
!dir.lastPathComponent.hasPrefix(".") else { continue }
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8), seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
posts.append(
|
||||
Post(
|
||||
id: dir.lastPathComponent,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: origin,
|
||||
type: type,
|
||||
project: projectDir.lastPathComponent,
|
||||
isArchived: isArchived,
|
||||
// #33: the remembered Micro.blog draft URL —
|
||||
// one flat key, read leniently like the rest.
|
||||
// #33 audit: imported frontmatter rides
|
||||
// verbatim, so the read-back gates on the same
|
||||
// format guard the decode applies — a hostile
|
||||
// value never pre-arms the publish sheet.
|
||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
||||
Micropub.trustworthyURL($0) ? $0 : nil
|
||||
},
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
),
|
||||
// #143: unchanged post.md (path + mtime + size) → reuse
|
||||
// the prior parse. The walk stays the truth; only the
|
||||
// read is skipped. One stamp serves consult AND store —
|
||||
// taken before both, so a mid-scan rewrite can never be
|
||||
// pinned as fresh (see store).
|
||||
let stamp = PostScanCache.stamp(at: fileURL)
|
||||
if let cached = cache?.cachedPost(at: fileURL, stamp: stamp) {
|
||||
guard seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
posts.append(cached)
|
||||
continue
|
||||
}
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8),
|
||||
seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
let post = parse(
|
||||
text: text,
|
||||
id: dir.lastPathComponent,
|
||||
project: projectDir.lastPathComponent,
|
||||
isArchived: isArchived,
|
||||
)
|
||||
cache?.store(post, at: fileURL, stamp: stamp)
|
||||
posts.append(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
return posts.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
|
||||
}
|
||||
|
||||
/// One post.md's text parsed into a Post — the scan's miss path (#143
|
||||
/// kept this a pure function of (text, location); the cache memoizes
|
||||
/// its output, nothing else).
|
||||
private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post {
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
return Post(
|
||||
id: id,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: origin,
|
||||
type: type,
|
||||
project: project,
|
||||
isArchived: isArchived,
|
||||
// #33: the remembered Micro.blog draft URL —
|
||||
// one flat key, read leniently like the rest.
|
||||
// #33 audit: imported frontmatter rides
|
||||
// verbatim, so the read-back gates on the same
|
||||
// format guard the decode applies — a hostile
|
||||
// value never pre-arms the publish sheet.
|
||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
||||
Micropub.trustworthyURL($0) ? $0 : nil
|
||||
},
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
)
|
||||
}
|
||||
|
||||
/// The `---`-delimited frontmatter block if present; empty otherwise.
|
||||
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
|
||||
static func frontmatter(of text: String) -> [String: String] {
|
||||
@@ -224,6 +251,80 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// #143 (OPT-F3): parse memo for `Post.scan`. A post.md whose PATH,
|
||||
/// mtime, and size are unchanged since the last parse is not re-read —
|
||||
/// the prior `Post` is reused — so a watcher burst (the autosave echo)
|
||||
/// costs the readdir walk plus the changed files, not O(library bytes).
|
||||
/// Path-keyed: a moved piece always re-parses and re-derives its
|
||||
/// project/isArchived from disk. Held by `PostsModel` across rescans.
|
||||
///
|
||||
/// ponytail: mtime+size is the invalidation key (make/rsync class) — a
|
||||
/// same-size rewrite inside APFS timestamp granularity could serve a stale
|
||||
/// parse; key on a content hash if that ever bites. Entries for vanished
|
||||
/// paths are never consulted again and merely linger (bytes each).
|
||||
///
|
||||
final nonisolated class PostScanCache: @unchecked Sendable {
|
||||
private struct Entry {
|
||||
let modified: Date
|
||||
let size: Int
|
||||
let post: Post
|
||||
}
|
||||
|
||||
private var entries: [String: Entry] = [:]
|
||||
private let lock = NSLock()
|
||||
/// Hit/miss observables (a miss = one disk read + parse); test-facing.
|
||||
private var hitCount = 0
|
||||
private var missCount = 0
|
||||
|
||||
var hits: Int {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return hitCount
|
||||
}
|
||||
|
||||
var misses: Int {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return missCount
|
||||
}
|
||||
|
||||
/// The cached parse when (path, mtime, size) all match the caller's
|
||||
/// pre-captured stamp; nil = re-read. No I/O here — the stamp travels
|
||||
/// with the scan loop's consult and store alike.
|
||||
func cachedPost(at url: URL, stamp: Stamp) -> Post? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let entry = entries[url.path],
|
||||
stamp.modified == entry.modified,
|
||||
stamp.size == entry.size else { return nil }
|
||||
hitCount += 1
|
||||
return entry.post
|
||||
}
|
||||
|
||||
/// Remember a fresh parse under the caller's PRE-READ stamp; one store
|
||||
/// = one counted miss (disk read). Overlapping rescans can interleave:
|
||||
/// a store that stamped the file itself could key a pre-rewrite parse
|
||||
/// as the post-rewrite version and pin stale content until the next
|
||||
/// write. Keying the pre-read stamp instead makes a mid-flight rewrite
|
||||
/// mismatch on the next scan — a miss, self-healed.
|
||||
func store(_ post: Post, at url: URL, stamp: Stamp) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
missCount += 1
|
||||
guard let modified = stamp.modified, let size = stamp.size else { return }
|
||||
entries[url.path] = Entry(modified: modified, size: size, post: post)
|
||||
}
|
||||
|
||||
/// A file's (mtime, size) at one moment — the invalidation key.
|
||||
struct Stamp {
|
||||
let modified: Date?
|
||||
let size: Int?
|
||||
}
|
||||
|
||||
/// Capture the stamp for a file (nils when it can't be read — the
|
||||
/// store then caches nothing, a conservative miss).
|
||||
static func stamp(at url: URL) -> Stamp {
|
||||
let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey])
|
||||
return Stamp(modified: values?.contentModificationDate, size: values?.fileSize)
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Substring {
|
||||
func trimmed() -> String {
|
||||
// whitespacesAndNewlines, not .whitespaces: a CRLF file's lines carry
|
||||
|
||||
@@ -157,6 +157,9 @@ final class PostsModel {
|
||||
/// Home the watcher is bound to; also the rescan target.
|
||||
private var watchedHome: URL?
|
||||
private var watcher = PostsWatcher()
|
||||
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
|
||||
/// post.md files, not the library (see PostScanCache).
|
||||
private let scanCache = PostScanCache()
|
||||
/// #93: per-file watcher on the open external file — the #67 conflict
|
||||
/// check reused verbatim for foreign files.
|
||||
private var externalWatcher = PostsWatcher()
|
||||
@@ -195,13 +198,18 @@ final class PostsModel {
|
||||
// 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)
|
||||
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 }
|
||||
posts = scanned
|
||||
// #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
|
||||
|
||||
@@ -20,7 +20,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. **#143:** the scan-cache pins over `PostScanCache`'s hit/miss observables — cold scan misses once per file, warm scan all hits with identical output, a changed file re-parses (title moves) while untouched files hit, a moved piece re-parses at its new path (path-keying — a folder move keeps bytes and mtime but `isArchived` re-derives), and a late store carrying a stale pre-read stamp never pins stale content (the overlapping-rescan race's end-state, same-size rewrite so the mtime axis alone carries it).
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
|
||||
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
|
||||
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
|
||||
|
||||
@@ -234,3 +234,77 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws {
|
||||
#expect(PostStore.folder(of: "mine", home: home)?
|
||||
.pathComponents.suffix(2).first == "posts")
|
||||
}
|
||||
|
||||
// MARK: #143 scan cache (OPT-F3)
|
||||
|
||||
@Test func `unchanged files parse once then serve from cache`() throws {
|
||||
let home = try makeHome { home in
|
||||
try writePost(home, "one", "## One\n")
|
||||
try writePost(home, "two", "## Two\n")
|
||||
try writePost(home, "three", "## Three\n")
|
||||
}
|
||||
let cache = PostScanCache()
|
||||
let first = Post.scan(home: home, cache: cache)
|
||||
#expect(cache.misses == 3) // cold scan: every file read + parsed once
|
||||
let second = Post.scan(home: home, cache: cache)
|
||||
#expect(cache.hits == 3) // warm scan: zero re-reads
|
||||
#expect(second == first) // identical result through the cache
|
||||
}
|
||||
|
||||
@Test func `changed file re-parses while untouched files hit`() throws {
|
||||
let home = try makeHome { home in
|
||||
try writePost(home, "one", "## One\n")
|
||||
try writePost(home, "two", "## Two\n")
|
||||
}
|
||||
let cache = PostScanCache()
|
||||
_ = Post.scan(home: home, cache: cache)
|
||||
// The autosave echo: one post.md rewritten (mtime + size both move).
|
||||
try "## Two Retitled\n".write(
|
||||
to: home.appendingPathComponent("projects/posts/two/post.md"),
|
||||
atomically: true,
|
||||
encoding: .utf8,
|
||||
)
|
||||
let posts = Post.scan(home: home, cache: cache)
|
||||
#expect(posts.first { $0.id == "two" }?.title == "Two Retitled")
|
||||
#expect(cache.misses == 3) // one re-read for the changed file
|
||||
#expect(cache.hits == 1) // one reuse for the untouched one
|
||||
}
|
||||
|
||||
@Test func `moved piece re-parses at its new path`() throws {
|
||||
// The cache is keyed by the post.md PATH — a folder move (archive,
|
||||
// move-to-project) keeps bytes and mtime but changes the path, so the
|
||||
// stale entry can never answer and isArchived re-derives from disk.
|
||||
let home = try makeHome { home in
|
||||
try writePost(home, "one", "## One\n")
|
||||
}
|
||||
let cache = PostScanCache()
|
||||
_ = Post.scan(home: home, cache: cache)
|
||||
try FileManager.default.createDirectory(
|
||||
at: home.appendingPathComponent("archive/posts", isDirectory: true),
|
||||
withIntermediateDirectories: true,
|
||||
)
|
||||
try FileManager.default.moveItem(
|
||||
at: home.appendingPathComponent("projects/posts/one", isDirectory: true),
|
||||
to: home.appendingPathComponent("archive/posts/one", isDirectory: true),
|
||||
)
|
||||
let posts = Post.scan(home: home, cache: cache)
|
||||
#expect(posts.first?.isArchived == true)
|
||||
#expect(posts.first?.project == "posts")
|
||||
}
|
||||
|
||||
@Test func `a late store carrying a stale stamp never pins stale content`() throws {
|
||||
// The overlapping-rescan race, pinned at its end-state: scan A reads
|
||||
// v1 and stalls, the file rewrites (v2), scan B caches v2, then A's
|
||||
// late store lands keyed on ITS pre-read (v1) stamp — the next scan
|
||||
// must mismatch, re-read, and serve disk truth, never v1.
|
||||
let home = try makeHome { home in
|
||||
try writePost(home, "one", "## One\n")
|
||||
}
|
||||
let cache = PostScanCache()
|
||||
let stale = try #require(Post.scan(home: home, cache: cache).first)
|
||||
let url = home.appendingPathComponent("projects/posts/one/post.md")
|
||||
let staleStamp = PostScanCache.stamp(at: url) // captured pre-rewrite
|
||||
try "## Two\n".write(to: url, atomically: true, encoding: .utf8)
|
||||
cache.store(stale, at: url, stamp: staleStamp) // A's late store
|
||||
#expect(Post.scan(home: home, cache: cache).first?.title == "Two")
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# #143 — scan parse cache: every save/watcher cycle re-reads the whole library
|
||||
|
||||
> **Date:** 2026-11-03
|
||||
> **Type:** issue
|
||||
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/143 ([museion-OPT-F3], audit `~/argus-audits/audit/2026-11-02/museion-opt.md`)
|
||||
|
||||
## Goal
|
||||
|
||||
Kill the full-store rescan: every FSEvents change (each 1 s autosave echo) ran `Post.scan` over EVERY post.md in the library — read + frontmatter parse + title per file, O(library bytes) per save cycle forever while writing — and replaced the `posts` array unconditionally, re-rendering every observing pane even when nothing changed.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- `Museion/PostLibrary.swift` — new `PostScanCache` (path+mtime+size-keyed parse memo, NSLock-guarded, `@unchecked Sendable`): `cachedPost(at:stamp:)` consults, `store(_:at:stamp:)` remembers, `stamp(at:)` captures the file's (mtime, size). The stamp is taken BEFORE the read and keys the store.
|
||||
- `Post.scan(home:cache:)` — additive `cache` param, nil default (all ~60 existing callers unchanged); hit path reuses the prior parse, miss path reads + parses + stores. Per-file parse extracted to `Post.parse(text:id:project:isArchived:)` (pure function of text + location — the memoized unit; also kept `scan` under the 50-line function-body ceiling).
|
||||
- `Museion/PostsModel.swift` — one app-scoped `scanCache` property, hoisted into the detached scan as a local (`scanMemo`); rescan skips the `posts` assignment when the scan equals the current list (`if scanned != posts { posts = scanned }` — @Observable invalidates on assignment regardless of equality).
|
||||
- `MuseionTests/PostLibraryTests.swift` — 4 pins: cold scan misses once per file; warm scan all hits with identical output; a changed file re-parses while untouched files hit; a moved piece re-parses at its new path (path-keying); a late store carrying a stale pre-read stamp never pins stale content.
|
||||
- DOX: `Museion/AGENTS.md` (PostLibrary + PostsModel entries), `MuseionTests/AGENTS.md` (PostLibraryTests entry); root `AGENTS.md` GitNexus counter auto-refreshed by analyze.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| mtime+size+path-keyed memo, not FSEvents-path-driven patching | The ticket's own fix direction names the "mtime/offset-keyed cache". The readdir walk stays the truth (zero drift risk — any change moves mtime); only the read is skipped. Path-driven patching risks silent divergence between `posts` and disk. |
|
||||
| Stamp captured BEFORE the read, keyed into `store` | Review-found race: a store that stats the file itself can key a pre-rewrite parse as the post-rewrite version when two rescans overlap (rescan re-enters at its `await`), pinning stale content until the next write. The pre-read stamp makes a mid-flight rewrite mismatch on the next scan — a conservative miss, self-healed. Pinned. |
|
||||
| `folder(of:)` caching SKIPPED | Stat-only walks (readdir + N `fileExists`), microseconds at human project counts; the pre-existing ponytail note at `PostStore.swift:41-43` says exactly this. Caching it risks stale id→folder resolution across folder moves — a correctness trade for no measurable win. |
|
||||
| `refreshCards` throttling SKIPPED | O(open piece), not O(library) — not the ticket's cost. Correctness-load-bearing: cards surface via the watcher-driven rescan tail (#23 path). |
|
||||
| Cache entry linger (no pruning of vanished paths) | Entries for vanished paths are never consulted again (the walk doesn't visit them); bytes each. Ponytail-marked in the class doc. |
|
||||
| `hits`/`misses` counters as plain internal observables | The honest test seam for "no re-read" (a black-box observable would need mtime-surgery fixtures); cheap and lock-guarded. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Stat-at-store race (spec review finding) | `store` originally stat'ed the file after the read; overlapping detached rescans could store a pre-rewrite parse keyed as post-rewrite | Pre-read `Stamp` captured in `scan` before the consult, passed to consult AND store; pinned by `a late store carrying a stale stamp never pins stale content` (same-size rewrite — mtime axis alone) |
|
||||
| Double `fstat` per file on miss paths (audit, 2 reviewers converged) | `cachedPost` stat'ed internally, `scan` stat'ed again for the store stamp | One stamp in `scan` serves both; `cachedPost(at:stamp:)` does no I/O (also closes the "I/O under the lock" nit) |
|
||||
| swiftformat stripped a load-bearing `self.` | `let scanCache = self.scanCache` — self-remove rule made it self-referential | Renamed the local to `scanMemo` (no shadowing, nothing for the formatter to strip) — don't fight the formatter (#142 learning) |
|
||||
| swiftformat fuzzy patch mangled a region twice | Loose `old_string` boundaries under wrapped-condition reflow | Re-read the region, restored, then anchored every later patch on exact current text |
|
||||
| `PostScanCache`'s `// ponytail:` note between doc block and class tripped `orphaned_doc_comment` | A `//` block after `///` detaches the doc comment | Folded into the `///` block |
|
||||
| `debounce flushes after idle` flaked in 2 of 3 full-suite runs | Known load-flake class (#30): the 5 s poll deadline starves under suite load; test shares no code path with the cache | Verified green in isolation (0.131 s) each time; not a regression |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/PostLibrary.swift` | `PostScanCache` + `scan(home:cache:)` + `parse(text:...)` helper |
|
||||
| `Museion/PostsModel.swift` | app-scoped cache threaded through rescan; equality-gated `posts` assignment |
|
||||
| `MuseionTests/PostLibraryTests.swift` | 4 cache pins |
|
||||
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass + GitNexus counter |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] PostsModel.swift lint debt: over `file_length` (1127/1000) and `type_body_length` (361/350) at HEAD already; this change adds +8 net lines. House-pattern fix = move the file-scope extensions (pass orchestration / blind read / cards / promote) to their own file. Say the word.
|
||||
- [ ] Known ceilings (ponytail-marked in `PostScanCache`): same-size rewrite inside APFS timestamp granularity could serve a stale parse (upgrade: content hash); vanished-path entries linger (upgrade: prune to walked paths).
|
||||
|
||||
---
|
||||
|
||||
*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 -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 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-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-01 | issue | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) | #34 illustrations: media-endpoint upload, refs rewrite INLINE with URLs (dogfood killed the photo property); audit: injection/symlink/dedup — 546 tests |
|
||||
|
||||
Reference in new issue
Block a user