diff --git a/.gitignore b/.gitignore index 125afe4..65ddda9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .build/ .swiftpm/ DerivedData/ +_build/ **/xcuserdata/ .DS_Store CLAUDE.md diff --git a/.swiftformat b/.swiftformat index f3d4fa5..cf56aab 100644 --- a/.swiftformat +++ b/.swiftformat @@ -1,3 +1,4 @@ --swiftversion 6.3 --language-mode 5 --indent tab +--test-case-name-format preserve # convention is backticked sentence names; filter-safe camelCase exceptions allowed (#195, #31/#134) diff --git a/.swiftlint.yml b/.swiftlint.yml index 28bac03..2250019 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,7 +1,14 @@ disabled_rules: - trailing_comma # SE-0439 allows them in Swift 6; SwiftFormat adds them + - identifier_name # short closure params/locals (tv/ns/lo/hi) are idiomatic, not a signal + - inclusive_language # master/masterRoot profile-root vocabulary is deliberate domain naming (2026-11-17) + - file_length # deliberately large cohesive units + - type_body_length # deliberately large cohesive units + - nesting # idiomatic nested CodingKeys/enums + - optional_data_string_conversion # intentional lossy String(decoding:) for process/file output excluded: - DerivedData + - spike # throwaway SPM experiments, not built into any target line_length: warning: 140 error: 180 diff --git a/AGENTS.md b/AGENTS.md index 5817dee..404faf7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,8 +14,12 @@ Commands: open Museion.xcodeproj # develop in Xcode ./scripts/build-and-run.sh # build + launch from CLI (⌘R equivalent) xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build # build -xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # test (unit + UI) +xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # ad-hoc run incl. UI smoke (outside the rail); full-suite verification → full-test.sh below swiftformat . && swiftlint . # lint (run --fix first if dirty) +./scripts/full-test.sh start && ./scripts/full-test.sh status # verify rail (#190): detached full unit suite, xcresult-authoritative counts; status exits 3 while live +./scripts/full-test.sh summary # finished run's executed/passed/failed +./scripts/install-hooks.sh # once per clone: pre-push lint gate + no-push-while-testing +./scripts/test-full-test.sh # pre-push hook acceptance rig (disposable git repo, all ref shapes) ``` # DOX framework @@ -109,6 +113,7 @@ When the user requests a durable behavior change, record it here or in the relev | `Museion/AGENTS.md` | App target — SwiftUI app shell, assets, entitlements | | `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) | | `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet | +| `scripts/` | Verify rail + hooks + build/deploy scripts — contracts live in each script's header; full-test.sh is the sanctioned verify rail (#190), no child doc | | `docs/AGENTS.md` | Durable documentation — ADRs and their conventions | | `ref/writing skills/AGENTS.md` | Bundled writing-skill set — the G3a payload seeded into the museion profile | | `GLOSSARY.md` | Binding project glossary — shared vocabulary for app, mentor, and docs | @@ -130,7 +135,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6864 symbols, 33665 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** (7072 symbols, 36395 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). @@ -175,16 +180,20 @@ This project is indexed by GitNexus as **museion** (6864 symbols, 33665 relation +### Tooling & gates +- Repo-wide lint is green (#194 disabled deliberate-style rules; #195/#196 cleared every finding — `spike/` stays excluded as unbuilt experiments): bare `swiftlint .` reports zero violations and `swiftformat .` reformats nothing. +- xcodebuild can serve STALE binaries on a source edited seconds before invocation (zero `SwiftCompile` lines, suite starts 3 s in) — rapid edit→test cycles and flip runs must `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green (#197) +- SwiftFormat's default `swiftTestingTestCaseNames` rewrites camelCase `@Test` names back into backticked sentence style — renaming a test to a filter-safe plain identifier (#195, #31/#134) needs `--test-case-name-format preserve` in `.swiftformat`; `standard-identifiers` would dirty all ~496 backticked test names repo-wide +- git resolves short refs through `refs/tags/` before `refs/remotes/` — hooks and scripts spell `refs/remotes//` in full or a fetched tag named `origin/main` shadows the ref (#190) +- A bash function invoked before its definition no-ops (`command not found`) under `set -uo` without `-e` — hoist definitions above first use and guard rig verdicts by executed-check count, never the banner (#190) +- GitNexus `detect-changes` in this machine's multi-repo registry needs `--repo /absolute/path` — it aborts on ambiguity but rejects the `name (path)` label form it prints (#193) +- When splitting a file, re-derive each side's imports from symbol usage, never copy the old import block — Swift has no unused-import warning, so a stranded import (PostsPaneView's AppKit) survives lint and only a diff review catches it (#193) + ### Testing +- Gate-running rules are encoded in `scripts/full-test.sh` (#190) — run `./scripts/full-test.sh start` + `status` polling (`summary` for the finished counts), never hand-rolled xcodebuild/xcresult incantations. The rest of this section is authoring rules the script cannot encode. - A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162) -- Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) -- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) -- `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178) +- Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197) - A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178) -- Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33); the race persists in a chained read one command later — read the bundle from a LATER terminal invocation and retry the identical read once before diagnosing (#179) -- A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177) -- Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177) -- `test-without-building` tests the BUILT PRODUCTS, not the sources — a rename/edit landing after `build-for-testing` (e.g. while a long suite runs in background) leaves the green detached from the tree; rebuild + rerun for the definitive gate (#182) - Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33) - An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151) - When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift ` check of the pure logic still verify honestly (#134) @@ -207,16 +216,15 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | -|------|-----| -| 2026-11-10 | [20261110-issue179-followup-bind-root-task_log.md](docs/devlog/20261110-issue179-followup-bind-root-task_log.md) | +| --- | --- | +| 2026-11-17 | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | +| 2026-11-17 | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | +| 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | +| 2026-11-17 | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | +| 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) | +| 2026-11-13 | [20261113-cold-turkey-full-tokenization_log.md](docs/devlog/20261113-cold-turkey-full-tokenization_log.md) | +| 2026-11-11 | [20261111-fix-library-search-stale-after-mutation_log.md](docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md) | | 2026-11-10 | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](docs/devlog/20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) | | 2026-11-10 | [20261110-issue182-profilelayout-config-set-rail_log.md](docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md) | | 2026-11-10 | [20261110-issue181-provider-descriptor-pass-readiness_log.md](docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md) | -| 2026-11-10 | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | -| 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) | -| 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) | -| 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | -| 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) | -| 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_log.md) | -| 2026-11-05 | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](docs/devlog/20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 48b2f55..e728ac9 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -23,8 +23,13 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in `docs/devlog/`. - `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system). -- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`. -- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column. +- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller). +- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`. +- `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108). +- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them. +- `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column. +- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process. +- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it. - `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects///post.md` AND `archive///post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil. - `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture. - `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `![alt](assets/…)` builder. @@ -36,7 +41,10 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4). - `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends. - Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept. -- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail. +- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive). +- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal`/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`). - `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID. - `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load. - `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction. diff --git a/Museion/ArchivePaneView.swift b/Museion/ArchivePaneView.swift new file mode 100644 index 0000000..4a2b5e9 --- /dev/null +++ b/Museion/ArchivePaneView.swift @@ -0,0 +1,176 @@ +// +// ArchivePaneView.swift +// Museion +// +// #193: the #108 Archive pane, moved from WorkspaceView.swift +// (file-length ceiling), code unchanged (private → internal: +// WorkspaceView instantiates it cross-file now). +// + +import SwiftUI + +/// #108: the Archive pane — archive/ as a rail destination (prototype +/// verdict: a destination, not a library disclosure). List-only: clicking a +/// piece selects it and hops to Posts, where the editor column lives. +struct ArchivePaneView: View { + var model: PostsModel + /// Fired after a row select — the pane can't reach WorkspaceView's + /// selection itself. + let onOpenPiece: () -> Void + @State private var renamingPost: Post? + /// #108: collapsed project sections — per-view state, not persisted + /// (mirrors the library column). + @State private var collapsed: Set = [] + + private var archivedByProject: [String: [Post]] { + Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project) + } + + /// #108: the prototype's toggle — click the project name (or chevron). + private func toggle(_ project: String) { + if collapsed.contains(project) { + collapsed.remove(project) + } else { + collapsed.insert(project) + } + } + + var body: some View { + VStack(spacing: 0) { + // No New button — things arrive here by being moved, not created. + // r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME + // fixed 720pt column the rows live in — one framed block. + PaneHeader(title: "Archive", hairlineMaxWidth: 720) + if archivedByProject.isEmpty { + emptyState + } else { + ScrollView { + LazyVStack(alignment: .leading, spacing: 4) { + // #108 audit: Finder order, matching the library's sort. + ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in + let pieces = archivedByProject[project] ?? [] + // Same section-head shape as the library (#108 + // variant B), plus the project-level way out. + // r7 (mercury#55, argon#41 — FINAL, supersedes the + // r6 D24 ladder): the content column is a FIXED + // 720pt frame (width, not maxWidth — the r6 + // content-hugging bound let the pill define the + // right edge), left-anchored. TWO axes only, the + // library's r7 ladder: the head row leads at x14 + // (chevron in a 14pt slot) with its label at x28 — + // the ONE indent, shared with the entry rows' + // inner text via the shared LibraryPostRow (cards + // lead at x14); the 'Unarchive Group' pill rides + // the header row's trailing edge INSIDE the frame + // (14 → 706), and the row hairlines are bounded by + // the same frame. Nothing spans past it. + HStack(alignment: .firstTextBaseline, spacing: 0) { + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .semibold)) + .frame(width: 14, alignment: .leading) + .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) + .foregroundStyle(DesignTokens.muted) + .onTapGesture { + withAnimation { toggle(project) } + } + .accessibilityLabel("Toggle \(project)") + .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") + Text(project) + .font(.system(size: 11, weight: .medium, design: DesignTokens.mono)) + .kerning(0.6) + .textCase(.uppercase) // #108: display-only — the folder name keeps its case + .foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final + .lineLimit(1) + .truncationMode(.tail) + .onTapGesture { + withAnimation { toggle(project) } + } + Text("· \(pieces.count)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .padding(.leading, 8) + Spacer(minLength: 8) + // The 'New Post · Fork · Compact' language — a + // bordered mono-11 secondary pill at the + // trailing edge INSIDE the fixed 720pt frame. + // r7 (mercury#55, argon#41): relabeled + // 'Unarchive Group' — it moves the whole + // project, not one piece. + Button("Unarchive Group") { + model.unarchiveProject(project) + } + .buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24)) + .help("Move the whole project back to projects/") + .accessibilityLabel("Unarchive \(project)") + } + .padding(.top, 12) + .padding(.horizontal, 14) + .padding(.bottom, 2) + if !collapsed.contains(project) { + ForEach(pieces) { post in + // r7: the shared LibraryPostRow ladder — + // card leads at x14 (PRIMARY), title text + // at x28 (the one indent). The hairline is + // BOUNDED to the fixed frame: x14 → 706. + LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { + model.select(post.id) + onOpenPiece() + } + .overlay(alignment: .bottom) { + Rectangle() + .fill(DesignTokens.border) + .frame(height: 1) + .padding(.horizontal, 14) + } + .contextMenu { + Button("Move Back to \(post.project)") { + model.restorePost(post) + } + Button("Rename…") { renamingPost = post } + // #114 (S4): works archived too — the piece + // stays where it is, only type + body flip. + if post.type == .outline { + Button("Convert to Post…") { + model.stageConversion(post) + } + } + } + } + } + } + } + // r7 (mercury#55, argon#41): the FIXED 720pt reading + // column — width, not maxWidth (the r6 content-hugging + // bound let the pill define the right edge); rows, + // hairlines, and the pill all live inside it. + // ponytail: fixed width clips on panes narrower than + // 720 — a width-floored variant if a small-window + // Archive ever matters. + .frame(width: 720, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.bottom, 12) + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(DesignTokens.background) + .sheet(item: $renamingPost) { post in + RenamePostSheet(post: post) { title in + model.rename(post, to: title) + } + } + } + + private var emptyState: some View { + VStack(spacing: 8) { + Text("Nothing archived") + .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) + Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + .multilineTextAlignment(.center) + } + .padding(38) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} diff --git a/Museion/LearningsPaneView.swift b/Museion/LearningsPaneView.swift index 598aea9..a346680 100644 --- a/Museion/LearningsPaneView.swift +++ b/Museion/LearningsPaneView.swift @@ -75,8 +75,10 @@ nonisolated enum LearningsIndex { ) else { return [] } var groups: [Group] = [] for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { - guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) - else { continue } + guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), + let files = try? FileManager.default.contentsOfDirectory( + at: dir, includingPropertiesForKeys: nil, + ) else { continue } // #27: the pass clock feeds the decay verdict — clocked dirs // carry their count, foreign dirs nil (no verdict; Entry's audit). let currentPass = LearningDecay.isClocked(dir.lastPathComponent) @@ -109,9 +111,14 @@ nonisolated enum LearningsIndex { return groups } + /// Parens load-bearing for readability — `&&` out-binds `??` (probed; + /// a finish-audit misread the bare form as a dead symlink clause). + /// lstat semantics: a symlink-to-dir reports isDirectory=false, so + /// both halves refuse it; the link clause is the belt for any future + /// resolved-URL caller. private static func isPlainDirectory(_ url: URL) -> Bool { let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false) + return (values?.isDirectory ?? false) && !(values?.isSymbolicLink ?? false) } } diff --git a/Museion/LibraryPostRow.swift b/Museion/LibraryPostRow.swift new file mode 100644 index 0000000..d0e36a9 --- /dev/null +++ b/Museion/LibraryPostRow.swift @@ -0,0 +1,94 @@ +// +// LibraryPostRow.swift +// Museion +// +// #193: the shared post row, moved from PostsPaneView.swift +// (file-length ceiling) — the Archive pane reuses it, code +// unchanged. +// + +import SwiftUI + +/// One post row per the export: title + origin-only mono-11 meta (the Pass +/// State rides the uppercase group label above; it stays in the a11y label). +/// #108 (variant B): 2px accent edge bar on the leading side when selected +/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, +/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the +/// Archive pane reuses it. +struct LibraryPostRow: View { + let post: Post + let selected: Bool + let select: () -> Void + @State private var hover = false + + var body: some View { + // `.vB .post-row { border-left: 2px solid transparent; + // border-radius: 0 8px 8px 0 }` — every row: leading corners square + // (the 2px strip below), trailing rounded 8. Only the strip's + // VISIBILITY changes on selection. + let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) + return Button(action: select) { + HStack(spacing: 0) { + // The leading strip is always 2px wide so hover/selection + // never shifts the title. r6 (mercury#49/52, argon#13): + // the shared SelectedRowStrip capsule — accent, radius-1 + // ends, vertically inset 6pt (was 3) so it sits INSIDE + // the card, never pasted on its square leading edge. + SelectedRowStrip() + .opacity(selected ? 1 : 0) + VStack(alignment: .leading, spacing: 5) { + HStack(alignment: .firstTextBaseline, spacing: 0) { + Text(post.title) + if post.type == .outline { + Text(" ✳") + .foregroundStyle(DesignTokens.muted) + } + } + // ui-polish r8: serif-13 per the row contract — `.callout` + // was the system sans design (the r6/r7 councils pixel- + // verified sans glyphs on the Archive rows). + .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + // Origin only — the Pass State already rides the uppercase + // group label above (it stays in the accessibility label). + // r7: the status micro-label sits INSIDE the row's content + // padding — same x as the title, never flush with the edge. + Text(post.origin.rawValue) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + } + .clipShape(shape) + } + .buttonStyle(.plain) + .foregroundStyle(DesignTokens.foreground) + .background { + if selected || hover { + // r8 (mercury#11): the selected row DROPS its gray outline — + // fill + accent capsule read as ONE shape; stacking fill + + // outline + capsule competed. Hover keeps its borderless + // 0.06 wash exactly as before. + shape + .fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06)) + } + } + // r7 (mercury#18, argon#12 — two-axis ladder): the row CARD + // leads at the PRIMARY inset (x14, the 'Posts' header text's + // edge); its INNER content (title + status micro-label, strip + // 2 + padding 12) lands at x28 — the ONE indent step, shared + // with the head text and the group labels. No other x-axis + // exists in the column. Vertical padding stays the content + // VStack's constant 10 whether or not the row shows its strip. + .padding(.horizontal, 14) + .onHover { hover = $0 } + // help sits on the row — the ✳ span isn't individually hoverable in + // SwiftUI (prototype: `title="outline"` on the star). + .help(post.type == .outline ? "\(post.title) — outline" : post.title) + .accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)") + } +} diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index 7008445..a6f519b 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -149,13 +149,17 @@ nonisolated enum SessionRoster { let dir = directory ?? defaultDirectory do { try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json") try JSONEncoder().encode(entries).write( - to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"), + to: rosterURL, options: .atomic, ) // Finish-audit: names+ids only, but piece titles are the writer's // business — the default umask would hand them to every local user. - try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path) + // ponytail: post-hoc chmod leaves a sub-second world-readable window + // between write and chmod — createFile(0600)+rename if a hostile + // local account ever matters. + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: rosterURL.path) } catch { // ponytail: the roster is a convenience index; a write failure must not crash the gate. } diff --git a/Museion/OutlineEditorView.swift b/Museion/OutlineEditorView.swift index b476b7b..98e5ed4 100644 --- a/Museion/OutlineEditorView.swift +++ b/Museion/OutlineEditorView.swift @@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter { _ nodes: [OutlineNode], folded: Set, zoomRootID: UUID? = nil, ) -> [Row] { var rows: [Row] = [] - if let zoomRootID, - let rootPath = path(of: zoomRootID, in: nodes), - let root = node(at: rootPath, in: nodes) - { + if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) { walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows) } else { walk(nodes, parent: [], depth: 0, folded: folded, into: &rows) @@ -776,27 +773,14 @@ extension OutlineEditorView { } case let .hop(direction): // ↑/↓ hop VISIBLE blocks — folded subtrees are skipped. - let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) - if let current = rows.firstIndex(where: { $0.id == focusedID }), - rows.indices.contains(current + direction) - { - focusedID = rows[current + direction].id - selectionAnchor = nil - pendingCaret = nil // caret at end of the target row - } + hopFocus(direction, clearsAnchor: true) case let .extend(direction): // ⇧↑/⇧↓: extend the block selection one visible row. First // press anchors at the focused row; a bare ↑/↓ or click clears. if let focusedID { extendSelection(to: focusedID) // arm the anchor at the current focus } - let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) - if let current = rows.firstIndex(where: { $0.id == focusedID }), - rows.indices.contains(current + direction) - { - focusedID = rows[current + direction].id - pendingCaret = nil - } + hopFocus(direction, clearsAnchor: false) case .deselect: _ = handleEscape() // selection first, then zoom — same order as the monitor case .indent, .outdent, .moveUp, .moveDown, .enter: @@ -804,20 +788,27 @@ extension OutlineEditorView { } } + /// Move focus `direction` visible rows from its current position (nil at + /// the list edges — folded subtrees are skipped). `clearsAnchor` + /// distinguishes hop (clears the block-selection anchor) from extend. + private func hopFocus(_ direction: Int, clearsAnchor: Bool) { + let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) + guard let current = rows.firstIndex(where: { $0.id == focusedID }), + rows.indices.contains(current + direction) + else { return } + focusedID = rows[current + direction].id + if clearsAnchor { + selectionAnchor = nil + } + pendingCaret = nil // caret at end of the target row + } + /// Tree-mutating ops (indent/outdent/move/enter). Serialize + route /// focus only when something actually changed (boundary no-ops are /// nil and leave the document alone). private func applyTree(_ op: OutlineRowTextView.StructureOp) { guard let focusedID else { return } - // Block selection + batchable op → run-wide apply. Moves treat - // the run as a unit (boundary leader no-ops the whole batch). - if let anchor = selectionAnchor, - let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1, - let batchOp = map(op) - { - if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { - pushToDocument() - } + if applyBatchIfPossible(op, focus: focusedID) { return } guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return } @@ -833,27 +824,52 @@ extension OutlineEditorView { case .moveDown: didChange = OutlineTree.move(&nodes, path: path, up: false) != nil case let .enter(caretGraphemes): - switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { - case .noOp: - break - case let .outdented(newPath): - didChange = newPath != nil // nil = boundary no-op - case let .newNode(newPath, caret): - didChange = true - if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id { - newFocus = (id, caret) - } - } + let enter = applyEnter(caretGraphemes: caretGraphemes, path: path) + didChange = enter.didChange + newFocus = enter.focus case .fold, .unfold, .hop, .extend, .deselect: return // unreachable — apply(_:) routes those to view state } - if didChange { - if let newFocus { - self.focusedID = newFocus.id - pendingCaret = newFocus.caret - } + commitIfChanged(didChange, newFocus) + } + + /// Serialize + route focus only when something actually changed. + private func commitIfChanged(_ didChange: Bool, _ newFocus: (id: UUID, caret: Int)?) { + guard didChange else { return } + if let newFocus { + focusedID = newFocus.id + pendingCaret = newFocus.caret + } + pushToDocument() + } + + /// Block-selection fast path: a batchable op over a multi-row run + /// (moves treat the run as a unit — a boundary leader no-ops the whole + /// batch). Returns true when the batch ran (caller stops here). + private func applyBatchIfPossible(_ op: OutlineRowTextView.StructureOp, focus: UUID) -> Bool { + guard let anchor = selectionAnchor, + let range = selectedRangeIDs(anchor: anchor, focus: focus), range.count > 1, + let batchOp = map(op) + else { return false } + if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { pushToDocument() } + return true + } + + /// Split (⏎) at `path`: serialize through OutlineTree.enter; focus + /// follows the NEW node when one was created (nil path = boundary + /// no-op). + private func applyEnter(caretGraphemes: Int, path: [Int]) -> (didChange: Bool, focus: (id: UUID, caret: Int)?) { + switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { + case .noOp: + return (false, nil) + case let .outdented(newPath): + return (newPath != nil, nil) // nil = boundary no-op + case let .newNode(newPath, caret): + let id = OutlinePresenter.node(at: newPath, in: nodes)?.id + return (true, id.map { ($0, caret) }) + } } /// The selected row ids in visible order (anchor↔focus, inclusive). diff --git a/Museion/PostsLibraryColumn.swift b/Museion/PostsLibraryColumn.swift new file mode 100644 index 0000000..4a5bac1 --- /dev/null +++ b/Museion/PostsLibraryColumn.swift @@ -0,0 +1,521 @@ +// +// PostsLibraryColumn.swift +// Museion +// +// #193: the Posts library column, moved from PostsPaneView.swift +// (file-length ceiling) — PostsLibraryColumn with its rename/move +// sheets, the file-scope librarySearch mount (#144), and +// LaunchFocusReset (r8), code unchanged. +// + +import AppKit +import SwiftUI + +/// #21: the library column, shared by the unfocused layout and the focus-mode +/// left reveal overlay — one implementation, both surfaces. Owns the rename + +/// move sheets and the context menu (they travel with the post rows). +/// #108 variant B: sections per project, Pass-State groups inside. +struct PostsLibraryColumn: View { + let home: URL + var model: PostsModel + @State private var renamingPost: Post? + @State private var movingPost: Post? + /// #108: collapsed project sections — per-view state, not persisted (a + /// fresh open shows everything; the prototype behaved the same). + @State private var collapsed: Set = [] + /// #144: the library search — live title+body filter over the + /// non-archived pieces. nil = not searching (sections render). + @State private var query = "" + /// #144 (mounted half): the landed sweep — results plus the key that + /// computed them. nil = not searching or recomputing (the sections / + /// spinner states); a snapshot that isn't `isFresh` for the current + /// key never renders. + @State private var snapshot: LibrarySearch.Snapshot? + /// r5 (argon#44, mercury#52, sol#37): focus state for the field's + /// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7 + /// onAppear-unfocus could never work — the launch focus is AppKit + /// assigning the window's INITIAL first responder to its first text + /// input (this field), at window-become-key, AFTER onAppear. FocusState + /// merely mirrors that back as true. LaunchFocusReset (below) resigns + /// it at the first become-key; from then on only the user drives this. + @FocusState private var searchFocused: Bool + + private var trimmedQuery: String { + query.trimmingCharacters(in: .whitespacesAndNewlines) + } + + /// #144 (mounted half): the sweep's identity — trimmed query, the + /// Home, and the library content revision (`PostsModel.contentRevision`, + /// bumped by the rescan rail on any list change or re-read body). The + /// `.task(id:)` below re-keys on ANY difference, so library writes and + /// Home repoints restart the sweep instead of leaving stale rows; the + /// landed snapshot renders only while `isFresh` for the current key. + private var searchKey: LibrarySearch.SearchKey { + LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision) + } + + private var isSearching: Bool { + !trimmedQuery.isEmpty + } + + /// Non-archived pieces keyed by project (scan order = title order holds + /// inside each group — filter preserves it). + private var activeByProject: [String: [Post]] { + Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project) + } + + var body: some View { + VStack(spacing: 0) { + PaneHeader(title: "Posts") { + Button { + model.newPost() + } label: { + Image(systemName: "plus") + } + .buttonStyle(.plain) + .foregroundStyle(DesignTokens.muted) + .help("New Post") + .accessibilityLabel("New Post") + } + searchField + if isSearching { + // #144 (mounted half): a landed sweep renders only while + // fresh for the CURRENT key — a library write that bumped + // the revision (archive, trash, rename, body edit) or a + // moved query drops to the recompute state, never stale rows. + if let snapshot, snapshot.isFresh(for: searchKey) { + if snapshot.results.isEmpty { + searchEmptyState + } else { + searchResults(snapshot.results) + } + } else { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } else if activeByProject.isEmpty { + emptyState + } else { + ScrollView { + LazyVStack(alignment: .leading, spacing: 4) { + // #108 audit: Finder order (scan's own sort), not Unicode-scalar + // order — the heads render lowercased, "Beta" must not read before "apple". + ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in + let pieces = activeByProject[project] ?? [] + // #108: the head is the prototype's toggle — click + // collapses the project's pieces (chevron rotates). + Button { + withAnimation { + if collapsed.contains(project) { + collapsed.remove(project) + } else { + collapsed.insert(project) + } + } + } label: { + // r7 (mercury#18, argon#12 — TWO-AXIS ladder, + // the r6 four-step collapse undone): the + // head ROW leads at the column's PRIMARY + // inset (x14) — chevron glyph in a 14pt slot + // — and every nested CONTENT shares the one + // indent step (x28): head text, group + // labels, and the rows' inner text. No third + // or fourth x-axis exists in the column. + HStack(alignment: .firstTextBaseline, spacing: 0) { + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .semibold)) + .frame(width: 14, alignment: .leading) + .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) + .foregroundStyle(DesignTokens.muted) + Text(project) + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + .textCase(.lowercase) // #108: display-only — the folder name keeps its case + .lineLimit(1) + .truncationMode(.tail) + Text("· \(pieces.count)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + Spacer(minLength: 0) + } + } + .buttonStyle(.plain) + .foregroundStyle(DesignTokens.foreground) + .accessibilityLabel("\(project), \(pieces.count) pieces") + .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") + .padding(.top, 16) + .padding(.horizontal, 14) + .padding(.bottom, 6) + if !collapsed.contains(project) { + passStateGroups(pieces) + } + } + } + .padding(.bottom, 12) + } + } + } + .frame(width: DesignTokens.libraryWidth) + // r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7 + // onAppear-unfocus — see LaunchFocusReset below for the mechanism. + .background(LaunchFocusReset()) + .sheet(item: $renamingPost) { post in + RenamePostSheet(post: post) { title in + model.rename(post, to: title) + } + } + .sheet(item: $movingPost) { post in + // #108 audit 2: disk-derived list, localized-sorted — same order + // the library renders (Unicode-scalar sort split them), and it + // includes empty projects (a fresh New Project has no pieces yet — + // it must already be a move target). + MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in + model.moveToProject(post, project: project) + } + } + // #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). Keyed to the full + // search key: a library write (revision bump) or a Home repoint + // restarts the sweep too. The snapshot lands under the key + // captured at start; a mid-sweep key change cancels here, and + // even a raced assignment can't render — body gates on isFresh. + .task(id: searchKey) { + let key = searchKey + guard !key.query.isEmpty else { + snapshot = nil + return + } + try? await Task.sleep(for: .milliseconds(250)) + guard !Task.isCancelled else { return } + let found = await librarySearch( + candidates: model.posts.filter { !$0.isArchived }, + matching: key.query, + home: home, + ) + guard !Task.isCancelled else { return } + snapshot = LibrarySearch.Snapshot(key: key, results: found) + } + } + + /// 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) { + model.select(post.id) + } + .contextMenu { + Button("Rename…") { renamingPost = post } + // #114 (S4): outline pieces only — the ask picks the + // body transform, then the piece becomes a prose post. + if post.type == .outline { + Button("Convert to Post…") { + model.stageConversion(post) + } + } + Button("Move to Project…") { movingPost = post } + Button("Move to Archive") { + model.archivePost(post) + } + Button("Move to Trash", role: .destructive) { + model.trash(post) + } + } + } + + /// Pass-State groups inside one project (`.vB .group-label`: smaller, + /// softer, indented under the section head). r2: the label binds to + /// its FIRST row (bottom 1 + stack 4) — it floated closer to the + /// preceding row than to its own children. + 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 { + // mercury#53 (r5): display-only normalization — the stored + // rawValues keep their hyphen ("Pass-1 Done"); the rendered + // label uses the space form so it matches the Pass 1 / Pass 2 + // vocabulary everywhere else. + Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " ")) + .font(.system(size: 11, weight: .medium, design: DesignTokens.mono)) + .kerning(0.6) + // r6 (sol#6/21 — contrast final): group labels are + // informational meta — FULL muted ink, no wash. + .foregroundStyle(DesignTokens.muted) + // r6 ladder: full muted ink. r7 two-axis: x28 — the ONE + // indent step, shared with the head text and the row + // cards' inner content. + .padding(.leading, 28) + .padding(.top, 10) + .padding(.bottom, 1) + ForEach(grouped) { post in + postRow(post) + } + } + } + } + + /// #144 + mercury#54 (r4): a real field surface — surface fill + hairline + /// border on the column's chrome, taller than a text row; the placeholder + /// r5 (argon#44, mercury#52, sol#37): the insertion caret tints + /// terracotta (.tint on the field), and the small magnifier glyph sits at + /// the field's leading edge (icon→text spacing rides the HStack's 6pt); + /// the placeholder is the native prompt wearing the palette's muted ink + /// (the composer's pattern). + /// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6, + /// present but never the strongest saturation on screen. + private var searchField: some View { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass") + .font(.system(size: 11)) + .foregroundStyle(DesignTokens.muted) + TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted)) + .textFieldStyle(.plain) + .font(.system(size: 12)) + .focused($searchFocused) + .tint(DesignTokens.accent) + if isSearching { + Button { + query = "" + } label: { + Image(systemName: "xmark.circle.fill") + } + .buttonStyle(.plain) + .foregroundStyle(DesignTokens.muted) + .accessibilityLabel("Clear search") + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 8) + .fill(DesignTokens.surface) + .overlay( + // r8 (argon#6, mercury#12): quiet focus — accent at 0.6, + // one step down from full strength. + RoundedRectangle(cornerRadius: 8) + .strokeBorder( + searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border, + lineWidth: 1, + ), + ), + ) + // r7 (mercury#18, argon#12 — two-axis ladder): the box spans the + // FULL padded column width at the PRIMARY inset — leading 14 + // (aligned with the 'Posts' header text) to trailing 14 — the + // same edges the row cards lead at. + .padding(.horizontal, 14) + .padding(.vertical, 8) + } + + /// 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: 11, design: DesignTokens.mono)) + .kerning(0.6) + // r6: full muted ink; r7 two-axis: x28 — the indent + // step, heading the flat result list exactly where + // group labels head their sections. + .foregroundStyle(DesignTokens.muted) + .padding(.leading, 28) + .padding(.top, 12) + .padding(.bottom, 1) + 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 { + VStack(spacing: 8) { + Text("No posts yet") + .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) + Text("Posts in this Home's projects/ folders appear here.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + .multilineTextAlignment(.center) + } + .padding(38) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +/// #144: the title+body scan — a thin mount for the pure +/// `LibrarySearch` seam (title matches first, stable partition, both +/// halves keep the scan's Finder order; body via readBody — frontmatter +/// never searched), pinned by MuseionTests/LibrarySearchTests.swift. +/// The reader's per-piece cancellation check stops a superseded sweep's +/// body reads between files; the in-memory title walk itself completes +/// cheaply and the caller's guard discards its result. File scope since +/// r6 (PostsLibraryColumn hit its type-body ceiling). +/// +/// ponytail: full-body re-read per sweep (folder(of:) re-walked per +/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex +/// posture); a PostScanCache-style body memo if it ever measures hot. +private nonisolated func librarySearch( + candidates: [Post], + matching trimmed: String, + home: URL, +) async -> [Post] { + LibrarySearch.results(for: trimmed, in: candidates) { post in + guard !Task.isCancelled else { return nil } + return PostStore.readBody(id: post.id, home: home) + } +} + +/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at +/// the source): the search field is the window's first — and at launch, +/// only — text input, and AppKit assigns the window's initial first +/// responder to it when the window becomes key. That happens AFTER +/// onAppear, so the r6/r7 `searchFocused = false` writes were always +/// overridden (FocusState mirrors the assignment back as true: terracotta +/// ring + caret, the strongest element on screen). This invisible rider +/// rides the library column and, at the window's FIRST become-key, +/// resigns focus back to the window itself (`makeFirstResponder(nil)` — +/// the neutral state; nothing gains focus instead). ONCE per process: a +/// pane-switch remount must never steal a focus the user set on return. +/// The second, next-runloop resign covers an assignment that lands after +/// the notification (the PostEditorView layout-race precedent). +private struct LaunchFocusReset: NSViewRepresentable { + /// Process-wide once-flag — launch is a once-per-process event. + private static var hasRun = false + + final class RiderView: NSView { + private var keyObserver: NSObjectProtocol? + + override func viewDidMoveToWindow() { + if let keyObserver { + NotificationCenter.default.removeObserver(keyObserver) + } + keyObserver = nil + guard let window else { return } + keyObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didBecomeKeyNotification, + object: window, + queue: .main, + ) { _ in + MainActor.assumeIsolated { + // The observer is scoped to `window` (object:), so the + // notification carries nothing we don't already hold — + // reading `note` here would cross a Sendable boundary. + guard !LaunchFocusReset.hasRun else { return } + LaunchFocusReset.hasRun = true + window.makeFirstResponder(nil) + DispatchQueue.main.async { window.makeFirstResponder(nil) } + } + } + } + } + + func makeNSView(context _: Context) -> RiderView { + RiderView() + } + + func updateNSView(_: RiderView, context _: Context) {} +} + +/// #108: Move to Project ask — radio list of the non-archived projects, +/// default = the piece's current project. Matches RenamePostSheet's shape. +struct MoveToProjectSheet: View { + let post: Post + let projects: [String] + let move: (String) -> Void + @Environment(\.dismiss) private var dismiss + @State private var target: String + + init(post: Post, projects: [String], move: @escaping (String) -> Void) { + self.post = post + self.projects = projects + self.move = move + _target = State(initialValue: post.project) + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Move to Project") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("“\(post.title)” moves into the chosen project. The file stays post.md.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + Picker("Project", selection: $target) { + ForEach(projects, id: \.self) { name in + Text(name).tag(name) + } + } + .pickerStyle(.radioGroup) + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Move") { + move(target) + dismiss() + } + .keyboardShortcut(.defaultAction) + .disabled(target == post.project) + } + } + .padding(20) + .frame(width: 360) + } +} + +/// #60: Explicit Rename dialog — asks the new Title (not a slug). +struct RenamePostSheet: View { + let rename: (String) -> Void + @Environment(\.dismiss) private var dismiss + @State private var title: String + + init(post: Post, rename: @escaping (String) -> Void) { + self.rename = rename + _title = State(initialValue: post.title) + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Rename Post") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("The folder moves to match the new Title. The file stays post.md.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + TextField("Title", text: $title) + .textFieldStyle(.roundedBorder) + .onSubmit { confirm() } + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Rename", action: confirm) + .keyboardShortcut(.defaultAction) + .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(20) + .frame(width: 360) + } + + private func confirm() { + let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + rename(trimmed) + dismiss() + } +} diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 7cc87a3..1d59bda 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -2,24 +2,19 @@ // PostsModel.swift // Museion // -// #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece -// roots (projects/ + archive/, #107) with a ~0.5 s debounced rescan (#61), -// selection, and the New Post draft lifecycle (#62). Own ops route through -// the same rescan: one path. -// #108: project targeting + the move/archive/restore ops behind the -// variant-B library and the Archive pane. -// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in -// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching -// + rescan sit in the file-scope watcher extension below (type-body -// ceiling). +// #18 (S1.1): the Posts pane's write side — selection and the New Post +// draft lifecycle (#62). Own ops route through the same rescan: one path. // #179: every library-reflecting store write rides `performWrite` — the // one write rail pairing each write with exactly one rescan and owning -// the error strip (card closes and the pass substrate stay off it: they -// never regroup the library); the model owns the Home (watchedHome), no -// method takes one. +// the error strip; the model owns the Home (watchedHome), no method +// takes one. +// #146/#193: the domain extensions live in their own files — guard+ +// Convert PostsModelOutline, passes+Blind Read PostsModelPasses, fix +// cards PostsModelCards, write rail+structural ops PostsModelWrites, +// external guest+imports PostsModelImports, watcher+rescan +// PostsModelWatcher. // -import CoreServices import Foundation import Observation @@ -38,55 +33,6 @@ struct PostDraft { let mountID = UUID() } -/// Recursive FSEvents stream on one or more directories (#61): file-level -/// events, so nested `projects///post.md` edits from Finder fire -/// too — a plain dir-FD dispatch source only sees direct children and misses -/// them. -final nonisolated class PostsWatcher: @unchecked Sendable { - /// Fired on the main actor when anything under a watched path changes. - var onEvent: (@MainActor @Sendable () -> Void)? - - private var stream: FSEventStreamRef? - - func start(urls: [URL]) { - stop() - var context = FSEventStreamContext( - version: 0, - info: Unmanaged.passUnretained(self).toOpaque(), - retain: nil, - release: nil, - copyDescription: nil, - ) - // C function pointer — no captures; `self` rides the info pointer. - let callback: FSEventStreamCallback = { _, info, _, _, _, _ in - let watcher = Unmanaged.fromOpaque(info!).takeUnretainedValue() - Task { @MainActor in watcher.onEvent?() } - } - guard let stream = FSEventStreamCreate( - kCFAllocatorDefault, - callback, - &context, - urls.map(\.path) as CFArray, - FSEventStreamEventId(kFSEventStreamEventIdSinceNow), - 0.5, // seconds; FSEvents coalesces within this latency (the #61 window) - FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents), - ) else { return } - FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) - FSEventStreamStart(stream) - self.stream = stream - } - - func stop() { - guard let stream else { return } - FSEventStreamStop(stream) - FSEventStreamInvalidate(stream) - FSEventStreamRelease(stream) - self.stream = nil - } - - deinit { stop() } -} - /// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern). /// The watcher runs while the workspace is open (app-scoped, #61). @MainActor @@ -94,7 +40,8 @@ final nonisolated class PostsWatcher: @unchecked Sendable { final class PostsModel { /// The scanned, title-sorted list — mirrors `projects/` + `archive/` at /// all times (#107). - private(set) var posts: [Post] = [] + /// #193: setter internal — PostsModelWatcher's rescan writes it. + var posts: [Post] = [] /// #144 (mounted half): the library content revision — the search /// snapshot's invalidation signal. The rescan rail bumps it whenever @@ -103,7 +50,8 @@ final class PostsModel { /// keeps the list still — yet the search must re-sweep). The `posts` /// assignment skip stays untouched: panes never regroup on bumps, /// only the mounted search re-keys. - private(set) var contentRevision = 0 + /// #193: setter internal — PostsModelWatcher's rescan bumps it. + var contentRevision = 0 /// The selected Post's id; nil = nothing selected (empty editor). /// #146: setter internal — the split-out domain extensions set it. @@ -121,11 +69,13 @@ final class PostsModel { /// #92: the external buffer's guest slot — one at a time, transient per /// launch. Takes the editor column; opening a Post or draft dismisses it /// (flush first). - private(set) var externalSession: EditorSession? + /// #193: setter internal — PostsModelImports owns the guest slot. + var externalSession: EditorSession? /// #94: a multi-file import waiting on its ONE Origin ask; the sheet /// answers, then the batch runs. - private(set) var pendingImportURLs: [URL]? + /// #193: setter internal — PostsModelImports stages the batch. + var pendingImportURLs: [URL]? /// #108: the explicit target for the NEXT new piece — set by New Project /// once the folder exists; outranks selection. Cleared when the draft @@ -136,7 +86,8 @@ final class PostsModel { /// #108: File ▸ New Project… stages its ask here — commands can't /// present sheets, so the model holds the flag and WorkspaceView /// presents (the pendingImportURLs pattern, #94). - private(set) var askNewProject = false + /// #193: setter internal — PostsModelWrites stages the ask. + var askNewProject = false /// #109: the just-saved outline draft's afterglow — the posts list /// lags one rescan (the FSEvents window), so the freshly-opened @@ -189,63 +140,21 @@ final class PostsModel { /// driven by WorkspaceView's root `.task(id: museionHome)` (first frame /// + every repoint, whichever pane is showing); no public method takes /// a Home parameter, callers pass none. - /// `private(set)` — the setter stays PostsModel.swift-file-private. - private(set) var watchedHome: URL? - private var watcher = PostsWatcher() + /// #193: setter internal — PostsModelWatcher's startWatching (the one + /// writer) is a split-out extension now. + var watchedHome: URL? + 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() + 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() - - /// Bind a Home: ensure both container roots exist (FSEvents on a missing - /// path is unreliable; archive/ is a watcher root now, #107), initial - /// scan + start (or restart) the watcher. Called from WorkspaceView's - /// root `.task(id: museionHome)` — first frame and every Home repoint, - /// pane-independent. - func bind(home: URL) { - startWatching(home: home) - Task { await rescan() } - } - - // MARK: Own ops (route through the same rescan, #61) - - // ponytail: the PostStore calls here run on MainActor — small single-file - // writes and same-volume moves; if a big Home ever stalls the UI, wrap - // them in Task.detached like rescan. - - /// #179: the write rail — ONE seam pairs every library store write with - /// exactly one rescan and owns the error strip. A verb passes its - /// PostStore write (plus any post-write state surgery); a throw lands - /// its reason in the strip with nothing rescanned, a clean run rescans - /// once. The strip clears BEFORE the write, so a batch write that sets - /// its own per-file failure messages mid-closure (importFiles) keeps - /// them. The editor's debounced flush stays OUTSIDE the rail — its - /// error semantics are the session's own (EditorSession.onError). - /// Returns nil when the write landed; the failure reason otherwise - /// (createProject hands that to its sheet). - @discardableResult - func performWrite(_ write: (URL) throws -> Void) -> String? { - guard let home = watchedHome else { - lastError = "No library is open yet — nothing was changed." - return lastError - } - lastError = nil - do { - try write(home) - Task { await rescan() } - return nil - } catch { - lastError = error.localizedDescription - return lastError - } - } + var externalWatcher = PostsWatcher() /// #107: the project a NEW piece lands in — #108: an explicit pending /// target first, else the selected non-archived post's project, else the /// default. One home; newPost/importFiles must not drift. - private var targetProject: String { + var targetProject: String { pendingProject ?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project ?? Post.defaultProject @@ -290,27 +199,6 @@ final class PostsModel { openPieceCards = [] // #23: no open piece, no cards } - /// #92: dismiss the external guest slot, flushing pending edits (the - /// guest is always leaving for somewhere — same posture as post - /// selection change). brief-25: the dismissal is GUARDED — a guest - /// whose flush fails (or whose #67 conflict is unanswered) STAYS, - /// buffer and watcher live: teardown would drop the only retained - /// copy of the unsaved edits. Callers abort their navigation on - /// false, before clearing anything. - /// #146: internal — the split-out domain extensions dismiss too. - @discardableResult - func dismissExternal() -> Bool { - guard let guest = externalSession else { - externalWatcher.stop() - return true - } - guard sessionMayDepart(guest) else { return false } - guest.teardown(flushFirst: false) // the gate already flushed - externalSession = nil - externalWatcher.stop() - return true - } - /// First save of the draft (#62): lazy folder, slug, #59 stamp all fire /// here. The saved post opens straight into an editing session — the /// writer keeps typing where they were. #179: the write rides the rail. @@ -427,298 +315,6 @@ final class PostsModel { return nil } - /// Explicit Rename = retitle + move (#60). Renaming the open post flushes - /// first (rename reads the file from disk — unflushed edits must land - /// before the move), then reopens a session at the new id. #179: the - /// write rides the rail. - func rename(_ post: Post, to title: String) { - // #108 audit 2: rename reads the file from disk — a failed write - // aborts (moving the folder would strand unflushed edits), and the - // session stays up, dirty and honest. - guard flushOrAbort(post.id) else { return } - performWrite { home in - let moved = try PostStore.rename(post, to: title, home: home) - if selectedPostID == post.id { - selectedPostID = moved.id - if session?.postID == post.id { - session = EditorSession(postID: moved.id, home: home) - wireSession() - } - } - } - } - - /// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it - /// was the post; the session is torn down (cancel only — the folder is - /// leaving, a flush would resurrect nothing but churn the watcher). - /// #179: the write rides the rail. - func trash(_ post: Post) { - performWrite { home in - try PostStore.trash(post, home: home) - if selectedPostID == post.id { - selectedPostID = nil - if let open = session, open.postID == post.id { - open.teardown(flushFirst: false) - session = nil - } - } - } - } - - // MARK: Projects (#108) - - /// #108: New Project's confirmed sheet — the folder exists, the next - /// draft targets it, and opens now. - func newProjectPending(named name: String) { - pendingProject = name - newPost() - } - - /// #108: raw create — the sheet composes on it. #179: rides the write - /// rail (one rescan pairs the new folder); the failure reason is BOTH - /// returned for the sheet's inline display AND owned by the strip — - /// the rail posture replaces the old sheet-only rule. - func createProject(named name: String) -> String? { - performWrite { try PostStore.createProject(named: name, home: $0) } - } - - /// #108: File ▸ New Project… — stage the ask (WorkspaceView presents). - func stageNewProject() { - askNewProject = true - } - - /// #108: the ask's Cancel. - func cancelNewProject() { - askNewProject = false - } - - /// #108 audit 2: the Move-to-Project list — every project on disk under - /// projects/ plus the default (bind creates the roots, not posts/ — an - /// empty Home must still offer it), localized-sorted to match the - /// library's section order. - func moveTargets() -> [String] { - guard let home = watchedHome else { return [Post.defaultProject] } - let root = home.appendingPathComponent("projects", isDirectory: true) - let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] - var names = Set(onDisk.filter { !$0.hasPrefix(".") }) - names.insert(Post.defaultProject) - return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } - } - - /// #108 audit: flush the open piece, aborting when the write failed — a - /// folder move must never carry away text that didn't land (the move - /// itself succeeds exactly when a file write fails). Returns false with - /// lastError set; the session stays up, dirty and honest. - /// #33: internal — the Micropub draft flow (Micropub.swift) flushes - /// through the same rail. - func flushOrAbort(_ postID: String) -> Bool { - guard let session, session.postID == postID else { return true } - return sessionMayDepart(session) - } - - /// brief-25 (failed-flush-discarded-on-document-switch): the departure - /// gate for ONE outgoing session — flushOrAbort's two gates lifted to - /// document departure. An unanswered #67 conflict means disk holds - /// foreign text with the session's version unwritten (#114 audit); a - /// failed flush means the edits never landed. Either way the document - /// may not leave: the caller aborts its navigation BEFORE clearing - /// document-specific state, so the dirty session stays retained and - /// honest while lastError says why (the structural rail's #108 - /// posture — now the navigation sites' too). - /// #146: internal — PostsModelOutline's openUnguarded gates too. - func sessionMayDepart(_ outgoing: EditorSession) -> Bool { - if outgoing.conflictAlert { - lastError = "This piece changed on disk underneath you — answer the reload question first." - return false - } - if !outgoing.flush() { - // Append, don't replace — the flush already routed the write's - // localizedDescription into lastError; only say what was skipped. - lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed." - return false - } - return true - } - - /// brief-25: the shared departure run for a full document switch — - /// the external guest and the post session both leave (newPost, - /// newOutline, openExternal). Each flushes through the departure gate - /// first; a failure retains BOTH exactly as they are and the - /// navigation aborts with nothing cleared. - @discardableResult - func departOpenDocuments() -> Bool { - guard dismissExternal() else { return false } - if let open = session { - guard sessionMayDepart(open) else { return false } - open.teardown(flushFirst: false) // the gate already flushed - session = nil - } - return true - } - - /// #108: Move to Project — flush first (move reads disk), then the - /// folder moves under projects/. Id stays the same; the session is - /// reopened anyway so folderURL re-resolves to the new parent. - /// #179: the write rides the rail. - func moveToProject(_ post: Post, project: String) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - try PostStore.move(post, to: project, home: home) - if session?.postID == post.id { - session = EditorSession(postID: post.id, home: home) - wireSession() - } - } - } - - /// #108: Move to Archive. Archiving the open piece clears it — the - /// editor is empty until the next selection (archived pieces open from - /// the Archive pane, where they're listed). #179: the write rides the - /// rail. - func archivePost(_ post: Post) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - try PostStore.archive(post, home: home) - if selectedPostID == post.id { - selectedPostID = nil - } - if let open = session, open.postID == post.id { - open.teardown(flushFirst: false) // already flushed above - session = nil - } - } - } - - /// #108: Move Back — the restored piece lands in its project and opens; - /// the writer stays in the piece they just revived. A session already - /// open on the piece survives `select` — reopen it so folderURL points - /// at projects/, not the archive path it was born with. - /// #179: the write rides the rail. - func restorePost(_ post: Post) { - guard flushOrAbort(post.id) else { return } - performWrite { home in - try PostStore.restore(post, home: home) - if let open = session, open.postID == post.id { - session = EditorSession(postID: post.id, home: home) - wireSession() - } else { - select(post.id) - } - } - } - - /// #108: whole-project unarchive from the Archive pane's section header. - /// Flush-first like every folder move (a dirty open piece inside the - /// project would otherwise race the move), and its session is reopened so - /// folderURL re-resolves off archive/ (same reason as restorePost). - /// #179: the write rides the rail. - func unarchiveProject(_ name: String) { - // #108 audit 2: disk-derived membership — the posts snapshot is stale - // the moment a Finder move lands. Captured BEFORE the move: after it - // the piece resolves under projects/ and its archive membership is - // invisible. dir − 1 = project dir (…/archive/), − 2 = root. - guard let boundHome = watchedHome else { return } - func openPieceInArchivedProject() -> String? { - guard let id = session?.postID, - let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(), - projectDir.lastPathComponent == name, - projectDir.deletingLastPathComponent().lastPathComponent == "archive" - else { return nil } - return id - } - let openID = openPieceInArchivedProject() - if let openID { - // #108 audit 2: the only #108 folder move that skipped the gate. - guard flushOrAbort(openID) else { return } - } - performWrite { home in - try PostStore.unarchiveProject(name, home: home) - if let openID { - session = EditorSession(postID: openID, home: home) - wireSession() - } - } - } - - // MARK: External buffer (#91–#93) + Import (#94/#95) - - /// #91/#92: open an external markdown file in the guest slot — one at a - /// time; opening anything else (file, Post, draft) flushed and replaced - /// it first. A Post session/draft stands down while the guest is up - /// (the editor column is the guest's; the selection stays for return). - /// Local files only (a dragged web link is not a document) and symlinks - /// resolve to their real target so the in-place write never severs the - /// link (rename over a symlink replaces it). - func openExternal(_ url: URL) { - guard url.isFileURL else { return } - let target = url.resolvingSymlinksInPath() - guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts - draft = nil - pendingProject = nil // #108 audit: the draft died here too — its target dies with it - lastDraftWasOutline = false // #109: same death, same clearing - proseOverridePostID = nil // #111: same death, same clearing - outlineGuardPieceID = nil // #111: the guest displaces any held ask - openPieceCards = [] // #23: the guest is not a piece - externalSession = EditorSession(target: .externalFile(target)) - if externalSession?.loadFailed == true { - lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." - externalSession = nil - return - } - wireSession() - startExternalWatch(url: target) - } - - /// #93: watch the open external file — its rescan is the #67 disk-change - /// check, reused verbatim for foreign files. PostsWatcher fires on the - /// main actor already; no re-hop needed. - private func startExternalWatch(url: URL) { - externalWatcher.onEvent = { [weak self] in - guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return } - session.diskDidChange(diskText: disk) - } - externalWatcher.start(urls: [url.deletingLastPathComponent()]) - } - - /// #94: stage a multi-file import — the ONE Origin ask presents; the - /// sheet's answer runs the batch. - func stageImport(_ urls: [URL]) { - guard !urls.isEmpty else { return } - pendingImportURLs = urls - } - - /// #94: dismiss the ask without an answer — the batch drops. - func cancelImport() { - pendingImportURLs = nil - } - - /// #94/#95: run the batch after the Origin answer — copy each file in as - /// a Post; a per-file failure continues the batch into lastError (stated - /// default, reversible; never an alert, never an abort). The last - /// imported post opens; a failure anywhere keeps its message up even - /// when other files landed. #107: the batch lands in the selected - /// post's project (newPost's target rule). #179: the batch rides the - /// rail — the strip was cleared up front, so the per-file failure - /// messages the loop sets survive the rail's success tail. - func importFiles(origin: Post.Origin) { - guard let urls = pendingImportURLs else { return } - pendingImportURLs = nil - let project = targetProject - var last: Post? - performWrite { home in - for url in urls { - do { - last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) - } catch { - lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" - } - } - } - if let last { - select(last.id) - } - } - /// #146: internal — the split-out domain extensions wire sessions too. func wireSession() { let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message } @@ -726,84 +322,3 @@ final class PostsModel { externalSession?.onError = route } } - -// MARK: Watcher (#61) — #146: file-scope extension (type_body_length) - -extension PostsModel { - private func startWatching(home: URL) { - guard watchedHome != home else { return } - watchedHome = home - let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) } - for root in roots { - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - } - watcher.onEvent = { [weak self] in Task { await self?.rescan() } } - watcher.start(urls: roots) - } - - /// Off-main scan; keeps selection valid across the fresh refresh. - /// FSEvents already coalesces bursts within its 0.5 s latency window — - /// no second debounce on top. - /// #146: internal — the split-out domain extensions trigger rescans. - func rescan() async { - guard let home = watchedHome else { return } - // Scan + the #67 disk read both run off-main (a synced large post.md - // must never stall the UI on a watcher burst). - let openPostID = session?.postID - // #114 audit: identity, not id — a same-id reopen (convert/restore/ - // move) must not receive the OLD session's stale disk text as a - // spurious #67 conflict. - let openSession = session - let scanMemo = scanCache // detached capture, not a property read - // The search's content signal: a re-read post.md (a cache miss) - // changed library content even when its Post compares equal. Read - // the counter before the scan so the delta after it says "this - // scan saw disk change" (#144's mounted half). - let missesBefore = scanMemo.misses - let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { - let posts = Post.scan(home: home, cache: scanMemo) - let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } - return (posts, disk) - }.value - guard !Task.isCancelled else { return } - // #143: @Observable invalidates on assignment regardless of equality — - // skip the no-op so panes don't regroup on our own autosave echoes. - let listChanged = scanned != posts - if listChanged { - posts = scanned - } - // #144's mounted half: any list change OR any re-read file bumps the - // content revision — the search snapshot's invalidation signal. - // Archive/trash/rename arrive as list changes; a body-only edit as - // a cache miss (metadata-equal — the skip above keeps the panes - // still, the bump alone re-keys the mounted search). - if listChanged || scanMemo.misses > missesBefore { - contentRevision += 1 - } - // Stale-scan guard (#137 suite find): the snapshot can PREDATE the - // current selection — bind's initial rescan (detached scan over the - // empty tree) can land its continuation after a select its scan never - // saw, "vanishing" a piece that exists. Disk is the truth for - // vanished; a stale snapshot must not kill a live session (teardown - // cancels the debounce — unflushed edits would die with it). - // #137 audit (finish): a scan that outlived a Home repoint speaks - // for the OLD tree — never let it kill a session selected under - // the NEW home (the id is missing from the old snapshot by - // construction); the next rescan under the new home owns it. - if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil { - selectedPostID = nil // the post vanished (deleted in Finder or here) - if let open = session, open.postID == id { - open.teardown(flushFirst: false) // post is gone; cancel the debounce - session = nil - } - } - // #67: watcher echo check on the open post — equality against the - // session's lastFlushedText suppresses our own writes exactly. - if openSession === session, let openDiskText { - openSession?.diskDidChange(diskText: openDiskText) - } - // #23: the open piece's stored fix cards ride the same rescan — - // the watcher fires on /cards/ writes too. - refreshCards() - } -} diff --git a/Museion/PostsModelImports.swift b/Museion/PostsModelImports.swift new file mode 100644 index 0000000..7de61cc --- /dev/null +++ b/Museion/PostsModelImports.swift @@ -0,0 +1,113 @@ +// +// PostsModelImports.swift +// Museion +// +// #193: the external guest (#91–#93) and the import batch (#94/#95), +// moved from PostsModel.swift (file-length ceiling) — openExternal, +// dismissExternal, the guest watch, and stageImport/cancelImport/ +// importFiles, code unchanged. +// + +import Foundation + +extension PostsModel { + /// #92: dismiss the external guest slot, flushing pending edits (the + /// guest is always leaving for somewhere — same posture as post + /// selection change). brief-25: the dismissal is GUARDED — a guest + /// whose flush fails (or whose #67 conflict is unanswered) STAYS, + /// buffer and watcher live: teardown would drop the only retained + /// copy of the unsaved edits. Callers abort their navigation on + /// false, before clearing anything. + /// #146: internal — the split-out domain extensions dismiss too. + @discardableResult + func dismissExternal() -> Bool { + guard let guest = externalSession else { + externalWatcher.stop() + return true + } + guard sessionMayDepart(guest) else { return false } + guest.teardown(flushFirst: false) // the gate already flushed + externalSession = nil + externalWatcher.stop() + return true + } + + // MARK: External buffer (#91–#93) + Import (#94/#95) + + /// #91/#92: open an external markdown file in the guest slot — one at a + /// time; opening anything else (file, Post, draft) flushed and replaced + /// it first. A Post session/draft stands down while the guest is up + /// (the editor column is the guest's; the selection stays for return). + /// Local files only (a dragged web link is not a document) and symlinks + /// resolve to their real target so the in-place write never severs the + /// link (rename over a symlink replaces it). + func openExternal(_ url: URL) { + guard url.isFileURL else { return } + let target = url.resolvingSymlinksInPath() + guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts + draft = nil + pendingProject = nil // #108 audit: the draft died here too — its target dies with it + lastDraftWasOutline = false // #109: same death, same clearing + proseOverridePostID = nil // #111: same death, same clearing + outlineGuardPieceID = nil // #111: the guest displaces any held ask + openPieceCards = [] // #23: the guest is not a piece + externalSession = EditorSession(target: .externalFile(target)) + if externalSession?.loadFailed == true { + lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." + externalSession = nil + return + } + wireSession() + startExternalWatch(url: target) + } + + /// #93: watch the open external file — its rescan is the #67 disk-change + /// check, reused verbatim for foreign files. PostsWatcher fires on the + /// main actor already; no re-hop needed. + private func startExternalWatch(url: URL) { + externalWatcher.onEvent = { [weak self] in + guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return } + session.diskDidChange(diskText: disk) + } + externalWatcher.start(urls: [url.deletingLastPathComponent()]) + } + + /// #94: stage a multi-file import — the ONE Origin ask presents; the + /// sheet's answer runs the batch. + func stageImport(_ urls: [URL]) { + guard !urls.isEmpty else { return } + pendingImportURLs = urls + } + + /// #94: dismiss the ask without an answer — the batch drops. + func cancelImport() { + pendingImportURLs = nil + } + + /// #94/#95: run the batch after the Origin answer — copy each file in as + /// a Post; a per-file failure continues the batch into lastError (stated + /// default, reversible; never an alert, never an abort). The last + /// imported post opens; a failure anywhere keeps its message up even + /// when other files landed. #107: the batch lands in the selected + /// post's project (newPost's target rule). #179: the batch rides the + /// rail — the strip was cleared up front, so the per-file failure + /// messages the loop sets survive the rail's success tail. + func importFiles(origin: Post.Origin) { + guard let urls = pendingImportURLs else { return } + pendingImportURLs = nil + let project = targetProject + var last: Post? + performWrite { home in + for url in urls { + do { + last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) + } catch { + lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" + } + } + } + if let last { + select(last.id) + } + } +} diff --git a/Museion/PostsModelWatcher.swift b/Museion/PostsModelWatcher.swift new file mode 100644 index 0000000..6669176 --- /dev/null +++ b/Museion/PostsModelWatcher.swift @@ -0,0 +1,151 @@ +// +// PostsModelWatcher.swift +// Museion +// +// #193: the watching domain of PostsModel, moved from PostsModel.swift +// (file-length ceiling) — the PostsWatcher FSEvents stream (#61), Home +// binding, startWatching, and the rescan rail, code unchanged. +// + +import CoreServices +import Foundation + +/// Recursive FSEvents stream on one or more directories (#61): file-level +/// events, so nested `projects///post.md` edits from Finder fire +/// too — a plain dir-FD dispatch source only sees direct children and misses +/// them. +final nonisolated class PostsWatcher: @unchecked Sendable { + /// Fired on the main actor when anything under a watched path changes. + var onEvent: (@MainActor @Sendable () -> Void)? + + private var stream: FSEventStreamRef? + + func start(urls: [URL]) { + stop() + var context = FSEventStreamContext( + version: 0, + info: Unmanaged.passUnretained(self).toOpaque(), + retain: nil, + release: nil, + copyDescription: nil, + ) + // C function pointer — no captures; `self` rides the info pointer. + let callback: FSEventStreamCallback = { _, info, _, _, _, _ in + let watcher = Unmanaged.fromOpaque(info!).takeUnretainedValue() + Task { @MainActor in watcher.onEvent?() } + } + guard let stream = FSEventStreamCreate( + kCFAllocatorDefault, + callback, + &context, + urls.map(\.path) as CFArray, + FSEventStreamEventId(kFSEventStreamEventIdSinceNow), + 0.5, // seconds; FSEvents coalesces within this latency (the #61 window) + FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents), + ) else { return } + FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) + FSEventStreamStart(stream) + self.stream = stream + } + + func stop() { + guard let stream else { return } + FSEventStreamStop(stream) + FSEventStreamInvalidate(stream) + FSEventStreamRelease(stream) + self.stream = nil + } + + deinit { stop() } +} + +// MARK: Watcher (#61) + +extension PostsModel { + /// Bind a Home: ensure both container roots exist (FSEvents on a missing + /// path is unreliable; archive/ is a watcher root now, #107), initial + /// scan + start (or restart) the watcher. Called from WorkspaceView's + /// root `.task(id: museionHome)` — first frame and every Home repoint, + /// pane-independent. + func bind(home: URL) { + startWatching(home: home) + Task { await rescan() } + } + + private func startWatching(home: URL) { + guard watchedHome != home else { return } + watchedHome = home + let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) } + for root in roots { + try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + watcher.onEvent = { [weak self] in Task { await self?.rescan() } } + watcher.start(urls: roots) + } + + /// Off-main scan; keeps selection valid across the fresh refresh. + /// FSEvents already coalesces bursts within its 0.5 s latency window — + /// no second debounce on top. + /// #146: internal — the split-out domain extensions trigger rescans. + func rescan() async { + guard let home = watchedHome else { return } + // Scan + the #67 disk read both run off-main (a synced large post.md + // must never stall the UI on a watcher burst). + let openPostID = session?.postID + // #114 audit: identity, not id — a same-id reopen (convert/restore/ + // move) must not receive the OLD session's stale disk text as a + // spurious #67 conflict. + let openSession = session + let scanMemo = scanCache // detached capture, not a property read + // The search's content signal: a re-read post.md (a cache miss) + // changed library content even when its Post compares equal. Read + // the counter before the scan so the delta after it says "this + // scan saw disk change" (#144's mounted half). + let missesBefore = scanMemo.misses + let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { + let posts = Post.scan(home: home, cache: scanMemo) + let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } + return (posts, disk) + }.value + guard !Task.isCancelled else { return } + // #143: @Observable invalidates on assignment regardless of equality — + // skip the no-op so panes don't regroup on our own autosave echoes. + let listChanged = scanned != posts + if listChanged { + posts = scanned + } + // #144's mounted half: any list change OR any re-read file bumps the + // content revision — the search snapshot's invalidation signal. + // Archive/trash/rename arrive as list changes; a body-only edit as + // a cache miss (metadata-equal — the skip above keeps the panes + // still, the bump alone re-keys the mounted search). + if listChanged || scanMemo.misses > missesBefore { + contentRevision += 1 + } + // Stale-scan guard (#137 suite find): the snapshot can PREDATE the + // current selection — bind's initial rescan (detached scan over the + // empty tree) can land its continuation after a select its scan never + // saw, "vanishing" a piece that exists. Disk is the truth for + // vanished; a stale snapshot must not kill a live session (teardown + // cancels the debounce — unflushed edits would die with it). + // #137 audit (finish): a scan that outlived a Home repoint speaks + // for the OLD tree — never let it kill a session selected under + // the NEW home (the id is missing from the old snapshot by + // construction); the next rescan under the new home owns it. + if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil { + selectedPostID = nil // the post vanished (deleted in Finder or here) + if let open = session, open.postID == id { + open.teardown(flushFirst: false) // post is gone; cancel the debounce + session = nil + } + } + // #67: watcher echo check on the open post — equality against the + // session's lastFlushedText suppresses our own writes exactly. + if openSession === session, let openDiskText { + openSession?.diskDidChange(diskText: openDiskText) + } + // #23: the open piece's stored fix cards ride the same rescan — + // the watcher fires on /cards/ writes too. + refreshCards() + } +} diff --git a/Museion/PostsModelWrites.swift b/Museion/PostsModelWrites.swift new file mode 100644 index 0000000..58b3cc2 --- /dev/null +++ b/Museion/PostsModelWrites.swift @@ -0,0 +1,259 @@ +// +// PostsModelWrites.swift +// Museion +// +// #193: the #179 write rail and the structural library ops, moved from +// PostsModel.swift (file-length ceiling) — performWrite, flushOrAbort, +// rename/trash, the #108 project ops, and move/archive/restore, code +// unchanged. +// + +import Foundation + +extension PostsModel { + // MARK: Own ops (route through the same rescan, #61) + + // ponytail: the PostStore calls here run on MainActor — small single-file + // writes and same-volume moves; if a big Home ever stalls the UI, wrap + // them in Task.detached like rescan. + + /// #179: the write rail — ONE seam pairs every library store write with + /// exactly one rescan and owns the error strip. A verb passes its + /// PostStore write (plus any post-write state surgery); a throw lands + /// its reason in the strip with nothing rescanned, a clean run rescans + /// once. The strip clears BEFORE the write, so a batch write that sets + /// its own per-file failure messages mid-closure (importFiles) keeps + /// them. The editor's debounced flush stays OUTSIDE the rail — its + /// error semantics are the session's own (EditorSession.onError). + /// Returns nil when the write landed; the failure reason otherwise + /// (createProject hands that to its sheet). + @discardableResult + func performWrite(_ write: (URL) throws -> Void) -> String? { + guard let home = watchedHome else { + lastError = "No library is open yet — nothing was changed." + return lastError + } + lastError = nil + do { + try write(home) + Task { await rescan() } + return nil + } catch { + lastError = error.localizedDescription + return lastError + } + } + + /// Explicit Rename = retitle + move (#60). Renaming the open post flushes + /// first (rename reads the file from disk — unflushed edits must land + /// before the move), then reopens a session at the new id. #179: the + /// write rides the rail. + func rename(_ post: Post, to title: String) { + // #108 audit 2: rename reads the file from disk — a failed write + // aborts (moving the folder would strand unflushed edits), and the + // session stays up, dirty and honest. + guard flushOrAbort(post.id) else { return } + performWrite { home in + let moved = try PostStore.rename(post, to: title, home: home) + if selectedPostID == post.id { + selectedPostID = moved.id + if session?.postID == post.id { + session = EditorSession(postID: moved.id, home: home) + wireSession() + } + } + } + } + + /// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it + /// was the post; the session is torn down (cancel only — the folder is + /// leaving, a flush would resurrect nothing but churn the watcher). + /// #179: the write rides the rail. + func trash(_ post: Post) { + performWrite { home in + try PostStore.trash(post, home: home) + if selectedPostID == post.id { + selectedPostID = nil + if let open = session, open.postID == post.id { + open.teardown(flushFirst: false) + session = nil + } + } + } + } + + // MARK: Projects (#108) + + /// #108: New Project's confirmed sheet — the folder exists, the next + /// draft targets it, and opens now. + func newProjectPending(named name: String) { + pendingProject = name + newPost() + } + + /// #108: raw create — the sheet composes on it. #179: rides the write + /// rail (one rescan pairs the new folder); the failure reason is BOTH + /// returned for the sheet's inline display AND owned by the strip — + /// the rail posture replaces the old sheet-only rule. + func createProject(named name: String) -> String? { + performWrite { try PostStore.createProject(named: name, home: $0) } + } + + /// #108: File ▸ New Project… — stage the ask (WorkspaceView presents). + func stageNewProject() { + askNewProject = true + } + + /// #108: the ask's Cancel. + func cancelNewProject() { + askNewProject = false + } + + /// #108 audit 2: the Move-to-Project list — every project on disk under + /// projects/ plus the default (bind creates the roots, not posts/ — an + /// empty Home must still offer it), localized-sorted to match the + /// library's section order. + func moveTargets() -> [String] { + guard let home = watchedHome else { return [Post.defaultProject] } + let root = home.appendingPathComponent("projects", isDirectory: true) + let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] + var names = Set(onDisk.filter { !$0.hasPrefix(".") }) + names.insert(Post.defaultProject) + return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + } + + /// #108 audit: flush the open piece, aborting when the write failed — a + /// folder move must never carry away text that didn't land (the move + /// itself succeeds exactly when a file write fails). Returns false with + /// lastError set; the session stays up, dirty and honest. + /// #33: internal — the Micropub draft flow (Micropub.swift) flushes + /// through the same rail. + func flushOrAbort(_ postID: String) -> Bool { + guard let session, session.postID == postID else { return true } + return sessionMayDepart(session) + } + + /// brief-25 (failed-flush-discarded-on-document-switch): the departure + /// gate for ONE outgoing session — flushOrAbort's two gates lifted to + /// document departure. An unanswered #67 conflict means disk holds + /// foreign text with the session's version unwritten (#114 audit); a + /// failed flush means the edits never landed. Either way the document + /// may not leave: the caller aborts its navigation BEFORE clearing + /// document-specific state, so the dirty session stays retained and + /// honest while lastError says why (the structural rail's #108 + /// posture — now the navigation sites' too). + /// #146: internal — PostsModelOutline's openUnguarded gates too. + func sessionMayDepart(_ outgoing: EditorSession) -> Bool { + if outgoing.conflictAlert { + lastError = "This piece changed on disk underneath you — answer the reload question first." + return false + } + if !outgoing.flush() { + // Append, don't replace — the flush already routed the write's + // localizedDescription into lastError; only say what was skipped. + lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed." + return false + } + return true + } + + /// brief-25: the shared departure run for a full document switch — + /// the external guest and the post session both leave (newPost, + /// newOutline, openExternal). Each flushes through the departure gate + /// first; a failure retains BOTH exactly as they are and the + /// navigation aborts with nothing cleared. + @discardableResult + func departOpenDocuments() -> Bool { + guard dismissExternal() else { return false } + if let open = session { + guard sessionMayDepart(open) else { return false } + open.teardown(flushFirst: false) // the gate already flushed + session = nil + } + return true + } + + /// #108: Move to Project — flush first (move reads disk), then the + /// folder moves under projects/. Id stays the same; the session is + /// reopened anyway so folderURL re-resolves to the new parent. + /// #179: the write rides the rail. + func moveToProject(_ post: Post, project: String) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + try PostStore.move(post, to: project, home: home) + if session?.postID == post.id { + session = EditorSession(postID: post.id, home: home) + wireSession() + } + } + } + + /// #108: Move to Archive. Archiving the open piece clears it — the + /// editor is empty until the next selection (archived pieces open from + /// the Archive pane, where they're listed). #179: the write rides the + /// rail. + func archivePost(_ post: Post) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + try PostStore.archive(post, home: home) + if selectedPostID == post.id { + selectedPostID = nil + } + if let open = session, open.postID == post.id { + open.teardown(flushFirst: false) // already flushed above + session = nil + } + } + } + + /// #108: Move Back — the restored piece lands in its project and opens; + /// the writer stays in the piece they just revived. A session already + /// open on the piece survives `select` — reopen it so folderURL points + /// at projects/, not the archive path it was born with. + /// #179: the write rides the rail. + func restorePost(_ post: Post) { + guard flushOrAbort(post.id) else { return } + performWrite { home in + try PostStore.restore(post, home: home) + if let open = session, open.postID == post.id { + session = EditorSession(postID: post.id, home: home) + wireSession() + } else { + select(post.id) + } + } + } + + /// #108: whole-project unarchive from the Archive pane's section header. + /// Flush-first like every folder move (a dirty open piece inside the + /// project would otherwise race the move), and its session is reopened so + /// folderURL re-resolves off archive/ (same reason as restorePost). + /// #179: the write rides the rail. + func unarchiveProject(_ name: String) { + // #108 audit 2: disk-derived membership — the posts snapshot is stale + // the moment a Finder move lands. Captured BEFORE the move: after it + // the piece resolves under projects/ and its archive membership is + // invisible. dir − 1 = project dir (…/archive/), − 2 = root. + guard let boundHome = watchedHome else { return } + func openPieceInArchivedProject() -> String? { + guard let id = session?.postID, + let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(), + projectDir.lastPathComponent == name, + projectDir.deletingLastPathComponent().lastPathComponent == "archive" + else { return nil } + return id + } + let openID = openPieceInArchivedProject() + if let openID { + // #108 audit 2: the only #108 folder move that skipped the gate. + guard flushOrAbort(openID) else { return } + } + performWrite { home in + try PostStore.unarchiveProject(name, home: home) + if let openID { + session = EditorSession(postID: openID, home: home) + wireSession() + } + } + } +} diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 5825b6b..fae7c4e 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -7,11 +7,13 @@ // trash. #19: the TextKit2 editor core (PostEditorView) replaces the stub; // mentor column (#14). // #108 (variant B, ref/prototypes/wf104-library-ui-prototype.html): sections -// per project (serif-15 head + mono count), Pass-State groups inside, and a -// 2px accent edge bar on the selected row. +// per project (serif-15 head + mono count), Pass-State groups inside, and +// a 2px accent edge bar on the selected row. +// #193: the split-out files — the library column + its sheets + the +// launch focus rider PostsLibraryColumn.swift, the shared +// LibraryPostRow.swift. // -import AppKit import SwiftUI /// The Posts destination: the workspace's full four-column layout @@ -181,596 +183,3 @@ struct PostsPaneView: View { .frame(width: DesignTokens.mentorWidth) } } - -/// #21: the library column, shared by the unfocused layout and the focus-mode -/// left reveal overlay — one implementation, both surfaces. Owns the rename + -/// move sheets and the context menu (they travel with the post rows). -/// #108 variant B: sections per project, Pass-State groups inside. -struct PostsLibraryColumn: View { - let home: URL - var model: PostsModel - @State private var renamingPost: Post? - @State private var movingPost: Post? - /// #108: collapsed project sections — per-view state, not persisted (a - /// fresh open shows everything; the prototype behaved the same). - @State private var collapsed: Set = [] - /// #144: the library search — live title+body filter over the - /// non-archived pieces. nil = not searching (sections render). - @State private var query = "" - /// #144 (mounted half): the landed sweep — results plus the key that - /// computed them. nil = not searching or recomputing (the sections / - /// spinner states); a snapshot that isn't `isFresh` for the current - /// key never renders. - @State private var snapshot: LibrarySearch.Snapshot? - /// r5 (argon#44, mercury#52, sol#37): focus state for the field's - /// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7 - /// onAppear-unfocus could never work — the launch focus is AppKit - /// assigning the window's INITIAL first responder to its first text - /// input (this field), at window-become-key, AFTER onAppear. FocusState - /// merely mirrors that back as true. LaunchFocusReset (below) resigns - /// it at the first become-key; from then on only the user drives this. - @FocusState private var searchFocused: Bool - - private var trimmedQuery: String { - query.trimmingCharacters(in: .whitespacesAndNewlines) - } - - /// #144 (mounted half): the sweep's identity — trimmed query, the - /// Home, and the library content revision (`PostsModel.contentRevision`, - /// bumped by the rescan rail on any list change or re-read body). The - /// `.task(id:)` below re-keys on ANY difference, so library writes and - /// Home repoints restart the sweep instead of leaving stale rows; the - /// landed snapshot renders only while `isFresh` for the current key. - private var searchKey: LibrarySearch.SearchKey { - LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision) - } - - private var isSearching: Bool { - !trimmedQuery.isEmpty - } - - /// Non-archived pieces keyed by project (scan order = title order holds - /// inside each group — filter preserves it). - private var activeByProject: [String: [Post]] { - Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project) - } - - var body: some View { - VStack(spacing: 0) { - PaneHeader(title: "Posts") { - Button { - model.newPost() - } label: { - Image(systemName: "plus") - } - .buttonStyle(.plain) - .foregroundStyle(DesignTokens.muted) - .help("New Post") - .accessibilityLabel("New Post") - } - searchField - if isSearching { - // #144 (mounted half): a landed sweep renders only while - // fresh for the CURRENT key — a library write that bumped - // the revision (archive, trash, rename, body edit) or a - // moved query drops to the recompute state, never stale rows. - if let snapshot, snapshot.isFresh(for: searchKey) { - if snapshot.results.isEmpty { - searchEmptyState - } else { - searchResults(snapshot.results) - } - } else { - ProgressView() - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - } else if activeByProject.isEmpty { - emptyState - } else { - ScrollView { - LazyVStack(alignment: .leading, spacing: 4) { - // #108 audit: Finder order (scan's own sort), not Unicode-scalar - // order — the heads render lowercased, "Beta" must not read before "apple". - ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in - let pieces = activeByProject[project] ?? [] - // #108: the head is the prototype's toggle — click - // collapses the project's pieces (chevron rotates). - Button { - withAnimation { - if collapsed.contains(project) { - collapsed.remove(project) - } else { - collapsed.insert(project) - } - } - } label: { - // r7 (mercury#18, argon#12 — TWO-AXIS ladder, - // the r6 four-step collapse undone): the - // head ROW leads at the column's PRIMARY - // inset (x14) — chevron glyph in a 14pt slot - // — and every nested CONTENT shares the one - // indent step (x28): head text, group - // labels, and the rows' inner text. No third - // or fourth x-axis exists in the column. - HStack(alignment: .firstTextBaseline, spacing: 0) { - Image(systemName: "chevron.down") - .font(.system(size: 10, weight: .semibold)) - .frame(width: 14, alignment: .leading) - .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) - .foregroundStyle(DesignTokens.muted) - Text(project) - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - .textCase(.lowercase) // #108: display-only — the folder name keeps its case - .lineLimit(1) - .truncationMode(.tail) - Text("· \(pieces.count)") - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.muted) - Spacer(minLength: 0) - } - } - .buttonStyle(.plain) - .foregroundStyle(DesignTokens.foreground) - .accessibilityLabel("\(project), \(pieces.count) pieces") - .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") - .padding(.top, 16) - .padding(.horizontal, 14) - .padding(.bottom, 6) - if !collapsed.contains(project) { - passStateGroups(pieces) - } - } - } - .padding(.bottom, 12) - } - } - } - .frame(width: DesignTokens.libraryWidth) - // r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7 - // onAppear-unfocus — see LaunchFocusReset below for the mechanism. - .background(LaunchFocusReset()) - .sheet(item: $renamingPost) { post in - RenamePostSheet(post: post) { title in - model.rename(post, to: title) - } - } - .sheet(item: $movingPost) { post in - // #108 audit 2: disk-derived list, localized-sorted — same order - // the library renders (Unicode-scalar sort split them), and it - // includes empty projects (a fresh New Project has no pieces yet — - // it must already be a move target). - MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in - model.moveToProject(post, project: project) - } - } - // #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). Keyed to the full - // search key: a library write (revision bump) or a Home repoint - // restarts the sweep too. The snapshot lands under the key - // captured at start; a mid-sweep key change cancels here, and - // even a raced assignment can't render — body gates on isFresh. - .task(id: searchKey) { - let key = searchKey - guard !key.query.isEmpty else { - snapshot = nil - return - } - try? await Task.sleep(for: .milliseconds(250)) - guard !Task.isCancelled else { return } - let found = await librarySearch( - candidates: model.posts.filter { !$0.isArchived }, - matching: key.query, - home: home, - ) - guard !Task.isCancelled else { return } - snapshot = LibrarySearch.Snapshot(key: key, results: found) - } - } - - /// 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) { - model.select(post.id) - } - .contextMenu { - Button("Rename…") { renamingPost = post } - // #114 (S4): outline pieces only — the ask picks the - // body transform, then the piece becomes a prose post. - if post.type == .outline { - Button("Convert to Post…") { - model.stageConversion(post) - } - } - Button("Move to Project…") { movingPost = post } - Button("Move to Archive") { - model.archivePost(post) - } - Button("Move to Trash", role: .destructive) { - model.trash(post) - } - } - } - - /// Pass-State groups inside one project (`.vB .group-label`: smaller, - /// softer, indented under the section head). r2: the label binds to - /// its FIRST row (bottom 1 + stack 4) — it floated closer to the - /// preceding row than to its own children. - 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 { - // mercury#53 (r5): display-only normalization — the stored - // rawValues keep their hyphen ("Pass-1 Done"); the rendered - // label uses the space form so it matches the Pass 1 / Pass 2 - // vocabulary everywhere else. - Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " ")) - .font(.system(size: 11, weight: .medium, design: DesignTokens.mono)) - .kerning(0.6) - // r6 (sol#6/21 — contrast final): group labels are - // informational meta — FULL muted ink, no wash. - .foregroundStyle(DesignTokens.muted) - // r6 ladder: full muted ink. r7 two-axis: x28 — the ONE - // indent step, shared with the head text and the row - // cards' inner content. - .padding(.leading, 28) - .padding(.top, 10) - .padding(.bottom, 1) - ForEach(grouped) { post in - postRow(post) - } - } - } - } - - /// #144 + mercury#54 (r4): a real field surface — surface fill + hairline - /// border on the column's chrome, taller than a text row; the placeholder - /// r5 (argon#44, mercury#52, sol#37): the insertion caret tints - /// terracotta (.tint on the field), and the small magnifier glyph sits at - /// the field's leading edge (icon→text spacing rides the HStack's 6pt); - /// the placeholder is the native prompt wearing the palette's muted ink - /// (the composer's pattern). - /// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6, - /// present but never the strongest saturation on screen. - private var searchField: some View { - HStack(spacing: 6) { - Image(systemName: "magnifyingglass") - .font(.system(size: 11)) - .foregroundStyle(DesignTokens.muted) - TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted)) - .textFieldStyle(.plain) - .font(.system(size: 12)) - .focused($searchFocused) - .tint(DesignTokens.accent) - if isSearching { - Button { - query = "" - } label: { - Image(systemName: "xmark.circle.fill") - } - .buttonStyle(.plain) - .foregroundStyle(DesignTokens.muted) - .accessibilityLabel("Clear search") - } - } - .padding(.horizontal, 10) - .padding(.vertical, 8) - .background( - RoundedRectangle(cornerRadius: 8) - .fill(DesignTokens.surface) - .overlay( - // r8 (argon#6, mercury#12): quiet focus — accent at 0.6, - // one step down from full strength. - RoundedRectangle(cornerRadius: 8) - .strokeBorder( - searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border, - lineWidth: 1, - ), - ), - ) - // r7 (mercury#18, argon#12 — two-axis ladder): the box spans the - // FULL padded column width at the PRIMARY inset — leading 14 - // (aligned with the 'Posts' header text) to trailing 14 — the - // same edges the row cards lead at. - .padding(.horizontal, 14) - .padding(.vertical, 8) - } - - /// 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: 11, design: DesignTokens.mono)) - .kerning(0.6) - // r6: full muted ink; r7 two-axis: x28 — the indent - // step, heading the flat result list exactly where - // group labels head their sections. - .foregroundStyle(DesignTokens.muted) - .padding(.leading, 28) - .padding(.top, 12) - .padding(.bottom, 1) - 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 { - VStack(spacing: 8) { - Text("No posts yet") - .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) - Text("Posts in this Home's projects/ folders appear here.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - .multilineTextAlignment(.center) - } - .padding(38) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } -} - -/// #144: the title+body scan — a thin mount for the pure -/// `LibrarySearch` seam (title matches first, stable partition, both -/// halves keep the scan's Finder order; body via readBody — frontmatter -/// never searched), pinned by MuseionTests/LibrarySearchTests.swift. -/// The reader's per-piece cancellation check stops a superseded sweep's -/// body reads between files; the in-memory title walk itself completes -/// cheaply and the caller's guard discards its result. File scope since -/// r6 (PostsLibraryColumn hit its type-body ceiling). -/// -/// ponytail: full-body re-read per sweep (folder(of:) re-walked per -/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex -/// posture); a PostScanCache-style body memo if it ever measures hot. -private nonisolated func librarySearch( - candidates: [Post], - matching trimmed: String, - home: URL, -) async -> [Post] { - LibrarySearch.results(for: trimmed, in: candidates) { post in - guard !Task.isCancelled else { return nil } - return PostStore.readBody(id: post.id, home: home) - } -} - -/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at -/// the source): the search field is the window's first — and at launch, -/// only — text input, and AppKit assigns the window's initial first -/// responder to it when the window becomes key. That happens AFTER -/// onAppear, so the r6/r7 `searchFocused = false` writes were always -/// overridden (FocusState mirrors the assignment back as true: terracotta -/// ring + caret, the strongest element on screen). This invisible rider -/// rides the library column and, at the window's FIRST become-key, -/// resigns focus back to the window itself (`makeFirstResponder(nil)` — -/// the neutral state; nothing gains focus instead). ONCE per process: a -/// pane-switch remount must never steal a focus the user set on return. -/// The second, next-runloop resign covers an assignment that lands after -/// the notification (the PostEditorView layout-race precedent). -private struct LaunchFocusReset: NSViewRepresentable { - /// Process-wide once-flag — launch is a once-per-process event. - private static var hasRun = false - - final class RiderView: NSView { - private var keyObserver: NSObjectProtocol? - - override func viewDidMoveToWindow() { - if let keyObserver { - NotificationCenter.default.removeObserver(keyObserver) - } - keyObserver = nil - guard let window else { return } - keyObserver = NotificationCenter.default.addObserver( - forName: NSWindow.didBecomeKeyNotification, - object: window, - queue: .main, - ) { _ in - MainActor.assumeIsolated { - // The observer is scoped to `window` (object:), so the - // notification carries nothing we don't already hold — - // reading `note` here would cross a Sendable boundary. - guard !LaunchFocusReset.hasRun else { return } - LaunchFocusReset.hasRun = true - window.makeFirstResponder(nil) - DispatchQueue.main.async { window.makeFirstResponder(nil) } - } - } - } - } - - func makeNSView(context _: Context) -> RiderView { - RiderView() - } - - func updateNSView(_: RiderView, context _: Context) {} -} - -/// #108: Move to Project ask — radio list of the non-archived projects, -/// default = the piece's current project. Matches RenamePostSheet's shape. -struct MoveToProjectSheet: View { - let post: Post - let projects: [String] - let move: (String) -> Void - @Environment(\.dismiss) private var dismiss - @State private var target: String - - init(post: Post, projects: [String], move: @escaping (String) -> Void) { - self.post = post - self.projects = projects - self.move = move - _target = State(initialValue: post.project) - } - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Move to Project") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("“\(post.title)” moves into the chosen project. The file stays post.md.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - Picker("Project", selection: $target) { - ForEach(projects, id: \.self) { name in - Text(name).tag(name) - } - } - .pickerStyle(.radioGroup) - HStack { - Spacer() - Button("Cancel", role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) - Button("Move") { - move(target) - dismiss() - } - .keyboardShortcut(.defaultAction) - .disabled(target == post.project) - } - } - .padding(20) - .frame(width: 360) - } -} - -/// #60: Explicit Rename dialog — asks the new Title (not a slug). -struct RenamePostSheet: View { - let rename: (String) -> Void - @Environment(\.dismiss) private var dismiss - @State private var title: String - - init(post: Post, rename: @escaping (String) -> Void) { - self.rename = rename - _title = State(initialValue: post.title) - } - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Rename Post") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("The folder moves to match the new Title. The file stays post.md.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - TextField("Title", text: $title) - .textFieldStyle(.roundedBorder) - .onSubmit { confirm() } - HStack { - Spacer() - Button("Cancel", role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) - Button("Rename", action: confirm) - .keyboardShortcut(.defaultAction) - .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) - } - } - .padding(20) - .frame(width: 360) - } - - private func confirm() { - let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return } - rename(trimmed) - dismiss() - } -} - -/// One post row per the export: title + origin-only mono-11 meta (the Pass -/// State rides the uppercase group label above; it stays in the a11y label). -/// #108 (variant B): 2px accent edge bar on the leading side when selected -/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, -/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the -/// Archive pane reuses it. -struct LibraryPostRow: View { - let post: Post - let selected: Bool - let select: () -> Void - @State private var hover = false - - var body: some View { - // `.vB .post-row { border-left: 2px solid transparent; - // border-radius: 0 8px 8px 0 }` — every row: leading corners square - // (the 2px strip below), trailing rounded 8. Only the strip's - // VISIBILITY changes on selection. - let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) - return Button(action: select) { - HStack(spacing: 0) { - // The leading strip is always 2px wide so hover/selection - // never shifts the title. r6 (mercury#49/52, argon#13): - // the shared SelectedRowStrip capsule — accent, radius-1 - // ends, vertically inset 6pt (was 3) so it sits INSIDE - // the card, never pasted on its square leading edge. - SelectedRowStrip() - .opacity(selected ? 1 : 0) - VStack(alignment: .leading, spacing: 5) { - HStack(alignment: .firstTextBaseline, spacing: 0) { - Text(post.title) - if post.type == .outline { - Text(" ✳") - .foregroundStyle(DesignTokens.muted) - } - } - // ui-polish r8: serif-13 per the row contract — `.callout` - // was the system sans design (the r6/r7 councils pixel- - // verified sans glyphs on the Archive rows). - .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) - .lineLimit(1) - .truncationMode(.tail) - .frame(maxWidth: .infinity, alignment: .leading) - // Origin only — the Pass State already rides the uppercase - // group label above (it stays in the accessibility label). - // r7: the status micro-label sits INSIDE the row's content - // padding — same x as the title, never flush with the edge. - Text(post.origin.rawValue) - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.muted) - .frame(maxWidth: .infinity, alignment: .leading) - } - .padding(.horizontal, 12) - .padding(.vertical, 10) - } - .clipShape(shape) - } - .buttonStyle(.plain) - .foregroundStyle(DesignTokens.foreground) - .background { - if selected || hover { - // r8 (mercury#11): the selected row DROPS its gray outline — - // fill + accent capsule read as ONE shape; stacking fill + - // outline + capsule competed. Hover keeps its borderless - // 0.06 wash exactly as before. - shape - .fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06)) - } - } - // r7 (mercury#18, argon#12 — two-axis ladder): the row CARD - // leads at the PRIMARY inset (x14, the 'Posts' header text's - // edge); its INNER content (title + status micro-label, strip - // 2 + padding 12) lands at x28 — the ONE indent step, shared - // with the head text and the group labels. No other x-axis - // exists in the column. Vertical padding stays the content - // VStack's constant 10 whether or not the row shows its strip. - .padding(.horizontal, 14) - .onHover { hover = $0 } - // help sits on the row — the ✳ span isn't individually hoverable in - // SwiftUI (prototype: `title="outline"` on the star). - .help(post.type == .outline ? "\(post.title) — outline" : post.title) - .accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)") - } -} diff --git a/Museion/ProfileBackup.swift b/Museion/ProfileBackup.swift index acea7ed..f32d878 100644 --- a/Museion/ProfileBackup.swift +++ b/Museion/ProfileBackup.swift @@ -84,9 +84,7 @@ nonisolated enum ProfileBackup { // Age check against the newest existing snapshot (#15: skips record no // state; the normal age check governs retry). - if let newest = sortedSnapshots(in: backupsRoot).first, - now.timeIntervalSince(newest.timestamp) < snapshotInterval - { + if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval { return .skippedFresh } diff --git a/Museion/ProfileProvisioner.swift b/Museion/ProfileProvisioner.swift index 3bd2dbf..e8213ea 100644 --- a/Museion/ProfileProvisioner.swift +++ b/Museion/ProfileProvisioner.swift @@ -139,16 +139,16 @@ nonisolated enum ProfileProvisioner { return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt)) } + let env = SurfaceEnv( + hermesBinary: hermesBinary, + profileRoot: profileRoot, + masterRoot: masterRoot, + manifest: manifest, + serverBinaryPath: serverBinaryPath, + timeout: timeout, + ) for surface in ProfileSurface.allCases { - switch provisionSurface( - surface, - hermesBinary: hermesBinary, - profileRoot: profileRoot, - masterRoot: masterRoot, - manifest: manifest, - serverBinaryPath: serverBinaryPath, - timeout: timeout, - ) { + switch provisionSurface(surface, env: env) { case let .seeded(deltaCopied, deltaPresent): copied += deltaCopied present += deltaPresent @@ -165,20 +165,27 @@ nonisolated enum ProfileProvisioner { return .seeded(copied: copied, present: present) } + /// Per-`perform` context threaded into every surface pass — everything + /// except the surface itself (the loop variable), so the per-surface + /// seam stays under the parameter-count ceiling. + private struct SurfaceEnv { + let hermesBinary: String? + let profileRoot: String + let masterRoot: String + let manifest: [String] + let serverBinaryPath: String? + let timeout: TimeInterval + } + /// Phases 1–4 for ONE surface profile (#134): create (or adopt), write /// defaults on fresh profiles via the CLI rail, link skills per /// allocation, register museion-tools (#23). private static func provisionSurface( _ surface: ProfileSurface, - hermesBinary: String?, - profileRoot: String, - masterRoot: String, - manifest: [String], - serverBinaryPath: String?, - timeout: TimeInterval, + env: SurfaceEnv, ) -> Outcome { let fileManager = FileManager.default - let profileDir = ProfileLayout.profileDir(surface.profileName, root: profileRoot) + let profileDir = ProfileLayout.profileDir(surface.profileName, root: env.profileRoot) // Phase 1 — profile create. Dir-check first; spawn only when // missing (#45). `museion` is adopted, never re-created (ADR-0014). @@ -186,12 +193,12 @@ nonisolated enum ProfileProvisioner { // carry only Museion's curated set — coding and writing never mix, G3). var createdFresh = false if !fileManager.fileExists(atPath: profileDir) { - guard let binary = hermesBinary else { + guard let binary = env.hermesBinary else { return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found") } let run = EngineProbe.execute( [binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"], - timeout: timeout, + timeout: env.timeout, ) // #43: exit 1 + "already exists" on stdout = success (a // concurrent create — not ours, so not fresh); all errors print on stdout. @@ -208,10 +215,10 @@ nonisolated enum ProfileProvisioner { // profile (interrupted before its marker landed) is healed, and // the adopted museion is never touched — its model is the user's. if createdFresh || (surface != .chat && !markerExists(at: profileDir)) { - guard let binary = hermesBinary else { + guard let binary = env.hermesBinary else { return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found") } - if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: timeout) { + if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: env.timeout) { return failure } // A marker we couldn't record = configure incomplete — surface it @@ -224,7 +231,7 @@ nonisolated enum ProfileProvisioner { // Phase 3 — per-profile skills: symlinks per allocation + the // copy-era → symlink migration (#133). - let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: masterRoot, manifest: manifest) + let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: env.masterRoot, manifest: env.manifest) if case .failed = linked { return linked } @@ -232,7 +239,7 @@ nonisolated enum ProfileProvisioner { // Phase 4 — museion-tools registration per profile (ADR-0008 // amendment). nil on either binary is the test-injection seam; // production always has both after a gate pass. - guard let hermesBinary, let serverBinaryPath else { + guard let hermesBinary = env.hermesBinary, let serverBinaryPath = env.serverBinaryPath else { Logger(subsystem: subsystem, category: "provisioning") .info("museion-tools registration skipped: engine or server binary missing") return linked @@ -241,7 +248,7 @@ nonisolated enum ProfileProvisioner { profile: surface.profileName, hermesBinary: hermesBinary, serverBinaryPath: serverBinaryPath, - timeout: timeout, + timeout: env.timeout, ) { return failure } @@ -511,6 +518,12 @@ nonisolated extension ProfileProvisioner { !name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" } } + /// True when `path` is a symlink (lstat-true, before any open) — the + /// payload never ships one, so a linked entry refuses the tree match. + private static func isSymlinked(_ path: String) -> Bool { + (try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil + } + /// Recursive byte-comparison of two dir trees — same entry names, every /// file byte-identical. `.DS_Store` is filtered from BOTH listings before /// the name-equality check (Finder noise, not a user edit — a @@ -532,9 +545,7 @@ nonisolated extension ProfileProvisioner { let rhsPath = (rhs as NSString).appendingPathComponent(name) // Neither side may carry a symlink at this entry (lstat-true, // before any open) — the payload never ships one. - if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil - || (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil - { + if isSymlinked(lhsPath) || isSymlinked(rhsPath) { return false } var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false diff --git a/Museion/ProseListTextView.swift b/Museion/ProseListTextView.swift index 26dd482..2eddd10 100644 --- a/Museion/ProseListTextView.swift +++ b/Museion/ProseListTextView.swift @@ -377,10 +377,7 @@ final class ProseListTextView: NSTextView { guard let scalar = Unicode.Scalar(Int(char)) else { return false } return CharacterSet.whitespacesAndNewlines.contains(scalar) } - if index > 0, index < length, - !isGap(buffer.character(at: index - 1)), - !isGap(buffer.character(at: index)) - { + if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) { while index < length, !isGap(buffer.character(at: index)) { index += 1 } diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index be824ff..586a46d 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -38,6 +38,39 @@ nonisolated enum ProsePresenter { classify(line, inFence: false) } + /// A fence delimiter line (``` or ~~~ prefix) — delimiter lines are + /// fences even inside a fence (they close it). + static func isFenceDelimiter(_ trimmed: Substring) -> Bool { + trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") + } + + /// Pure rule/mark syntax (horizontal rules, dinkus) — no content. + static func isRuleSyntax(_ trimmed: Substring) -> Bool { + trimmed.allSatisfy { $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" } + } + + /// CommonMark ATX heading level (1–6) of a trimmed line — a heading + /// needs 1–6 hashes followed by a space or end-of-line; 7+ hashes or a + /// glued-on word is body text. + static func headingLevel(of trimmed: Substring) -> Int? { + let hashes = trimmed.prefix(while: { $0 == "#" }).count + guard hashes > 0, hashes <= 6 else { return nil } // CommonMark caps at 6; 7+ is body + let after = trimmed.dropFirst(hashes) + guard after.hasPrefix(" ") || after.isEmpty else { return nil } + return hashes + } + + /// Heading ladder for a valid ATX level — 1–3 are named steps, 4–6 + /// share the h4+ rung (CommonMark). + private static func headingKind(_ hashes: Int) -> LineKind { + switch hashes { + case 1: .heading1 + case 2: .heading2 + case 3: .heading3 + default: .heading4Plus + } + } + /// Delimiter lines are fences even inside a fence (they close it) — so the /// delim test runs before the inFence shortcut and `applyStyles` toggles /// on `kind == .fence` instead of re-deriving the prefix. @@ -46,28 +79,19 @@ nonisolated enum ProsePresenter { if trimmed.isEmpty { return .blank } - if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { + if isFenceDelimiter(trimmed) { return .fence } if inFence { return .fenceInterior } - let hashes = trimmed.prefix(while: { $0 == "#" }).count - if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body - let after = trimmed.dropFirst(hashes) - if after.hasPrefix(" ") || after.isEmpty { - switch hashes { - case 1: return .heading1 - case 2: return .heading2 - case 3: return .heading3 - default: return .heading4Plus - } - } + if let hashes = headingLevel(of: trimmed) { + return headingKind(hashes) } if trimmed.hasPrefix(">") { return .quote } - if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { + if isRuleSyntax(trimmed) { return .syntaxOnly } if line.firstMatch(of: listMarkerPattern) != nil { @@ -102,7 +126,7 @@ nonisolated enum ProsePresenter { var count = 0 for line in text.split(separator: "\n", omittingEmptySubsequences: false) { let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) - if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { + if isFenceDelimiter(trimmed) { count += 1 } } @@ -171,58 +195,76 @@ nonisolated enum ProsePresenter { /// Count unclosed fences before `end` (``` or ~~~ delim lines toggle). private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool { var inFence = false - for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) { - if classify(line.text, inFence: inFence) == .fence { - inFence.toggle() - } + let prefix = NSRange(location: 0, length: min(end, nsText.length)) + for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence { + inFence.toggle() } return inFence } + /// The #…​ ATX marker of a heading line, dimmed to the code face. + private static func dimHeadingMarker(_ out: NSMutableAttributedString, line: Line) { + let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count + let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count + let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) + if marker.length > 0 { + out.addAttributes(ProseTypography.codeAttributes, range: marker) + } + } + + /// Kinds whose text content carries inline trait styling (bold/italic/ + /// code/link spans). + static func carriesInlineTraits(_ kind: LineKind) -> Bool { + kind == .body || kind == .quote || kind == .listMarker + } + + /// Non-empty UTF-16 marker range of `pattern` at the line start, or nil. + private static func markerRange(_ pattern: Regex, in line: Line) -> NSRange? { + guard let marker = markerRangeUTF16(pattern, in: line.text), marker.length > 0 else { return nil } + return marker + } + + /// List marker dim + hanging indent: wrapped list lines align with the + /// item's text, not the paragraph margin — the marker prefix (leading + /// whitespace + "- "/"1. ") sets headIndent, mirroring reading.css's + /// hanging lists (padding-left + outside markers; #ui-r1, sol#13; #ui-r2 + /// argon#53 flush fix). Nested items hang at their own prefix width. + /// The prefix is measured in the EXACT attributes it renders in + /// (listMarkerAttributes — the line's face and size), so the + /// continuation lands flush; a different measuring face drifts + /// per-glyph (~4pt left in r1). ponytail: a tab in the prefix measures + /// at the default tab stop; the corpus uses spaces — widen if tabbed + /// lists drift. + private static func applyListMarker(_ out: NSMutableAttributedString, line: Line) { + guard let marker = markerRange(listMarkerPattern, in: line) else { return } + out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content)) + let prefix = String(line.text.prefix(NSMaxRange(marker))) + let indent = NSAttributedString( + string: prefix, + attributes: ProseTypography.listMarkerAttributes, + ).size().width + let hanging = NSMutableParagraphStyle() + hanging.setParagraphStyle(paragraph(.body)) + hanging.headIndent = indent + // #ui-r7 sol#29: inter-item rhythm (reading.css list margins) + // — before-space only, the CSS block has no bottom margin. + hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore + out.addAttribute(.paragraphStyle, value: hanging, range: line.full) + } + private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) { guard line.full.length > 0 else { return } out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full) let dim = ProseTypography.codeAttributes // codeFont + syntaxColor switch kind { case .heading1, .heading2, .heading3, .heading4Plus: - let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count - let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count - let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) - if marker.length > 0 { - out.addAttributes(dim, range: marker) - } + dimHeadingMarker(out, line: line) case .quote: - if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 { + if let marker = markerRange(quoteMarkerPattern, in: line) { out.addAttributes(dim, range: shifted(marker, into: line.content)) } case .listMarker: - if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 { - out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content)) - // Hanging indent (#ui-r1, sol#13; #ui-r2 argon#53 flush - // fix): wrapped list lines align with the item's text, not - // the paragraph margin — the marker prefix (leading - // whitespace + "- "/"1. ") sets headIndent, mirroring - // reading.css's hanging lists (padding-left + outside - // markers). Nested items hang at their own prefix width. - // The prefix is measured in the EXACT attributes it - // renders in (listMarkerAttributes — the line's face and - // size), so the continuation lands flush; a different - // measuring face drifts per-glyph (~4pt left in r1). - // ponytail: a tab in the prefix measures at the default tab - // stop; the corpus uses spaces — widen if tabbed lists drift. - let prefix = String(line.text.prefix(NSMaxRange(marker))) - let indent = NSAttributedString( - string: prefix, - attributes: ProseTypography.listMarkerAttributes, - ).size().width - let hanging = NSMutableParagraphStyle() - hanging.setParagraphStyle(paragraph(.body)) - hanging.headIndent = indent - // #ui-r7 sol#29: inter-item rhythm (reading.css list margins) - // — before-space only, the CSS block has no bottom margin. - hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore - out.addAttribute(.paragraphStyle, value: hanging, range: line.full) - } + applyListMarker(out, line: line) case .syntaxOnly: if line.content.length > 0 { out.addAttributes(dim, range: line.content) @@ -232,7 +274,7 @@ nonisolated enum ProsePresenter { case .fenceInterior, .blank, .body: break } - if kind == .body || kind == .quote || kind == .listMarker { + if carriesInlineTraits(kind) { styleInline(out, content: line.content, text: line.text) } } @@ -256,98 +298,119 @@ nonisolated enum ProsePresenter { private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/ /// Trait-style inline constructs. Marks dim; content gets real traits. - /// Priority: code > link > bold > italic; later matches skip claimed spans. + /// Priority: code > link > bold > italic; later matches skip claimed + /// spans (`claim` is the shared overlap gate, so each family's loop + /// stays honest about the ones before it). private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) { guard content.length > 0 else { return } var claimed: [Range] = [] + styleCodeAndLinks(out, content: content, text: text, claimed: &claimed) + styleEmphasis(out, content: content, text: text, claimed: &claimed) + dimStraySyntax(out, content: content, text: text, claimed: &claimed) + } - func claim(_ span: Range) -> Bool { - guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } - claimed.append(span) - return true - } + /// Claim `span` unless an earlier (higher-priority) match overlaps it. + private static func claim(_ claimed: inout [Range], _ span: Range) -> Bool { + guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } + claimed.append(span) + return true + } - func dim(_ utf16: Range) { - let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) - out.addAttributes(ProseTypography.codeAttributes, range: range) - } + /// Dim a utf16 span in the code face (marks, brackets, stray syntax). + private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range) { + let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) + out.addAttributes(ProseTypography.codeAttributes, range: range) + } - func attr(_ utf16: Range, _ attrs: [NSAttributedString.Key: Any]) { - let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) - out.addAttributes(attrs, range: range) - } + /// Apply `attrs` to a utf16 span. + private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range, _ attrs: [NSAttributedString.Key: Any]) { + let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) + out.addAttributes(attrs, range: range) + } - let boldFont = ProseTypography.boldBodyFont - let italicFont = ProseTypography.italicBodyFont + /// Inline code + links (priority 1–2). Code: marks + content in the code + /// face, content at ink. Links: label ink + underline (CSS: ink text, + /// muted rule); the brackets, ]( and the URL dim (reading hides them; + /// dim is the editor's closest parity move). + private static func styleCodeAndLinks( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { let codeFont = ProseTypography.codeFont let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor] let linkAttrs: [NSAttributedString.Key: Any] = [ .underlineStyle: NSUnderlineStyle.single.rawValue, .underlineColor: ProseTypography.mutedColor, ] - // inline code — marks + content in the code face, content at ink for match in text.matches(of: codePattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) + guard claim(&claimed, span) else { continue } + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) } - // links — label ink + underline (CSS: ink text, muted rule); the - // brackets, ]( and the URL dim (reading hides them; dim is the - // editor's closest parity move). for match in text.matches(of: linkPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let whole = match.output // whole match (no capture groups) guard let sep = whole.firstRange(of: "](") else { continue } // sep indices are valid in text (Substring shares indices) let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!) let label = span.lowerBound + 1 ..< sepOffset - dim(span.lowerBound ..< span.lowerBound + 1) // [ - attr(label, linkAttrs) - dim(sepOffset ..< span.upperBound) // ](url) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [ + attr(out, content: content, label, linkAttrs) + dim(out, content: content, sepOffset ..< span.upperBound) // ](url) } - // bold + } + + /// Bold + italic (priority 3–4). CommonMark: intraword `_` never + /// emphasizes (file_name_here); intraword `*` does. No lookbehind in + /// swift-regex, so boundary chars are checked by hand. + private static func styleEmphasis( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { + let boldFont = ProseTypography.boldBodyFont + let italicFont = ProseTypography.italicBodyFont for match in text.matches(of: boldPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } - dim(span.lowerBound ..< span.lowerBound + 2) - dim(span.upperBound - 2 ..< span.upperBound) - attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) + guard claim(&claimed, span) else { continue } + dim(out, content: content, span.lowerBound ..< span.lowerBound + 2) + dim(out, content: content, span.upperBound - 2 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) } - // italic — two forms. CommonMark: intraword `_` never emphasizes - // (file_name_here); intraword `*` does. No lookbehind in swift-regex, - // so boundary chars are checked by hand. for match in text.matches(of: emStarPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) - if lo == "*" || hi == "*" || lo == "_" || hi == "_" { + if isMarkAdjacent(lo, hi) { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } for match in text.matches(of: emUnderPattern) { let span = match.range.utf16Range(in: text) - guard claim(span) else { continue } + guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) - if lo == "*" || hi == "*" || lo == "_" || hi == "_" { + if isMarkAdjacent(lo, hi) { continue } - if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true { + if isIntraword(lo, hi) { continue } - dim(span.lowerBound ..< span.lowerBound + 1) - dim(span.upperBound - 1 ..< span.upperBound) - attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) + dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) + dim(out, content: content, span.upperBound - 1 ..< span.upperBound) + attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } - // fallback: dim stray syntax chars outside claimed spans + } + + /// Fallback: dim stray syntax chars outside claimed spans. + private static func dimStraySyntax( + _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], + ) { let syntax = inlineSyntax for (offset, codeUnit) in text.utf16.enumerated() { guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue } @@ -355,10 +418,22 @@ nonisolated enum ProsePresenter { if claimed.contains(where: { $0.overlaps(unit) }) { continue } - dim(unit) + dim(out, content: content, unit) } } + /// True when the char at either boundary of an emphasis span is itself + /// a mark (`**foo**`'s inner `*` is bold, not emphasis). + private static func isMarkAdjacent(_ lo: Character?, _ hi: Character?) -> Bool { + lo == "*" || hi == "*" || lo == "_" || hi == "_" + } + + /// True when an `_…_` span sits inside a word (file_name_here never + /// emphasizes). + private static func isIntraword(_ lo: Character?, _ hi: Character?) -> Bool { + lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true + } + // MARK: Base attributes static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index 0267a33..0d7e9d2 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -31,10 +31,12 @@ nonisolated enum ProseTypography { /// Headings = Concourse OT (the designer's own pairing with Valkyrie); /// Semibold carries heading weight better than Book on screen. - nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) + nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) + ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) /// h2 = the headings face at CSS's 0.85× ladder step (#77). - nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) + nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) + ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) /// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B /// cut has no 600 member — the bold trait (700, real or synthesized) is diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index d202cc8..8ea6c20 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter { // swiftlint:disable:next force_try let regex = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#) let mutable = NSMutableString(string: html) - regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"") + regex.replaceMatches(in: mutable, range: NSRange(location: 0, length: mutable.length), withTemplate: "<$2 data-source-line=\"$1\"") return mutable as String } @@ -207,7 +207,8 @@ nonisolated enum ReadingPresenter { /// apex failure / missing binary → editing-treated source text (#69's /// fallback rule: fallback = the source, not a second renderer). static func fallbackPage(_ text: String) -> String { - "
\(escapeHTML(text))
" + "" + + "
\(escapeHTML(text))
" } static func escapeHTML(_ text: String) -> String { diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 4c00754..bf5840c 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -172,6 +172,13 @@ struct ReadingSurface: NSViewRepresentable { wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line)) } + /// True for our own loadHTMLString main-frame load (file URL or + /// about:blank) — the only navigation reading allows in-app. + private func isOwnMainFrameLoad(_ nav: WKNavigationAction) -> Bool { + guard nav.targetFrame?.isMainFrame == true, let url = nav.request.url else { return false } + return url.scheme == "file" || url.absoluteString == "about:blank" + } + /// Allow our own loadHTMLString main-frame load (about:blank); a /// blanket .cancel would kill the page before it paints. Everything /// else is cancelled — reading never navigates in-app (#74 lesson). @@ -180,9 +187,7 @@ struct ReadingSurface: NSViewRepresentable { decidePolicyFor nav: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void, ) { - if nav.targetFrame?.isMainFrame == true, - let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank" - { + if isOwnMainFrameLoad(nav) { decisionHandler(.allow) return } diff --git a/Museion/WorkspaceChrome.swift b/Museion/WorkspaceChrome.swift new file mode 100644 index 0000000..015a0f1 --- /dev/null +++ b/Museion/WorkspaceChrome.swift @@ -0,0 +1,96 @@ +// +// WorkspaceChrome.swift +// Museion +// +// #193: the shared workspace chrome, moved from WorkspaceView.swift +// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle, +// PaneHeader; every pane reuses them, code unchanged. +// + +import SwiftUI + +/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt +/// accent capsule with radius-1 rounded ends, vertically inset 6pt from +/// the row's edges so it sits INSIDE the card/fill (Posts library rows, +/// Settings sidebar rows). Callers toggle it via opacity so the 2pt +/// reservation keeps layout constant. +struct SelectedRowStrip: View { + var body: some View { + RoundedRectangle(cornerRadius: 1) + .fill(DesignTokens.accent) + .frame(width: 2) + .padding(.vertical, 6) + } +} + +/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a +/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings' +/// Choose…). 36pt tall by default — a real hit target, not a text-size +/// pill; pass a smaller `minHeight` where the row is compact. +struct BorderedSecondaryButtonStyle: ButtonStyle { + var minHeight: CGFloat = 36 + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.foreground) + .padding(.horizontal, 12) + .frame(minHeight: minHeight) + .background( + RoundedRectangle(cornerRadius: 8) + .fill(DesignTokens.surface) + .overlay( + RoundedRectangle(cornerRadius: 8) + .strokeBorder(DesignTokens.border), + ), + ) + .opacity(configuration.isPressed ? 0.7 : 1) + } +} + +/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border). +/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`). +struct PaneHeader: View { + let title: String + /// Leading inset of the title row. Export default 14; the Learnings pane + /// passes 26 so its title shares one leading edge with headings + rows. + var titleInset: CGFloat = 14 + /// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom + /// hairline is bounded to the same column the pane's content sits in + /// (Archive/Learnings' 720pt reading column) — title, hairline, and + /// content read as one framed block instead of a full-width rule over + /// a bounded column. nil = full width (every other pane's default). + var hairlineMaxWidth: CGFloat? + @ViewBuilder var trailing: () -> Trailing + + init( + title: String, + titleInset: CGFloat = 14, + hairlineMaxWidth: CGFloat? = nil, + @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }, + ) { + self.title = title + self.titleInset = titleInset + self.hairlineMaxWidth = hairlineMaxWidth + self.trailing = trailing + } + + var body: some View { + VStack(spacing: 0) { + HStack { + Text(title) + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Spacer() + trailing() + } + .padding(.horizontal, titleInset) + .frame(minHeight: 52) + Rectangle() + .fill(DesignTokens.border) + .frame(height: 1) + // r8: the bound shares the content column's leading edge + // (x0) and width — leading-aligned, never centered. + .frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading) + } + } +} diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index bb02166..a126643 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -7,6 +7,9 @@ // rail 56 | library 232 | editor min 420 | mentor 356. // #108: the Archive rail destination (box icon, above Settings) + the // New Project ask both live here. +// #193: the split-out files — ArchivePaneView.swift, the house ask +// sheets WorkspaceViewSheets.swift, the shared chrome +// WorkspaceChrome.swift; RailButton stays (the rail is its only caller). // import SwiftUI @@ -355,346 +358,6 @@ struct WorkspaceView: View { } } -/// #108: the Archive pane — archive/ as a rail destination (prototype -/// verdict: a destination, not a library disclosure). List-only: clicking a -/// piece selects it and hops to Posts, where the editor column lives. -private struct ArchivePaneView: View { - var model: PostsModel - /// Fired after a row select — the pane can't reach WorkspaceView's - /// selection itself. - let onOpenPiece: () -> Void - @State private var renamingPost: Post? - /// #108: collapsed project sections — per-view state, not persisted - /// (mirrors the library column). - @State private var collapsed: Set = [] - - private var archivedByProject: [String: [Post]] { - Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project) - } - - /// #108: the prototype's toggle — click the project name (or chevron). - private func toggle(_ project: String) { - if collapsed.contains(project) { - collapsed.remove(project) - } else { - collapsed.insert(project) - } - } - - var body: some View { - VStack(spacing: 0) { - // No New button — things arrive here by being moved, not created. - // r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME - // fixed 720pt column the rows live in — one framed block. - PaneHeader(title: "Archive", hairlineMaxWidth: 720) - if archivedByProject.isEmpty { - emptyState - } else { - ScrollView { - LazyVStack(alignment: .leading, spacing: 4) { - // #108 audit: Finder order, matching the library's sort. - ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in - let pieces = archivedByProject[project] ?? [] - // Same section-head shape as the library (#108 - // variant B), plus the project-level way out. - // r7 (mercury#55, argon#41 — FINAL, supersedes the - // r6 D24 ladder): the content column is a FIXED - // 720pt frame (width, not maxWidth — the r6 - // content-hugging bound let the pill define the - // right edge), left-anchored. TWO axes only, the - // library's r7 ladder: the head row leads at x14 - // (chevron in a 14pt slot) with its label at x28 — - // the ONE indent, shared with the entry rows' - // inner text via the shared LibraryPostRow (cards - // lead at x14); the 'Unarchive Group' pill rides - // the header row's trailing edge INSIDE the frame - // (14 → 706), and the row hairlines are bounded by - // the same frame. Nothing spans past it. - HStack(alignment: .firstTextBaseline, spacing: 0) { - Image(systemName: "chevron.down") - .font(.system(size: 10, weight: .semibold)) - .frame(width: 14, alignment: .leading) - .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) - .foregroundStyle(DesignTokens.muted) - .onTapGesture { - withAnimation { toggle(project) } - } - .accessibilityLabel("Toggle \(project)") - .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") - Text(project) - .font(.system(size: 11, weight: .medium, design: DesignTokens.mono)) - .kerning(0.6) - .textCase(.uppercase) // #108: display-only — the folder name keeps its case - .foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final - .lineLimit(1) - .truncationMode(.tail) - .onTapGesture { - withAnimation { toggle(project) } - } - Text("· \(pieces.count)") - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.muted) - .padding(.leading, 8) - Spacer(minLength: 8) - // The 'New Post · Fork · Compact' language — a - // bordered mono-11 secondary pill at the - // trailing edge INSIDE the fixed 720pt frame. - // r7 (mercury#55, argon#41): relabeled - // 'Unarchive Group' — it moves the whole - // project, not one piece. - Button("Unarchive Group") { - model.unarchiveProject(project) - } - .buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24)) - .help("Move the whole project back to projects/") - .accessibilityLabel("Unarchive \(project)") - } - .padding(.top, 12) - .padding(.horizontal, 14) - .padding(.bottom, 2) - if !collapsed.contains(project) { - ForEach(pieces) { post in - // r7: the shared LibraryPostRow ladder — - // card leads at x14 (PRIMARY), title text - // at x28 (the one indent). The hairline is - // BOUNDED to the fixed frame: x14 → 706. - LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { - model.select(post.id) - onOpenPiece() - } - .overlay(alignment: .bottom) { - Rectangle() - .fill(DesignTokens.border) - .frame(height: 1) - .padding(.horizontal, 14) - } - .contextMenu { - Button("Move Back to \(post.project)") { - model.restorePost(post) - } - Button("Rename…") { renamingPost = post } - // #114 (S4): works archived too — the piece - // stays where it is, only type + body flip. - if post.type == .outline { - Button("Convert to Post…") { - model.stageConversion(post) - } - } - } - } - } - } - } - // r7 (mercury#55, argon#41): the FIXED 720pt reading - // column — width, not maxWidth (the r6 content-hugging - // bound let the pill define the right edge); rows, - // hairlines, and the pill all live inside it. - // ponytail: fixed width clips on panes narrower than - // 720 — a width-floored variant if a small-window - // Archive ever matters. - .frame(width: 720, alignment: .leading) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.bottom, 12) - } - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(DesignTokens.background) - .sheet(item: $renamingPost) { post in - RenamePostSheet(post: post) { title in - model.rename(post, to: title) - } - } - } - - private var emptyState: some View { - VStack(spacing: 8) { - Text("Nothing archived") - .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) - Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - .multilineTextAlignment(.center) - } - .padding(38) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } -} - -/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the -/// immutability line (CONTEXT.md: Origin). Answering runs the batch. -private struct OriginAskSheet: View { - let count: Int - let answer: (Post.Origin) -> Void - @Environment(\.dismiss) private var dismiss - @State private var origin: Post.Origin = .writer - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Who wrote this?") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text(count == 1 - ? "Importing 1 file as a Post — the original is untouched." - : "Importing \(count) files as Posts — the originals are untouched.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - Picker("Origin", selection: $origin) { - Text("I wrote it (writer)").tag(Post.Origin.writer) - Text("AI-assisted (ai)").tag(Post.Origin.ai) - } - .pickerStyle(.radioGroup) - Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.") - .font(.caption) - .foregroundStyle(DesignTokens.muted) - HStack { - Spacer() - Button("Cancel", role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) - Button("Import") { - answer(origin) - dismiss() - } - .keyboardShortcut(.defaultAction) - } - } - .padding(20) - .frame(width: 380) - } -} - -/// #111 (S7): the mixed-content outline guard ask. The piece has prose -/// lines the outliner can't show — opening it as an outline would drop -/// them on the next save. Prose = nothing drops; Outline = the explicit -/// choice the ruling requires. -private struct OutlineGuardSheet: View { - let openInProse: () -> Void - let openAsOutline: () -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Open as outline or prose?") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - HStack { - Spacer() - // Dismissal itself is the cancel (binding set(false) → - // cancelOutlineGuard) — Esc and ⌘. land here too. - Button("Cancel", role: .cancel) {} - .keyboardShortcut(.cancelAction) - Button("Open as Outline") { - openAsOutline() - } - Button("Open in Prose") { - openInProse() - } - .keyboardShortcut(.defaultAction) - } - } - .padding(20) - .frame(width: 420) - } -} - -/// #114 (S4): the Convert to Post ask — which body the piece becomes. -/// Verbatim (default) keeps every line; the ladder re-maps outline levels -/// to headings. On mixed content the ladder would drop prose lines — -/// the sheet says so. -private struct ConvertSheet: View { - let lossy: Bool - /// false = verbatim bullets, true = headings ladder — one decision, - /// one model call. - let convert: (Bool) -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Convert to Post") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - if lossy { - Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - } - Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - HStack { - Spacer() - // Dismissal itself is the cancel (binding set(false) → - // cancelConversion) — Esc and ⌘. land here too. - Button("Cancel", role: .cancel) {} - .keyboardShortcut(.cancelAction) - Button("Headings") { - convert(true) - } - Button("Verbatim Bullets") { - convert(false) - } - .keyboardShortcut(.defaultAction) - } - } - .padding(20) - .frame(width: 440) - } -} - -/// #108: New Project ask — the sheet behind File ▸ New Project… (and any -/// future materialize path). Create runs through the model's raw op; the -/// thrown reason is shown inline and the sheet stays up. -private struct NewProjectSheet: View { - /// Create + open a draft in it; nil = success, a string = the failure - /// reason to show inline (keeps the sheet up). - let create: (String) -> String? - @Environment(\.dismiss) private var dismiss - @State private var name = "" - @State private var failure: String? - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("New Project") - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Text("Pieces land here when it's selected.") - .font(.callout) - .foregroundStyle(DesignTokens.muted) - TextField("Name", text: $name) - .textFieldStyle(.roundedBorder) - .onSubmit { confirm() } - if let failure { - Text(failure) - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.accent) - } - HStack { - Spacer() - Button("Cancel", role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) - Button("Create", action: confirm) - .keyboardShortcut(.defaultAction) - .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) - } - } - .padding(20) - .frame(width: 360) - } - - private func confirm() { - let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return } - if let reason = create(trimmed) { - failure = reason - } else { - dismiss() - } - } -} - /// Rail button: 44×44 muted icon, hover wash, the current pane raised as /// a tile. NO visible edge bar — ui-polish r2 re-ruling: the export's /// `::before` selection bar paints behind the app border in the export's @@ -761,89 +424,3 @@ private struct RailButton: View { .accessibilityLabel(label) } } - -/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt -/// accent capsule with radius-1 rounded ends, vertically inset 6pt from -/// the row's edges so it sits INSIDE the card/fill (Posts library rows, -/// Settings sidebar rows). Callers toggle it via opacity so the 2pt -/// reservation keeps layout constant. -struct SelectedRowStrip: View { - var body: some View { - RoundedRectangle(cornerRadius: 1) - .fill(DesignTokens.accent) - .frame(width: 2) - .padding(.vertical, 6) - } -} - -/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a -/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings' -/// Choose…). 36pt tall by default — a real hit target, not a text-size -/// pill; pass a smaller `minHeight` where the row is compact. -struct BorderedSecondaryButtonStyle: ButtonStyle { - var minHeight: CGFloat = 36 - - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.system(size: 11, design: DesignTokens.mono)) - .foregroundStyle(DesignTokens.foreground) - .padding(.horizontal, 12) - .frame(minHeight: minHeight) - .background( - RoundedRectangle(cornerRadius: 8) - .fill(DesignTokens.surface) - .overlay( - RoundedRectangle(cornerRadius: 8) - .strokeBorder(DesignTokens.border), - ), - ) - .opacity(configuration.isPressed ? 0.7 : 1) - } -} - -/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border). -/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`). -struct PaneHeader: View { - let title: String - /// Leading inset of the title row. Export default 14; the Learnings pane - /// passes 26 so its title shares one leading edge with headings + rows. - var titleInset: CGFloat = 14 - /// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom - /// hairline is bounded to the same column the pane's content sits in - /// (Archive/Learnings' 720pt reading column) — title, hairline, and - /// content read as one framed block instead of a full-width rule over - /// a bounded column. nil = full width (every other pane's default). - var hairlineMaxWidth: CGFloat? - @ViewBuilder var trailing: () -> Trailing - - init( - title: String, - titleInset: CGFloat = 14, - hairlineMaxWidth: CGFloat? = nil, - @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }, - ) { - self.title = title - self.titleInset = titleInset - self.hairlineMaxWidth = hairlineMaxWidth - self.trailing = trailing - } - - var body: some View { - VStack(spacing: 0) { - HStack { - Text(title) - .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) - Spacer() - trailing() - } - .padding(.horizontal, titleInset) - .frame(minHeight: 52) - Rectangle() - .fill(DesignTokens.border) - .frame(height: 1) - // r8: the bound shares the content column's leading edge - // (x0) and width — leading-aligned, never centered. - .frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading) - } - } -} diff --git a/Museion/WorkspaceViewSheets.swift b/Museion/WorkspaceViewSheets.swift new file mode 100644 index 0000000..ebd999e --- /dev/null +++ b/Museion/WorkspaceViewSheets.swift @@ -0,0 +1,189 @@ +// +// WorkspaceViewSheets.swift +// Museion +// +// #193: the house ask sheets, moved from WorkspaceView.swift +// (file-length ceiling) — OriginAskSheet (#94), OutlineGuardSheet +// (#111), ConvertSheet (#114), NewProjectSheet (#108) — code +// unchanged (private → internal: WorkspaceView presents them +// cross-file now). +// + +import SwiftUI + +/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the +/// immutability line (CONTEXT.md: Origin). Answering runs the batch. +struct OriginAskSheet: View { + let count: Int + let answer: (Post.Origin) -> Void + @Environment(\.dismiss) private var dismiss + @State private var origin: Post.Origin = .writer + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Who wrote this?") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text(count == 1 + ? "Importing 1 file as a Post — the original is untouched." + : "Importing \(count) files as Posts — the originals are untouched.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + Picker("Origin", selection: $origin) { + Text("I wrote it (writer)").tag(Post.Origin.writer) + Text("AI-assisted (ai)").tag(Post.Origin.ai) + } + .pickerStyle(.radioGroup) + Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.") + .font(.caption) + .foregroundStyle(DesignTokens.muted) + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Import") { + answer(origin) + dismiss() + } + .keyboardShortcut(.defaultAction) + } + } + .padding(20) + .frame(width: 380) + } +} + +/// #111 (S7): the mixed-content outline guard ask. The piece has prose +/// lines the outliner can't show — opening it as an outline would drop +/// them on the next save. Prose = nothing drops; Outline = the explicit +/// choice the ruling requires. +struct OutlineGuardSheet: View { + let openInProse: () -> Void + let openAsOutline: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Open as outline or prose?") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text( + "This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline " + + "drops them on the next save. Prose mode shows everything.", + ) + .font(.callout) + .foregroundStyle(DesignTokens.muted) + Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + HStack { + Spacer() + // Dismissal itself is the cancel (binding set(false) → + // cancelOutlineGuard) — Esc and ⌘. land here too. + Button("Cancel", role: .cancel) {} + .keyboardShortcut(.cancelAction) + Button("Open as Outline") { + openAsOutline() + } + Button("Open in Prose") { + openInProse() + } + .keyboardShortcut(.defaultAction) + } + } + .padding(20) + .frame(width: 420) + } +} + +/// #114 (S4): the Convert to Post ask — which body the piece becomes. +/// Verbatim (default) keeps every line; the ladder re-maps outline levels +/// to headings. On mixed content the ladder would drop prose lines — +/// the sheet says so. +struct ConvertSheet: View { + let lossy: Bool + /// false = verbatim bullets, true = headings ladder — one decision, + /// one model call. + let convert: (Bool) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Convert to Post") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + if lossy { + Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + } + Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + HStack { + Spacer() + // Dismissal itself is the cancel (binding set(false) → + // cancelConversion) — Esc and ⌘. land here too. + Button("Cancel", role: .cancel) {} + .keyboardShortcut(.cancelAction) + Button("Headings") { + convert(true) + } + Button("Verbatim Bullets") { + convert(false) + } + .keyboardShortcut(.defaultAction) + } + } + .padding(20) + .frame(width: 440) + } +} + +/// #108: New Project ask — the sheet behind File ▸ New Project… (and any +/// future materialize path). Create runs through the model's raw op; the +/// thrown reason is shown inline and the sheet stays up. +struct NewProjectSheet: View { + /// Create + open a draft in it; nil = success, a string = the failure + /// reason to show inline (keeps the sheet up). + let create: (String) -> String? + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var failure: String? + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("New Project") + .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) + Text("Pieces land here when it's selected.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + TextField("Name", text: $name) + .textFieldStyle(.roundedBorder) + .onSubmit { confirm() } + if let failure { + Text(failure) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.accent) + } + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Create", action: confirm) + .keyboardShortcut(.defaultAction) + .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(20) + .frame(width: 360) + } + + private func confirm() { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + if let reason = create(trimmed) { + failure = reason + } else { + dismiss() + } + } +} diff --git a/Museion/WritingLockState.swift b/Museion/WritingLockState.swift index 9291cf3..1ea4d60 100644 --- a/Museion/WritingLockState.swift +++ b/Museion/WritingLockState.swift @@ -299,12 +299,19 @@ enum WritingLockKiosk { return false } + private static func shouldRefuse(_ event: NSEvent) -> Bool { + WritingLockState.active?.isLocked == true + && refusesKey( + keyCode: event.keyCode, + characters: event.charactersIgnoringModifiers, + modifiers: event.modifierFlags, + ) + } + private static func installRefusalMonitor() { guard refusalMonitor == nil else { return } refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in - if WritingLockState.active?.isLocked == true, - Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags) - { + if Self.shouldRefuse(event) { return nil // swallowed — the lock holds } return event diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 8e4fd73..6695739 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -12,6 +12,7 @@ Owned by the root AGENTS.md contract. - Uses Swift Testing (`@Test`, `#expect`) — not XCTest. - Always give `@Suite` its string argument — bare `@Suite` is stripped by this repo's swiftformat. +- `@Test` names: backticked sentence style is the convention; plain lowercase-camel identifiers are the deliberate exception where name-level `-only-testing` addressability matters (#195) — `.swiftformat` sets `--test-case-name-format preserve`, so both shapes are format-clean. - Imports `@testable import Museion`; app code is default-MainActor, so cross-actor tests need `@MainActor` or nonisolated declarations in app code. - Deployment target and versions follow the app target; leave `CURRENT_PROJECT_VERSION = 1` here. @@ -50,7 +51,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — ## Verification -- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -only-testing:MuseionTests test` — verify by the xcresult EXECUTED count, never the SUCCEEDED banner. +- `./scripts/full-test.sh start` + `status` polling is the sanctioned verify rail (#190): detached run, per-run pinned bundle, counts from `xcresulttool` only, zero-match filters FAIL (vacuous-green trap), `--serialized` rerun for parallel-load flakes, per-test timeouts naming wedged tests. ## Child DOX Index diff --git a/MuseionTests/LearningsPaneTests.swift b/MuseionTests/LearningsPaneTests.swift index 676aefe..c41f734 100644 --- a/MuseionTests/LearningsPaneTests.swift +++ b/MuseionTests/LearningsPaneTests.swift @@ -124,6 +124,25 @@ struct LearningsPaneTests { #expect(LearningsIndex.scan(home: home).isEmpty) } + /// Scenario: the skip posture Post.scan pins, on this scan — a symlinked + /// type dir must not be followed. Defended in depth: the lstat guard + /// (a symlink reports isDirectory=false) AND contentsOfDirectory's own + /// refusal of a symlinked entry — flip-verified: the pin fails only when + /// BOTH go traversal-shaped (fileExists guard + resolved-URL listing). + @Test func `a symlinked type dir never surfaces`() throws { + let home = try makeHome { home in + try writeLearning(home, "posts", "20261021-one-real-entry.md", "# real\n") + } + let learnings = home.appendingPathComponent("learnings", isDirectory: true) + try FileManager.default.createSymbolicLink( + at: learnings.appendingPathComponent("linked", isDirectory: true), + withDestinationURL: learnings.appendingPathComponent("posts", isDirectory: true), + ) + let groups = LearningsIndex.scan(home: home) + #expect(groups.map(\.type) == ["posts"]) // the link's alias never groups + #expect(groups.flatMap(\.entries).count == 1) // its view of posts never doubles + } + // MARK: Decay surface (#27, S4.2) /// Scenario: Entry carries the decay verdict — visible learnings read diff --git a/MuseionTests/LibrarySearchTests.swift b/MuseionTests/LibrarySearchTests.swift index 5130730..7e59549 100644 --- a/MuseionTests/LibrarySearchTests.swift +++ b/MuseionTests/LibrarySearchTests.swift @@ -96,7 +96,8 @@ struct LibrarySearchTests { /// while it `isFresh` for the CURRENT key. The controller pins drive /// the real rescan rail (write verbs + the rail's own rescan Task) and /// prove archive, trash, and a same-query body edit each move the -/// revision — without that signal a standing snapshot outlives the +/// revision, and an unchanged rescan over a quiesced FSEvent burst +/// keeps it — without that signal a standing snapshot outlives the /// library it searched (archived rows linger in the results; edited /// bodies never enter or leave them until the query changes). @Suite("library search snapshot invalidation") @@ -192,9 +193,22 @@ struct LibrarySearchSnapshotTests { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Settled\n", home: home) try await pollUntil { model.posts.contains { $0.id == post.id } } + // The FSEvent burst can still hold a sibling rescan that snapshotted + // its miss count BEFORE the landing scan stamped the shared + // PostScanCache — both count the same first read, each bumps the + // revision (#144's counter; an extra bump only over-invalidates a + // search snapshot). This pin is the SETTLED contract: wait out the + // burst (FSEvents latency is 0.5 s) before snapshotting. + var quiet = false + for _ in 0 ..< 20 where !quiet { + let seen = model.contentRevision + try await Task.sleep(nanoseconds: 500_000_000) + quiet = model.contentRevision == seen + } + #expect(quiet) // endless revision churn would never settle let settled = model.contentRevision - await model.rescan() // nothing changed since the last scan — all cache hits + await model.rescan() // nothing changed since the burst — all cache hits #expect(model.contentRevision == settled) } diff --git a/MuseionTests/PolishSeamTests.swift b/MuseionTests/PolishSeamTests.swift index 2a58a08..c0c65df 100644 --- a/MuseionTests/PolishSeamTests.swift +++ b/MuseionTests/PolishSeamTests.swift @@ -18,7 +18,7 @@ struct PolishSeamTests { /// whitespace-only buffer has none (nil); a buffer with no leading /// blanks returns 0. The same walker styles the title line and hops /// programmatic carets past the invisible blank fragment. - @Test func `firstContentLocation skips leading blanks`() { + @Test func firstContentLocationSkipsLeadingBlanks() { let plain = "Title\n\nbody" as NSString #expect(ProsePresenter.firstContentLocation(plain) == 0) let blankLead = "\n\n \nTitle\nbody" as NSString @@ -31,7 +31,7 @@ struct PolishSeamTests { /// The ladder keeps the full path, then each shorter variant with one /// more leading component kept whole; ≤2 components has nothing to /// elide. `elide` picks the longest candidate that fits. - @Test func `ElidedPathText candidate ladder and elision`() { + @Test func elidedPathTextCandidateLadderAndElision() { let path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion" let ladder = ElidedPathText.candidates(path) #expect(ladder.first == path) diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 1b0f844..11ed076 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -532,7 +532,8 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws withIntermediateDirectories: true, ) } - #expect(!decomposed.utf8.elementsEqual("한국".utf8)) // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract + // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract + #expect(!decomposed.utf8.elementsEqual("한국".utf8)) #expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2") } diff --git a/MuseionTests/ProfileProvisionerFailureTests.swift b/MuseionTests/ProfileProvisionerFailureTests.swift index ba4afd0..eef50ab 100644 --- a/MuseionTests/ProfileProvisionerFailureTests.swift +++ b/MuseionTests/ProfileProvisionerFailureTests.swift @@ -44,14 +44,17 @@ struct ProfileProvisionerFailureTests { func configUntouched() -> Bool { (try? String(contentsOfFile: configPath, encoding: .utf8)) == config } + // Shared per-phase runner: same binary/root/payload master, the + // server seam varying per phase (default = perform's own default). + func pass(_ payload: String, server: String? = Bundle.main.executableURL?.path) -> ProfileProvisioner.Outcome { + ProfileProvisioner.perform( + hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload, + masterRoot: master, serverBinaryPath: server, + ) + } // Failed pass: registration never reached, config untouched. - let failed = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: badPayload, - masterRoot: master, - ) + let failed = pass(badPayload) guard case .failed = failed else { Issue.record("expected copy failure, got \(failed)") return @@ -61,13 +64,7 @@ struct ProfileProvisionerFailureTests { // Skipped pass: nil serverBinaryPath is the test seam — nothing // registers, config untouched. (The failed pass already seeded the // shared master — 2 present there, only the 6 profile links copy.) - let skipped = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: goodPayload, - masterRoot: master, - serverBinaryPath: nil, - ) + let skipped = pass(goodPayload, server: nil) #expect(skipped == .seeded(copied: 6, present: 2)) #expect(configUntouched()) for profile in ["museion", "museion-pass1", "museion-pass2"] { @@ -77,13 +74,7 @@ struct ProfileProvisionerFailureTests { // Registering pass: the CLI rail ran (markers + invocations per // profile) and still not one byte of config.yaml is written by the // provisioner — the entry lands through the CLI, or not at all. - let registered = ProfileProvisioner.perform( - hermesBinary: binary, - profileRoot: profileRoot, - payloadRoot: goodPayload, - masterRoot: master, - serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion", - ) + let registered = pass(goodPayload, server: "/fake/Museion.app/Contents/MacOS/Museion") #expect(registered == .seeded(copied: 0, present: 8)) #expect(configUntouched()) #expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion"))) diff --git a/MuseionTests/ProfileProvisionerTests.swift b/MuseionTests/ProfileProvisionerTests.swift index 69c50e4..05445c7 100644 --- a/MuseionTests/ProfileProvisionerTests.swift +++ b/MuseionTests/ProfileProvisionerTests.swift @@ -44,8 +44,8 @@ struct SeedSkill { /// and `config unset ` (argv log `/config-unset-`, /// store line removed, "✓ Unset …"; unset-when-absent = the not-set line, /// exit 1) — the live-probed wire shapes HermesSettingsWriter pins. -// #136: the config rail (set/get/unset over the config-store map) — its -// own literal so makeFakeHermes stays under its function-body ceiling. +/// #136: the config rail (set/get/unset over the config-store map) — its +/// own literal so makeFakeHermes stays under its function-body ceiling. private func fakeHermesConfigCLI() -> String { """ if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then @@ -94,6 +94,67 @@ private func fakeHermesConfigCLI() -> String { """ } +/// #23: the mcp rail (list/add over marker files) — its own literal so +/// makeFakeHermes stays under its function-body ceiling (config-rail +/// precedent directly above). +private func fakeHermesMcpCLI() -> String { + """ + if [[ "$1" == "-p" && "$3" == "mcp" ]]; then + PROFILE="$2" + if [[ "$4" == "list" ]]; then + if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then + print "museion-tools enabled" + exit 0 + fi + print "No MCP servers configured." + exit 0 + fi + if [[ "$4" == "add" ]]; then + if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then + print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9" + exit 1 + fi + if [[ -f "${0:h}/mcp-add-fails" ]]; then + print "Error: mcp add exploded" + exit 1 + fi + read -r ANSWER + if [[ "$ANSWER" != "y" ]]; then + print "Cancelled." + exit 1 + fi + print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE" + touch "${0:h}/mcp-registered-$PROFILE" + print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml" + exit 0 + fi + fi + """ +} + +/// Fake `hermes`: `profile create ` behaves per `mode` (#43 semantics). +/// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on +/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1. +/// stderr-only: error on stderr with empty stdout (#48 fallback). +/// +/// Also speaks `mcp` and `config set` behind the `-p ` global flag +/// (#23, #134): `mcp list` prints "museion-tools" iff +/// `/mcp-registered-` exists, else "No MCP servers +/// configured."; `mcp add` verifies its argv, reads ONE "y" line from stdin +/// (mismatch/EOF → "Cancelled.", exit 1 — nothing saved), records the exact +/// invocation in `/mcp-add-invocation-`, drops the +/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire +/// strings). `config set [--force]` appends the exact argv to +/// `/config-set-` and prints the verified "✓ Set …" +/// line. `/mcp-add-fails` / `config-set-fails` / `config-unset-fails` +/// force the matching failure. Every `profile create` name appends to +/// `/profile-create-log`. +/// #136: `config set` also records KEY=VALUE into +/// `/config-store-` (dedup per key), and the fake speaks +/// `config get ` (store value, or the not-set line on stderr exit 1) +/// and `config unset ` (argv log `/config-unset-`, +/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line, +/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins. func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String { let path = (dir as NSString).appendingPathComponent(name) let createBlock = switch mode { @@ -128,36 +189,7 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St print -r -- "$NAME" >> "${0:h}/profile-create-log" \(createBlock) fi - if [[ "$1" == "-p" && "$3" == "mcp" ]]; then - PROFILE="$2" - if [[ "$4" == "list" ]]; then - if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then - print "museion-tools enabled" - exit 0 - fi - print "No MCP servers configured." - exit 0 - fi - if [[ "$4" == "add" ]]; then - if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then - print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9" - exit 1 - fi - if [[ -f "${0:h}/mcp-add-fails" ]]; then - print "Error: mcp add exploded" - exit 1 - fi - read -r ANSWER - if [[ "$ANSWER" != "y" ]]; then - print "Cancelled." - exit 1 - fi - print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE" - touch "${0:h}/mcp-registered-$PROFILE" - print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml" - exit 0 - fi - fi + \(fakeHermesMcpCLI()) \(fakeHermesConfigCLI()) exit 97 """ diff --git a/MuseionTests/ProfileSurfaceTests.swift b/MuseionTests/ProfileSurfaceTests.swift index 269c28d..27efd51 100644 --- a/MuseionTests/ProfileSurfaceTests.swift +++ b/MuseionTests/ProfileSurfaceTests.swift @@ -343,7 +343,8 @@ struct ProfileSurfaceTests { ) #expect(outcome == .seeded(copied: 8, present: 0)) for profile in ProfileSurface.allCases { - #expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)"))) + let invocation = (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)") + #expect(!FileManager.default.fileExists(atPath: invocation)) } } diff --git a/MuseionTests/ProsePresenterTests.swift b/MuseionTests/ProsePresenterTests.swift index 69a4c60..58533d7 100644 --- a/MuseionTests/ProsePresenterTests.swift +++ b/MuseionTests/ProsePresenterTests.swift @@ -58,7 +58,11 @@ struct ProsePresenterTests { // sample at the heading TEXT, not offset 0 (the dimmed marker) let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont #expect(h1?.pointSize == 30) - #expect(h1?.fontName.contains("ConcourseOT") == true || h1?.fontName.contains("Semibold") == true || h1?.fontName.contains("Bold") == true) + #expect( + h1?.fontName.contains("ConcourseOT") == true + || h1?.fontName.contains("Semibold") == true + || h1?.fontName.contains("Bold") == true, + ) let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont #expect(h2?.pointSize == 22) let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index c3fc526..5645f14 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -27,7 +27,8 @@ struct ReadingPresenterTests { @Test func `stamper rewrites attributes`() { let html = "

T

\n\n

A

\n\n
    \n
  • B
  • \n
" - #expect(ReadingPresenter.stampHTML(html) == "

T

\n

A

\n
    \n
  • B
  • \n
") + let expected = "

T

\n

A

\n
    \n
  • B
  • \n
" + #expect(ReadingPresenter.stampHTML(html) == expected) } /// The #68 click→edit map: blocks are monotonic, lines are 1-based, and diff --git a/docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md b/docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md new file mode 100644 index 0000000..88229d9 --- /dev/null +++ b/docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md @@ -0,0 +1,73 @@ +# Port classis full-test.sh as the Museion verify rail + pre-push hook + +> **Date:** 2026-11-17 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/190 + +## Goal + +One command verifies a branch: port classis's `scripts/full-test.sh` (source commit 071966e) to Museion with the same CLI (`run` / `start` / `status` / `summary`), encoding the suite learnings (#33/#179 bundle race, #31/#178 xcresult authority, #31/#134 vacuous green, #30/#147 serialized rerun, #134 wedge family, #177 detached pattern), plus the hook pair (`install-hooks.sh` + pre-push lint gate, no-push-while-live, autofix-tree guard). The 2026-11-16 retro measured this loop at 29% of all session terminal calls. + +## What Was Done + +- `scripts/full-test.sh` — classis port adapted to Museion: scheme Museion, `Museion.xcodeproj` at root, `-destination 'platform=macOS'`, default test selection `-only-testing:MuseionTests` (dropped the moment the caller forwards their own `-only-testing` — union semantics would make a finer filter a no-op), no default parallel flags (`--workers N` opts in, `--serialized` is the #30/#147 rerun hatch), header maps every encoded behavior to its Museion issue numbers. +- `scripts/install-hooks.sh` — idempotent `git config core.hooksPath scripts/hooks`, with a trust note (versioned hooks = repo content executes at push). +- `scripts/hooks/pre-push` — (1) blocks push while ANY full-test run is live (scans all run dirs, not just `current`); (2) lint gate scoped to the PUSH's Swift files; (3) autofix guard: a swiftformat pass that rewrites files after verification fails the push. +- `scripts/test-full-test.sh` — in-tree pre-push acceptance rig: disposable bare+clone, real hook + real lint tools, 23 checks over every push shape, with an executed-count guard on the verdict. +- DOX: root AGENTS.md commands + `scripts/` Child DOX Index row; MuseionTests/AGENTS.md Verification names the rail; `.gitignore` += `_build/`. +- Finish-audit (4 rounds × 3 reviewers) — accepted fixes: merge-base delta gating for new-ref pushes, delete-ref skip, `--scheme` path guard, fail-closed on unscopable history, full `refs/remotes/origin/main` spelling (anti-tag-shadow), rig's vacuous first check + count guard. + +## Verification (step-2 gates, 2026-11-17) + +- `./scripts/full-test.sh run` — **692 executed / 692 passed / 0 failed / 0 skipped**, exit 0 (run twice through the rail itself). +- `./scripts/test-full-test.sh` — **23/23**, exit 0; all four hook guards flip-verified in both directions this session. +- `swiftformat .` — 0/141 files formatted, exit 0. +- `swiftlint lint --quiet` — exit 2 from **pre-existing** error-severity findings (59 in `spike/`, 1 in `MuseionTests/PolishSeamTests.swift:34`); this diff touches zero Swift — outside the seam, named here per the finish-up exception. +- `node .gitnexus/run.cjs detect-changes` — 3 files, 22 doc symbols, 0 affected processes, risk low (index-relative; the untracked scripts carry no indexed symbols). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Pre-push lint gate scoped to the pushed diff's Swift files | Bare `swiftlint .` exits 2 on main (spike/ + one tests file) — a repo-wide gate would block every push forever. The gate guards the push's own files; no Swift in the push → nothing to gate. | +| New-ref pushes lint the merge-base delta vs `refs/remotes/origin/main`; no resolvable base fails closed | Whole-tree lint on a new branch hits the same pre-existing violations (always-block); a silent skip is a vacuous pass — the #31/#134 class. Orphan-history/missing-ref pushes refuse loudly. | +| Hardcoded `refs/remotes/origin/main`, not `$1`-derived | Ponytail + security converged: `$1` (remote name or URL) breaks bootstrap pushes to new remotes, URL-direct pushes, and master-default remotes — and buys nothing on a single-remote repo. Full-ref spelling also defeats `refs/tags/origin/main` shadowing (git resolves short refs through refs/tags/ first). | +| Vacuity gate on `passed + failed == 0` (skipped ≠ executed) | A filter matching only skipped tests has zero executed tests; per AC3 that must fail, and "0 passed / 0 failed / N skipped" with exit 0 is a vacuous green. | +| No `scripts/AGENTS.md` child doc | Contracts live in each script's header + root AGENTS.md index row; four files don't warrant a new doc layer. | +| Classis port fidelity kept (CLI flags, FT_BASE_DIR, allocator walk vs mktemp, status-branch structure) | Upstream alignment: classis bug fixes keep flowing into this copy; deviations were only made where Museion's reality differs (single bundle, default unit-scope filter). | +| Rig verdict = executed-count guard (`n_checks == 23`), never the banner | The repo's own #31 rule; a deleted/dead check fails loudly (flip-proven: disabling one check yields "22/23 executed"). | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| `swiftlint --quiet \| tail -3; echo $?` reported exit 0 while swiftlint exits 2 | Pipe reports the LAST command's exit — the pager's, not the gate's | Run gates bare or read `$?` from the un-piped command; caught the hook's repo-wide gate shipping unpassable this way | +| Rig's first check never executed ("22/22" was 23 checks with one dead) | `check` called at line 30, defined at line 33 — bash defines functions incrementally; `set -uo` without `-e` swallows the 127 | Hoisted `fails=0`/`check()` above the first call + executed-count guard; all three round-4 reviewers reproduced it | +| First push of any new branch was unconditionally blocked | Zero-sha remote ref took the whole-tree ls-tree path → spike/'s 59 error-severity violations | Merge-base delta vs `refs/remotes/origin/main` | +| Delete pushes printed `fatal: bad object 000…` | `git diff $rsha $zero-sha` on ref deletions | `[[ "$lsha" == "$zero" ]] && continue` before the diff | +| A reviewer staged a stale `pre-push` into the index | Read-only ban violated via `git add` while checking an exec bit | `git restore --staged` + explicit re-verification of `git status` after every fanout; later goals said "check modes with ls -l" | +| Rig bootstrap broke after the fail-closed fix | The rig's bare repo starts empty — its own first push is a new-ref create with no default ref | Bootstrap seeded with `--no-verify` BEFORE hook activation (a fresh remote's first push is --no-verify by definition) | +| Orphan fixture push sailed through | `git rm -qrf .` in the orphan branch deleted the hook itself | `git checkout main -- scripts …` to keep the hook in the orphan tree | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `scripts/full-test.sh` | new — detached, xcresult-authoritative verify rail (567-line classis port, Museion-adapted) | +| `scripts/install-hooks.sh` | new — core.hooksPath installer with trust note | +| `scripts/hooks/pre-push` | new — live-run scan + push-scoped lint gate + autofix guard | +| `scripts/test-full-test.sh` | new — 23-check pre-push acceptance rig with executed-count guard | +| `AGENTS.md` | commands section (rail/summary/install/rig), `scripts/` Child DOX Index row | +| `MuseionTests/AGENTS.md` | Verification names the rail as the sanctioned verify path | +| `.gitignore` | `_build/` (run dirs, logs, bundles) | + +## Open Items & Next Steps + +- [ ] `./scripts/install-hooks.sh` once per clone (core.hooksPath is local config) +- [ ] Pre-existing lint debt: `spike/` (59 error-severity) + `MuseionTests/PolishSeamTests.swift:34` keep bare `swiftlint .` red on main — tuning `.swiftlint.yml` (classis-style disables or excludes) is a separate ticket +- [ ] Deferred port: classis's 25KB `test-full-test.sh` stub harness for the RUNNER itself (this session pinned the hook only; the rail's ACs were verified via one-off scratch harnesses) +- [ ] Rejected-with-rationale (audit record): versioned-hooks/formatter-config/forgeable-verdict/symlink/OSC/pidfile-DoS family (repo-write already = code-exec via Swift tests; same-uid ceiling), mktemp-vs-allocator (upstream fidelity), `base==lsha` harden (no-new-content push is a correct pass) + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md b/docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md new file mode 100644 index 0000000..3a9c6a4 --- /dev/null +++ b/docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md @@ -0,0 +1,57 @@ +# Collapse the gate-running AGENTS.md learnings into the verify-rail pointer + +> **Date:** 2026-11-17 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/192 + +## Goal + +Shrink root AGENTS.md's testing learnings to what `scripts/full-test.sh` cannot encode: the gate-running recitals (executed-count-not-banner #31/#178, newest-bundle race #33/#179, build/test split #177, vacuous filters #31/#134, the #30 flake ritual, the #182 stale-green corollary, the lint-gate scoping recital) collapse into one pointer line; test-authoring rules stay; MuseionTests/AGENTS.md Verification names the script instead of the raw xcodebuild line. + +## What Was Done + +- Root `AGENTS.md` Testing section: deleted 7 gate-running bullets, added the one-line pointer — gate rules are encoded in `scripts/full-test.sh` (#190), run `start` + `status`, never hand-rolled xcodebuild/xcresult incantations +- Root `AGENTS.md` Tooling & gates: deleted the lint-gate-scoping sentence from the lint bullet (survives verbatim in `scripts/hooks/pre-push` header + scoping loop; `#191` closed as superseded — tree went green, no baseline file ever landed) +- `MuseionTests/AGENTS.md` Verification: deleted the raw xcodebuild line; the section now names only `./scripts/full-test.sh start` + `status` +- Root Commands block: annotated the raw `xcodebuild … test` line as ad-hoc/outside-the-rail so it no longer contradicts the pointer (review follow-up) +- Scoped the pointer's "everything below" to "the rest of this section" — it had swept in the heading-less format bullets and the Trust boundaries section (review follow-up) +- Two-axis review (parallel subagents: Standards + Spec) — Spec verified all 8 deletion mappings against the script *body*, not just header claims (zero-executed VACUOUS fail at `full-test.sh:431-449`, pinned `-resultBundlePath` at `:190`, `--serialized` at `:192`) + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Deletion test = "can the script encode it?" | Issue AC2: authoring rules retained, nothing deleted the script does not encode. Each of the 8 deletions maps to verified script/hook behavior (table in the issue comment trail / commit body) | +| Keep #197 stale-binary learning | `full-test.sh` does not verify `SwiftCompile` lines — the trap survives even scripted runs | +| Keep #134 reboot remedy | Script *detects* the wedge family via per-test timeouts but cannot encode "reboot the machine"; the emergency workaround (standalone `swift ` check) is machine-level knowledge | +| Delete #182 despite partial encoding | Encoded by obviation: the sanctioned rail builds+tests in one detached run, so no built-products-vs-sources gap exists; mid-run-edit residual is covered by the hook's no-push-while-live guard + kept #197 | +| Keep lint green-contract sentence, delete only the gate-scoping sentence | The green contract is #197's documented state; the scoping recital duplicates the pre-push hook header (DOX: no duplication where the script header is the contract's home) | +| Authoring halves of deleted bullets survive in the child | MuseionTests/AGENTS.md already carries suite-name-filter notes (L15, L28), spawnsTicker/`#30/#147` family (L27), keychain/makeHome guidance (L24) — untouched | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Pointer line claimed "everything below is test authoring" | The section below also holds format-shape bullets and flows into Trust boundaries — sentence overshot its scope | Rescoped to "the rest of this section is authoring rules the script cannot encode" | +| Commands block still listed bare `xcodebuild … test` beside the new "never hand-rolled incantations" pointer | Pre-existing tension, aggravated by the new prohibition | Annotated the line: ad-hoc run incl. UI smoke (outside the rail), full-suite verification → full-test.sh | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `AGENTS.md` | 8 gate-running learnings → one verify-rail pointer; lint recital sentence dropped; Commands annotation; GitNexus auto-managed counter refresh (7035→7044 nodes) | +| `MuseionTests/AGENTS.md` | Verification names only `./scripts/full-test.sh` (raw xcodebuild line deleted) | + +## Verification + +- `swiftformat --lint .` → 0/141 require formatting; `swiftlint` → 0 findings (read-only checks, run before the suite so the green attaches to exact bytes) +- `./scripts/full-test.sh start` + `status` → **693 executed / 693 passed / 0 failed / 0 skipped**, xcodebuild exit 0 +- `gitnexus detect-changes` → 2 files, 19 symbols (docs-shaped only), 0 affected processes, risk low + +## Open Items & Next Steps + +- None — commit body carries the deletion→script-behavior mapping table (AC1); `Closes #192` auto-closes on push. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md b/docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md new file mode 100644 index 0000000..ea358f0 --- /dev/null +++ b/docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md @@ -0,0 +1,68 @@ +# Split the fat files along the PostsModel pattern (#193) + +> **Date:** 2026-11-17 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/193 + +## Goal + +Split the 2026-11-16 retro's three most-re-read files — PostsModel.swift, WorkspaceView.swift, PostsPaneView.swift — into cohesive extension files the way PostsModelPasses / PostsModelCards already split PostsModel. Mechanical, module-internal moves: symbols keep names and module, zero call-site edits, zero behavior change, one commit per source file, Museion/AGENTS.md map gains the new entries. + +## What Was Done + +- `PostsModel.swift` 775 → 325 lines; split into `PostsModelWatcher.swift` (151 — `PostsWatcher`, `bind`, `startWatching`, `rescan`), `PostsModelWrites.swift` (233 — `performWrite` rail, `flushOrAbort`, rename/trash, #108 project ops), `PostsModelImports.swift` (104 — external guest, import batch). Commit `902e860`. +- `WorkspaceView.swift` 852 → 426; split into `ArchivePaneView.swift` (176), `WorkspaceViewSheets.swift` (189 — the four house ask sheets), `WorkspaceChrome.swift` (96 — `SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`). `RailButton` stayed in-core (its only caller is the rail; keeps `private`). Commit `70cd1c2`. +- `PostsPaneView.swift` 776 → 186; split into `PostsLibraryColumn.swift` (521 — column + rename/move sheets + file-scope `librarySearch` + `LaunchFocusReset`) and `LibraryPostRow.swift` (94 — reused by the Archive pane). Commit `2a02b95` (amended with the audit fix). +- Moves executed by a boundary-asserted Python range script: 68 exact line-content checks on PostsModel (plus equivalents on the views) before any write; every new file verified byte-identical to its extracted ranges; each boundary assert names the line it expected so a miss fails loudly. +- 15 access widenings `private`→internal, each structurally required (Swift admits `private` members only to same-file extensions): 10 PostsModel members (6 carrying `/// #193: setter internal — ` lines in the #146 convention), `ArchivePaneView`, and the 4 sheet structs (disclosed in their file headers). +- Import hygiene: `import CoreServices` dropped from PostsModel core (FSEvents moved); `import AppKit` dropped from PostsPaneView after the audit (LaunchFocusReset was its last AppKit user). +- DOX pass: Museion/AGENTS.md map — 8 new file bullets, the 3 parent bullets rewritten, moved-detail sentences relocated to the owning bullets, one stale `private(set)` doc claim corrected. +- finish-audit (3 fresh-context reviewers): move-only confirmed by a third independent method (per-line counters / normalized line-multiset); security PASS with all trust-boundary guards verified byte-identical and the write-rail call graph intact; one LOW fixed (the AppKit import), one LOW deferred. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Widen privates (option A) over keeping private-touching methods in-core (option B) | Option B left the core at ~520 lines with incohesive domains; option A lands 325 and matches the repo's #146 precedent exactly ("setter internal — the split-out domain extensions set it"). The widenings are module-internal only. | +| One commit per source file, with each commit's slice of the AGENTS.md map | The AC's revert-independence. The map's first hunk interleaved two splits' adjacent bullet lines, so plain `git add -p` couldn't separate them — solved by staging asserted intermediate versions of AGENTS.md (HEAD+split1 edits, +split2 edits, final), verified equal to a from-HEAD reconstruction. | +| PostsLibraryColumn keeps its sheets, search mount, and focus rider at 521 lines | They travel with the post rows by the file's own documented contract; cohesive and far under the 800 ceiling. Splitting them out would scatter one surface across files. | +| RailButton stays in WorkspaceView.swift | Only the nav rail instantiates it; moving it would force a widening for zero cohesion gain. | +| No new tests | Zero behavior change by construction; the existing 693-test suite is the pin (AC forbids behavior change). | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| GitNexus `impact`/`detect-changes` abort with "Multiple repositories indexed. Specify repo" but reject the very label format they print | CLI registry disambiguation quirk | `--repo /absolute/path/to/repo` works; used for all subsequent calls | +| Root AGENTS.md showed an unrequested diff hunk (GitNexus counters 7044→7072) after `analyze` | The index run rewrites the auto-managed `gitnexus:` block | Reverted the hunk (auto-managed, re-bumps on the next index); reviewers confirmed no other scope creep | +| An over-broad guard (`"FSEvent" not in core_text`) false-tripped on prose | Doc comments mention "the FSEvents window" — substring guards match prose | Tightened guards to the exact import line / API symbol (`import CoreServices`, `FSEventStream`) | +| `import AppKit` left behind in PostsPaneView.swift | I deliberately didn't touch imports at split time ("code unchanged" posture); the compiler has no unused-import warning | Caught by the finish-audit general reviewer; dropped and amended into the split commit | +| `detect-changes` reports "No changes detected" at wrap-up | The session's own mid-flight `analyze` already synced the index to the tree — clean by construction | Reported as index-relative; the real affected-scope check is the pre-analyze run (163 symbols / 73 flows, all relocations) plus the diff-scope reviews | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostsModel.swift` | 775→325; core keeps properties, draft lifecycle, select, Cold Turkey mirrors; 10 widenings | +| `Museion/PostsModelWatcher.swift` | new — PostsWatcher + bind + startWatching + rescan | +| `Museion/PostsModelWrites.swift` | new — #179 write rail + structural ops | +| `Museion/PostsModelImports.swift` | new — external guest + import batch | +| `Museion/WorkspaceView.swift` | 852→426; keeps WorkspaceView + RailButton | +| `Museion/ArchivePaneView.swift` | new — #108 Archive pane (private→internal) | +| `Museion/WorkspaceViewSheets.swift` | new — 4 house ask sheets (private→internal) | +| `Museion/WorkspaceChrome.swift` | new — shared chrome (SelectedRowStrip, BorderedSecondaryButtonStyle, PaneHeader) | +| `Museion/PostsPaneView.swift` | 776→186; keeps the pane layout only | +| `Museion/PostsLibraryColumn.swift` | new — library column + sheets + search mount + LaunchFocusReset | +| `Museion/LibraryPostRow.swift` | new — shared post row | +| `Museion/AGENTS.md` | map: 8 new bullets, 3 parents rewritten, detail relocated to owners | + +## Open Items & Next Steps + +- [x] Close #193 (rides the docs commit: `Closes #193`) +- [ ] Known limitation, documented in code + map: `watchedHome`'s single-writer invariant is doc-convention now, not compiler-enforced (security reviewer: Low, no reachable exploit, discipline verified holding) — revisit only if PostsModel ever gains a second Home writer + +--- + +**Verification:** `xcodebuild build` SUCCEEDED (SwiftCompile lines confirmed for every split file — no stale-binary serve); `./scripts/full-test.sh` run `20261117T165454Z`: **693 executed / 693 passed / 0 failed / 0 skipped, exit 0**, on the exact final bytes (audit fix included; the subsequent amend changed no file bytes); `swiftlint .` 0 violations; `swiftformat .` 0/149. GitNexus re-indexed (7,072 nodes / 36,395 edges). + +*Log written by write-log skill* diff --git a/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md b/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md new file mode 100644 index 0000000..95ab5f1 --- /dev/null +++ b/docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md @@ -0,0 +1,72 @@ +# Close out: repo-wide swiftlint green becomes the documented lint contract (#197) + +> **Date:** 2026-11-17 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/197 + +## Goal + +With #195 and #196 done, make the docs and code comments honest about repo-wide lint being green: refresh the pre-push hook's stale "pre-existing violations" rationale (gate semantics unchanged), prune/replace the stale #190 learning in AGENTS.md, confirm the root lint line is literally true — and land a green full unit suite. + +Tree composition note: the working tree also carries the uncommitted #194/#195/#196 batches (lint policy, test renames + `.swiftformat` name-format pin, warning-fix sweep) from earlier sessions today; this session implemented #197 on top, then ran a three-reviewer finish-audit over the whole 27-file diff. + +## What Was Done + +- `scripts/hooks/pre-push` — all three stale rationale blocks refreshed (header "pre-existing findings", gate block "a bare `swiftlint .` gate can never pass", NEW-ref note "pre-existing violations could never clear it") to the settled #190 design wording. Comment-only; gate logic byte-identical (reviewer grep-verified). +- `AGENTS.md` — the Tooling & gates learning rewritten to the true contract: repo-wide lint green (#194 policy, #195/#196 cleared every finding, `spike/` excluded as unbuilt), bare `swiftlint .` = 0 violations + `swiftformat .` reformats nothing, gates stay push-scoped. Root lint line confirmed literally true by execution. +- `MuseionTests/LibrarySearchTests.swift` — hardened `an unchanged rescan keeps the revision` against a pre-existing watcher-race flake: two FSEvent-burst rescans can snapshot the shared `PostScanCache` miss count before either stamps it, double-counting one first read → `contentRevision` double-bump (benign over-invalidation). The test now quiesces the burst (bounded 20 × 0.5 s stability loop, own deadline, post-loop `#expect`) before snapshotting. Suite scenario header names the fourth pin. +- Finish-audit (3 parallel reviewers: ponytail / security / general over the full uncommitted diff): + - Reviewer's "dead symlink clause" bug in `LearningsIndex.isPlainDirectory` **disproved by scratch probes** — `&&` out-binds `??` (`a ?? false && b` parses as `(a ?? false) && b`; second `??`/`&&` precedence claim probe-settled in this repo, see #26) and `URL.resourceValues` is lstat-style (symlink-to-dir → `isDirectory=false`). Kept parens + doc as readability hygiene; the expression had fooled a capable reviewer. + - `Museion/LearningsPaneView.swift` — guard reordered so the cheap rejections (`isPlainDirectory`, dot-prefix) short-circuit before the directory listing. + - `MuseionTests/LearningsPaneTests.swift` — new pin `a symlinked type dir never surfaces` (the documented "same skip posture as Post.scan" contract was unpinned). Flip-verified: the contract is **defended in depth** (lstat guard AND `contentsOfDirectory`'s own refusal of a symlinked entry URL) — the pin fails only when both go traversal-shaped (fileExists guard + resolved-URL listing failed the pin + a sibling pin; restored green). + - `Museion/MentorSessionModel.swift` — pre-existing `sessions.json` world-readable sub-second window (atomic write → 0o600 chmod) parked with a `ponytail:` ceiling comment naming the upgrade path (createFile-0600 + rename). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Fix the LibrarySearchTests race in the TEST, not the model | The model's revision over-bump only over-invalidates a search snapshot (conservative-safe); serializing rescans or making the miss counter race-free is real machinery for a signal that tolerates false positives. The test's timing assumption was the bug (#147 family). | +| Keep parens in `isPlainDirectory` despite the finding being disproved | Behavior-identical, two characters, and the bare form demonstrably costs reviewer time — this audit burned a slot misreading it. | +| Symlink pin added although no behavior changed | The documented contract was unpinned; the flip cycle showed it is held up by two accidental mechanisms, exactly the kind of seam a future "simplification" breaks silently. | +| Chmod window parked, not fixed | Pre-existing, local-only, single-user workstation threat model; from-creation 0600 changes a pinned write path — ceiling comment names the trigger (hostile local account). | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Full suite failed 1/692 on first run (`an unchanged rescan keeps the revision`, `contentRevision 2 ≠ 1`) | Two FSEvent-burst rescans double-count one shared `PostScanCache` miss; the test snapshotted mid-burst | Quiesce loop before snapshotting; verified in isolation (7/7), full (693/693) | +| Flip cycle "passed" with the guard flipped — twice | **xcodebuild served stale binaries**: a source edit made seconds before invocation was not compiled (zero `SwiftCompile` lines, suite start 3 s after invocation) | `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green; with that, guard-flip green → both-belts flip red → restored green | +| Reviewer precedence claim contradicted the code's comment | `a ?? b && c` precedence is genuinely easy to misread (this repo's second such dispute) | Scratch probes settle it empirically — never rewrite comments on a reviewer's word | +| `swiftlint` line_length (187 chars) after the guard reorder | swiftformat merges adjacent guards into one long condition list | Wrap the call arguments inside the condition (the shape the same function already uses for its root listing); format-stable on re-run | +| Rail scoped reruns looked green during the flip | Stale-build hazard above | Always confirm compile lines in the run log for rapid edit→test cycles | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `scripts/hooks/pre-push` | Three stale rationale comment blocks refreshed; logic untouched | +| `AGENTS.md` | Tooling & gates learning rewritten to the true lint contract | +| `MuseionTests/LibrarySearchTests.swift` | Quiesce loop hardening + scenario header names the settled-state pin | +| `Museion/LearningsPaneView.swift` | Guard reorder, parens + doc on `isPlainDirectory` | +| `MuseionTests/LearningsPaneTests.swift` | New symlink-skip pin with flip-verified doc | +| `Museion/MentorSessionModel.swift` | Ceiling comment on the roster chmod window | + +(The commit also carries the #194/#195/#196 batches from earlier sessions: `.swiftlint.yml`, `.swiftformat`, `MuseionTests/AGENTS.md`, `PolishSeamTests.swift`, and the #196 warning-fix sweep across 11 app files + test files + `prototypes/GateUIPrototype.swift`.) + +## Open Items & Next Steps + +- [ ] User: commit + push (carries `Closes #197`; #194–#196 already closed on the tracker), verify auto-close +- [ ] Candidate project learning: xcodebuild can skip recompiling a source edited seconds before invocation — flip/edit-test cycles must `touch` and verify `SwiftCompile` lines in the run log +- [ ] Parked: roster 0600-from-creation if a hostile local account ever matters (`Museion/MentorSessionModel.swift` ceiling comment) + +## Verification + +- `swiftlint .` — 0 violations / 130 files, exit 0 +- `swiftformat .` — 0/141 formatted, tree unchanged +- `./scripts/test-full-test.sh` — 23/23 hook acceptance checks +- `./scripts/full-test.sh` — **693 executed / 693 passed / 0 failed** (run `20261117T151013Z-Museion`; no source file newer than the run — the green attaches to the committed bytes) +- GitNexus: `detect-changes` risk **critical** (breadth: 100+ symbols across the four-ticket mechanical batch — affected-scope checked by the 3-reviewer fanout, probes, and the suite); `analyze` reindexed (7,035 nodes / 34,056 edges) + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index f4ecd37..dea187d 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,10 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-17 | issue | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | Three most-re-read files split into 8 domain-extension files, move-only (three audits concur); 693/693 | +| 2026-11-17 | issue | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | Root gate-running learnings collapse into the full-test.sh pointer; 8 deletions mapped to script/hook behavior; authoring rules retained; 693/693 | +| 2026-11-17 | issue | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | Lint-green doc truth (#197) + finish-audit; watcher-race test quiesced, symlink pin flip-verified, stale-xcodebuild hazard found; 693/693 | +| 2026-11-17 | feat | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | Classis full-test.sh ported as the verify rail + pre-push hook; 4-round finish-audit; suite 692/692 via the rail, hook rig 23/23 | | 2026-11-16 | fix | [20261116-failed-flush-discarded-on-document-switch_log.md](20261116-failed-flush-discarded-on-document-switch_log.md) | Unticketed fix (brief-25, argus cycle-4): document departure aborts on a failed flush — one sessionMayDepart gate (flushOrAbort's conflict+flush gates) behind dismissExternal/departOpenDocuments and select/openUnguarded; both navigation families pinned RED-first (6 pins); unit suite 699 green ×2 | | 2026-11-13 | opt | [20261113-fold-typing-budget-pin_log.md](20261113-fold-typing-budget-pin_log.md) | Unticketed pin (brief-24): typing-cost guard for the #142 re-key — per-call line-scan observer through the real keystroke pipeline; zero scans beside a fold at N/2N, exact-count control 206/406, mutation-checked | | 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 | diff --git a/prototypes/GateUIPrototype.swift b/prototypes/GateUIPrototype.swift index 3853964..e86f72f 100644 --- a/prototypes/GateUIPrototype.swift +++ b/prototypes/GateUIPrototype.swift @@ -240,7 +240,11 @@ struct MockWorkspace: View { } private var previewText: String { - String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6) + String( + repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. " + + "Sentences shorten. Claims retreat. ", + count: 6, + ) } } @@ -316,7 +320,9 @@ struct VariantA: View { switch model.phase { case .checking: "Running hermes acp --check." case .passed: "Hermes \(model.version) answered the health check. The mentor is available." - case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available." + case .failed: + "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions " + + "without it — the editor below stays available." } } } diff --git a/scripts/full-test.sh b/scripts/full-test.sh new file mode 100755 index 0000000..4c74d3f --- /dev/null +++ b/scripts/full-test.sh @@ -0,0 +1,594 @@ +#!/usr/bin/env bash +# full-test.sh — detached, xcresult-authoritative full-suite runner. +# +# Ported from classis scripts/full-test.sh (matured through classis +# #649–#729, source commit 071966e) and adapted to Museion (#190). Encodes +# the session learnings so sessions stop re-deriving them — the 2026-11-16 +# retro measured this loop at 29% of all terminal calls (77 xcodebuild + +# 76 hand-rolled xcresult reads in ≥8 incantation variants): +# #177 — run xcodebuild DETACHED and poll; the full suite can exceed a +# tool call's timeout budget (the #177 build-for-testing / +# test-without-building split existed only to dodge that cap — +# and detached runs make it unnecessary). +# #31/#178 — pass/fail counts are authoritative ONLY in the completed +# .xcresult (`xcresulttool get test-results summary`), never in +# grepped output; #178: totalTestCount counts a parameterized +# @Test as ONE test — reconcile executed counts from the summary, +# never from log lines. +# #31/#134 — an -only-testing filter that matches ZERO executed tests +# FAILS the run: single-name filters and suite names with +# spaces/backticks match zero Swift Testing tests and "pass" +# vacuously. A zero-executed summary exits nonzero, always. +# #30/#147 — a parallel-load flake settles via a serialized rerun +# (-parallel-testing-enabled NO); that green is the record (each +# rerun allocates its own run dir and becomes `current`). +# #134 — per-test execution-time allowances are enforced by the runner +# (-test-timeouts-enabled YES): a wedged test FAILS at its +# allowance — host killed, restarted, named in the xcresult — +# instead of holding the run silent (the machine-wedge family: +# testmanagerd / IDE-session hangs). The runner rounds the +# DEFAULT allowance UP to whole minutes (60s stays 60s). +# EngineSmokeTests' real child processes (one wire smoke per LLM +# surface) sit well inside the 60s default — raise via +# --test-timeout if that ever changes. +# #33/#179 — every launch pins its own result bundle (-resultBundlePath) +# into an ATOMICALLY allocated run dir, and `run` polls ITS OWN +# dir: never "newest .xcresult" (the #33 bundle race), never +# `current` (a same-second twin launch repoints it — the #179 +# pin). Concurrent sessions can never race for a bundle. +# Wedge observability (classis #716 machinery, ported): live `status` +# names the last test event + its exact age, what is IN FLIGHT, +# flags STOPPED (state T) descendants immediately, and separates +# advisory "no test progress" from the hard STALLED warning. +# +# Usage: +# scripts/full-test.sh run [--serialized] [--workers N] [--scheme S] [--stall-min N] [--test-timeout N] [--no-test-timeouts] [-- xcodebuild-args...] +# scripts/full-test.sh start [same flags] # spawn detached, print run dir, exit +# Detached via nohup + setsid-when-available (escapes the caller's process +# group, so a tool-call timeout cannot take the run down). Without setsid, +# agent callers should prefer `setsid nohup ./scripts/full-test.sh run … > log 2>&1 < /dev/null &`. +# scripts/full-test.sh status # live: last test event + age, wedge/stall warnings; exits 3 +# # finished: final summary +# scripts/full-test.sh summary [run-dir] # print a finished run's summary +# +# run blocks until done — only from a caller with enough timeout budget; +# otherwise use start + status (the #177-safe pattern). +# status exits 3 while the run is live, so callers can poll in a loop. +# +# Default test selection is the hosted unit bundle (-only-testing:MuseionTests); +# forward your own -only-testing to take over selection (multiple -only-testing +# flags UNION, so the default is dropped the moment you bring one). The UI +# smoke target stays out of the rail. No parallel flags are passed by default +# (single hosted bundle — worker pinning buys nothing); --workers N opts in. +# +# Do NOT lint concurrently with a live run (#30 — real-process fake-ACP tests +# flake under concurrent load). + +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +# Acceptance harnesses point FT_BASE_DIR at an isolated directory. Run-dir +# allocation is unique per launch, but the bases must stay disjoint: a stub +# launch must never repoint the real base's `current` file under a live +# agent's polling loop. Absolute-path requirement enforced below die(). +BASE="${FT_BASE_DIR:-$ROOT/_build/full-test}" +CURRENT="$BASE/current" +# Per-test timeouts bound a wedged test at --test-timeout; the stall warning +# is the BACKSTOP (non-test silence: build, host launch, post-phases). 10 min +# comfortably exceeds the 5-min maximum allowance plus kill/restart overhead. +# Keep it above --test-timeout if you raise that. +STALL_MIN_DEFAULT=10 +# Per-test allowance seconds. The runner rounds the DEFAULT allowance UP to +# whole minutes; the maximum caps any per-test raise (XCTest +# executionTimeAllowance / Swift Testing .timeLimit). EngineSmokeTests spawns +# real child processes per LLM surface — seconds, well inside 60s. +TEST_TIMEOUT_DEFAULT=60 +TEST_TIMEOUT_MAX=300 +POLL_SECS=15 + +die() { echo "full-test.sh: $*" >&2; exit 2; } +[[ -z ${FT_BASE_DIR:-} || $FT_BASE_DIR == /* ]] \ + || die "FT_BASE_DIR must be an absolute path, got: ${FT_BASE_DIR:-}" + +# Numeric flag values feed bash arithmetic downstream — a crafted value like +# `x[$(cmd)]` or a leading-zero octal literal would be EVALUATED there, not +# compared. Accept only plain decimal integers (≤9 digits, so arithmetic +# can't overflow either); zero is legal only where the caller allows it. +valid_int() { [[ $1 =~ ^(0|[1-9][0-9]{0,8})$ ]]; } +require_int() { # $1=flag-name $2=value — positive only + valid_int "$2" && [[ $2 != 0 ]] || die "$1 must be a positive integer (no leading zeros), got: $2" +} +require_nonneg_int() { # $1=flag-name $2=value — zero allowed (--stall-min) + valid_int "$2" || die "$1 must be a non-negative integer (no leading zeros), got: $2" +} + +usage() { local last; last=$(awk '/^set -euo pipefail/{print NR - 2; exit}' "$0"); sed -n "2,${last}p" "$0" | sed 's/^# \{0,1\}//'; exit 2; } + +MODE="${1:-run}" +case "$MODE" in + run | start | status | summary) if [[ $# -gt 0 ]]; then shift; fi ;; + *) usage ;; +esac + +SCHEME=Museion +SERIALIZED=0 +STALL_MIN=$STALL_MIN_DEFAULT +TIMEOUT_ENABLED=1 +TEST_TIMEOUT=$TEST_TIMEOUT_DEFAULT +# 0 = pass NO explicit parallel flags (the historical Museion invocation; +# single hosted bundle — bundle-worker parallelism buys nothing). --workers N +# opts in; --serialized is the #30/#147 flake rerun hatch. +WORKERS=0 +FORWARD=() +POSITIONAL=() +# The run dir allocated by THIS invocation's start_run. `run` mode polls its +# own directory — a same-second twin launch repoints `current` at its own +# run, which must not steal this poll loop (#179). +THIS_RUN="" +while [[ $# -gt 0 ]]; do + case "$1" in + --serialized) SERIALIZED=1 ;; + --workers) [[ $# -ge 2 ]] || die "--workers needs a value"; require_int --workers "$2"; WORKERS="$2"; shift ;; + --scheme) [[ $# -ge 2 ]] || die "--scheme needs a value"; [[ $2 == */* ]] && die "--scheme must be a bare scheme name (no path separators), got: $2"; SCHEME="$2"; shift ;; + --stall-min) [[ $# -ge 2 ]] || die "--stall-min needs a value"; require_nonneg_int --stall-min "$2"; STALL_MIN="$2"; shift ;; + --test-timeout) [[ $# -ge 2 ]] || die "--test-timeout needs a value (seconds)"; require_int --test-timeout "$2"; TEST_TIMEOUT="$2"; shift ;; + --no-test-timeouts) TIMEOUT_ENABLED=0 ;; + --) shift; FORWARD=("$@"); break ;; + -*) die "unknown flag: $1" ;; + *) POSITIONAL+=("$1") ;; + esac + shift +done +[[ ${#POSITIONAL[@]} -le 1 ]] || die "unexpected arguments: ${POSITIONAL[*]:1}" + +SUFFIX="" +if [[ $SERIALIZED == 1 ]]; then SUFFIX="-serialized"; fi + +start_run() { + local run_id run_dir timeout_max n cand merr have_only=0 a + # The enforced maximum never sits below the default, so a large + # --test-timeout stays coherent (computed once; used by args + banner). + timeout_max=$(( TEST_TIMEOUT > TEST_TIMEOUT_MAX ? TEST_TIMEOUT : TEST_TIMEOUT_MAX )) + # Allocate the run dir by ATOMIC test-and-create. The bare second-granular + # id is tried first (ids unchanged in the common case); a same-second + # launch of the same scheme+mode finds it taken and walks a serial tail + # (-2, -3, … — unbounded: every taken name was allocated by a real + # launch, so the walk always terminates). Each attempt is itself atomic — + # bare mkdir fails EEXIST under POSIX, so concurrent starts can never + # both win one candidate; there is no check-then-create window. A mkdir + # failure whose path does NOT then exist is a real error (e.g. + # permissions), not a collision, and dies loudly. The tail only ever + # follows the timestamp+scheme base, so ids stay sorted by start time. + run_id="$(date -u +%Y%m%dT%H%M%SZ)-$SCHEME$SUFFIX" + run_dir="" + mkdir -p "$BASE" + n=1 + while :; do + if (( n == 1 )); then + cand="$BASE/$run_id" + else + cand="$BASE/$run_id-$n" + fi + if mkdir "$cand" 2>/dev/null; then + run_dir="$cand" + break + fi + if [[ ! -e $cand && ! -L $cand ]]; then + merr="$(mkdir "$cand" 2>&1)" || true + die "could not create run dir $cand${merr:+ — $merr}" + fi + n=$((n + 1)) + done + THIS_RUN="$run_dir" + + local args=( + -allowProvisioningUpdates + -project "$ROOT/Museion.xcodeproj" + -scheme "$SCHEME" + -destination 'platform=macOS' + test + -resultBundlePath "$run_dir/result.xcresult" + ) + if [[ $SERIALIZED == 1 ]]; then args+=(-parallel-testing-enabled NO) + elif (( WORKERS > 0 )); then args+=(-parallel-testing-enabled YES -parallel-testing-worker-count "$WORKERS"); fi + # Runner-enforced per-test allowances — a wedged test fails at its + # allowance (host killed + restarted, named in the xcresult). The maximum + # never sits below the default, so a large --test-timeout stays coherent. + if [[ $TIMEOUT_ENABLED == 1 ]]; then + args+=( + -test-timeouts-enabled YES + -default-test-execution-time-allowance "$TEST_TIMEOUT" + -maximum-test-execution-time-allowance "$timeout_max" + ) + fi + # Default test selection: the hosted unit bundle (#190). Multiple + # -only-testing flags UNION — a bundle-level default beside a finer + # forwarded filter would make the filter a no-op — so the default is + # dropped the moment the caller forwards any -only-testing of their own. + if [[ ${#FORWARD[@]} -gt 0 ]]; then + for a in "${FORWARD[@]}"; do [[ $a == -only-testing* ]] && have_only=1; done + fi + if (( have_only == 0 )); then args+=(-only-testing:MuseionTests); fi + if [[ ${#FORWARD[@]} -gt 0 ]]; then args+=("${FORWARD[@]}"); fi + + # nohup + stdin /dev/null 2>&1 && DETACHER=(setsid) + ( cd "$ROOT" && nohup ${DETACHER[@]+"${DETACHER[@]}"} bash -c ' + log="$1"; exitf="$2"; shift 2 + set -o pipefail + xcodebuild "$@" 2>&1 < /dev/null | stamp_stream >"$log" + echo $? >"$exitf" + ' _ "$run_dir/xcodebuild.log" "$run_dir/exit-code" "${args[@]}" >/dev/null 2>&1 & + echo $! >"$run_dir/pid" + ) + + # Publish `current` ATOMICALLY. A truncating `>` from two same-second + # launches can interleave — the shorter write lands over a longer earlier + # one and leaves trailing bytes, corrupting current for every reader. + # Write a per-launch temp and rename(2) it into place (same directory ⇒ + # one filesystem ⇒ atomic). + printf '%s\n' "$run_dir" >"$BASE/.current.tmp.$$" + mv "$BASE/.current.tmp.$$" "$CURRENT" + echo "run dir : $run_dir" + echo "pid : $(cat "$run_dir/pid")" + echo "scheme : $SCHEME$SUFFIX" + if [[ $SERIALIZED == 1 ]]; then echo "parallel: NO (--serialized)" + elif (( WORKERS > 0 )); then echo "parallel: YES ($WORKERS workers)" + else echo "parallel: default (no flags)"; fi + if (( have_only == 0 )); then echo "tests : MuseionTests (default)" + else echo "tests : caller -only-testing filter"; fi + if [[ $TIMEOUT_ENABLED == 1 ]]; then echo "timeout : ${TEST_TIMEOUT}s per test (max ${timeout_max}s)"; else echo "timeout : DISABLED (--no-test-timeouts)"; fi + if [[ ${#FORWARD[@]} -gt 0 ]]; then echo "forwarded: ${FORWARD[*]}"; fi +} + +current_run_dir() { + [[ -f $CURRENT ]] || die "no run recorded — call 'start' first" + local d + d="$(cat "$CURRENT")" + [[ -d $d ]] || die "recorded run dir missing: $d" + printf '%s' "$d" +} + +pid_alive() { kill -0 "$1" 2>/dev/null; } + +# --- wedge observability ----------------------------------------------------- +# Test-progress lines are the test phase's heartbeat. The wrapper stamps every +# log line "YYYY-MM-DD HH:MM:SS ", so the last progress line carries an exact +# event time; unstamped (legacy) logs fall back to the log mtime for its age. + +# Stamp every stdin line with a local wall-clock prefix "YYYY-MM-DD HH:MM:SS ". +# Runs inside the detached wrapper's shell via `export -f` — exported bash +# functions travel through nohup to the `bash -c` child, keeping the runner +# self-contained (no stamper file whose absence would silently empty the log). +# `date` is cached per second: stamps are second-granular anyway, so the fork +# cost is one date per wall-clock second of output. The `|| [[ -n $line ]]` +# arm keeps a final unterminated line. Verified: bash's printf builtin writes +# through per invocation — no stdio buffering — so the log's mtime tracks +# real output for stall detection. +stamp_stream() { + local line stamp='' last_sec=-1 + while IFS= read -r line || [[ -n $line ]]; do + if (( SECONDS != last_sec )); then + last_sec=$SECONDS + stamp="$(date '+%Y-%m-%d %H:%M:%S')" + fi + printf '%s %s\n' "$stamp" "$line" + done +} +export -f stamp_stream + +fmt_age() { # seconds → "45s" / "12m 03s" + local s="$1" + if (( s >= 60 )); then printf '%dm %02ds' $(( s / 60 )) $(( s % 60 )) + else printf '%ds' "$s"; fi +} + +age_since() { # $1=epoch seconds → age in seconds, clamped at 0 (clock-skew guard) + local a=$(( $(date +%s) - $1 )) + (( a < 0 )) && a=0 + printf '%s' "$a" +} + +describe_progress_line() { # $1=line → TP_DESC, TP_EPOCH (stamp epoch; empty when unstamped) + local rest="$1" + TP_DESC=""; TP_EPOCH="" + if [[ $rest =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2})\ (.*)$ ]]; then + TP_EPOCH="$(date -j -f '%Y-%m-%d %H:%M:%S' "${BASH_REMATCH[1]}" +%s 2>/dev/null || true)" + rest="${BASH_REMATCH[2]}" + fi + if [[ $rest =~ [Tt]est\ [Ss]uite\ \'([^\']+)\'\ (started|passed|failed) ]]; then + TP_DESC="suite '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}" + elif [[ $rest =~ [Tt]est\ [Cc]ase\ \'([^\']+)\'\ (passed|failed) ]]; then + TP_DESC="test '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}" + elif [[ $rest =~ [Tt]est\ [Cc]ase\ (.+)\ started\.$ ]]; then + TP_DESC="test ${BASH_REMATCH[1]} started" + elif [[ $rest =~ [Ss]uite\ ([A-Za-z0-9_.]+)\ (started|passed|failed) ]]; then + # Swift Testing verbose (serialized logs, glyph-prefixed): "Suite NAME passed after …" + TP_DESC="suite '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}" + elif [[ $rest =~ [Tt]est\ ([A-Za-z0-9_.]+\(\))\ (started|passed|failed) ]]; then + # Swift Testing verbose: "Test fnName() started." + TP_DESC="test '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}" + elif [[ $rest =~ [Tt]est\ run\ with\ ([0-9]+)\ tests?\ in\ ([0-9]+)\ suites?\ (passed|failed) ]]; then + TP_DESC="run (${BASH_REMATCH[1]} tests) ${BASH_REMATCH[3]}" + elif [[ $rest == "Testing started" ]]; then + TP_DESC="testing started" + else + TP_DESC="progress: ${rest:0:80}" + fi + return 0 +} + +last_progress_event() { # $1=log → TP_DESC, TP_EPOCH; rc 1 = no progress line yet + local line + TP_DESC=""; TP_EPOCH="" + line="$(grep -iE "test suite|test case|test run with|testing started|suite .* (started|passed|failed)|test .*\(.*\) (started|passed|failed)" "$1" 2>/dev/null | tail -n 1)" || true + [[ -n $line ]] || return 1 + describe_progress_line "$line" +} + +# What is IN FLIGHT right now: the suite each host is currently in, plus the +# last started per-test line when the log shape provides one (classic/ +# serialized modes, where a started line has no matching completion). This is +# the "last-started test" the wedge report names. Closing rules match the +# real log shapes: parallel hosts run suites SEQUENTIALLY and never emit +# suite-finished lines — a new suite-start on a host closes its previous one — +# while classic/serialized logs close suites explicitly. Ages come from the +# wrapper stamps; unstamped legacy logs report "?". +open_flights() { # $1=log → lines "kindnamehoststamp" + awk ' + function stampof(s) { + split(s, w, " ") + if (w[1] ~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/ && w[2] ~ /^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/) return w[1] " " w[2] + return "" + } + function close_suite(h, n) { if (h in openName && openName[h] == n) { delete openName[h]; delete openStamp[h] } } + { + st = stampof($0) + body = st == "" ? $0 : substr($0, 21) + sub(/^[^A-Za-z]*/, "", body) # strip Swift Testing glyph prefixes + if (body ~ /^(Test|Suite) /) { + split(body, a, "\047") # single-quote split: a[2] = quoted name + if (body ~ /^Test [Ss]uite/ && body ~ / started/) { + host = (a[3] ~ / on $/) ? a[4] : "-" + openName[host] = a[2]; openStamp[host] = st # sequential host: supersedes + } else if (body ~ /^Test [Ss]uite/ && body ~ /passed|failed/) { + host = (a[3] ~ / on $/) ? a[4] : "-" + close_suite(host, a[2]) + inflDone = 1 # suite finished ⇒ its last started test did too + } else if (body ~ /^Suite/ && body ~ / started/) { + # Swift Testing verbose (serialized logs): "Suite NAME started." + split(body, sw, " "); openName["-"] = sw[2]; openStamp["-"] = st + } else if (body ~ /^Suite/ && body ~ /passed|failed/) { + split(body, sw, " "); close_suite("-", sw[2]); inflDone = 1 + } else if (body ~ /^Test/ && body ~ /started\.$/) { + # classic quoted cases, Swift "Test case passing …" and "Test fn() started." + if (body ~ /^Test [Cc]ase /) + inflN = (a[2] != "") ? a[2] : substr(body, 11, length(body) - 19) + else { + inflN = substr(body, 6); sub(/ started\.$/, "", inflN) + } + inflS = st; inflDone = 0 + } else if (body ~ /^Test run with/ && body ~ /passed|failed/) { + inflDone = 1 # Swift Testing bundle finished + } else if (body ~ /^Test/ && body ~ /passed|failed/) { + if (inflN != "" && index(body, inflN)) inflDone = 1 + } + } + } + END { + for (h in openName) if (openName[h] != "") print "suite\t" openName[h] "\t" h "\t" openStamp[h] + if (inflN != "" && !inflDone) print "test\t" inflN "\t-\t" inflS + } + ' "$1" +} + +# Every live descendant of $1 whose ps state is T (stopped). A SIGSTOPed test +# host is the recorded wedge simulation; real machine wedges (#134 +# testmanagerd/IDE-session family) go silent instead and surface through the +# progress-age tiers. +stopped_descendants() { # $1=root pid → "pidcommand" lines + local root="$1" seen=" " pid st kids k n=0 + local front=("$root") + while (( ${#front[@]} > 0 )); do + pid="${front[0]}" + front=(${front[@]+"${front[@]:1}"}) + [[ $seen == *" $pid "* ]] && continue + seen+="$pid " + (( n += 1 )); (( n > 500 )) && return 0 + st="$(ps -o stat= -p "$pid" 2>/dev/null | tr -d ' ')" + if [[ $st == T* ]]; then + printf '%s\t%s\n' "$pid" "$(ps -o command= -p "$pid" 2>/dev/null | cut -c 1-100)" + fi + kids="$(pgrep -P "$pid" 2>/dev/null || true)" + for k in $kids; do front+=("$k"); done + done + return 0 +} + +summarize_run() { + local run_dir="$1" + local result="$run_dir/result.xcresult" + local exit_code_file="$run_dir/exit-code" + [[ -f $exit_code_file ]] || die "run not finished (no exit-code in $run_dir) — use 'status'" + local xc_exit + xc_exit="$(cat "$exit_code_file")" + if [[ ! -d $result ]]; then + { + echo "full-test.sh: result bundle missing in $run_dir (xcodebuild exit $xc_exit)" + echo " A run killed mid-write corrupts the bundle (#177). Rerun; if the first" + echo " run wedged, add --serialized (#30/#147)." + } >&2 + exit 2 + fi + xcrun xcresulttool get test-results summary --path "$result" >"$run_dir/summary.json" || + die "xcresulttool could not read $result" + python3 - "$run_dir" "$xc_exit" <<'PY' +import json, sys + +run_dir, xc_exit = sys.argv[1], int(sys.argv[2]) +s = json.load(open(f"{run_dir}/summary.json")) +def count(key): + return int(s.get(key) or 0) +passed, failed, skipped = count("passedTests"), count("failedTests"), count("skippedTests") +executed = passed + failed # skipped tests were selected, not executed +# #31/#134: a filter matching zero executed tests must FAIL, never pass +# vacuously (single-name / spaces / backticks match zero Swift Testing tests). +if executed == 0: + print(f"result : VACUOUS — 0 tests executed, {skipped} skipped (xcodebuild exit {xc_exit}) — summary.json beside the log") + print(" Nothing executable matched (#31/#134); fix the -only-testing value.") + sys.exit(1) +print(f"result : {executed} executed / {passed} passed / {failed} failed / {skipped} skipped " + f"(xcodebuild exit {xc_exit}) — summary.json beside the log") +sys.exit(0 if xc_exit == 0 and failed == 0 else 1) +PY +} + +case "$MODE" in + start) + start_run + ;; + run) + start_run + # Poll THIS launch's dir, not `current` — a same-second twin launch + # repoints `current` at its own run mid-loop (#179). + run_dir="$THIS_RUN" + pid="$(cat "$run_dir/pid")" + echo "polling every ${POLL_SECS}s…" + while pid_alive "$pid"; do sleep "$POLL_SECS"; done + summarize_run "$run_dir" + ;; + status) + run_dir="$(current_run_dir)" + pid="$(cat "$run_dir/pid")" + if pid_alive "$pid"; then + log="$run_dir/xcodebuild.log" + elapsed="$(ps -p "$pid" -o etime= | tr -d ' ')" + if [[ ! -f $log ]]; then + # launch window: wrapper wrote pid but not the first log line yet + echo "live : pid $pid, elapsed $elapsed, log not yet written" + exit 3 + fi + last_write="$(stat -f '%Sm' -t '%H:%M:%S' "$log")" + stall_age=$(( $(date +%s) - $(stat -f '%m' "$log") )) + echo "live : pid $pid, elapsed $elapsed, log last written $last_write ($(wc -l < "$log" | tr -d ' ') lines)" + tp_desc=""; tp_age=0; have_progress=0 + if last_progress_event "$log"; then + have_progress=1 + tp_desc="$TP_DESC" + tp_when="${TP_EPOCH:-$(stat -f '%m' "$log")}" + tp_age="$(age_since "$tp_when")" + echo "last : $tp_desc $(fmt_age "$tp_age") ago" + fi + + # In-flight work — open suites (parallel logs) and the last started + # test without a completion (classic/serialized logs). This is what a + # wedge report names; the heartbeat only says when progress last + # HAPPENED. Collected once, reused by the display and the warnings. + FL_KIND=(); FL_NAME=(); FL_HOST=(); FL_AGE=() + fk= fn= fh= fs= fep= fage= + while IFS=$'\t' read -r fk fn fh fs; do + [[ -n $fk ]] || continue + fage="?" + if [[ -n $fs ]]; then + fep="$(date -j -f '%Y-%m-%d %H:%M:%S' "$fs" +%s 2>/dev/null || true)" + [[ -n $fep ]] && fage="$(fmt_age "$(age_since "$fep")")" + fi + FL_KIND+=("$fk"); FL_NAME+=("$fn"); FL_HOST+=("$fh"); FL_AGE+=("$fage") + done < <(open_flights "$log") + # Drop in-flight entries whose HOST has exited: parallel logs never emit + # suite-finished lines, and a dead test host's suite is finished — only + # a live host can be genuinely stuck. Host-less entries ("-", classic + # logs) and entries whose host text carries no "(pid)" are kept. + fl_keep=() + for i in "${!FL_KIND[@]}"; do + if [[ ${FL_HOST[$i]} =~ \(([0-9]+)\) ]] && ! pid_alive "${BASH_REMATCH[1]}"; then + continue + fi + fl_keep+=("$i") + done + if (( ${#fl_keep[@]} != ${#FL_KIND[@]} )); then + FL_K=(); FL_N=(); FL_H=(); FL_A=() + for i in ${fl_keep[@]+"${fl_keep[@]}"}; do + FL_K+=("${FL_KIND[$i]}"); FL_N+=("${FL_NAME[$i]}"); FL_H+=("${FL_HOST[$i]}"); FL_A+=("${FL_AGE[$i]}") + done + # bash 3.2: unguarded "${FL_K[@]}" on an empty array aborts under set -u + # (all hosts exited while the wrapper lives → fl_keep empty → status dies + # instead of reporting the live run). Same guard idiom as fl_keep above. + FL_KIND=(${FL_K[@]+"${FL_K[@]}"}); FL_NAME=(${FL_N[@]+"${FL_N[@]}"}); FL_HOST=(${FL_H[@]+"${FL_H[@]}"}); FL_AGE=(${FL_A[@]+"${FL_A[@]}"}) + fi + open_desc="" + for i in "${!FL_KIND[@]}"; do + fdisp="${FL_HOST[$i]}"; fdisp="${fdisp#My Mac - }" + [[ $fdisp == "-" ]] && fdisp="" || fdisp=" (host: $fdisp)" + open_desc+="${open_desc:+; }${FL_KIND[$i]} '${FL_NAME[$i]}' ${FL_AGE[$i]}$fdisp" + done + [[ -n $open_desc ]] && echo "open : $open_desc" + + # A STOPPED (state T) descendant is a wedge signature that is + # detectable immediately — no stall-min wait. Name the in-flight work + # on that host (hosts appear in the log as "(pid)") plus its last + # event (#134 machine-wedge family). + while IFS=$'\t' read -r wpid wcmd; do + [[ -n $wpid ]] || continue + wopen="" + for i in "${!FL_KIND[@]}"; do + if [[ ${FL_HOST[$i]} == *"($wpid)"* ]]; then + wopen+="${wopen:+ and }${FL_KIND[$i]} '${FL_NAME[$i]}' ${FL_AGE[$i]}" + fi + done + wlast="" + wline="$(grep -F "($wpid)" "$log" 2>/dev/null | tail -n 1)" || true + if [[ -n $wline ]]; then + describe_progress_line "$wline" + wlast="$TP_DESC" + if [[ -n $TP_EPOCH ]]; then + wage="$(age_since "$TP_EPOCH")" + wlast="$wlast $(fmt_age "$wage") ago" + fi + fi + { + echo "CANDIDATE WEDGE : descendant pid $wpid is STOPPED (state T) — #134 machine-wedge family.${wopen:+ Stuck in: $wopen.}" + [[ -n $wlast ]] && echo " last event on that host: $wlast" + [[ -n $wcmd ]] && echo " process: $wcmd" + } >&2 + done < <(stopped_descendants "$pid") + + # No test progress past stall-min while the log is still being written + # is NOT silence — advisory only, never the STALLED warning (from + # outside, a healthy slow test looks exactly like a wedged worker). + if (( have_progress )) && (( tp_age > STALL_MIN * 60 )) && (( stall_age <= STALL_MIN * 60 )); then + { + echo "CANDIDATE WEDGE : no test progress for $(fmt_age "$tp_age") (last: $tp_desc), but the" + echo " log is still being written $(fmt_age "$stall_age") ago — one worker may be" + echo " wedged (#134 family); a healthy slow test looks the same." + } >&2 + fi + + # True silence (no writes at all) keeps the stall-min semantics, now + # naming the last test event whenever the test phase was reached. + if (( stall_age > STALL_MIN * 60 )); then + { + echo "STALLED : no log output for $(( stall_age / 60 )) min — #134 machine-wedge family." + echo " Wait, or kill $pid and rerun with --serialized (#30/#147)." + if (( have_progress )); then + echo " last test progress: $tp_desc $(fmt_age "$tp_age") ago" + fi + } >&2 + fi + exit 3 + fi + summarize_run "$run_dir" + ;; + summary) + if [[ ${#POSITIONAL[@]} -ge 1 ]]; then run_dir="${POSITIONAL[0]}"; else run_dir="$(current_run_dir)"; fi + summarize_run "$run_dir" + ;; +esac diff --git a/scripts/hooks/pre-push b/scripts/hooks/pre-push new file mode 100755 index 0000000..c999b20 --- /dev/null +++ b/scripts/hooks/pre-push @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# pre-push — lint gate + no-push-while-testing guard + autofix-tree guard (#190). +# +# Ports the classis pre-push (classis #679/#684 classes) to Museion: +# 1. no push while a full-test run is live — concurrent load flakes the +# real-process suites (#30), and pushing mid-verification defeats the run; +# 2. lint gate scoped to the push's own Swift files — failing closed on +# violations there (settled #190 design: the gate guards what the +# push itself carries, not the whole tree); +# 3. autofix guard — a lint autofix pass that rewrites files AFTER +# verification must not ride the push untested: the push fails, the +# rewrite gets reviewed and re-verified via scripts/full-test.sh. +# Pre-existing unrelated dirt only warns. +# +# Installed via scripts/install-hooks.sh (git config core.hooksPath scripts/hooks). + +set -euo pipefail + +ROOT="$(git rev-parse --show-toplevel)" +cd "$ROOT" + +# GUI git clients (Xcode, …) inherit launchd's sparse PATH, which lacks +# Homebrew — resolve the lint tools from the standard tool dirs. +# Append-only: the caller's PATH keeps priority. +for dir in /opt/homebrew/bin /usr/local/bin; do + if [[ -d "$dir" && ":$PATH:" != *":$dir:"* ]]; then + PATH="$PATH:$dir" + fi +done +export PATH + +# 1. Never push while ANY full-test run is live: concurrent load flakes the +# real-process suites (#30), and pushing mid-verification defeats the run. +# Concurrent runs each pin their own dir (#190) — `current` only names the +# newest, so scan every run dir for a live pid. +live="" +for d in _build/full-test/*/; do + [[ -f "${d}pid" ]] || continue + p="$(cat "${d}pid")" + kill -0 "$p" 2>/dev/null && live="$live $d(pid $p)" +done +if [[ -n $live ]]; then + echo "pre-push: full-test run(s) live:$live — wait for them, then push." >&2 + exit 1 +fi + +# 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the gate guards +# what the push itself carries — settled #190 design, kept even now +# that bare `swiftlint .` runs green repo-wide (#195/#196 cleared the +# last findings). No Swift in the push → nothing to gate. +before="$(git status --porcelain)" +zero=0000000000000000000000000000000000000000 +# Default-branch base for NEW-ref scoping: the project's default branch at +# origin, as a FULL ref — short names resolve refs/tags/ first, so a fetched +# tag "origin/main" would shadow the remote ref. Hardcoded, not $1-derived: +# pushes to other remotes or by URL are still scoped against origin/main, +# which is correct for this project's delta. A remote with a divergent +# default would need its own scoping — add per-remote resolution then. +default_ref="refs/remotes/origin/main" +swift_files=() +while read -r lref lsha rref rsha; do + [[ "$lsha" == "$zero" ]] && continue # ref deletion — no content to lint + if [[ "$rsha" == "$zero" ]]; then + # NEW ref: lint the delta against the default branch, never the whole + # tree (the gate is the push's delta, not the repo). No resolvable + # base FAILS CLOSED — a silent skip is a vacuous pass (#31/#134 class). + base="$(git merge-base "$lsha" "$default_ref" 2>/dev/null || true)" + [[ -n "$base" ]] || { + echo "pre-push: no common history with $default_ref — cannot scope the lint gate (orphan branch or missing default ref); refusing." >&2 + exit 1 + } + range=("$base" "$lsha") + else + range=("$rsha" "$lsha") + fi + while IFS= read -r f; do swift_files+=("$f"); done < <(git diff --name-only --diff-filter=ACMR "${range[@]}" -- '*.swift') +done +# NOTE: lints the WORKING-TREE copies of the pushed files, not the pushed +# blobs — a local uncommitted fix lints clean while the broken blob ships. +# Inherent to worktree pre-push hooks; blob-lint via `git show` if it bites. +if [[ ${#swift_files[@]} -gt 0 ]]; then + if ! { swiftformat "${swift_files[@]}" && swiftlint lint --quiet "${swift_files[@]}"; }; then + echo "pre-push: linters failed — fix the violations above, then push again." >&2 + exit 1 + fi +fi + +# 3. Autofix guard: if the pass MODIFIED anything, the pushed commits no +# longer match the verified tree. Review, re-verify (scripts/full-test.sh), +# commit, push again. Pre-existing unrelated dirt only warns. +after="$(git status --porcelain)" +if [[ $before != "$after" ]]; then + echo "pre-push: linters MODIFIED the working tree:" >&2 + git status --short >&2 + echo "Review these, re-run scripts/full-test.sh, commit the results, push again." >&2 + exit 1 +fi +if [[ -n $after ]]; then + echo "pre-push: note — unrelated uncommitted changes present (not blocked):" >&2 + git status --short >&2 +fi diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh new file mode 100755 index 0000000..d84f5f7 --- /dev/null +++ b/scripts/install-hooks.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# install-hooks.sh — activate the repo-versioned git hooks (#190). +# Idempotent; safe to re-run after cloning or when hooks go missing. +# Trust note: versioned hooks mean repo content executes at push time — +# install only in repos whose code you already build and run. +set -euo pipefail + +cd "$(dirname "$0")/.." +git config core.hooksPath scripts/hooks +echo "core.hooksPath -> scripts/hooks (pre-push lint gate active)" diff --git a/scripts/test-full-test.sh b/scripts/test-full-test.sh new file mode 100755 index 0000000..b78bfe8 --- /dev/null +++ b/scripts/test-full-test.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# test-full-test.sh — pre-push acceptance rig (#190 AC7; finish-audit rounds 1-3). +# Builds a DISPOSABLE bare remote + clone, installs the REAL hook, and pushes +# every ref shape the gate must handle: clean/autofix/lint-fail/live-run +# blocks, docs-only skip, endpoint scoping (in-range block, out-of-range +# pass), new-branch delta gating, delete pushes, orphan/shadow-tag refusals, +# non-origin and by-URL pushes. Run: ./scripts/test-full-test.sh (no args; a +# throwaway mktemp dir under /tmp is kept after the run for post-mortem). +# Exits nonzero on any FAIL or on an unexpected executed-check count. +set -uo pipefail + +H="$(mktemp -d /tmp/museion-hook-rig.XXXXXX)" # kept after the run for post-mortem +REPO="$(cd "$(dirname "$0")/.." && pwd)" +fails=0; n_checks=0 +check() { # $1=label $2=expected $3=actual + n_checks=$((n_checks + 1)) + if [[ "$2" == "$3" ]]; then echo "PASS: $1"; else echo "FAIL: $1 — expected [$2] got [$3]"; fails=$((fails+1)); fi +} +EXPECTED_CHECKS=23 # executed-count guard: a deleted/dead check fails loudly (#31) +cd "$H" +git init -q --bare remote.git +git clone -q remote.git work +cd work +git config user.email t@t; git config user.name t +mkdir -p scripts/hooks +cp "$REPO/scripts/hooks/pre-push" scripts/hooks/ +cp "$REPO/scripts/install-hooks.sh" scripts/ +cp "$REPO/.swiftlint.yml" . +cp "$REPO/.swiftformat" . +# bootstrap: seed the remote's main BEFORE activating hooks (a fresh remote +# has no default ref for the gate to scope against — first push is --no-verify +# by definition, like any repo bootstrap) +printf 'let ok = 1\n' >Good.swift +git add -A; git commit -qm bootstrap +git push -q --no-verify origin HEAD:refs/heads/main 2>/dev/null +bash scripts/install-hooks.sh >/dev/null +check "AC7 install-hooks sets core.hooksPath" "scripts/hooks" "$(git config core.hooksPath)" + +push_out() { git push origin HEAD:refs/heads/main 2>&1; } + +# clean tree → push passes +printf 'let ok2 = 2\n' >Good2.swift +git add -A; git commit -qm clean +out="$(push_out)"; rc=$? +check "AC7 clean tree pushes" 0 "$rc" + +# committed MISFORMAT → swiftformat rewrites the working tree → BLOCK +printf 'let bad=1\n' >Bad.swift +git add Bad.swift; git commit -qm misformat +out="$(push_out)"; rc=$? +[[ "$out" == *"linters MODIFIED the working tree"* ]]; check "AC7 autofix rewrite blocks push" 0 $? +check "AC7 autofix block exits nonzero" 1 "$rc" +git rm -qf Bad.swift; git commit -qm drop-bad + +# committed LINT VIOLATION (>180-char line) → swiftlint fails → BLOCK +{ printf 'let long = "'; printf 'A%.0s' {1..190}; printf '"\n'; } >Long.swift +git add Long.swift; git commit -qm violation +out="$(push_out)"; rc=$? +[[ "$out" == *"linters failed"* ]]; check "AC7 lint violation blocks push" 0 $? +check "AC7 lint block exits nonzero" 1 "$rc" +git rm -q Long.swift; git commit -qm drop-long + +# LIVE full-test run → BLOCK +mkdir -p _build/full-test/run1 +sleep 30 & livepid=$! +echo "$livepid" >_build/full-test/run1/pid +printf '%s\n' "$PWD/_build/full-test/run1" >_build/full-test/current +out="$(push_out)"; rc=$? +[[ "$out" == *"full-test run(s) live"* ]]; check "AC7 live run blocks push" 0 $? +check "AC7 live block exits nonzero" 1 "$rc" +# regression (#190 review): a live run that `current` does NOT name (concurrent +# runs repoint it) must still block — the hook scans all run dirs. +mkdir -p _build/full-test/run2; echo 999999 >_build/full-test/run2/pid +printf '%s\n' "$PWD/_build/full-test/run2" >_build/full-test/current +out="$(push_out)"; rc=$? +[[ "$out" == *"run1"* ]]; check "AC7 live run outside current blocks push" 0 $? +check "AC7 outside-current block exits nonzero" 1 "$rc" +kill "$livepid" 2>/dev/null + +# docs-only commit (no Swift in the push) → passes (lint has nothing to gate; +# the skip itself is not directly observable here — every Swift file is clean) +printf '# Doc\n' >DOC.md +git add DOC.md; git commit -qm docs +out="$(push_out)"; rc=$? +check "AC7 docs-only push passes" 0 "$rc" + +# pre-existing violation OUTSIDE the push range must NOT block (endpoint diff) +{ printf 'let old = "'; printf 'B%.0s' {1..190}; printf '"\n'; } >Old.swift +git add Old.swift; git commit -qm add-old +out="$(push_out)"; rc=$? # Old.swift IS in range → blocked +[[ "$out" == *"linters failed"* ]]; check "AC7 in-range violation still blocks" 0 $? +git rm -q Old.swift; git commit -qm drop-old +out="$(push_out)"; rc=$? # endpoints no longer contain Old.swift; the range's only +# entry is its deletion (ACMR excludes D) — genuine out-of-tree scoping is +# pinned by the new-branch case below (Remote.swift outside the delta) +check "AC7 deleted-in-range file does not block" 0 "$rc" + +# plant a violating file on the remote default branch (pushed around the gate) +{ printf 'let remote = "'; printf 'C%.0s' {1..190}; printf '"\n'; } >Remote.swift +git add Remote.swift; git commit -qm remote-violation +git push --no-verify -q origin HEAD:refs/heads/main 2>/dev/null + +# NEW branch (zero rsha), clean delta → passes despite the remote's violation +git checkout -qb feat +printf 'let feat = 1\n' >Feat.swift +git add Feat.swift; git commit -qm feat +out="$(git push origin HEAD:refs/heads/feat 2>&1)"; rc=$? +check "AC7 new-branch push gated on delta only" 0 "$rc" + +# NEW branch carrying a violation → still blocked (gate applies to the delta) +git checkout -qb featbad +{ printf 'let fb = "'; printf 'D%.0s' {1..190}; printf '"\n'; } >FeatBad.swift +git add FeatBad.swift; git commit -qm featbad +out="$(git push origin HEAD:refs/heads/featbad 2>&1)"; rc=$? +[[ "$out" == *"linters failed"* ]]; check "AC7 new-branch violation blocks" 0 $? +git checkout -q main + +# DELETE push (zero lsha) → no fatal noise, passes +out="$(git push origin :refs/heads/feat 2>&1)"; rc=$? +[[ "$out" != *"fatal:"* ]]; check "AC7 delete push no fatal noise" 0 $? +check "AC7 delete push passes" 0 "$rc" + +# push to a NON-origin remote (alt; its alt/main tracking ref deleted): +# still scoped against origin/main — the project's delta — and passes +git remote add alt "$PWD/../remote.git"; git fetch -q alt +git update-ref -d refs/remotes/alt/main +git checkout -qb feat2 +printf 'let f2 = 1\n' >F2.swift +git add F2.swift; git commit -qm feat2 +out="$(git push alt HEAD:refs/heads/feat2 2>&1)"; rc=$? +check "AC7 non-origin push scoped via origin/main passes" 0 "$rc" + +# push BY URL ($1 is the URL, not a remote name): still scoped and passes +out="$(git push "$PWD/../remote.git" HEAD:refs/heads/byurl 2>&1)"; rc=$? +check "AC7 URL push scoped via origin/main passes" 0 "$rc" + +# orphan-history branch → fails closed (silent skip would be a vacuous pass) +git checkout -q main +git checkout -q --orphan orph +git rm -qrf . >/dev/null 2>&1 +printf 'let orph = 1\n' >Orph.swift +git checkout -q main -- scripts .swiftlint.yml .swiftformat # keep the hook in the orphan tree +git add -A; git commit -qm orphan +out="$(git push origin HEAD:refs/heads/orph 2>&1)"; rc=$? +[[ "$out" == *"no common history"* ]]; check "AC7 orphan push fails closed with message" 0 $? +check "AC7 orphan push blocked" 1 "$rc" + +# shadow tag: a LOCAL tag named origin/main pointing at the branch tip must +# NOT choose the lint base (short-ref resolution consults refs/tags/ first) +git checkout -q main +git checkout -qb shadow +{ printf 'let sh = "'; printf 'E%.0s' {1..190}; printf '"\n'; } >Shadow.swift +git add Shadow.swift; git commit -qm shadow +git tag -f origin/main shadow >/dev/null +out="$(git push origin HEAD:refs/heads/shadow 2>&1)"; rc=$? +[[ "$out" == *"linters failed"* ]]; check "AC7 shadow tag cannot void the lint base" 0 $? +check "AC7 shadow-tag push blocked" 1 "$rc" +git tag -d origin/main >/dev/null; git checkout -q main + +echo "----" +if [[ "$fails" -eq 0 && "$n_checks" -eq "$EXPECTED_CHECKS" ]]; then + echo "ALL HOOK ACCEPTANCE CHECKS PASSED ($n_checks/$EXPECTED_CHECKS)" +else echo "$fails CHECK(S) FAILED, $n_checks/$EXPECTED_CHECKS executed"; exit 1 +fi