Compare commits

..
73 Commits
Author SHA1 Message Date
AlexKucera 6aa31a419a feat(microblog): show Micro.blog publish status
The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
2026-12-04 17:45:35 +01:00
AlexKucera 6938826101 feat(microblog): add app token settings page and honest 5xx wording
The app token could only be entered in the publish sheet, and that
field came back only after a 401/403, so a saved token had no standing
way to be replaced or removed. The new Settings → Micro.blog page
writes the same `MicropubTokenStore` slot the sheet reads, with a
status row read back from the Keychain after every write so a locked
keychain fails visibly instead of claiming "stored". The sheet now
names the stored token a send carries when its field is hidden.

Micro.blog's errors arrive as HTML pages, never Micropub JSON, so
`decodeFailure` fell through to a bare `HTTP 503` that said nothing
about whose side it was on. Any 5xx without a JSON description now
reads "unavailable on their side — retry in a few minutes"; a
described 5xx keeps its description and a 4xx keeps the bare status.
One decode covers create, publish, q=config, and media uploads.

Docs: AGENTS.md bullets, CHANGELOG [Unreleased] Added/Fixed, and the
devlog for this task plus the 0.1.2 release log.
2026-12-04 15:06:00 +01:00
AlexKucera 9aa0314564 feat(posts): reveal in Finder and copy path
Every piece row gains a Finder hand-off: Reveal in Finder opens
the piece's post.md selected, Copy Path puts its absolute path on
the clipboard (#205). One shared FinderHandOffButtons fragment in
the workspace chrome serves both menus - the library column
(between Move to Archive and the destructive Trash) and the
Archive pane (appended after Convert). Both act on
PostsModel.fileURL(for:), which resolves the piece through the
one PostStore.folder(of:home:) resolver against the watched Home
(never the scan snapshot) and answers nil when the piece is gone,
so a vanished row no-ops instead of revealing a stale path.

fileURL lives in PostsModelIdentity - the (Home, ID) file - not
the write rail: a pure read, nothing written, no strip. A
View-extension wrapper was tried and deleted as a Middle Man; the
menus mount the struct directly.

+3 tests (projects/ resolve, archive/ resolve, vanished -> nil),
flip-verified: bypassing the resolver reddens exactly the
vanished and archive pins (733/735). Rail 735/735; SwiftFormat
and SwiftLint clean. Reviews: standards + spec (two rounds), then
finish-audit (general, security, ponytail) - the audit added the
archive-root pin and fixed three stale headers. DOX: five
Museion/AGENTS bullets.

The release 0.1.2 log's rows still belong to another session and
stay in the working tree; INDEX and the AGENTS window here carry
only the #205 row.

Closes #205
2026-12-03 18:16:12 +01:00
AlexKucera dd8637e7c7 docs(devlog): #204 session log, INDEX row, window
The Fix Cards Jump log: the four grilling answers, the caret-rail
reuse decision, both review rounds, and the flip-verified pins.
INDEX and the AGENTS window carry the row; the rolling window
drops issue192's entry. The release 0.1.2 log's rows belong to
another session and stay in the working tree.
2026-12-03 17:48:55 +01:00
AlexKucera 97893147a6 feat(fix-cards): jump to the anchor
Jump on a Fix Card selects the anchor's span in the piece's
editor and makes the main window key (#204). The span is the
card's quote at its 1-based occurrence, resolved against the
LIVE session text so a dirty buffer still lands, and it rides
the reading flip-back's caret rail: caretHint widens from a
(location, token) tuple to FixCardRevealRequest (SwiftLint
large_tuple), one shared token counter so a jump and a flip-back
can never collide, a zero-length range stays a bare caret and a
non-zero range selects. A jump leaves reading mode first
(reading = false, not exitReading, which stamps its own
zero-length hint), writes nothing, and re-fires per click.

The palette offers Jump on every non-stale card that still shows
an action row; stale anchors have nothing to land on. The
landing math is ProseTextView.landingSpan - a bare caret hops
past leading blanks, a span never does (a quote that IS the
leading blanks selects those blanks) - and appliedText now
routes through anchorRange so Apply and Jump share one
occurrence math.

Two review rounds closed the view-layer gaps the pure pins
could not see: a jump dropped in reading mode; a main window
that never became key (NSApp.activate is a no-op once the
palette's click activated the app - the Coordinator makes
tv.window key instead); a cursor record taken before the scroll.

+3 tests (anchorRange occurrence math with a UTF-16 fixture, the
model's reveal stamp, landingSpan), each flip-verified. Rail
732/732; SwiftFormat and SwiftLint clean. DOX: Museion/AGENTS,
MuseionTests/AGENTS, GLOSSARY gains Jump.
2026-12-03 17:48:55 +01:00
AlexKucera d183d735d7 chore: ignore .hermes directory 2026-12-03 16:44:34 +01:00
AlexKucera c959b67f14 chore(release): 0.1.2
Patch bump for a bug-fix cut (the release skill's rule):
MARKETING_VERSION 0.1.1 → 0.1.2 on every target and configuration,
CURRENT_PROJECT_VERSION unchanged. The changelog's former
[Unreleased] entry — the macOS 27.2 image-drop fix — moves under the
0.1.2 heading with a pointer to the notes. apex stays at 1.1.59:
GitHub's latest release is still the bundled version. Rail 729/729 on
this tree; SwiftFormat and SwiftLint clean.
2026-12-03 16:44:07 +01:00
AlexKucera 653ca69d1f build(release): 0.1.2 release notes
Human-readable notes for 0.1.2 in the 0.1.1 shape: the image-drop
fix told for a reader who never saw the ticket (the macOS 27.2 drag
routing in one paragraph, what the editor does now, the two
deliberate refusals), known limits unchanged from 0.1.0, install
copy, suite 729 at the tag.
2026-12-03 16:43:53 +01:00
AlexKucera 1b0c23ae5b docs(release): clarify patch vs minor version bump in release skill 2026-12-03 16:41:39 +01:00
AlexKucera 46e87e678c fix(editor): editor owns file drops on macOS 27.2
Dropping an image file on the prose editor pasted the file path
instead of ingesting it (#141 follow-up, unticketed; dogfood on
macOS 27.2.1). #141 was field-verified on 27.0.1, where the
window-level SwiftUI dropDestination starved every deeper
destination; 27.2 routes a drag to the deepest destination, and a
live NSTextView registers itself for drag types, so its stock
performDragOperation pasted the path and the window destination
never fired — the same for a markdown file dropped on the editor.

The editor text views now share a FileDropTextView base that owns
the drops landing on them: URL-bearing drags route (never super) —
the prose editor through the one new AppGateState.routeFileDrop
(Cold Turkey guard, markdown → guest, anything else → ingestDrop),
which the window destination also uses for drops landing outside
the editor; the outline rows bounce; text-only drags keep the stock
drop; the pasteboard probe is memoized per changeCount. A web URL
refuses with the type strip, a vanished file refuses as missing.

+9 tests (a real NSDraggingInfo mock drives the overrides; the
router's guest/lock/ingest branches pinned), all flip-verified.
Finish-audit: three reviewers; the text-drag regression and the
outline rows' identical exposure fixed, two pre-existing ceilings
deferred in the devlog. Rail 729/729, swiftformat 0/153, swiftlint 0.
2026-12-03 16:36:47 +01:00
AlexKucera 64a7eaa37e docs: add buy me a coffee announcement to release runbook and readme
The release skill (0.2.0 → 0.3.0) now ends with a Buy Me a Coffee
announcement left as a draft, mirroring the Micro.blog draft: step 12
fixes the INPUT (`create`, `mode: "draft"`, `audience: "public"`) and
delegates the browser mechanics to the `buymeacoffee-post` skill, done
only when `RESULT.mode` is "draft" and `RESULT.editUrl` is a real edit
URL. Ego Browser logged in to BMC joins the prerequisites, and the
verification section checks both drafts. Neither announcement is ever
published by the agent; both wait in Alexander's queues.

The README gains a "Support Museion" section linking the Buy Me a Coffee
page, since the app suite is the author's only income.
2026-12-03 12:22:56 +01:00
AlexKucera d5a515091a docs(devlog): release 0.1.1 session log; release skill gains the Micro.blog draft step
Session log for the 0.1.1 cut: apex 1.1.59 refreshed first, bump + tag
4a056f9, rail 720/720 with the freshness proof, notarized DMG sha256
e7add45a…, the go (push + Gitea release id 28, token-authenticated
download byte-identical), and the Micro.blog announcement left as a
draft. The gotchas table carries the six post-go traps: silent
tea releases create, Gitea's tag_name, no PyYAML on the system python,
security add-generic-password needing </dev/null, and an account with
no default microblog.

Release skill 0.2.0: new step 11 posts the announcement to Micro.blog as
post-status: draft — token in the login keychain under its own service
(never the app's production micropub slot), mp-destination mandatory
because q=config shows three blogs and none is default, mp-channel
default, q=source read-back before reporting. Intro, Prerequisites,
Quick Reference, Pitfalls and Verification updated to match; root
AGENTS.md Child DOX Index row mentions the draft step.
2026-12-03 08:02:06 +01:00
AlexKucera 4a056f9c53 chore(release): 0.1.1
Bug-fix release. MARKETING_VERSION 0.1.0 → 0.1.1 on all six
target/configuration pairs (CURRENT_PROJECT_VERSION stays at 1);
CHANGELOG gains the [0.1.1] - 2026-12-03 heading over the external-watch
normalizer fix that sat under [Unreleased], a Changed entry for the
apex 1.1.59 refresh, a fresh empty [Unreleased] above, and a pointer to
docs/releases/0.1.1.md. Rail at this tree: 720/720.
2026-12-03 07:47:43 +01:00
AlexKucera 570abb32c0 fix(reading): bump bundled apex to 1.1.59
The reading-mode renderer moves from 1.1.58 to the current upstream
release, packaged exactly as the 0.1.0 bundling (ADR-0011): the arm64
slice of the official universal release tarball, .sha256 verified against
the published checksum, the three CI/Homebrew rpaths stripped and
replaced by the single @executable_path/../Resources/libyaml.bundle,
Developer ID-signed with the hardened runtime. 1.1.59 still links
libyaml dynamically, so the vendored libyaml.bundle stays beside it;
--no-mixed-lists (ADR-0011's load-bearing flag) is still present. Proven
in a scratch Resources/ layout before the copy: --version reports
1.1.59 and a mixed bullet/ordered list renders as two lists.
2026-12-03 07:47:35 +01:00
AlexKucera bba4688dcb build(release): add the release skill and 0.1.1 release notes
.agents/skills/release/SKILL.md is the end-to-end runbook: refresh the
bundled apex renderer, bump, changelog heading, notes, the verify rail,
sliced commits, annotated tag, release.sh DMG, then a go-gated push and
Gitea release. Step one is now an unconditional apex refresh with the
full recipe inline (GitHub releases/latest → .sha256 → lipo arm64 →
strip every rpath → add the libyaml.bundle rpath → Developer ID sign
with the hardened runtime → prove it in a scratch Resources/ layout
before it touches the tree) instead of a "compare --version" check that
read as optional. Homebrew is a fallback only: its formula trailed the
GitHub release by a version on the 0.1.1 cut day. The skill bumps its
own version to 0.1.1.

docs/releases/0.1.1.md distills the CHANGELOG section for humans — the
false #67 conflict on BOM/CRLF guest files and the apex 1.1.59 refresh
— and becomes the Gitea release body. Root AGENTS.md gains the
.agents/skills/ Child DOX Index row.
2026-12-03 07:47:29 +01:00
AlexKucera 2d5073e421 Merge pull request 'museion/external-watch-compares-unnormalized-text: guest watch reads through the ONE shared external normalizer — false #67 conflict gone' (#203) from fix/external-watch-compares-unnormalized-text into main
CI / ci (push) Canceled after 0s
2026-12-03 07:36:51 +01:00
AlexKucera 07da076f41 merge main (3197b927) into fix/external-watch-compares-unnormalized-text (0.1.0 release wave)
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Conflict resolution (keep-both, nothing from either side lost):
- CHANGELOG.md: the branch external-watch entry stays under [Unreleased]
  (unreleased fix, PR #203); the owner 0.1.0 release entries stay in [0.1.0].
- docs/devlog/INDEX.md: union of rows, newest-first — the 2026-12-01 release
  row above the 2026-11-30 external-watch row.

Purity: code dirs carry trunk 3197b927 hunks verbatim (diff-of-diffs cmp clean);
fix code and the branch devlog are byte-identical to reviewed 822b1b5.
2026-12-01 20:19:29 +01:00
AlexKucera 3197b9276e docs: add fonts section to readme
CI / ci (push) Canceled after 0s
Explain that Museion's typography uses commercial
Butterick typefaces that must be installed manually,
list the three faces with links, and note the system
fallbacks so users know the app works without them.
2026-12-01 15:23:20 +01:00
AlexKucera 23afcdf3b6 docs(devlog): notarization and apex bundling
CI / ci (push) Canceled after 0s
The release 0.1.0 log gains the chapter the first draft could not have:
the Developer ID creation workaround, the five script fixes the real
runs forced, the apex/libyaml bundling (1.1.58), and the gotchas table
rows for each. Open items now only the authorization-gated ones: tag
move, push, Gitea release, re-sign on certificate rotation.
2026-12-01 15:12:25 +01:00
AlexKucera fd806e9e76 fix(reading): ship apex with libyaml, signed
CI / ci (push) Canceled after 0s
The bundled apex had never run on a Mac without Homebrew: its release
build resolves libyaml through rpaths for its CI runner and the
Homebrew prefixes, and macOS ships no libyaml, so reading mode silently
fell back to the raw source for everyone else since #76. The notary
service rejected it too (an unsigned Mach-O in Resources), which is how
this surfaced during the 0.1.0 cut.

Resources/apex is now the arm64 slice of 1.1.58 (was 1.1.17), Developer
ID-signed with the hardened runtime, with one rpath that resolves in
the bundle and in the checkout alike. libyaml 0.2.5 rides beside it in
libyaml.bundle/, same team signature: a bare dylib in the synced folder
is classified by content and silently linked into the app, so the
.bundle wrapper is load-bearing. THIRD-PARTY-NOTICES.md ships with both
MIT texts; ADR-0011's bundling consequence is rewritten to match.
2026-12-01 15:12:25 +01:00
AlexKucera 5f92241308 fix(release): make packaging survive real runs
The first real notarization runs exposed five ways the script lied or
stopped short. codesign's Authority output was grepped through a pipe,
so under pipefail a grep -q match SIGPIPEd codesign and a good export
read as "not Developer ID signed"; the dump is captured first. notarytool
--wait exits 0 for an Invalid submission, so the verdict is now the
status field of its JSON, with Apple's log printed on anything but
Accepted. The DMG itself is signed before submission (Gatekeeper's
open-assessment needs a signature for the ticket to ride), and the
staple is retried because the ticket can reach the CDN after Accepted.

Two checks run before anything is notarized: the exported app must not
link libyaml and the bundled apex must run from the export. Both would
have caught the broken bundle the first Accepted DMG carried. The
identity refusal now points at developer.apple.com + a Keychain Access
CSR, because Xcode 27.2's Manage Certificates refuses Developer ID
creation even for the Account Holder.
2026-12-01 15:12:25 +01:00
AlexKucera 217a87324e docs(devlog): release 0.1.0 session log
Milestone log for the release cut; INDEX row and the AGENTS.md window rebuilt from the ten newest rows (the 11-23 log had never entered the window).
2026-12-01 12:33:38 +01:00
AlexKucera d470615ac7 chore(release): 0.1.0
First release. MARKETING_VERSION 1.0 → 0.1.0 on all targets;
CHANGELOG gains the [0.1.0] - 2026-12-01 heading over the Unreleased
entries and a pointer to docs/releases/0.1.0.md.
2026-12-01 12:31:32 +01:00
AlexKucera 58355aa292 build(release): add release.sh and 0.1.0 release notes
scripts/release.sh cuts a release from an already-bumped commit:
archive → Developer ID export → UDZO DMG → notarytool → stapler,
refusing before any build when the Developer ID identity is missing
(the private key lives only on the Mac that created the certificate).
diskutil image create replaces hdiutil create, deprecated on macOS 27.

CHANGELOG.md stays the entry-by-entry record with issue numbers;
docs/releases/<version>.md is the human-readable distillation pasted
into the Gitea release (DOX contract in docs/AGENTS.md). dist/ is
gitignored. Root AGENTS.md: commands block, scripts index row, and the
Stack line corrected to macOS 27+ to match MACOSX_DEPLOYMENT_TARGET.
2026-12-01 12:31:32 +01:00
AlexKucera c10477da35 docs(readme): rewrite as feature list and usage guide
The README was a developer getting-started plus the Home section. For
the first release it now leads with what the app does — writing,
outlines, library, the Mentor loop, trends, publishing — grounded in
the shipped menus and shortcuts, then requirements, install, a quick
start, a shortcut table, and the development commands. Deployment
target corrected to macOS 27: the pbxproj says 27.0 and the old
"26.5+" was stale.
2026-12-01 12:31:31 +01:00
AlexKucera 822b1b562e docs: brief-32 session log, INDEX row, changelog entry
CI / ci (pull_request) Canceled after 0s
CI / ci (push) Canceled after 0s
Devlog records the class-site re-derivation (post-side rescan
disclosed as representation-consistent with evidence), the helper
location decision (EditorSession.swift beside readDocument — no
ceiling pressure, no new file), and the RED/GREEN evidence chain.
2026-11-30 22:19:19 +01:00
AlexKucera 70dd47ed8c fix(editor): normalize the guest watch's disk read
The external guest's watch read disk raw while the session's text and
lastFlushedText came through readDocument's normalizing external
branch, so diskTextChanged saw a difference on every BOM/CRLF file and
raised conflictAlert on unchanged content — re-arming after each
sibling directory event and after either alert answer, blocking
departures and quit until the user's own flush rewrote the file
normalized (finding museion/external-watch-compares-unnormalized-text,
argus cycle-6; unticketed, brief-32).

Extract the external branch (BOM strip + CRLF->LF) into
EditorSession.readExternalDocument(at:) — one shared normalizer, two
callers: the open read (readDocument) and the watch's onEvent. The #67
compare is now normalized-to-normalized; what readDocument loads is
unchanged.
2026-11-30 22:17:13 +01:00
AlexKucera b69ddd3963 test(editor): pin the external watch's false 67 conflict
CI / ci (push) Canceled after 0s
The external guest's watch (PostsModelImports.startExternalWatch)
reads disk raw while the session's text/lastFlushedText came through
readDocument's normalizing external branch (BOM strip + CRLF->LF), so
diskTextChanged raised conflictAlert on unchanged BOM/CRLF files —
re-arming after every sibling directory event and after either alert
answer, blocking departures and quit (brief-32, argus cycle-6).

Three RED pins over the real watch closure
(externalWatcher.onEvent): no conflict on an unchanged BOM/CRLF
guest, no re-arm after yes-reload or keep-local, and the load-bearing
negative — a real foreign write still raises. Targeted rail at base:
11 executed / 8 passed / 3 failed (all three new pins), 164
SwiftCompile lines.
2026-11-30 22:15:58 +01:00
AlexKucera 3bb178220f Merge remote-tracking branch 'origin/main'
CI / ci (push) Canceled after 0s
2026-11-24 08:56:30 +01:00
AlexKucera 5341c4ee53 Merge pull request 'fix(editor): Home repoint rides the departure gate; document identity is (Home, ID) [museion/home-repoint-retains-old-editor-target]' (#202) from fix/home-repoint-retains-old-editor-target into main
CI / ci (push) Canceled after 0s
2026-11-24 08:55:35 +01:00
AlexKucera cac66f6e76 docs(brief-28 r1): evidence classes, r1 verify line, changelog/index to 717
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
N-2: "Identity checks — evidence classes" — pinned (card hop-back,
rescan hoist, #179 guard) vs correct by construction (the Micropub
stamp) vs invariant-equivalent defensive depth (the synchronous sweep
and openPostID's gate: never independently observable under the
gate-first invariant — belt to the gate's suspenders, not
"every site test-verified"). Verify line for r1 at 92344e2: full rail
717/717, filtered 19/19, MF-1 mutation 9/8/1 restored byte-exact,
lint 0/0. Gotchas: the partial patch regeneration, the status/current
race. N-3 is the regenerated owner-apply patch beside the handoff.
2026-11-23 22:38:43 +01:00
AlexKucera 92344e224c test(editor): pin the rescan stale-Home verdict and the draft-survives repoint (review r1)
CI / ci (push) Canceled after 0s
MF-1: the hoisted `guard watchedHome == home` in rescan was live logic
with no pin — the only new guard still observable after the gate (a
scan started under A can sit in its detached hop while the gate passes
and bind flips to B; landing after B's own scan it would hold A's list
under the B binding until the next B-side event, which with nothing
open is never). `scanLibrary` is the per-model injectable library
scanner beside `scanPieceCards` (captured before the hop); the pin
parks an A scan past the repoint, lets B's scan land, releases, and
asserts the list is still B's and `contentRevision` did not move.

Mutation check: hoist removed → rail-filtered `9 executed / 8 passed /
1 failed`, ONLY that pin, `posts.map(\.id) → ["alpha"]` and
`contentRevision → 3` vs `revision → 2`; restored byte-exact (sha256
prefix d86ce09d6b7e6bd2 before and after).

N-1: the draft-survives-repoint decision pinned — newPost targets the
selected A piece's project, the draft rides the repoint intact, and
`saveDraft()` lands under B only, in the draft's OWN project even
though B does not have it (materialize creates with intermediates).

Filtered GREEN: PostsModelRepointTests + PostsModelDepartureTests
19/19. swiftformat 0/152, swiftlint 0.
2026-11-23 22:34:23 +01:00
AlexKucera 97712fbacb docs(brief-28): name the filter trap precisely — file name ≠ suite name
CI / ci (push) Canceled after 0s
The PostsModelTests.swift file holds free-function @Tests AND the
PostsModelWriteRailTests suite; the filter matched neither. The devlog
row said 'free functions' alone, which undersold it.
2026-11-23 20:26:54 +01:00
AlexKucera 108075239d docs(brief-28): session log, INDEX row, changelog entry
CI / ci (push) Canceled after 0s
Home repoint rides the departure gate — devlog with the pattern-
exhaustive identity table, the decisions (gate placement, nothing
auto-reopens, draft survives, refusal posture, the disclosed not-
converted sites), the gotchas (pollUntil's consuming probe, the
free-function filter trap, the current-session teardown shape), and
the Verify line: RED 6/6 at ca265d3b, full rail 715/715 at 8b0d43a,
stale-scan pin mutation-checked, lint 0/0.

The AGENTS.md DOX pass ships as an owner-apply patch beside the
handoff (~/daedalus-builds/museion/brief-28-agents-owner-apply.patch,
git apply --check clean against the branch head) — never written by
this session, per the brief's standing rule.
2026-11-23 20:26:27 +01:00
AlexKucera 8b0d43aed8 fix(editor): Home repoint rides the departure gate; document identity is (Home, ID)
CI / ci (push) Canceled after 0s
Settings committed the new Home and bind flipped watchedHome without
departing the open session: the session's immutable target kept the
OLD Home, a same-slug piece in the new library made the ID-only
reselect return it, and autosave/Save/quit wrote the old library
while structural operations resolved against the new one. #198's
departure gate never saw this seam; a no-collision piece was torn
down by the vanish path with its dirty buffer dropped.

The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a
document departure through the same sessionMayDepart (all three legs:
unanswered #67, failed flush, never-loaded retype — no parallel
gate); on refusal nothing changes (preference, watchedHome, the
session's (A, id) target, its buffer), on acceptance the departed
piece's state dies with it. AppGateState.repointMuseionHome(to:)
commits the preference and its persistence only after the gate;
WorkspaceView's Settings binding routes through it and the root
.task(id:) binds the model after that commit — the dumb binder. A
refusal speaks the #198 reason the way #200's quit refusal does
(hosted-guarded alert: no Posts strip is in sight from Settings).
Nothing auto-reopens after an accepted repoint — the writer picks
from the new list; the in-memory draft survives (no Home until first
save; dropping it would drop the only copy).

Document identity is (Home, ID) everywhere — EditorSession.targets
is the pair, PostsModel.openSessionTargets the model-side question;
every ID-only session comparison is retired: select's reselect
no-op, openUnguarded, the structural rail (rename/trash/move/archive/
restore/unarchive + flushOrAbort), conversion, the pass guard (its
answer now carries the Home it validated), Micropub's launch, the
lock's arm/body reads. Async continuations re-validate identity at
COMPLETION: refreshCards (launch and hop-back — the old ID-only guard
let a scan from the previous library land its cards on the new
library's same-slug piece) and rescan (the stale-Home verdict is
hoisted: a scan that outlived a repoint applies nothing, not just
the vanish check; the #67 disk read runs only for a session targeting
the scan's own Home). scanPieceCards is the per-model injectable
scanner the deterministic stale-scan pin needs.

Tests: PostsModelRepointTests (7) move to the gated entry and go
green (17/17 with PostsModelDepartureTests — the #198 matrix stays
green and composes); the stale-scan pin's RED is a mutation check
(completion guard reverted to ID-only → only that pin fails, cards
→ ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin
drives the real Settings path now (repoint + bind). swiftformat 0/152,
swiftlint 0.
2026-11-23 20:23:57 +01:00
AlexKucera bce6abb38b test(editor): pin Home repoint as a document departure — RED at ca265d3
CI / ci (push) Canceled after 0s
PostsModelRepointTests (6 pins over a two-Home same-slug rig,
projects/posts/shared/post.md in both libraries): the gate runs
before anything changes (failed flush, unanswered #67, never-loaded
retype — sessionMayDepart's three legs), the same-slug piece opens
from B and saves there (flush AND quit), a no-collision repoint lands
the dirty buffer before tearing down, and a pass started after the
repoint runs against the new library.

RED at ca265d3bd3 on the rail
(-only-testing:MuseionTests/PostsModelRepointTests): 6 executed /
0 passed / 6 failed, zero compile errors — each on the finding's
signature: the retained A session under the B binding
(session.text = "A body, typed in A", targets(home: B) false), B's
edits landing on A's disk, watchedHome = B despite a refused flush,
and the no-collision vanish path dropping the dirty buffer.

The tests speak the Settings path as it exists at base (bind), which
has no gate to refuse through; the fix commit moves each repoint call
to the gated entry. EditorSession gains the pure identity predicates
the assertions speak in (targets(postID:home:) / targets(home:)) —
read-only, no behavior change.
2026-11-23 20:16:02 +01:00
AlexKucera 1df46a816f chore: remove GitNexus tooling
Session-log audit (3,393 tool executions, ~987 sessions) found near-zero information value: impact ratings systematically overridden (import-fanout inflation), detect_changes 45% zero-affected, structural index staleness (1,228 rebuilds). Extension, binaries, indexes and skill copies removed machine-wide on 2026-11-19.
2026-11-19 19:22:51 +01:00
AlexKucera ca265d3bd3 docs(issue-201): apply brief-25 AGENTS sentences
CI / ci (push) Canceled after 0s
Apply PR #198's consented owner-apply sentences to the
PostsModelWrites/PostsModelImports bullets: the departure gate
(sessionMayDepart/departOpenDocuments) and the guarded dismissal
(dismissExternal -> Bool) now name brief-25's contract. Patch
regenerated against merged HEAD (cbe16f0); git apply --check clean,
3-way clean, no other AGENTS.md content touched.

One disclosed deviation from round 1 (its accuracy-extension
precedent): "the same two gates" -> "the same gates" — #200's
finish-audit added a third sessionMayDepart leg (never-loaded
session hold), so "two" would contradict the adjacent flushOrAbort
clause.

Closes #201
2026-11-19 13:28:21 +01:00
AlexKucera cbe16f0442 docs(issue-200): log, changelog, AGENTS contracts
CI / ci (push) Canceled after 0s
Session log + INDEX row + rolling window, CHANGELOG Fixed entry,
and the #200 quit-gate contracts in the Museion/AGENTS.md chain
(delegate's two refusals, PostsModel shutdown/active, gate
family, wiring) plus the MuseionTests suite map rows — including
the PR #198 gap (PostsModelDepartureTests had never been listed)
and the gitnexus index-count refresh.
2026-11-19 13:18:26 +01:00
AlexKucera 2334afc392 fix(editor): quit rides the departure gate
shutdown() flushed both sessions best-effort and ignored the
results — quitting with an unanswered #67 conflict wrote local
text over the foreign disk body (flush() holds for conflicts
only in the debounce), and a failed quit-time flush silently
dropped the only copy of the edits.

Quit now routes through the same departure gate as navigation:
documentsMayDepart runs both sessions through sessionMayDepart,
and the failed-flush-at-quit posture is BLOCK QUIT —
applicationShouldTerminate (quitReply(posts:), before the Cold
Turkey ask) refuses termination with one spoken reason via a
hosted-guarded alert. PostsModel.active (weak, registered by
AppGateState.init — the WritingLockState.active precedent) is
the delegate's reachability.

Finish-audit fixes folded in: sessionMayDepart refuses a
never-loaded session's retyped words (its flush is a vacuous
success — the same gap closed for navigation); shutdown stays
void (no production reader of a Bool).

+5 pins (conflict hold, clean flush, guest flush, never-loaded
refusal, delegate refusal incl. chmod-injected flush failure),
all flip-verified. Rail 708/708; format+lint clean.

Closes #200
2026-11-19 13:18:19 +01:00
AlexKucera 55be3d1a2f Merge pull request 'fix(acp): engine backpressure cannot defeat deadlines or teardown [museion/acp-backpressure-defeats-timeout-and-shutdown]' (#199) from fix/acp-backpressure-defeats-timeout-and-shutdown into main
CI / ci (push) Canceled after 0s
2026-11-19 10:38:17 +01:00
AlexKucera 9ccfe83ec0 refactor(acp): land PR #199 audit fixes
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Reviewer fanout (ponytail/security/general) over #199 found no
behavior defects. Apply the accepted non-behavioral findings:

- requestOutcome helper dedups the two outcome tasks; the two
  discarded wedge tasks drop their unread do/catch scaffolding
- awaitBounded doc names its real bound (window is green-world
  only; the RED-world watchdog is the fake's /bin/sleep 30 exit)
- send() gains a ponytail ceiling comment: queued sends are
  unbounded and a send racing close() writes onto a closed handle
  (benign, probe-verified) — bounded by the model's sequential
  sends; guard if a looping caller appears
- request() doc notes a timed-out request's bytes may still land
  on the wire (late replies dropped, ids never reused)

Suite 697/697 green post-change; format+lint clean.
2026-11-19 10:34:16 +01:00
AlexKucera ce21057586 docs(audit-199): record brief-27 writerQueue contract in the AGENTS chain 2026-11-19 10:17:47 +01:00
AlexKucera b2d01c852a Merge pull request 'fix(editor): guard document departure on failed flushes [museion/failed-flush-discarded-on-document-switch]' (#198) from fix/failed-flush-discarded-on-document-switch into main
CI / ci (push) Canceled after 0s
2026-11-19 09:45:30 +01:00
AlexKucera ae3b99c7ea docs: brief-27 session log, INDEX row, changelog entry
CI / ci (pull_request) Canceled after 0s
CI / ci (push) Canceled after 0s
Docs-only (code identical to the fix commit 89cd377, where the
697/697 suite ran): devlog carries the site-class enumeration with
disproofs, the decisions table, and the gates; CHANGELOG gains the
user-facing acp backpressure entry.
2026-11-17 22:36:56 +01:00
AlexKucera 89cd377814 fix(acp): engine backpressure cannot defeat deadlines or teardown
CI / ci (push) Canceled after 0s
A hung engine that stops reading stdin fills the 64 KB pipe, and
the client's synchronous send blocked its one serial queue — the
same queue that carries request deadlines, request registration,
and close()'s bookkeeping barrier. A blocked writer therefore
defeated the request timeout, starved Stop/lifecycle calls, and
made close() queue.sync behind the stuck write before SIGTERM was
ever reachable; EngineHost's MainActor close callers turned that
into an app-wide unbounded hang on restart or quit (argus probe:
2M-char request with 0.1 s timeout never timed out; a watchdog
close never returned).

Separate the writer from the state: stdin writes (and the stdin
handle's own close, which a blocked write may still own) now ride
a dedicated serial writerQueue, so the state queue is I/O-free —
deadlines fire, Stop is accepted, follow-up requests register,
and close() runs bookkeeping, SIGTERM -> grace -> SIGKILL -> reap
without ever queueing behind the writer. Wire order is preserved
(all send sites funnel through the one serial writer queue) and
the healthy-engine contract is untouched.

Focused serialized EngineSmokeTests: 6 executed / 6 passed at the
fix (3 of them RED at base on exactly the three mechanisms).
2026-11-17 22:27:49 +01:00
AlexKucera 33b7fe0f9f test(acp): pin blocked-writer backpressure regressions
CI / ci (push) Canceled after 0s
RED at base for the acp-backpressure finding: on the unfixed
transport a hung engine that stops reading stdin fills its pipe,
and the synchronous send wedges the client's one serial queue —
the request deadline never fires, follow-up bookkeeping starves,
and close() blocks behind the stuck write (argus probe: 2M-char
request, 0.1 s timeout, watchdog close never returned).

Three smokes over the existing rig, using a new neverRead fake
mode (execs /bin/sleep — the probe's inert non-reading child;
never a real profile): deadline fires while blocked, Stop +
bookkeeping answer while blocked, close returns bounded and reaps
the child. A fourth smoke (new serverPing fake mode) pins the
healthy contract — round trip, -32601 reply delivery over the
wire, idempotent clean close — and passes at base.

Focused serialized run at base: 6 executed / 3 passed / 3 failed
— exactly the three blocked-writer smokes fail, on mechanism.
2026-11-17 22:26:05 +01:00
AlexKucera ffb9457a63 integrate main: #193 PostsModel split (Watcher/Writes/Imports) into failed-flush departure guard
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
# Conflicts:
#	Museion/PostsModel.swift
#	docs/devlog/INDEX.md
2026-11-17 20:12:53 +01:00
AlexKucera bb4bfa2675 docs: #193 session log + distilled learnings
CI / ci (push) Canceled after 0s
Split PostsModel/WorkspaceView/PostsPaneView into 8 domain-extension
files (move-only, three audits concur; 693/693 via the verify rail).
One commit per source file precedes this log.

Closes #193
2026-11-17 18:00:10 +01:00
AlexKucera 2a02b95ed0 refactor(posts): split PostsPaneView into PostsLibraryColumn/LibraryPostRow (#193) 2026-11-17 17:55:47 +01:00
AlexKucera 70cd1c2b55 refactor(workspace): split WorkspaceView into ArchivePaneView/Sheets/Chrome (#193) 2026-11-17 17:39:39 +01:00
AlexKucera 902e860bd8 refactor(posts): split PostsModel into Watcher/Writes/Imports files (#193) 2026-11-17 17:39:39 +01:00
AlexKucera f50fecfc60 docs: gate-running learnings → full-test.sh rail
CI / ci (push) Canceled after 0s
Collapse #192: the root AGENTS.md testing learnings shrink to what
scripts/full-test.sh cannot encode. Eight gate-running recitals become
the one-line pointer; MuseionTests/AGENTS.md Verification names the
script instead of the raw xcodebuild line.

Deleted → encoded by:
- #30 flake ritual → --serialized rerun + no-concurrent-lint rule;
  pre-push no-push-while-live pid scan
- #31/#134 executed-count-not-banner + vacuous filters →
  xcresulttool-authoritative counts; zero-executed summary exits
  nonzero (full-test.sh:431-449)
- #178 parameterized @Test count arithmetic → summary-based counting
- #33/#179 newest-bundle race → per-run pinned -resultBundlePath
  (:190), each run polls its own dir
- #177 grep -c chain break → the script is the single gate command
- #177 build/test split under timeout cap → detached run (the split
  existed only to dodge the cap)
- #182 test-without-building stale green → obviation: rail builds+tests
  in one detached run; residual covered by no-push-while-live + kept
  #197 learning
- lint-gate scoping recital → scripts/hooks/pre-push header + push-
  delta scoping loop

Retained (script cannot encode): #197 stale binaries + FSEvent quiesce,
#162 ticker, #178 transport double, #33 keychain, #151 seam, #134
reboot remedy, #147 pair, #142/#143/#180/#181 format family.

Two-axis review (Standards + Spec subagents): spec PASS — all 8
mappings verified against script body, not header claims; standards
follow-ups applied (pointer scoped to its section; Commands-block
xcodebuild line marked ad-hoc/outside-the-rail).

Verify: swiftformat --lint 0/141, swiftlint 0 findings, full-test.sh
693/693; gitnexus detect-changes low, 0 flows.

Closes #192
2026-11-17 16:52:56 +01:00
AlexKucera d7fd11cf0d chore(lint): repo-wide green becomes the contract
CI / ci (push) Canceled after 0s
Close the lint arc #194-#197: deliberate-style rule disables with
rationales (#194), filter-safe test renames + --test-case-name-format
preserve (#195), every surviving warning fixed through the sanctioned
lint-stable shapes (#196), and the docs now state the true contract
(#197): bare swiftlint . reports zero violations and swiftformat .
reformats nothing, while push gates stay scoped to the push's own
files (settled #190 design) — the pre-push hook's stale 'pre-existing
violations' rationale blocks refreshed, gate logic untouched.

Also in the sweep: quiesce the FSEvent-burst watcher race in
LibrarySearchTests (two rescans double-count one shared PostScanCache
miss; benign revision over-bump), pin the learnings scan's symlink-skip
contract (flip-verified — defended in depth by the lstat guard AND
contentsOfDirectory's own symlink refusal), reorder that scan's guard
so cheap rejections precede the directory listing, and park the roster
chmod window with a ceiling comment.

Finish-audit: 3 reviewers, 0 blocking; the one code finding was
disproved by probe (&& out-binds ?? — the guard was correct). Suite
693/693 via scripts/full-test.sh; swiftlint 0 violations; swiftformat
0/141; hook rig 23/23.

Closes #197
2026-11-17 16:29:46 +01:00
AlexKucera 0ab00eb7b6 feat(scripts): verify rail + pre-push hook
CI / ci (push) Canceled after 0s
Port classis full-test.sh (071966e) as Museion's one-command verify
loop: run/start/status/summary over detached xcodebuild, per-run
pinned xcresult bundles with atomic run-dir allocation (#33/#179),
xcresulttool-authoritative counts (#31/#178), zero-match filters
fail (#31/#134), --serialized rerun is the record (#30/#147), per-
test timeouts + wedge observability (#134). Default scope:
MuseionTests.

install-hooks.sh + pre-push: no push while any run is live, lint
gate scoped to the push's Swift files (bare swiftlint . exits 2 on
main — spike/ + one tests file), autofix-rewrite guard. New-ref
pushes lint the merge-base delta vs refs/remotes/origin/main and
fail closed on unscopable history; a full-ref spelling defeats
refs/tags shadowing.

scripts/test-full-test.sh: 23-check acceptance rig with an
executed-count guard. Four finish-audit rounds; every guard
flip-verified both directions. Suite 692/692 through the rail
itself.

Closes #190
2026-11-17 12:14:12 +01:00
AlexKucera 9497661145 docs(devlog): brief-25 session log + INDEX row
CI / ci (push) Canceled after 0s
brief-25 [failed-flush-discarded-on-document-switch]
2026-11-16 21:01:06 +01:00
AlexKucera 250a662f3e fix(editor): guard document departure on failed flushes
teardown(flushFirst:) discarded flush()'s result, so document
navigation (newPost, newOutline, select, openExternal, dismissExternal,
openUnguarded) dropped the outgoing dirty session after a failed write
and replaced the only retained copy of the unsaved prose.

One shared departure gate now covers every site, placed before any
document-specific state clears:

- sessionMayDepart(_:): flushOrAbort's two gates (unanswered #67
  conflict holds; failed flush holds) lifted to document departure —
  flushOrAbort routes through it unchanged.
- dismissExternal() -> Bool: the guest departs only when its flush
  lands; on failure the guest, its buffer, and its watcher stay live.
- departOpenDocuments(): the full-switch composition (guest + post
  session) behind newPost/newOutline/openExternal.
- select/openUnguarded gate their same-id-conditional session teardowns
  through sessionMayDepart directly.

Departure now aborts with the strip error set and the dirty session
retained; retrying after writability returns lands the edits and
completes the switch. All six PostsModelDepartureTests pins RED at
11b196d, GREEN with this change.

brief-25 [failed-flush-discarded-on-document-switch]
2026-11-16 20:17:58 +01:00
AlexKucera ecd14d1714 test(editor): pin document departure aborting on failed flushes
CI / ci (push) Canceled after 0s
RED at pinned base 11b196d: all six PostsModelDepartureTests pins fail.
Document departure (newPost, newOutline, select, openExternal,
dismissExternal, openUnguarded) tears the outgoing session down with
teardown(flushFirst: true), discards the flush result, and replaces the
only retained copy of unsaved prose when the write fails. Both
navigation families (saved-post session, external guest) pinned with
injected write failures (read-only piece folder / guest directory), plus
the unanswered #67 conflict hold. Retry after writability is restored
proves the edits land and the switch then completes.

brief-25 [failed-flush-discarded-on-document-switch]
2026-11-16 20:14:32 +01:00
AlexKucera 11b196d68a Merge pull request 'test(folds): typing-budget operation-count pin at N/2N [fold-typing-budget-pin]' (#189) from opt/fold-typing-budget-pin into main
CI / ci (push) Canceled after 0s
2026-11-14 08:03:53 +01:00
AlexKucera a5dc06d67f docs(devlog): brief-24 — fold typing budget pin
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Session log + INDEX row: instrument design, the three pins, the
dual-dispatch incident and hunk-level decontamination, fresh
post-decontamination gates (692/692, mutation pair), and two
typing-cost observations routed to the dispatcher (chrome-layer
parent rescan per keystroke; fenceDelimCount whole-buffer pass per
keystroke).
2026-11-13 17:21:24 +01:00
AlexKucera c460545c59 test(folds): pin the typing budget at N/2N
CI / ci (push) Canceled after 0s
The #142 in-place re-key had correctness coverage but no typing-cost
guard — a quiet fallback to the full pass keeps every correctness
pin green while restoring O(buffer) work per keystroke. Add an
operation-count instrument (never wall-time): ProseList.parents
gains an observeLines reporter, refreshFolds/refreshFoldRendering
thread a per-call observer, and a per-instance onLineScan hook
windows the paths that call refreshFolds() bare (the PostEditorView
coordinator tail). No shared state — the hosted suite is parallel.

Three pins: zero scanned lines for typing beside a fold at N=204
and 2N=404 lines; an exact-count control (206/406) proving the
instrument is live and scaling; and a through-seam pin driving real
insertText through a real ProseTextView.Coordinator into
refreshFolds() — zero scans, fold survives, self-controlling with
its own 206 liveness assert. Mutation-checked: severing the single
observer firing fails the control and the through-seam pin.
2026-11-13 17:21:16 +01:00
AlexKucera 7ed304124e Merge pull request 'opt(goal): minutes feeds do no word work; word rail goes count-only [cold-turkey-full-tokenization]' (#188) from opt/cold-turkey-full-tokenization into main
CI / ci (push) Canceled after 0s
Reviewed-on: #188
2026-11-13 16:51:04 +01:00
AlexKucera 7cd5e6964e merge main (2cfd8b9) into opt branch
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Fold origin/main (2cfd8b9, #187 library-search stale-after-mutation)
into opt/cold-turkey-full-tokenization. Only conflict was the
docs/devlog/INDEX.md both-added-row; resolved keep-both in
newest-first order. No code files touched by the resolution:
Museion/ and MuseionTests/ carry #187's hunks verbatim.
2026-11-13 16:41:15 +01:00
AlexKucera 2cfd8b9f79 Merge pull request 'fix(search): re-key the mounted sweep on Home + library content revision (museion/library-search-stale-after-mutation)' (#187) from fix/library-search-stale-after-mutation into main
CI / ci (push) Canceled after 0s
2026-11-13 10:00:58 +01:00
AlexKucera 7de8e2f7a1 docs(devlog): cold-turkey full-tokenization opt branch
CI / ci (push) Canceled after 0s
CHANGELOG [Unreleased] > Changed entry + session log + INDEX row for
the unticketed opt pass (minutes feeds skip word counting; word rail
count-only; no token array per keystroke). Suite 684.
2026-11-13 04:24:04 +01:00
AlexKucera 9f4d9ef9ea perf(cold-turkey): minutes feeds skip word counting; word rail goes count-only
CI / ci (push) Canceled after 0s
Root cause (re-derived live at 5915178): WritingLockState.feed ->
WritingGoalRun.update counted words for EVERY goal type, and
DraftStats.words built the complete lowercased token array
(text.split(whereSeparator:).map(lowercased)) just to return .count —
O(document) allocation + lowercasing per keystroke on the main actor
for minutes goals whose verdict/progress/readout never read the count
(argus probe at efbde25c: minutes ~0.32/3.07/16.64 ms per update at
1k/10k/50k words, linear in document size).

Fix, two halves, semantics byte-stable:
- update(text:) guards on .words — a minutes run does no word work
  on feed at all; its accounting freezes at the arm-time baseline
  (currentWords was dead state for minutes runs: readout, isMet,
  progress, and the completion note all ride the clock).
- DraftStats.words becomes a count-only Character pass over maximal
  isLetter/isNumber runs — never materializing the lowercased
  [String]. Identical count by construction: the tokenizer's split
  (which always omits empty subsequences) yields exactly the maximal
  runs; equivalence pinned against the split expression over a
  mixed-script/emoji/punctuation/number corpus in DraftStatsTests.

WritingGoalRun.init (arm-time baseline) keeps counting once per arm
through the same rail — now also allocation-free. Callers unchanged
(update's countWords defaults to DraftStats.words); the words-goal
net accounting is pinned unchanged ('a words update takes exactly
one word-rail trip' + all existing net-delta pins).
2026-11-13 04:21:28 +01:00
AlexKucera dde99c8a75 test(goal): pin zero word-rail trips for minutes updates (RED)
CI / ci (push) Canceled after 0s
The argus opt pass (2026-11-09, unticketed digest finding
cold-turkey-full-tokenization): every editor keystroke feeds the whole
document through WritingGoalRun.update, which counted words for ALL
goal types — a minutes verdict ignores the count, so the feed paid
whole-document tokenization (lowercased [String] allocation) per
keystroke on the main actor for nothing (argus probe: ~16.6 ms/update
at 50k words, linear in document size).

Pins, RED-first where constructible:
- WritingGoalTests 'a minutes update takes zero word-rail trips' —
  RED at base (base takes one trip per update).
- WritingGoalTests 'a words update takes exactly one word-rail trip' —
  the skip boundary: words goals keep live accounting.
- DraftStatsTests 'word rail equals the split tokenizer over a mixed
  corpus' — semantic equivalence pin (old split expression as inline
  reference over mixed scripts, emoji, punctuation, numbers,
  empties); green at base by design — it is the equivalence proof.

Instrument: update(text:countWords:) gains an injectable word-rail
seam (default DraftStats.words) — per-call counting instead of a
global counter, which would race the hosted suite's parallel
DraftStats calls. No behavior change in this commit; update still
counts for every goal.
2026-11-13 04:20:15 +01:00
AlexKucera 93d97f2e35 docs(devlog): library search stale-after-mutation fix
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Session log + INDEX row + CHANGELOG entry for the snapshot
invalidation fix: the rescan-rail content revision and the mounted
key/gate, with the red-first verification trail.
2026-11-11 22:21:46 +01:00
AlexKucera becad45883 fix(search): re-key sweep on Home and content revision
CI / ci (push) Canceled after 0s
The snapshot's only task identity was the trimmed query, so library
mutations never restarted the sweep: archived and trashed rows kept
rendering in the results, and renamed, new, or since-edited pieces
never entered them until the query changed or the view remounted.

Extend the #179 write rail's rescan with the missing signal: every
scan that changes the Post list OR re-reads any post.md (a body-only
edit compares equal as a Post — #143's skip) bumps
PostsModel.contentRevision. Key the mounted sweep to the full
LibrarySearch.SearchKey (query + Home + revision) and gate rendering
on Snapshot.isFresh, so a landed sweep drops to the recompute state
the moment the library moves under it. The posts-assignment skip
stays: panes never regroup on the bumps, only the search re-keys.
2026-11-11 22:20:14 +01:00
AlexKucera c0cd60b798 test(search): red pin for snapshot invalidation
CI / ci (push) Canceled after 0s
The mounted search snapshot is keyed only to the trimmed query, so
library mutations never restart the sweep: archived/trashed rows
linger in the results and edited bodies never enter them until the
query changes or the view remounts.

Pin the invalidation contract at controller level, the way the pure
seam is pinned: LibrarySearch.SearchKey (query + Home + the model's
content revision) and the LibrarySearch.Snapshot isFresh gate decide
whether a landed sweep may render. The rail pins drive the real
rescan path and prove archive, trash, and a same-query body edit
each move PostsModel.contentRevision. The property is a stub here —
never bumped — so those three pins fail red on this commit.
2026-11-11 22:19:01 +01:00
AlexKucera 5915178ce8 docs(design): capture product and design system
CI / ci (push) Canceled after 0s
Record durable product truth in PRODUCT.md (platform, users, the
Mentor Loop, hard rules, brand commitments) and the incumbent visual
system in DESIGN.md (the Scholar's Desk two-paper world with
normative tokens and named rules), plus the impeccable config and
renderable-component sidecar. Gives the design tooling an authority
to check future UI work against.
2026-11-11 16:35:48 +01:00
AlexKucera 06ab149c55 Merge pull request 'fix(posts): bind rides the WorkspaceView root task (#179 follow-up)' (#186) from fix/posts-bind-root-task into main
CI / ci (push) Canceled after 0s
2026-11-10 16:56:39 +01:00
AlexKucera b8089534cf fix(posts): bind rides the WorkspaceView root task (#179 follow-up)
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
The pane-local PostsPaneView .task(id: home) unmounted with the Posts
pane, leaving watchedHome stale after a Settings Home repoint while the
Archive pane and every root sheet (import / new project / convert) kept
writing through it. The bind now rides the WorkspaceView root task:
first frame + every repoint, whichever pane is showing. Comments and
the Museion/AGENTS.md bullet name the one writer honestly.

Follow-up to #179 (5bf0955) from the PR #185 finish-audit; PR #185
closed as superseded — two complete implementations of the same ticket,
main's stack carries six commits on top. Suite 681/681, lint parity.
2026-11-10 16:56:17 +01:00
122 changed files with 9584 additions and 2213 deletions

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
---
name: release
description: "Cut a Museion release: bump, notes, rail, DMG, tag, publish."
platforms: [macos]
version: 0.3.0
author: Hermes
metadata:
hermes:
tags: [Release, Museion, Xcode, Notarization, Gitea, apex, Micro.blog, BuyMeACoffee]
---
# Cutting a Museion release
Runs a release end to end: refresh the bundled apex renderer, version bump, changelog heading, release notes, the verify rail, sliced commits, an annotated tag, the notarized DMG from `scripts/release.sh`, then push and the Gitea release, then the announcements — Micro.blog and Buy Me a Coffee — each left as a **draft** for Alexander to publish. The skill decides nothing about signing — `release.sh` and the Account Holder's keychain do that — and it bumps no version on its own. Push and the forge release wait for Alexander's explicit go (root `AGENTS.md`, User Preferences); neither announcement is ever published by the agent.
## When to Use
- "cut / ship / tag / bump a release", "make a DMG", "X.Y.Z is ready"
- notarization came back `Invalid`, or a bundled binary changed (`Museion/Resources/apex`) — rerun steps 6–9 and move the still-local tag
- release notes or the README have to match what shipped
## Prerequisites
- Clean tree on `main`. `MARKETING_VERSION` is the only version source; read it from build settings, never from the pbxproj text.
- A valid **Developer ID Application** identity: `security find-identity -v -p codesigning`. When it is missing, the fix is Alexander's (developer.apple.com + a Keychain Access CSR — the `scripts/release.sh` header has the route); the agent imports nothing.
- Notary profile `museion-notary`, registered once by the Account Holder. The agent never runs `notarytool store-credentials`.
- `tea` logged in to `git.babylondreams.de` (the default login).
- Micro.blog announcement token in the login keychain: `security find-generic-password -a micro.blog -s com.babylondreams.Museion.release-announce -w` prints it (step 11 has the one-time `add-generic-password`). When missing, Alexander generates an App Token (Micro.blog → Account → App Tokens) and the agent stores it — never the other way around.
- Ego Browser running and logged in to Buy Me a Coffee — `buymeacoffee-post` has the one-time check.
- Budget: ~2 min for `release.sh`, ~7 min for the rail.
## Procedure
Run through the `terminal` tool. Each step ends on a check; the next starts when it passes.
1. **Refresh apex FIRST — every release, no "is it current?" gate.** The bundled renderer is stale by definition between releases; the upgrade is the first step, never a comparison that can be skipped. Both sources are the same official binary; pick one:
**GitHub release (canonical):**
```bash
W=$(mktemp -d) && cd "$W"
curl -fsSL https://api.github.com/repos/ApexMarkdown/apex/releases/latest -o rel.json
TAG=$(python3 -c 'import json;print(json.load(open("rel.json"))["tag_name"])') # v1.1.NN
V=${TAG#v}
curl -fsSLO "https://github.com/ApexMarkdown/apex/releases/download/$TAG/apex-$V-macos-universal.tar.gz"{,.sha256}
awk '{print $1}' apex-$V-macos-universal.tar.gz.sha256 | shasum -a 256 -c - # must print OK — stop otherwise
tar xzf apex-$V-macos-universal.tar.gz
SRC=apex-$V-macos-universal/apex
```
**Homebrew (fallback only — the formula lags GitHub by days; on 0.1.1's cut day it still carried 1.1.58):**
```bash
brew update && brew upgrade apex
SRC=$(brew --prefix)/bin/apex # a symlink; lipo reads through it
```
Either way `lipo -info "$SRC"` must list `arm64` (GitHub ships x86_64+arm64; Homebrew on Apple Silicon is arm64-only — `lipo -thin` still works on a thin file).
**Then the one recipe (ADR-0011 — 1.1.59 still links libyaml dynamically; the vendored `libyaml.bundle` stays):**
```bash
cd <repo root>
SIGNER="Developer ID Application: Alexander Kucera (3M7APDAAC5)"
lipo "$SRC" -thin arm64 -output "$W/apex-arm64"
# strip EVERY rpath the binary carries — list them first and delete each one; a Homebrew build carries $(brew --prefix)/lib instead of the CI paths
otool -l "$W/apex-arm64" | grep -A2 LC_RPATH | grep path
for r in /Users/runner/work/apex/apex/deps/libyaml-universal/lib /usr/local/lib /opt/homebrew/lib "$(brew --prefix)/lib"; do
install_name_tool -delete_rpath "$r" "$W/apex-arm64" 2>/dev/null || true # absent paths are fine to skip; the Done-check catches a survivor
done
install_name_tool -add_rpath '@executable_path/../Resources/libyaml.bundle' "$W/apex-arm64"
codesign -f -s "$SIGNER" --options runtime --timestamp "$W/apex-arm64"
# PROVE it in the shipped layout before it touches the tree
mkdir -p "$W/proof/Resources/libyaml.bundle" && cp "$W/apex-arm64" "$W/proof/Resources/apex" \
&& cp Museion/Resources/libyaml.bundle/libyaml-0.2.dylib "$W/proof/Resources/libyaml.bundle/"
"$W/proof/Resources/apex" --version
printf -- '- a\n\n1. one\n' | "$W/proof/Resources/apex" --no-mixed-lists # two lists, <ul> then <ol> — never one merged <ul>
cp "$W/apex-arm64" Museion/Resources/apex
```
Bump `## apex X.Y.Z` + the `vX.Y.Z` prose in `Museion/Resources/THIRD-PARTY-NOTICES.md`; add a `### Changed` → `- **reading:**` line under the release heading in `CHANGELOG.md`. Done when `otool -l Museion/Resources/apex | grep -A2 LC_RPATH | grep path` prints exactly `@executable_path/../Resources/libyaml.bundle`, `codesign -dvv` shows `flags=0x10000(runtime)` + the Developer ID authority, `Museion/Resources/apex --version` prints the new version, and `--no-mixed-lists` appears in `--help` (ADR-0011's load-bearing flag). If a future apex links libyaml statically (asked upstream), drop the rpath/codesign dylib steps and the `.bundle`, and update this skill. An upgrade found after tagging costs a second rail run and a second notarization.
2. **Bump.** Patch for a bug-fix cut (`X.Y.0` → `X.Y.1`), minor for a feature cut (`X.Y.1` → `X.Y+1.0`) — `MARKETING_VERSION` on every target and configuration in `Museion.xcodeproj/project.pbxproj`; `CURRENT_PROJECT_VERSION` stays. Read back: `xcodebuild -project Museion.xcodeproj -scheme Museion -configuration Release -destination 'platform=macOS,arch=arm64' -showBuildSettings | awk -F'= ' '/MARKETING_VERSION = /'`. Done when it prints the new version.
3. **Changelog heading.** `## [X.Y.Z] - YYYY-MM-DD` over the former `[Unreleased]` entries, a fresh empty `[Unreleased]` above, one pointer line to the notes (`CHANGELOG.md` follows Common Changelog). Done when every entry since the last tag sits under the heading.
4. **Release notes** — `docs/releases/X.Y.Z.md`, the CHANGELOG section distilled for humans: what is in it (grouped highlights), the milestones it closes, install, known limits, numbers. Shape precedent: `docs/releases/0.1.0.md`. Written from the shipped surface — every claim traces to a CHANGELOG entry or to source.
5. **README matches what shipped:** install copy, requirements, license pointer; the minimum macOS from `MACOSX_DEPLOYMENT_TARGET`, never from prose.
6. **Verify rail on the tree you will tag.** `./scripts/full-test.sh start`, poll `./scripts/full-test.sh status` (exit 3 = live), counts from `./scripts/full-test.sh summary`. Done when executed == passed == the baseline and the run directory is newer than the last edit. Then `swiftformat . && swiftlint .` clean, and `shellcheck scripts/release.sh` when the script changed.
7. **Commit in slices, then tag.** `docs(readme)` · `build(release)` (tooling + notes + DOX) · `chore(release)` (bump + changelog heading) · later fixes as `fix(scope)`. Plain prose bodies, no trailers. Tag: `git tag -a vX.Y.Z -m "Museion X.Y.Z — <one line>"` on the commit whose tree the DMG is built from. A fix found after tagging: commit it, then `git tag -f vX.Y.Z <fix commit>` while the tag is still local. Done when `git describe --tags --exact-match HEAD` prints the tag and the tree is clean.
8. **Build and prove the DMG.** `./scripts/release.sh` — refuses without the identity, reads the version from build settings, writes `dist/Museion-X.Y.Z.dmg`, and ends with `spctl` → `accepted, source=Notarized Developer ID`. Then mount the image and run `Contents/Resources/apex --version` from it, `xcrun stapler validate dist/Museion-X.Y.Z.dmg`, and record `shasum -a 256 dist/Museion-X.Y.Z.dmg`. Done when all four pass and the sha256 is in the report.
9. **Handoff gate.** Report the tag commit, the sha256, and what changed. Push and the forge release happen on Alexander's go.
10. **On go — push, release, verify.**
```bash
git push origin main vX.Y.Z
{ cat docs/releases/X.Y.Z.md; printf '\n\n[Generated by AI]\n'; } > "$TMPDIR/notes.md" # house rule: the AI marker closes every tea body
tea releases create --tag vX.Y.Z --target <tag-commit-sha> -t "Museion X.Y.Z" -f "$TMPDIR/notes.md" -a ./dist/Museion-X.Y.Z.dmg
tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'
```
Done when the API shows `draft: false`, one asset at the local byte size, and a token-authenticated download of the asset sha256-matches the local file.
11. **Micro.blog announcement — a DRAFT, never a publish.** The post goes to Micro.blog as `post-status: draft` so Alexander reviews and publishes it himself (the `preview` link lands in the report). Token: a Micro.blog **App Token** (Account → App Tokens) stored ONCE in the login keychain under its own service — never the app's production slot (`com.babylondreams.Museion.micropub`, account `micro.blog` — that is the app's live credential, see MuseionTests/AGENTS.md), never a file in the repo:
```bash
security add-generic-password -U -a micro.blog -s com.babylondreams.Museion.release-announce -w '<app token>' </dev/null
```
(The `</dev/null` is load-bearing: without it `security` prompts for a retype.) Then:
```bash
TOK=$(security find-generic-password -a micro.blog -s com.babylondreams.Museion.release-announce -w)
curl -sS -H "Authorization: Bearer $TOK" 'https://micro.blog/micropub?q=config' # read destinations + channels
```
**`mp-destination` is mandatory on this account**: `q=config` lists three microblogs and `microblog-default` is `false` on every one, so a post without it is ambiguous. The main blog is `https://AlexKucera.micro.blog/` (name `alexanderkucera.com`); the other two are a tweets cross-post and a test blog. Article posts take `mp-channel: default` (the `channels` list: `default` = Posts, `pages` = Pages). Post:
```bash
python3 - "$TOK" <<'PY'
import json, sys, urllib.request
tok = sys.argv[1]
payload = {"type": ["h-entry"], "properties": {
"name": ["Museion X.Y.Z"],
"content": ["<the announcement, markdown>"],
"post-status": ["draft"],
"mp-destination": ["https://AlexKucera.micro.blog/"],
"mp-channel": ["default"]}}
req = urllib.request.Request("https://micro.blog/micropub", data=json.dumps(payload).encode(),
headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=30) as r:
print(r.status, r.headers.get("Location"), r.read().decode())
PY
```
Body: `docs/releases/X.Y.Z.md` is too long for a microblog post — distill it to a short announcement (what was fixed in plain words, the download link, the release-page link, "Developer ID signed and notarized"). A draft does NOT syndicate, so the `syndicate-to` targets in `q=config` (Mastodon/Bluesky/Threads) are not touched until Alexander publishes. Read back before reporting: `GET '/micropub?q=source&url=<Location>'` must show `post-status: draft` and the content intact — a 2xx alone is not a result. Done when the read-back says draft and the report carries the `url` (the post's final address) and the `preview` link. `preview` is display-only — never the publish/update target. A token pasted into chat is in the transcript: recommend rotation after the run.
12. **Buy Me a Coffee announcement — a DRAFT, never a publish.** The step-11 announcement as a BMC post, left for Alexander to publish. The mechanics (Ego Browser, the `scripts/bmc.js` driver, selectors, pitfalls) live in the `buymeacoffee-post` skill; the release only fixes the `INPUT`:
```js
action: "create", mode: "draft", audience: "public",
title: "Museion X.Y.Z",
html: <the step-11 announcement as HTML>,
```
Done when `RESULT.mode` is `"draft"` and `RESULT.editUrl` is a `https://buymeacoffee.com/posts/<id>/edit` URL — the script prints `null` when the drafts list does not show the row, and that is not done. The edit URL goes in the report beside the Micro.blog `preview` link.
13. **Session log + DOX.** `write-log` for the release; the devlog commit follows the tag (the log is the record about the release, not part of it). DOX pass: root `AGENTS.md` (commands block, scripts index, session-log window) and `docs/AGENTS.md`. The log commit rides the next go.
## Quick Reference
- apex: GitHub `releases/latest` → `.sha256` → `lipo -thin arm64 -output` → strip ALL rpaths → add `@executable_path/../Resources/libyaml.bundle` → `codesign --options runtime` → prove in a scratch `Resources/` layout → copy into `Museion/Resources/apex` + bump `THIRD-PARTY-NOTICES.md`. Every release, first. (Homebrew lags GitHub — fallback only.)
- Version: `xcodebuild -showBuildSettings … | awk '/MARKETING_VERSION = /'`
- Rail: `./scripts/full-test.sh start` · `status` · `summary`
- Lint: `swiftformat . && swiftlint .`
- Tag: `git tag -a vX.Y.Z -m "Museion X.Y.Z — <one line>"` · move while local: `git tag -f vX.Y.Z <sha>`
- DMG: `./scripts/release.sh` → `dist/Museion-X.Y.Z.dmg` (`NOTARIZE=0` skips notarize + staple)
- Gatekeeper: `spctl -a -t open --context context:primary-signature -v dist/Museion-X.Y.Z.dmg`
- Push: `git push origin main vX.Y.Z`
- Release: `tea releases create --tag vX.Y.Z --target <sha> -t "Museion X.Y.Z" -f <notes> -a ./dist/Museion-X.Y.Z.dmg`
- Read back: `tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'` (Gitea spells it `tag_name`, not `tag`)
- Micro.blog: `POST https://micro.blog/micropub` JSON `h-entry` + `post-status: draft` + `mp-destination` (mandatory — no default blog) + `mp-channel: default` → `202` + `Location`; read back `q=source&url=…` → `post-status: draft`. Token: Keychain service `com.babylondreams.Museion.release-announce`. Never publish.
- Buy Me a Coffee: `buymeacoffee-post` → `create` + `mode: "draft"` + `audience: "public"` → `RESULT.editUrl` into the report. Never publish.
## Pitfalls
- `release.sh` packages whatever `MARKETING_VERSION` says, from the current tree — it bumps and tags nothing.
- The old "compare `--version`, upgrade if stale" step read as optional and got skipped by habit — the refresh is unconditional. A `brew upgrade apex` that prints "already up-to-date" proves nothing: the formula can trail the GitHub release by days (it did on the 0.1.1 cut). GitHub `releases/latest` is the version of record.
- `install_name_tool -delete_rpath` fails loudly on a path the binary does not carry — list the rpaths with `otool -l` first and delete exactly those; the Homebrew build carries `$(brew --prefix)/lib`, the GitHub build the three CI/Homebrew paths. The Done-check (exactly ONE rpath left) catches a survivor before the rail, where `release.sh` would only catch a missing dylib.
- A `cp` over the signed `Resources/apex` must happen AFTER the scratch-layout proof — a binary that fails `--no-mixed-lists` in scratch has already touched nothing.
- A green `full-test.sh status` read right after a resource-only edit can be the PREVIOUS run's summary. Compare run-directory timestamps; zero `SwiftCompile` lines is normal then, and freshness is the `CpResource` line for the changed file plus running it from the test host's built bundle.
- A DMG built before the last binary or script change is stale: rebuild, re-notarize, and the sha256 in the report is the one that ships.
- The tag moves only while local; after the push a fix is a new version.
- `tea releases create` takes the tag via `--tag` OR the positional — both is "ambiguous arguments". `@file` bodies work only on `tea api`; releases take `-f <file>`.
- The release asset download 404s without a token (private repo). Read the token from `~/Library/Application Support/tea/config.yml` into a shell variable for the `curl` — never print it. `grep -E '^\s*token:'` + `sed` is enough; PyYAML is not installed on the system python.
- `tea releases create` prints NOTHING on success (exit 0, empty output). The `tea api` read-back is the only proof — and Gitea's release JSON has `tag_name`, not GitHub's `tag`.
- `security add-generic-password -w <value>` without `</dev/null` prompts for a retype and fails with "passwords don't match" when stdin is not a tty; the item is NOT stored and the next read returns 0 chars. Always `</dev/null`, always read the length back.
- A Micro.blog post without `mp-destination` is a gamble on this account — `q=config` shows three microblogs and none is `microblog-default`. Read `q=config` before every announcement; the destination set can change.
- `q=source&url=…` read-back does not echo `mp-destination` or `mp-channel`; the post's `Location` host (`alexanderkucera.com`) is the evidence the destination took.
- `core.hooksPath=scripts/hooks`: the pre-push hook is the lint gate; the rail is yours to run before tagging.
- A dylib dropped into a synced Resources folder gets linked into the app by Xcode's classifier; vendored libraries ride a `.bundle` folder (ADR-0011).
## Verification
`tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'` → `draft: false`, one asset whose downloaded sha256 equals `shasum -a 256 dist/Museion-X.Y.Z.dmg`; `spctl -a -t open --context context:primary-signature -v dist/Museion-X.Y.Z.dmg` → `accepted, source=Notarized Developer ID`. Micro.blog: `GET https://micro.blog/micropub?q=source&url=<Location>` → `post-status: draft`, content intact. Buy Me a Coffee: `RESULT.mode: "draft"` + `RESULT.editUrl` in the report. Both drafts sit in Alexander's queues awaiting his publish.
+3
View File
@@ -1,9 +1,12 @@
.build/
.swiftpm/
DerivedData/
_build/
dist/
**/xcuserdata/
.DS_Store
CLAUDE.md
.claude/
*.profraw
.secrets
.hermes
+3
View File
@@ -0,0 +1,3 @@
{
"buildPath": "code"
}
+288
View File
@@ -0,0 +1,288 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-11T15:32:43Z",
"title": "Design System: Museion",
"extensions": {
"colorMeta": {
"terracotta-seal": {
"role": "primary",
"displayName": "Terracotta Seal",
"canonical": "#C96442",
"tonalRamp": [
"#382018",
"#683726",
"#984d34",
"#c86442",
"#d3876d",
"#ddab9a",
"#e7cfc6",
"#f2f2f2"
]
},
"pine": {
"role": "semantic",
"displayName": "Pine",
"canonical": "#36664F",
"tonalRamp": [
"#143023",
"#29523e",
"#45705b",
"#6a897a",
"#8fa198",
"#b4bab7",
"#d5d5d5",
"#f2f2f2"
]
},
"field-paper": {
"role": "neutral",
"displayName": "Field Paper",
"canonical": "#FAF9F3",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9a",
"#b9b8b6",
"#d6d5d1",
"#f4f3ed"
]
},
"page": {
"role": "neutral",
"displayName": "Page",
"canonical": "#FFFEFB",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9a",
"#b8b8b7",
"#d6d5d3",
"#f3f2f0"
]
},
"iron-gall-ink": {
"role": "neutral",
"displayName": "Iron-Gall Ink",
"canonical": "#1A1916",
"tonalRamp": [
"#272624",
"#444342",
"#61615f",
"#7e7e7d",
"#9b9b9b",
"#b8b8b8",
"#d5d5d5",
"#f2f2f2"
]
},
"faded-ink": {
"role": "neutral",
"displayName": "Faded Ink",
"canonical": "#6B6964",
"tonalRamp": [
"#272624",
"#454340",
"#62615c",
"#7f7e7a",
"#9c9b98",
"#b9b8b6",
"#d5d5d5",
"#f2f2f2"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"canonical": "#E8E5DF",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7d",
"#9c9b99",
"#bab8b4",
"#d8d5d0",
"#f5f2ed"
]
},
"substrate": {
"role": "neutral",
"displayName": "Substrate",
"canonical": "#F5F5F7",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9b",
"#b8b8b9",
"#d5d5d6",
"#f2f2f4"
]
},
"reading-ink": {
"role": "neutral",
"displayName": "Reading Ink",
"canonical": "#1D1D1F"
},
"reading-secondary": {
"role": "neutral",
"displayName": "Reading Secondary",
"canonical": "#48484D"
},
"reading-muted": {
"role": "neutral",
"displayName": "Reading Muted",
"canonical": "#6E6E73"
},
"reading-hairline": {
"role": "neutral",
"displayName": "Reading Hairline",
"canonical": "#D2D2D7"
},
"reading-rule": {
"role": "neutral",
"displayName": "Reading Rule",
"canonical": "#A1A1A6"
}
},
"shadows": [
{
"name": "panel-float",
"value": "0 14px 36px rgba(26,25,22,0.14)",
"purpose": "Floating palettes and popover cards (Fix Cards palette)."
},
{
"name": "overlay-lift",
"value": "0 24px 80px rgba(26,25,22,0.18)",
"purpose": "Modal overlays and large floating surfaces."
}
],
"breakpoints": [
{
"name": "collapse-mentor",
"value": "920px",
"purpose": "Window width below which the mentor column hides."
},
{
"name": "collapse-library",
"value": "1100px",
"purpose": "Window width below which the library column hides."
}
]
},
"components": [
{
"name": "Nav Rail",
"kind": "nav",
"refersTo": "nav-rail",
"description": "The desk's spine: 56px icon rail on Field Paper with the engine-status pill at the foot.",
"html": "<nav class=\"ds-nav-rail\"><button class=\"ds-nav-item ds-active\" aria-label=\"Posts\"><svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\"><rect x=\"2\" y=\"3\" width=\"14\" height=\"12\" rx=\"2\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"M5 7h8M5 10h5\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg></button><button class=\"ds-nav-item\" aria-label=\"Sessions\"><svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\"><path d=\"M3 4.5C3 3.7 3.7 3 4.5 3h9C14.3 3 15 3.7 15 4.5v7c0 .8-.7 1.5-1.5 1.5h-9C3.7 13 3 12.3 3 11.5v-7z\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"M6 15h6\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg></button><div class=\"ds-nav-spacer\"></div><div class=\"ds-nav-pill\"><span class=\"ds-nav-dot\"></span>ready</div></nav>",
"css": ".ds-nav-rail { display: flex; flex-direction: column; align-items: center; gap: 6px; width: 56px; padding: 14px 0; background: #FAF9F3; border-right: 1px solid #E8E5DF; } .ds-nav-item { display: flex; align-items: center; justify-content: center; width: 38px; height: 38px; border: none; border-radius: 10px; background: transparent; color: #6B6964; cursor: pointer; } .ds-nav-item:hover { background: rgba(26,25,22,0.05); } .ds-nav-item:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: 1px; } .ds-nav-item.ds-active { background: #FFFEFB; color: #1A1916; } .ds-nav-spacer { flex: 1; } .ds-nav-pill { display: flex; align-items: center; gap: 5px; padding: 4px 8px; border-radius: 12px; background: #FFFEFB; border: 1px solid #E8E5DF; color: #6B6964; font-family: -apple-system, system-ui, sans-serif; font-size: 10px; } .ds-nav-dot { width: 6px; height: 6px; border-radius: 50%; background: #36664F; }"
},
{
"name": "Library Post Row",
"kind": "custom",
"refersTo": "library-column",
"description": "Library row: 2px leading state strip, ink title, faded metadata, hover tint.",
"html": "<div class=\"ds-library-row\" tabindex=\"0\"><span class=\"ds-row-strip\"></span><div class=\"ds-row-body\"><div class=\"ds-row-title\">The expected value of showing</div><div class=\"ds-row-meta\">Pass-1 Done · 6 min</div></div></div>",
"css": ".ds-library-row { display: flex; align-items: stretch; gap: 10px; padding: 8px 12px 8px 0; border-radius: 10px; cursor: default; } .ds-library-row:hover { background: rgba(26,25,22,0.04); } .ds-library-row:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: -2px; } .ds-row-strip { width: 2px; border-radius: 1px; background: #6B6964; } .ds-row-body { min-width: 0; } .ds-row-title { font-family: -apple-system, system-ui, sans-serif; font-size: 13px; color: #1A1916; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .ds-row-meta { font-family: -apple-system, system-ui, sans-serif; font-size: 11px; color: #6B6964; margin-top: 2px; }"
},
{
"name": "Fix Card",
"kind": "card",
"refersTo": "fix-card",
"description": "The critique made visible: problem → diagnostic → fix on the Page color; Apply is ask-before.",
"html": "<article class=\"ds-fix-card\"><header class=\"ds-card-head\"><span class=\"ds-card-chip\">structure</span><span class=\"ds-card-chip ds-chip-quiet\">engine</span></header><h4 class=\"ds-card-pattern\">Buried thesis</h4><p class=\"ds-card-problem\">The argument arrives in paragraph four; the reader has already guessed a different essay.</p><p class=\"ds-card-diagnostic\">Could a reader state the claim after the first paragraph?</p><p class=\"ds-card-fix\">Move the thesis to the opening; demote its current paragraph to support.</p><div class=\"ds-card-actions\"><button class=\"ds-card-apply\">Apply…</button><button class=\"ds-card-skip\">Skip</button></div></article>",
"css": ".ds-fix-card { background: #FFFEFB; border: 1px solid #E8E5DF; border-radius: 10px; padding: 16px; box-shadow: 0 14px 36px rgba(26,25,22,0.14); max-width: 340px; } .ds-card-head { display: flex; gap: 6px; margin-bottom: 10px; } .ds-card-chip { font-family: -apple-system, system-ui, sans-serif; font-size: 10px; color: #6B6964; border: 1px solid #E8E5DF; border-radius: 6px; padding: 1px 6px; } .ds-chip-quiet { border-style: dashed; } .ds-card-pattern { font-family: -apple-system, system-ui, sans-serif; font-size: 13px; font-weight: 600; color: #1A1916; margin: 0 0 6px; } .ds-card-problem, .ds-card-diagnostic, .ds-card-fix { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; line-height: 1.5; margin: 0 0 6px; color: #1A1916; } .ds-card-diagnostic { color: #6B6964; font-style: italic; } .ds-card-actions { display: flex; gap: 8px; margin-top: 10px; } .ds-card-apply { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; color: #C96442; background: transparent; border: 1px solid rgba(201,100,66,0.45); border-radius: 8px; padding: 4px 12px; cursor: pointer; } .ds-card-apply:hover { background: rgba(201,100,66,0.08); } .ds-card-apply:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: 1px; } .ds-card-skip { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; color: #6B6964; background: transparent; border: none; border-radius: 8px; padding: 4px 8px; cursor: pointer; } .ds-card-skip:hover { color: #1A1916; }"
},
{
"name": "Mentor Header",
"kind": "custom",
"refersTo": "mentor-column",
"description": "Serif mentor title with the Pine ready dot and lowercase status.",
"html": "<header class=\"ds-mentor-head\"><h3 class=\"ds-mentor-title\">Mentor</h3><span class=\"ds-mentor-status\"><span class=\"ds-mentor-dot\"></span>ready</span></header>",
"css": ".ds-mentor-head { display: flex; align-items: baseline; gap: 10px; padding: 14px 16px; border-bottom: 1px solid #E8E5DF; } .ds-mentor-title { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 17px; font-weight: 400; color: #1A1916; margin: 0; } .ds-mentor-status { display: inline-flex; align-items: center; gap: 5px; font-family: -apple-system, system-ui, sans-serif; font-size: 11px; color: #6B6964; } .ds-mentor-dot { width: 7px; height: 7px; border-radius: 50%; background: #36664F; }"
},
{
"name": "Editor Page",
"kind": "custom",
"refersTo": "editor-page",
"description": "The Page-colored writing surface: serif body on the 66ch measure.",
"html": "<div class=\"ds-editor-page\"><h1 class=\"ds-doc-title\">The expected value of showing</h1><p class=\"ds-doc-body\">The workshop answer is to show the work. The honest answer is that showing is a wager: you pay in attention you could have spent elsewhere, and the payout is a reader who stays.</p><p class=\"ds-doc-body\">What follows is an accounting of that wager.</p></div>",
"css": ".ds-editor-page { background: #FFFEFB; max-width: 66ch; margin: 0 auto; padding: 24px; } .ds-doc-title { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 22px; font-weight: 400; color: #1A1916; margin: 0 0 16px; line-height: 1.15; } .ds-doc-body { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 17px; line-height: 1.8; color: #1A1916; margin: 17px 0 0; }"
},
{
"name": "Code Panel",
"kind": "custom",
"refersTo": "code-panel",
"description": "Recessed well for code: Substrate ground, mono 14/1.5.",
"html": "<pre class=\"ds-code-panel\"><code>measure = 66ch\npadding = 24px</code></pre>",
"css": ".ds-code-panel { background: #F5F5F7; border-radius: 8px; padding: 14px 16px; margin: 17px 0 0; font-family: ui-monospace, Menlo, monospace; font-size: 14px; line-height: 1.5; color: #1A1916; white-space: pre-wrap; }"
}
],
"narrative": {
"northStar": "The Scholar's Desk",
"overview": "Museion is one writer's private study rendered in software: warm paper, iron-gall ink, a single enameled accent. The world is two papers — Field Paper for the desk's chrome (rails, pane grounds, the focus field) and Page for everything that is the document (the editor's ground, reading, cards, transcript bubbles). They differ by three points of warmth; that difference is the whole depth system at rest. Hairlines structure, ink speaks, and the Terracotta Seal appears the way a wax seal does on a letter — rarely, and meaningfully.\n\nThe document's voice is serif (Valkyrie OT B for prose, Concourse OT for headings, UbuntuMono for code); the chrome's voice is the platform's system sans, quiet and small. Nothing else gets a personality. The mentor is present but paper-toned — critique arrives as Fix Cards on the same Page color as the writing, never as toasts or chrome-noise. Light-only by design: one palette, live-calibrated with the owner, deliberately departed from the flatter single-surface export palette (#89). Motion is the platform default — nothing is authored, nothing performs.\n\nConfirmed visual anti-references: the sans heading face titling the document (rejected — chrome disconnected from the serif document; the title speaks the document's own voice), and dark mode (the world is one light palette).",
"keyCharacteristics": [
"Two warm papers, never more: Field Paper chrome, Page content",
"Serif document voice on a 66-character measure; system sans chrome",
"One accent (Terracotta Seal) used sparingly; one semantic green with a fixed meaning",
"Flat at rest — hairlines, not shadows; shadows only for floating panels",
"Critique is first-class: cards are content, on the Page color",
"Radius 10 world, light-only, macOS-native controls"
],
"rules": [
{
"name": "The Two-Paper Rule",
"body": "Exactly two papers exist: Field Paper for chrome, Page for content. Editing, reading, and cards share the Page — a third surface color may never be introduced.",
"section": "colors"
},
{
"name": "The One Seal Rule",
"body": "Terracotta Seal is the only accent. If a second hue is needed, the design is wrong.",
"section": "colors"
},
{
"name": "The Meaning-Green Rule",
"body": "Pine appears exclusively as the engine-ready dot. Using it as decoration, success styling, or a second accent is a violation of its meaning.",
"section": "colors"
},
{
"name": "The Document Speaks Serif Rule",
"body": "Anything that is content — the piece, the transcript's agent turns, the document title — wears the serif voice. The sans face titles nothing the writer wrote.",
"section": "typography"
},
{
"name": "The One Measure Rule",
"body": "Prose sets on the 66-character measure (24px side padding). The editor and reading mode agree on it; editing sizes mirror reading.css exactly (px → pt 1:1).",
"section": "typography"
},
{
"name": "The Floating-Panel Rule",
"body": "Shadows belong only to surfaces that float above the desk (palettes, overlays, sheets). Resting chrome never casts one; focus chrome hovers over the measure without pushing it.",
"section": "elevation"
}
],
"dos": [
"Do keep editing, reading, and cards on the same Page color — the Two-Paper Rule is the depth system.",
"Do set anything the writer wrote or the mentor said in the serif voice.",
"Do hold prose to the 66ch measure with 24px side padding.",
"Do keep critique first-class: Fix Cards are content surfaces, rendered and interacted with like the document itself.",
"Do structure with 1px hairlines at rest; reserve the two float shadows for floating surfaces only.",
"Do mirror reading.css values exactly when touching editing typography (px → pt 1:1 at 1×)."
],
"donts": [
"Don't add a dark mode or theme variants — the world is one light palette, live-calibrated.",
"Don't use Pine anywhere but the engine-ready dot — it is a meaning, not a style.",
"Don't introduce a second accent color, gradients, or colored washes; Terracotta Seal is the only hue that isn't paper or ink.",
"Don't put shadows on resting chrome.",
"Don't set a document title or content in the sans face — that was tried and rejected as chrome disconnected from the document.",
"Don't flatten domain modules into generic cards or framework-default styling; the export's geometry and states are the contract."
]
}
}
+1
View File
@@ -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)
+7
View File
@@ -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
+36 -64
View File
@@ -4,7 +4,7 @@
Museion — the Agentic Writing Environment (AWE): a native SwiftUI macOS app where scholars, texts, and AI minds work under a single roof. Named for the Mouseion of Alexandria.
- **Stack**: native Xcode project (`Museion.xcodeproj` at repo root, filesystem-synchronized groups — disk is truth). SwiftUI on macOS 26.5+, latest Xcode/Swift only (ADR-0001). Swift language mode 6 with default MainActor isolation, tabs.
- **Stack**: native Xcode project (`Museion.xcodeproj` at repo root, filesystem-synchronized groups — disk is truth). SwiftUI on macOS 27+ (`MACOSX_DEPLOYMENT_TARGET = 27.0`, Apple Silicon only), latest Xcode/Swift only (ADR-0001). Swift language mode 6 with default MainActor isolation, tabs.
- **Forge**: Gitea @ git.babylondreams.de (`tea` CLI), CI via Gitea Actions (ADR-0003) — needs a self-hosted macOS runner.
- **License**: GPL-3.0-or-later (ADR-0002).
@@ -14,8 +14,13 @@ 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)
./scripts/release.sh # release packaging: Developer ID export → notarized DMG in dist/ (refuses without the cert)
```
# DOX framework
@@ -109,6 +114,8 @@ 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/release-packaging scripts — contracts live in each script's header; full-test.sh is the sanctioned verify rail (#190), release.sh cuts the DMG from an already-bumped commit, no child doc |
| `.agents/skills/` | Project-local agent skills (cross-tool convention, committed) — `release/`: the end-to-end release runbook (apex refresh → bump → notes → rail → tag → DMG → go-gated push + Gitea release → Micro.blog + Buy Me a Coffee announcements as drafts); 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 |
@@ -127,64 +134,27 @@ Default five canonical roles, label string = role name. See `docs/agents/triage-
Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/domain.md`.
<!-- gitnexus:start -->
# 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.
> 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).
## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "main"})`.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method without first running `impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/museion/context` | Codebase overview, check index freshness |
| `gitnexus://repo/museion/clusters` | All functional areas |
| `gitnexus://repo/museion/processes` | All execution flows |
| `gitnexus://repo/museion/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
## Project Learnings
<!-- distill-learnings: project-learnings -->
### 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/<remote>/<branch>` 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.
- macOS 27.2 (verified on 27.2.1) routes a drag to the DEEPEST destination — a LIVE NSTextView registers itself for drag types (a bare `NSTextView(frame:)` reads `registeredDraggedTypes == []`, so a standalone probe lies; lldb on the running app shows the list), matches Finder drags via `NSFilenamesPboardType`, and its stock `performDragOperation` pastes the file path; the window-level SwiftUI `.dropDestination` never fires over it — the inverse of the 27.0.1 ruling #141 was verified on. Drag routing is an OS-version claim: own the drop at the view (override the `NSDraggingDestination` methods without super) and re-dogfood after every OS point release; instrumented real handlers + one human drag settle which destination fires (#141 follow-up, 2026-12-03)
- A pin that drives a seam introduced WITH the fix has no broken-build past to fail on — drive the framework entry point itself (`DragInfoStub` for `NSDraggingDestination`, the scripted transport for the ACP wire), or the pin passes with the fix reverted (#141 follow-up, `image-drop-27-2-drag-routing-pastes-path`)
- 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)
- A subscript after a count expectation (`log.requests[2]` after `#expect(count == 3)`) traps the hosted runner — every queued test reports `Crash:` too; read elements through an optional accessor (#206)
- 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 <file>` check of the pure logic still verify honestly (#134)
@@ -196,10 +166,12 @@ This project is indexed by GitNexus as **museion** (6864 symbols, 33665 relation
- A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147)
- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180)
- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181)
- `value of type 'X' has no member` while the emitted module DOES carry the symbol is a spelling drift between targets, not a stale build — grep the exact name across app AND tests before hunting binaries: a fresh test file's `microblogStatus` against the code's `micropubStatus` reads exactly like the stale-binary signature above and cost a DerivedData dive (#206)
### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33)
- A format gate is not an ownership gate — when a change raises a sink's stakes (status flip → content replace), re-ask who may write the value, not merely whether it is well-formed (#206)
## Session Logs
@@ -208,14 +180,14 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 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) |
<!-- write-log: window-end -->
| 2026-12-04 | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) |
| 2026-12-04 | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) |
| 2026-12-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) |
| 2026-12-03 | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) |
| 2026-12-03 | [20261203-release-012-image-drop-fix_log.md](20261203-release-012-image-drop-fix_log.md) |
| 2026-12-03 | [20261203-image-drop-27-2-drag-routing-pastes-path_log.md](20261203-image-drop-27-2-drag-routing-pastes-path_log.md) |
| 2026-12-03 | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_log.md) |
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) |
| 2026-11-30 | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) |
| 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) |
<!-- write-log: window-end -->
+49
View File
@@ -4,12 +4,61 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
### Added
- **publish:** the library shows where each piece stands on Micro.blog (#206) — a published piece's row reads `published <date>` and its menu opens the live post; a sent-but-unpublished one reads `draft on Micro.blog`. Publish is remembered now (`micropub_published` stamped in the piece's frontmatter — the sheet used to flip the draft and forget, so nothing on disk ever said a piece was out). Sending a piece again no longer duplicates it: a piece that remembers its post updates that post in place (same URL — a draft refreshes for review, a published piece edits live via **Update Live Post**), and an image whose bytes haven't changed rides its earlier upload instead of uploading a second copy (a per-piece `.museion-uploads.json` memo keyed by content hash). When Micro.blog answers 404 — the post was deleted there — the piece forgets the dead link and the sheet offers a fresh draft instead of failing forever. A file brought in by Import carries no Micro.blog memory: its `micropub_url`/`micropub_published` lines are dropped at the boundary, so a file from someone else can never aim a send at one of your existing posts. Pieces published before this build read as drafts until their next Publish (or the `micropub_published` key is added to the frontmatter by hand — `yyyy-MM-dd'T'HH:mm:ss`, local time). The row's micro-label shows the status in origin's place (the 178pt row cannot hold both); VoiceOver reads both.
- **settings:** **Micro.blog** page in Settings — the app token's home (unticketed; owner report 2026-12-04) — the token could only be entered in the publish sheet, and that field came back only after a 401/403, so a saved token had no standing way to be replaced or removed (a 503 left the writer stuck with whatever was stored). The new sidebar destination, after Provider Keys, writes the SAME login-keychain slot the sheet reads (`MicropubTokenStore`): a status row under the field (✓ Token saved in your Keychain / No token saved), a Save field that replaces the stored token, and a Remove button while one is stored. `saved` is read back from the Keychain after every write instead of assumed — a locked keychain fails the save and the status row says so rather than claiming "stored". The publish sheet picks up a Settings-saved token unchanged, and names it when it sends with the stored one (the field's absence alone never said which token a send carried). No new pins (a view over the already-pinned token store; the repo pins pure seams, not SwiftUI). Suite 736
- **library:** **Reveal in Finder** and **Copy Path** on every piece row — the library column's menu and the Archive pane's (#205) — one shared `FinderHandOffButtons` fragment in the workspace chrome over a model-resolved path: `PostsModel.fileURL(for:)` answers the piece's `post.md` through the one `PostStore.folder(of:home:)` resolver against the watched Home (never the scan snapshot), and a vanished piece answers nil so both entries no-op instead of revealing a stale path. Reveal selects the file in Finder; Copy Path puts the POSIX path on the pasteboard (Finder's own form; the pasteboard is cleared first). Library placement sits between Move to Archive and the destructive Trash behind a divider; the Archive menu appends after Convert. +3 tests (projects/ resolve, archive/ resolve, vanished → nil), flip-verified — bypassing the resolver reddens exactly the vanished and archive pins. Suite 735
- **fix cards:** **Jump** on a Fix Card selects the anchor's span in the piece's editor and makes the main window key (#204) — the borderless button sits in every non-stale card's action row (closed cards keep it; a stale anchor has nothing to land on); the span is the card's quote at its 1-based occurrence, resolved against the LIVE session text so a dirty buffer still lands, and it rides the reading flip-back's caret rail (one token counter; a zero-length hint stays a bare caret, a non-zero range selects). A jump leaves reading mode first, writes nothing, and re-fires on every click. Two review rounds closed the view-layer gaps the pure pins could not see: a jump dropped in reading mode, a main window that never became key (`NSApp.activate` is a no-op once the palette's click activated the app), a leading-blank caret hop that moved a span onto the title, and a cursor record taken before the scroll. +3 tests (`anchorRange` occurrence math with a UTF-16 fixture, the model's reveal stamp, the editor's `landingSpan`), all flip-verified. Suite 732
### Fixed
- **publish:** A Micro.blog 5xx names their outage instead of a bare `HTTP 503` (unticketed; owner report 2026-12-04) — their errors arrive as HTML pages, never Micropub JSON, so `decodeFailure` fell through to the status code and the sheet read "Micro.blog said 503: HTTP 503", which says nothing about whose side it is on. A live probe at report time found the endpoint healthy (25/25 tokenless POSTs answered the usual 400; their news feed logs repeated 503 incidents), so the 503 was theirs and transient. The decode now answers `unavailable on their side — retry in a few minutes (status.micro.blog)` for any 5xx that carries no JSON description — ONE decode, so create, publish, q=config, and media uploads all speak it; a described 5xx keeps its description, a 4xx keeps the bare status. +1 test (a 503 over an HTML body → the their-side wording; a 422 over the same body → `HTTP 422`; a 502 with `error_description` → the description), flip-verified — the guard off reddens exactly that pin with `detail → "HTTP 503"`. Suite 736
## [0.1.2] - 2026-12-03
Human-readable notes: [docs/releases/0.1.2.md](docs/releases/0.1.2.md).
### Fixed
- **editor:** Dropping an image file on the prose editor pastes the file path instead of ingesting it (#141 follow-up; macOS 27.2.1 dogfood 2026-12-03; unticketed fix) — #141 was field-verified on 27.0.1, where the window-level SwiftUI `.dropDestination` starved every deeper destination; 27.2 routes a drag to the DEEPEST destination, and a live NSTextView registers itself for drag types (it matches Finder drags through `NSFilenamesPboardType`), so its stock `performDragOperation` → `readSelection` pasted the path and the window destination never fired — the same for a markdown file dropped on the editor (path instead of guest). The editor text views now share a `FileDropTextView` base that owns the drops landing on them: URL-bearing drags route (never `super`) — the prose editor through the one new `AppGateState.routeFileDrop` (Cold Turkey guard → markdown → guest, anything else → `ingestDrop`), which the window destination also uses for drops landing outside the editor (one router, one surface per drag; a landed drop hops to Posts as markdown always did); the outline rows have no route and bounce instead of pasting the path; text-only drags keep the stock drop; URL-less drags bounce. The pasteboard probe is memoized per `changeCount` (a 20k-URL drag measured 137 ms per mouse-move uncached). `ingestDrop` refuses web URLs loudly with the type strip (a browser image drag has no file to copy), and a file that vanished between drag and drop refuses as missing, not as a folder. +9 tests — the drag overrides driven through a real `NSDraggingInfo` mock (a Finder-shaped drag routes and never pastes the path, an unrouted view claims nothing, a text drag keeps the stock drop, raw image data bounces, the probe follows the pasteboard, the outline rows bounce, web URLs and vanished files refuse with the right notice) and the router's own pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal); all 9 flip-verified. Verified with one real Finder drag on 27.2.1. Suite 729
## [0.1.1] - 2026-12-03
Human-readable notes: [docs/releases/0.1.1.md](docs/releases/0.1.1.md).
### Fixed
- **editor:** The external guest's file watch compares normalized text (finding `museion/external-watch-compares-unnormalized-text`, argus cycle-6; unticketed fix, brief-32) — `startExternalWatch`'s onEvent read the disk RAW while the session's `text`/`lastFlushedText` came through `readDocument`'s normalizing external branch (BOM strip + CRLF→LF), so `diskDidChange` raised the #67 conflict whenever the raw bytes differed from BOTH normalized snapshots — which they ALWAYS did for a BOM- or CRLF-carrying file, even with content unchanged. The false alarm blocked departures (select/newPost/newOutline/openExternal) and quit (the #200 gate), and re-armed after every sibling directory event (the watch observes the containing folder) and after either alert answer, until the writer's own flush rewrote the file normalized. The external branch is now the ONE shared read — `EditorSession.readExternalDocument(at:)` (raw UTF-8 → BOM strip → CRLF→LF) — called by both the open read (`readDocument`) and the watch's onEvent, so the #67 compare is normalized-to-normalized; what `readDocument` loads is unchanged (no second normalizer at the compare site, and `diskDidChange` itself is untouched). A real foreign write still raises the alert — the departure gate is not blinded. +3 tests over the real watch closure (`externalWatcher.onEvent`): no conflict on an unchanged BOM/CRLF guest (initially and across sibling events), a real write still conflicts, and no re-arm after either alert answer (yes-reload and keep-local); RED-first 3/3 at the pin (11 executed / 8 passed / 3 failed — the three new pins). Suite 720
### Changed
- **reading:** The bundled apex renderer is 1.1.59 (was 1.1.58) — the arm64 slice of the official universal release tarball, `.sha256` verified, the same single `@executable_path/../Resources/libyaml.bundle` rpath and Developer ID + hardened-runtime signature as the 0.1.0 bundling (ADR-0011 recipe unchanged; 1.1.59 still links libyaml dynamically). `--no-mixed-lists` still present.
## [0.1.0] - 2026-12-01
First release. Human-readable notes: [docs/releases/0.1.0.md](docs/releases/0.1.0.md).
### Fixed
- **reading:** The bundled apex renderer is self-contained and notarizable. apex's release build links libyaml through CI/Homebrew rpaths, so on any Mac without Homebrew it failed to launch and reading mode silently fell back to the raw source — the bundle promised "no install gate" (ADR-0011) and didn't deliver; Apple's notary service also rejects an unsigned Mach-O in Resources, which is how the 0.1.0 release run found it. Now `Resources/apex` is the arm64 slice of apex 1.1.58 (the bundle had shipped 1.1.17), Developer ID–signed with the hardened runtime, with one rpath (`@executable_path/../Resources/libyaml.bundle`) that resolves in the bundle and in the checkout alike; `Resources/libyaml.bundle/libyaml-0.2.dylib` (0.2.5, MIT) rides beside it, same team signature — inside a `.bundle` folder because Xcode's synced-folder classifier silently links a bare dylib into the app. `release.sh` now proves the shipped layout: apex must run from the export and the app must not link libyaml, before anything is notarized. `THIRD-PARTY-NOTICES.md` ships in the bundle.
- **editor:** A Home repoint is a guarded document departure (finding `museion/home-repoint-retains-old-editor-target`, argus cycle-5; unticketed fix, brief-28) — Settings → Choose… committed the new Home and flipped `watchedHome` without departing the open session: the session's immutable target kept the OLD Home, so a same-slug piece in the new library made the ID-only reselect return it (autosave/Save/quit wrote the old library while structural operations resolved against the new one), the new library's rescan raised a spurious reload conflict on it, a no-collision piece was torn down by the vanish path with its dirty buffer dropped, and a card scan from the old library could land on the new library's same-slug piece. #198's departure gate never saw this seam. Now `PostsModel.repoint(to:)` runs the SAME gate (`sessionMayDepart`'s three legs — unanswered conflict, failed flush, never-loaded retype; no parallel gate) BEFORE anything commits: a refusal changes nothing (preference, binding, the session's target and buffer stay; the #198 reason spoken once, the #200 quit-refusal posture, since no Posts strip is in sight from Settings), an acceptance lands the edits on the old library first and clears the departed piece's state — nothing auto-reopens. Document identity is (Home, ID) everywhere (`EditorSession.targets`, `PostsModel.openSessionTargets`): every bare `session.postID ==` comparison is retired across select, the structural rail, conversion, the pass guard, Micropub and the card refresh, and async continuations re-validate identity at COMPLETION (the card-scan hop-back; `rescan`'s stale-Home verdict is hoisted to cover the list, the revision and the #67 text, not just the vanish check). The in-memory draft survives a repoint (no Home until first save). +9 tests over a two-Home same-slug rig (the three refusal legs with ordering pinned, same-slug open + save on flush AND quit, no-collision cleanup, stale card scan via the per-model `scanPieceCards` seam — mutation-checked, pass after repoint; review r1: the hoisted `rescan` stale-Home verdict via the `scanLibrary` seam — mutation-checked — and the draft-survives repoint), RED-first 6/6 at the pin. Suite 717 (unticketed fix, brief-28)
- **editor:** Quit no longer bypasses the document departure gate (#200, follow-up to the #198 audit) — `PostsModel.shutdown()` flushed both sessions best-effort and ignored the results, so quitting with an unanswered reload-conflict alert wrote the local text over the foreign disk body (`flush()` holds for conflicts only in the debounce, never itself), and a failed quit-time flush silently dropped the only copy of the edits. Quit now routes through the same departure gate as navigation (`documentsMayDepart` → `sessionMayDepart`): an unanswered conflict never writes over the foreign body, and the failed-flush-at-quit posture is BLOCK QUIT — `WritingLockAppDelegate.applicationShouldTerminate` refuses termination with one spoken reason (running before the Cold Turkey ask, so a refusal never strands a walked-away block), pinned at the pure `quitReply(posts:)` seam. Finish-audit additions: a never-loaded session's retyped words refuse too (their flush is a vacuous success — the same gap closed for navigation), and the external guest's quit-time flush is pinned. +5 tests, all flip-verified. Suite 708
- **acp:** Engine backpressure can no longer defeat request deadlines, Stop, or teardown (finding `museion/acp-backpressure-defeats-timeout-and-shutdown`, argus cycle-4) — a hung engine that stops reading stdin fills the 64 KB pipe, and the ACP client's synchronous send blocked its ONE serial queue, the same queue carrying request-id allocation, pending registration, the timeout deadline, and close()'s bookkeeping barrier: the deadline never fired (a 0.1 s timeout on a 2 MB prompt stayed pending forever), a follow-up request hung at registration, Stop queued behind the stuck write, and close() synced behind it before SIGTERM was ever reachable — on MainActor (restart/quit) that was an app-wide unbounded hang. Stdin writes (and the stdin handle's own close, which a blocked write may still own) now ride a dedicated serial writer queue, leaving the state queue I/O-free: deadlines fire, Stop is accepted, bookkeeping answers, and close() runs SIGTERM → grace → SIGKILL → reap without queueing behind the writer. Wire order preserved (every send funnels through the one serial writer); healthy-engine contract untouched. +4 real-process smokes over two new zsh-fake modes (`neverRead` execs /bin/sleep — the probe's inert non-reading child, never a real profile; `serverPing` pins -32601 reply delivery): 3 RED-first at base on exactly the three mechanisms, healthy-contract pin green at base. Suite 697 (unticketed fix, brief-27)
- **search:** Library search results no longer go stale after library writes (finding `museion/library-search-stale-after-mutation`, the #144/#157 mounted gap) — the search snapshot's only task identity was the trimmed query, so nothing re-ran the sweep when the library moved underneath it: archiving or trashing a piece from a result row's own context menu left it sitting in the non-archived results after the rescan, and new, renamed, or externally edited pieces never entered or left the results until the query changed or the pane remounted. The #179 write rail's rescan now bumps a content revision whenever a scan sees the library change — a Post-list change OR any re-read post.md, so a body-only edit (which parses to an equal Post and is invisible to #143's equality-gated assignment) counts — and the mounted sweep keys on query + Home + that revision, rendering a landed snapshot only while it stays fresh for the current key (stale rows drop to the recompute spinner; panes never regroup — the assignment skip is untouched). +5 tests (pure key/gate pin; controller-level archive, trash, and same-query body-edit pins over the real rescan rail, red-first; an unchanged-rescan guard). Suite 686
- **session:** a deferred nil scope drains as an explicit clear (PR #184, finding class #176) — `pendingScopePieceTitle: String?` let "a scope request is pending" and "which piece it targets" ride the same optionality, so a nil-target request (the writer leaves the piece mid-stream or mid-replay: New Post, unsaved draft, external guest, nothing open) deferred correctly but at drain time read as "no pending request" and returned without touching `activeEntry` — the old piece's conversation stayed live under a nothing-open context, at all four drain sites. Pending-ness now rides `PendingScope` (`.none` | `.scope(String?)`): a nil target is an explicit clear everywhere it drains. Finish-audit fanout (3 reviewers): dead `Equatable` cut, the same-turn `pendingRestart` ceiling documented at the drain (the scope is lost in respawn's `.starting` window — consume-at-apply is the upgrade path), and the titled-apply half pinned for the first time over a new `hangOnPromptLoad` rig mode (prompt parks, load answers; flip-verified). Suite 654 (PR #184)
### Changed
- **cold-turkey:** Live word accounting leaves the per-keystroke path (unticketed opt pass, argus 2026-11-09, digest finding cold-turkey-full-tokenization) — the editor's `onTextChange` feed drove `WritingGoalRun.update` through `DraftStats.words` for every goal type, and `words` built the complete lowercased token array (`split(whereSeparator:)` + `map(lowercased)`) just to return its count: O(document) allocation and lowercasing per keystroke on the main actor, linear in document size (argus probe: ~0.32/3.07/16.64 ms per update at 1k/10k/50k words) — while minutes goals never read the count (verdict, progress, readout, and the completion note all ride the clock). A minutes run now does no word work on feed at all (its accounting freezes at the arm-time baseline — dead state either way), and `words` is a count-only Character pass over maximal isLetter/isNumber runs: the token array is never built, semantics byte-identical (split with omitted empty subsequences yields exactly the maximal runs; pinned against the old split expression over a mixed-script/emoji/punctuation/number corpus). Arm-time baselines still count once per arm through the same rail, now allocation-free; words-goal net accounting unchanged (exactly one rail trip per update, pinned). +3 tests — RED-first minutes zero-trips pin through an injectable word-rail seam on `update` (per-call counting; a global counter would race the hosted suite's parallel DraftStats calls), the words one-trip skip boundary, and the corpus equivalence proof. Suite 684 (unticketed opt pass)
- **home:** Fresh installs default to iCloud (#171, resolution of #170/map #167 — plain build slice for #145) — with no stored Home override, launch resolves once and PINS the winner so the Home never silently moves: a legacy `~/Documents/Museion` directory wins (existing Homes migrate manually, never silently; a stray plain file is not a Home and falls through), else `<CloudDocs>/Museion` when iCloud Drive is present (dynamically resolved unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path, plain FileManager probing — no ubiquity entitlements per ADR-0009), else the silent Documents fallback. No dialog, no rail pill — Settings just shows the resolved path. Repoint-only stands (ADR-0004), zero mover code. The probe/defaults seam is injectable and default constructions under hosted tests neither probe nor pin — the runner app's real iCloud state and defaults are never touched. +9 tests incl. the flip-verified CloudDocs spelling pin and the non-destructive hosted no-write guard. Suite 628 (issue #171)
- **cold-turkey:** The writing lock (#162, wayfinder map #158 — Build S2; wires #161's goal engine + #160's contract into the app) — Cold Turkey is live: armed from a quiet dot in focus mode's bottom-right corner (hover-labeled) or View ▸ Start Cold Turkey…, the arm-bar carries a chip that blends into the focus ground (ground color, faintest hairline, no shadow — the bare seat let document text show through) with minutes|words selector, ± steppers AND a directly typeable value (parsed and clamped at every read; what you type is what arms — 1…1000 words / 1…60 min, defaults 250/5); Start enters the macOS app-kiosk per the #159 factsheet (7-option presentation combo + fullscreen, the window restored on completion) and the readout follows — numerals + 2px hairline, terracotta inside the last 20%, on the same blending chip. While the block holds: ⌥⌘F/reading/new-buffer paths refused (the open Piece stays the counted one), library + mentor hover zones suppressed (editor-only), ⌘W/⌃⌘F/⌘N swallowed by a key-code-matched monitor (charactersIgnoringModifiers is layout- and Caps-Lock-blind while AppKit menus match the physical key — the audit-caught hole; no .closeItem placement exists and SwiftUI owns the window delegate), and ⌘Q asks once (#163's ruling): "Walk away from the block?" — Walk Away quits cleanly, Keep Writing holds. Typing is never interrupted by the unlock: lock ⇒ focus freezes the view branch under the editor, chrome mounts as overlays only, and the fullscreen round trip preserves the first responder. Completion returns quietly to focus with a fading mono note ("● 250 words · 14:02"). Nothing persists — the block dies with the session. Glossary term landed; +19 tests incl. flip-verified refusal-key, parse-fallback, and canArm-mirror pins; finish-audit fanout (3 reviewers) landed the key-match fix, a ticker-race test seam, chip dedup, and window-capture-on-exit. Suite 620 (issue #162)
+228
View File
@@ -0,0 +1,228 @@
---
name: Museion
description: The Scholar's Desk — warm paper, iron-gall ink, one enameled accent
colors:
terracotta-seal: "#C96442"
pine: "#36664F"
field-paper: "#FAF9F3"
page: "#FFFEFB"
iron-gall-ink: "#1A1916"
faded-ink: "#6B6964"
hairline: "#E8E5DF"
substrate: "#F5F5F7"
reading-ink: "#1D1D1F"
reading-secondary: "#48484D"
reading-muted: "#6E6E73"
reading-hairline: "#D2D2D7"
reading-rule: "#A1A1A6"
typography:
display:
fontFamily: "Valkyrie OT B, Iowan Old Style, Charter, Georgia, serif"
fontSize: "22px"
fontWeight: 400
headline:
fontFamily: "Concourse OT Semibold, Georgia, serif"
fontSize: "30px"
fontWeight: 600
lineHeight: 1.15
title:
fontFamily: "Concourse OT Semibold, Georgia, serif"
fontSize: "22px"
fontWeight: 600
lineHeight: 1.15
subheading:
fontFamily: "Valkyrie OT B, Georgia, serif"
fontSize: "19px"
fontWeight: 700
body:
fontFamily: "Valkyrie OT B, Iowan Old Style, Charter, Georgia, serif"
fontSize: "17px"
fontWeight: 400
lineHeight: 1.8
code:
fontFamily: "UbuntuMono NFM, ui-monospace, monospace"
fontSize: "14px"
lineHeight: 1.5
label:
fontFamily: "-apple-system, system-ui, sans-serif"
rounded:
sm: "8px"
md: "10px"
lg: "12px"
spacing:
list-item: "5px"
branch: "10px"
paragraph: "17px"
page-padding: "24px"
heading-after: "30px"
heading-before: "90px"
components:
nav-rail:
backgroundColor: "{colors.field-paper}"
width: "56px"
library-column:
width: "232px"
mentor-column:
width: "356px"
editor-page:
backgroundColor: "{colors.page}"
width: "66ch"
fix-card:
backgroundColor: "{colors.page}"
textColor: "{colors.iron-gall-ink}"
rounded: "{rounded.md}"
padding: "16px"
code-panel:
backgroundColor: "{colors.substrate}"
rounded: "{rounded.sm}"
padding: "14px 16px"
typography: "{typography.code}"
---
# Design System: Museion
## Overview
**Creative North Star: "The Scholar's Desk"**
Museion is one writer's private study rendered in software: warm paper, iron-gall ink, a single enameled accent. The world is two papers — Field Paper for the desk's chrome (rails, pane grounds, the focus field) and Page for everything that *is* the document (the editor's ground, reading, cards, transcript bubbles). They differ by three points of warmth; that difference is the whole depth system at rest. Hairlines structure, ink speaks, and the Terracotta Seal appears the way a wax seal does on a letter — rarely, and meaningfully.
The document's voice is serif (Valkyrie OT B for prose, Concourse OT for headings, UbuntuMono for code); the chrome's voice is the platform's system sans, quiet and small. Nothing else gets a personality. The mentor is present but paper-toned — critique arrives as Fix Cards on the same Page color as the writing, never as toasts or chrome-noise. Light-only by design: one palette, live-calibrated with the owner, deliberately departed from the flatter single-surface export palette (#89). Motion is the platform default — nothing is authored, nothing performs.
Confirmed visual anti-references: the sans heading face titling the document (rejected — chrome disconnected from the serif document; the title speaks the document's own voice), and dark mode (the world is one light palette).
**Key Characteristics:**
- Two warm papers, never more: Field Paper chrome, Page content
- Serif document voice on a 66-character measure; system sans chrome
- One accent (Terracotta Seal) used sparingly; one semantic green with a fixed meaning
- Flat at rest — hairlines, not shadows; shadows only for floating panels
- Critique is first-class: cards are content, on the Page color
- Radius 10 world, light-only, macOS-native controls
## Colors
A warm paper-and-ink palette: every neutral leans warm, and exactly one accent carries meaning.
### Primary
- **Terracotta Seal** (#C96442): the single accent — enameled copper-terracotta. Interactive emphasis, key actions, focus rings (reading mode's `:focus-visible` outline rides it at 55% opacity). Rare by design.
### Semantic
- **Pine** (#36664F): the mentor's ready dot and nothing else. It means "engine healthy" — a status, never a style color.
### Neutral
- **Field Paper** (#FAF9F3): the desk — workspace root, nav rail, pane chrome grounds, the focus-mode editor ground.
- **Page** (#FFFEFB): the document — editor ground at rest, reading surface, fix cards, transcript bubbles, selected sidebar items.
- **Iron-Gall Ink** (#1A1916): primary text on both papers.
- **Faded Ink** (#6B6964): secondary text, metadata, quiet labels.
- **Hairline** (#E8E5DF): 1px structure — pane separators, card outlines, dividers.
- **Substrate** (#F5F5F7): code panels and recessed wells (reading surface; cooler on purpose — the reading surface has its own cooler ink family below).
- **Reading inks** — Reading Ink #1D1D1F, Reading Secondary #48484D, Reading Muted #6E6E73, Reading Hairline #D2D2D7, Reading Rule #A1A1A6: the reading mode's own slightly cooler micro-palette (reading.css `:root`), used inside the rendered document only.
### Named Rules
**The Two-Paper Rule.** Exactly two papers exist: Field Paper for chrome, Page for content. Editing, reading, and cards share the Page — a third surface color may never be introduced.
**The One Seal Rule.** Terracotta Seal is the only accent. If a second hue is needed, the design is wrong.
**The Meaning-Green Rule.** Pine appears exclusively as the engine-ready dot. Using it as decoration, success styling, or a second accent is a violation of its meaning.
## Typography
**Display Font:** Valkyrie OT B (fallback: Iowan Old Style / Charter / Georgia serif)
**Heading Font:** Concourse OT Semibold (fallback: Georgia serif)
**Body Font:** Valkyrie OT B (fallback: same as display)
**Code Font:** UbuntuMono NFM (fallback: system monospace)
**Chrome/Label Font:** system sans (`-apple-system`)
**Character:** A bookish serif carries everything the writer wrote or the mentor said; a quiet humanist sans carries only the furniture. The pairing is deliberate: the document speaks serif, the desk speaks sans.
### Hierarchy
- **Display** (400, 22px): the open document's title — the serif body face at the h2 rung. Never the sans face.
- **Headline** (600, 30px, 1.15): H1 — Concourse OT Semibold; 90px space before closes the prior section, 30px after.
- **Title** (600, 22px, 1.15): H2 — Concourse OT Semibold.
- **Subheading** (700, 19px): H3 — the serif body face, bold.
- **Body** (400, 17px, 1.8): prose on a 66ch measure; paragraph space 17px; list items 5px apart, branches 10px; blank separators render half-height (9px).
- **Code** (400, 14px, 1.5): inline and fenced, on Substrate panels.
- **Label** (system sans): chrome labels, sentence case; the mentor header's `ready` reads lowercase.
### Named Rules
**The Document Speaks Serif Rule.** Anything that is content — the piece, the transcript's agent turns, the document title — wears the serif voice. The sans face titles nothing the writer wrote.
**The One Measure Rule.** Prose sets on the 66-character measure (24px side padding). The editor and reading mode agree on it; editing sizes mirror reading.css exactly (px → pt 1:1).
## Layout
A fixed four-column workspace: nav rail (56px) | library column (232px) | editor (flexible, 420px min) | mentor column (356px). Columns collapse rather than squeeze — the library hides below 1100px window width, the mentor below 920px — mirroring the export's media queries as pane collapse. Settings runs its own two-column shape: 190px sidebar, detail forms left-anchored with a 480px max width. Reading mode centers the 66ch measure with 24px page padding. The conversation surface wears the editor's typography: Valkyrie for agent turns, Concourse OT Book for the user capsule and composer, UbuntuMono as the quiet mono voice.
## Elevation & Depth
Paper-flat at rest: resting chrome conveys structure with hairlines and the two-paper tonal step, never shadows. Depth is reserved for transient surfaces — the Fix Cards palette (a floating window), overlays, and sheets — which cast the export's two large soft shadows, tinted with ink rather than black.
### Shadow Vocabulary
- **Panel float** (`0 14px 36px rgba(26,25,22,0.14)`): floating palettes and popover cards.
- **Overlay lift** (`0 24px 80px rgba(26,25,22,0.18)`): modal overlays and large floating surfaces.
### Named Rules
**The Floating-Panel Rule.** Shadows belong only to surfaces that float above the desk (palettes, overlays, sheets). Resting chrome never casts one; focus chrome hovers over the measure without pushing it.
## Shapes
A radius-10 world: cards, panels, and interactive containers round at 10px; small controls and reading-surface code/images at 8px; the engine-status pill at 12px. Status dots are full circles. Library rows carry a 2px leading state strip. Borders are 1px hairlines; blockquotes get a 3px rule edge (1.5px for nesting).
## Components
### Navigation Rail
The desk's spine: 56px wide on Field Paper, icon destinations (Posts / Sessions / Learnings / Trends / Archive), the engine-status pill, and Settings at the foot. Icons quiet; the active destination reads by tone, not by a colored block.
### Library Column
232px; project section heads over Pass-State groups, per-view collapse toggle. **Library Post Row**: Page-colored row with a 2px leading strip encoding pass state, `✳` marking outline pieces, title in ink, metadata in Faded Ink; row menu (Rename / Convert / Move / Trash) in the system style. Selected rows fill with Page against the Field Paper ground.
### Editor Page
The Page-colored writing surface: 66ch measure, Valkyrie 17/1.8, autosave. Focus mode repaints the editor's ground to Field Paper — the two papers merge; overlays hover without pushing the measure. Reading mode (⌘R) renders the same Page via the reading pipeline with its own cooler inks.
### Mentor Column
356px; serif header with the engine chip (Pine dot + lowercase `ready`), the shared transcript, and the composer. Agent turns in Valkyrie, user capsule and composer in Concourse OT Book. **PassBar**: Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry their reason inline, the missing-key line links to Settings.
### Fix Cards (signature)
The critique made visible: Page-colored cards, radius 10, hairline border, problem → diagnostic question → fix, with lane and emitter chips and anchored quote. They live in a floating palette window (open cards first) and Apply is ask-before — a blocking sheet shows the exact edit. Never a toast, never auto-applied, never batch.
### Code Panel
Substrate ground, radius 8, 14px/1.5 UbuntuMono, 14px 16px padding. Fenced blocks in the document and code anywhere it appears.
### Sheets
The house ask sheets (Origin ask, Outline guard, Convert, New Project) ride the platform sheet with Page grounds and left-anchored forms — one decision per sheet, refusal keeps buttons visible.
## Do's and Don'ts
### Do:
- **Do** keep editing, reading, and cards on the same Page color — the Two-Paper Rule is the depth system.
- **Do** set anything the writer wrote or the mentor said in the serif voice.
- **Do** hold prose to the 66ch measure with 24px side padding.
- **Do** keep critique first-class: Fix Cards are content surfaces, rendered and interacted with like the document itself.
- **Do** structure with 1px hairlines at rest; reserve the two float shadows for floating surfaces only.
- **Do** mirror reading.css values exactly when touching editing typography (px → pt 1:1 at 1×).
### Don't:
- **Don't** add a dark mode or theme variants — the world is one light palette, live-calibrated.
- **Don't** use Pine anywhere but the engine-ready dot — it is a meaning, not a style.
- **Don't** introduce a second accent color, gradients, or colored washes; Terracotta Seal is the only hue that isn't paper or ink.
- **Don't** put shadows on resting chrome.
- **Don't** set a document title or content in the sans face — that was tried and rejected as chrome disconnected from the document.
- **Don't** flatten domain modules into generic cards or framework-default styling; the export's geometry and states are the contract.
+16
View File
@@ -123,6 +123,10 @@ _Avoid_: reject, dismiss
Accepting a mechanical Fix Card so its edit lands in the file. Demonstration cards never offer it — they close Done or Skip.
_Avoid_: accept, fix (verb)
**Jump**:
Selecting a Fix Card's anchor span in the piece's editor — the span the card points at, revealed and selected, the editor made key. A view act: records nothing, writes nothing. A stale anchor offers none.
_Avoid_: go to, scroll to, reveal
**Done**:
Closing a Fix Card because the writer rewrote the span — the demonstration lane's terminal, beside Apply and Skip. Records nothing.
_Avoid_: applied, complete
@@ -152,3 +156,15 @@ _Avoid_: permission mode
**Provenance**:
The origin record carried by a Fix Card or Learning (piece, date, engine).
_Avoid_: metadata
## Discovered Terms
<!-- distill-learnings: discovered-terms -->
### Publish Record
What a Piece remembers about Micro.blog in its frontmatter: `micropub_url` (the post it was sent to) and, once Publish succeeded from here, `micropub_published` (the stamp, local time). Museion bookkeeping — written only by the app or the writer's own hand; Import drops both keys. A remembered URL without the stamp is a draft on Micro.blog.
_Avoid_: publish state (it is a record on disk, never a live query), status (that is Pass State)
### Upload Memo
The per-Piece sidecar `.museion-uploads.json` mapping an illustration's bytes (`sha256`) to the URL Micro.blog returned, so an unchanged image uploads once. Finder-invisible, dies with the Piece folder, never trusted from outside — a symlinked memo or an untrustworthy entry is no memory.
_Avoid_: upload cache (it is Piece-local bookkeeping, not a shared cache)
+8 -6
View File
@@ -405,6 +405,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
@@ -423,7 +424,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -441,6 +442,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
@@ -459,7 +461,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -482,7 +484,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -504,7 +506,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -524,7 +526,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -544,7 +546,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
+45 -8
View File
@@ -75,6 +75,9 @@ nonisolated extension JSONValue {
/// matches responses to pending requests, and delivers notifications in wire
/// order. Requests are expected to be strictly sequential (initialize →
/// session/new → prompt), matching the pane's usage.
/// brief-27: stdin writes ride a dedicated writer queue, so engine
/// backpressure (a full pipe) can stall a send but never a deadline,
/// Stop delivery, or teardown.
///
/// Wire facts baked in (verified against adapter 0.20.6 + the acp SDK):
/// - `session/cancel` is a JSON-RPC *notification* (interfaces.py — CancelNotification).
@@ -94,6 +97,12 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
private let stderrPipe = Pipe()
/// All mutable state below is confined to this serial queue.
private let queue = DispatchQueue(label: "com.babylondreams.Museion.acp-client")
/// brief-27: stdin writes (and the stdin handle's own close) ride this
/// dedicated writer queue. The state queue NEVER touches the pipe — a
/// full pipe (hung engine not reading stdin) blocks only this writer, so
/// request deadlines, Stop delivery, and close()'s bookkeeping stay live
/// behind it. Serial = the wire order every send site already had.
private let writerQueue = DispatchQueue(label: "com.babylondreams.Museion.acp-client-writer")
private var pending: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
private var buffer = Data()
private var currentID = 0
@@ -148,6 +157,10 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Send a JSON-RPC request and await its matching response result.
/// A request that gets no answer within `timeout` fails — a hung engine
/// must surface as an error (→ restart prompt), never an eternal await.
/// brief-27: a timed-out request's bytes may still reach the engine once
/// the child unblocks (the deadline fails the caller, never dequeues the
/// write) — phantom engine work only: ids are never reused and the
/// response path drops unknown ids, so a late reply can never misroute.
/// (No default arguments: the only caller is EngineHost, which rides the
/// seam — `EngineTransport.request`'s convenience owns the default shape.)
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? {
@@ -174,7 +187,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
continuation.resume(throwing: TransportError(message: "engine closed before \(method)"))
return
}
queue.async { self.send(raw) }
// brief-27: straight to the writer queue — never through the state
// queue, so a blocked write can't pin the deadline armed below.
send(raw)
// ponytail: deadline on the same serial queue — fires only if the
// response hasn't already resumed and removed the continuation.
queue.asyncAfter(deadline: .now() + timeout) {
@@ -194,11 +209,15 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
queue.async { self.send(raw) }
// brief-27: writer queue, not the state queue (see request).
send(raw)
}
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the child
/// never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the
/// child never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// brief-27: bounded even when a stdin write is blocked on a full pipe —
/// bookkeeping syncs on the (I/O-free) state queue, and child
/// termination never queues behind the writer.
func close() {
let alreadyClosed = queue.sync {
if closed {
@@ -227,7 +246,14 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
}
}
process.waitUntilExit()
try? stdinPipe.fileHandleForWriting.close()
// brief-27: the stdin WRITE handle closes on the writer queue — a
// blocked write may still own it (it unblocks only once the child's
// read end died, which the kill above just arranged); closing under
// a live write would race Foundation. The reader handles have no
// writers — their handlers are already off, so they close here.
writerQueue.async {
try? self.stdinPipe.fileHandleForWriting.close()
}
try? stdoutPipe.fileHandleForReading.close()
try? stderrPipe.fileHandleForReading.close()
}
@@ -236,10 +262,21 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Frame and write one NDJSON line. A failed write (child gone) is dropped:
/// the crash path owns the UX, not the send.
/// brief-27: the write runs on the WRITER queue, never the state queue —
/// a blocked write here starves no deadline and no teardown.
private func send(_ data: Data) {
var framed = Data(data)
framed.append(0x0A)
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
// ponytail: queued sends are unbounded, and a send racing close() writes
// onto a closed handle (benign — write throws a catchable CocoaError 512
// that try? swallows; probe-verified by two independent reviewers).
// Bounded today by MentorSessionModel's sequential-send discipline (a
// request is awaited before the next; worst case one prompt + one
// cancel). Add a closed/depth guard here if a looping or
// non-MainActor caller ever appears.
writerQueue.async {
var framed = Data(data)
framed.append(0x0A)
try? self.stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
}
/// Fail every pending request and surface the crash — the one exit path
+26 -17
View File
@@ -15,7 +15,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `AppMetadata` is the single source for displayed name/tagline; members `nonisolated`.
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
- App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no `.entitlements` file.
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007).
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007), and the per-piece Finder-invisible sidecars that die with the piece folder — the cursor state `.museion-state.json` (#66) and the Micro.blog upload memo `.museion-uploads.json` (#206).
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
## Workspace shell
@@ -23,29 +23,38 @@ 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.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/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-<n>.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.
- `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`: the drop surface for drags that land OUTSIDE the editor — macOS 27.2.1 routes a drag to the DEEPEST destination, so over the editor the text view takes the drag itself (`FileDropTextView`'s drag handlers) and this destination never fires (the inverse of the 27.0.1 ruling #141 was verified on); both route through `AppGateState.routeFileDrop` — the ONE file-drop router (pure-markdown → external guest, anything else → `ingestDrop`, Cold Turkey–guarded; a mixed md+image set and web URLs refuse loudly). A landed drop hops to Posts (unreachable for images today — the editor mounts only there). 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`. Row menu: Move Back / Rename / Convert, plus #205 Reveal in Finder / Copy Path and #206 Open on Micro.blog.
- `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. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops. #206 `MicroblogHandOffButton` — Open on Micro.blog, only for a PUBLISHED piece (a draft's final URL answers Not Found until the post is published — owner-verified 2026-12-04); mounted beside the Finder pair in both menus.
- `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 (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). 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/Reveal in Finder/Copy Path/Open on Micro.blog (#206, published pieces)/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. #206: the mono-11 micro-label shows the piece's Micro.blog status when it has one (`published <date>` / `draft on Micro.blog`) in origin's place — 178pt of row content cannot carry both — and VoiceOver reads both (`accessibilityText`); origin stays one hover away (the label's tooltip).
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/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` through the ONE trust gate (`Micropub.rememberedURL`, format-only — ownership is settled upstream: the import boundary drops the key, so only Museion or the writer's own hand writes one); #206 `micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape, read by the shared `parseStamp`) and the row label `micropubStatus` (`published <date>` / `draft on Micro.blog` / nil).
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`), `stampFormat` (the frontmatter timestamp shape both stamp writers and the reader share), 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, and the Micro.blog bookkeeping dropped: `micropubKeys` — #206, a foreign file carries no post of this library), update-keys (`updating` — the in-place line-walk, every other line byte-identical; `dropping:` removes named keys' lines — the import and the 404 forget). 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 and the Micro.blog bookkeeping dropped (#206: an imported `micropub_url` would aim the next send's content replace). 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-<n>.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; a file the disk can't stat refuses as `missing`, never as a folder); `illustrationRef` is the one `![alt](assets/…)` builder. `stampMicropub` / `forgetMicropub` — the frontmatter-only micropub stamps (`micropub_url`, the #206 publish record `micropub_published`; on a 404 both lines are REMOVED — `forgetMicropub` throws when that write cannot land, so a failed clear refuses instead of claiming the link is gone), outside the write rail.
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session.
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. `WritingLockAppDelegate` (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — `quitReply(posts:)` is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk.
- `TrendsPaneView.swift` — per-metric line charts over first-draft captures; only pieces with `firstDraftStats` appear (the view answers "am I getting better", never "is this draft good"); one capture shows a value, no verdict. `TrendMetric` (pure): fixed y-domains (burstiness −1…1, TTR + trigram 0…1, sentenceVariation scaled to 1.2× peak, floor 1), verdict at ±0.01 (trigram inverted), one explain line per metric.
- `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `<home>/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress).
- `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`, construction + Settings repoint; 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).
- 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; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `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) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). 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; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries).
- `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`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — 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; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSend` (#206; was `micropubSendDraft`) = flush-first, ONE disk read serves the wire fields and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update; `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- `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, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through `sessionMayDepart`/`departOpenDocuments` — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25).
- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal` (`-> Bool` — false holds the departure)/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 — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); `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.
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump). Rides `FileDropTextView` with no route mounted: a file drag landing on a row bounces (no path paste).
- `FileDropTextView.swift` — the editor text views' drag base (macOS 27.2.1 routing): a live NSTextView registers itself for drag types and receives the drag a window-level SwiftUI destination never sees; URL-bearing drops route through `onFileDrop` (nil = bounce), text-only drops keep the stock drop, everything else bounces — never `super` for URLs (stock NSTextView pastes the dropped file's PATH via `readSelection` on NSFilenamesPboardType). The pasteboard probe is memoized per `changeCount` (`draggingUpdated` fires per mouse-move).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling). `ProseListTextView` rides `FileDropTextView` with `onFileDrop` → the gate's `routeFileDrop`, so file drags landing on it ingest (never paste the path); `lastIngestNotice` is the refusal text the pins read.
- Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage).
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: surface writes and the base_url write-through ride the HermesConfigRail (#182 — the writer only builds its key list: provider, default, effort set-or-unset, base_url LAST); provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection; paths via ProfileLayout). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys · Micro.blog (the app token's home — `MicroblogSettingsPage` in SettingsPagesView.swift: a standing saved-status row / replace / remove over `MicropubTokenStore`); the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: surface writes and the base_url write-through ride the HermesConfigRail (#182 — the writer only builds its key list: provider, default, effort set-or-unset, base_url LAST); provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection; paths via ProfileLayout). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
- Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only.
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary (arm64, Developer ID–signed with the hardened runtime at commit time, beside `libyaml.bundle/libyaml-0.2.dylib` — self-contained through the single rpath `@executable_path/../Resources/libyaml.bundle`; the `.bundle` wrapper is load-bearing: a bare dylib in the synced folder (with or without extension — Xcode sniffs Mach-O content) becomes the APP's link target; re-sign both when the Developer ID certificate rotates) with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
- `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `<CloudDocs>/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.
## Engine check (gateless launch)
@@ -69,17 +78,17 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## museion-tools MCP server
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam. #177: both submit tools decode through `ToolPayloads` (below) — the strict entry throws named `CardError`s (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias).
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `appliedText` = the pure nth-occurrence mechanical apply (nil, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `anchorRange` = the nth-occurrence span (nil = stale, empty quote, or occurrence below 1 — never a wrong span; the lane never gates it); `appliedText` = the mechanical apply over that span (lane-gated, nil on a stale anchor, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
- `LearningDecay.swift` — the pass clock `learnings/pass-counts.json` (lenient read, clamped values); `passesHidden` is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); `dismiss` stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
- `ToolPayloads.swift` — #177: THE tool-payload decoder, one home for the `submit_fix_cards`/`submit_research_notes` wire shapes; the MCP server (strict — required fields throw `CardError`) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in `ToolPayloadsTests` — a shape change fails one suite.
## ACP bridge
- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm; #204 **Jump** on every non-stale card that still shows an action row (a closed-and-promoted card has none) — leaves reading mode, selects the anchor span in the editor, reveals it, and makes the main window key (the coordinator owns `tv.window`; `NSApp.activate` is a no-op once the palette's click already activated the app)), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop).
## Work Guidance
+179
View File
@@ -0,0 +1,179 @@
//
// 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<String> = []
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)
}
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: 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)
}
}
+20 -2
View File
@@ -79,10 +79,28 @@ nonisolated struct DraftStats: Equatable {
/// Word count over the same token semantics every text metric
/// rides (#161: Cold Turkey net-words counts with this — one
/// tokenizer, no drift). "writer's" is two words here, headings
/// word rail, no drift). "writer's" is two words here, headings
/// are body text, frontmatter is not (the editor never shows it).
/// Count-only (opt pass 2026-11-09): one Character pass counting
/// maximal isLetter/isNumber runs — the lowercased [String] the
/// per-keystroke editor feed once paid for is never built. Equal
/// to the tokenizer's split by construction (omitting empty
/// subsequences leaves exactly the maximal runs); pinned against
/// the split expression over a mixed-script corpus.
static func words(in text: String) -> Int {
tokens(in: text).count
var count = 0
var inRun = false
for character in text {
if character.isLetter || character.isNumber {
if !inRun {
count += 1
inRun = true
}
} else {
inRun = false
}
}
return count
}
/// Lowercased runs of Characters where isLetter || isNumber — the
+35 -6
View File
@@ -63,6 +63,24 @@ final class EditorSession {
return nil
}
/// brief-28: document identity — a post session is (Home, ID), never the
/// bare id: two libraries can hold the same slug, and only the pair says
/// which piece the buffer belongs to. The target is immutable, so the
/// Home here is the one the session was BORN under — a model whose
/// `watchedHome` moved past it must treat this session as a foreign
/// document, not as its own open piece.
func targets(postID id: String, home: URL) -> Bool {
guard case let .post(mine, myHome) = target else { return false }
return mine == id && myHome == home
}
/// brief-28: the Home half alone — does this post session live under
/// `home`? External guests never do.
func targets(home: URL) -> Bool {
guard case let .post(_, myHome) = target else { return false }
return myHome == home
}
/// The document's folder — the piece's resolved folder under projects/
/// or archive/ for posts (image resolution #71; resolved once at init,
/// ADR-0012 — a vanished piece still needs some path, so an unresolvable
@@ -139,16 +157,27 @@ final class EditorSession {
private static func readDocument(_ target: SessionTarget) -> String? {
switch target {
case let .post(id, home):
return PostStore.readBody(id: id, home: home)
PostStore.readBody(id: id, home: home)
case let .externalFile(url):
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") {
text.removeFirst()
}
return text.replacingOccurrences(of: "\r\n", with: "\n")
readExternalDocument(at: url)
}
}
/// #67/brief-32: the ONE external-target disk read — raw UTF-8, BOM
/// stripped, CRLF normalized to LF. Every reader of an external file's
/// bytes goes through here (the open read above, the guest watch in
/// PostsModelImports, Yes-reload, keep-local), so the #67 compare is
/// always normalized-to-normalized: the watch used to read raw and
/// raised a false conflict on every directory event over an unchanged
/// BOM/CRLF file.
static func readExternalDocument(at url: URL) -> String? {
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") {
text.removeFirst()
}
return text.replacingOccurrences(of: "\r\n", with: "\n")
}
/// Target-aware write: posts → `PostStore.overwrite` (+ sidecar);
/// external → the whole text, in place, no sidecar (#93).
private func writeDocument() throws {
+89
View File
@@ -0,0 +1,89 @@
//
// FileDropTextView.swift
// Museion
//
// #141 (macOS 27.2.1): a drag goes to the DEEPEST destination, and a live
// NSTextView registers itself for drag types — so a file drag landing on
// an editor text view is delivered to the view, not to the window-level
// SwiftUI .dropDestination (the inverse of the 27.0.1 ruling #141 was
// verified on). Stock NSTextView handling pastes the dropped file's PATH
// (`readSelection` on NSFilenamesPboardType). This base replaces that for
// URL-bearing drags and leaves text-only drags to the stock behavior. The
// prose editor routes through the gate's one router (`AppGateState.
// routeFileDrop`); the outline rows have no route and bounce.
//
import AppKit
class FileDropTextView: NSTextView {
/// Where a URL-bearing drop routes. Nil = the view claims nothing
/// (outline rows: images don't ingest there, so the drag bounces
/// instead of pasting a path).
var onFileDrop: (([URL]) -> Bool)?
/// One classification per pasteboard state — `draggingUpdated` fires on
/// every mouse-move and the read is a pasteboard round-trip (a hostile
/// 20k-URL drag measured 137 ms per move uncached).
private var dropProbe: (changeCount: Int, kind: DropKind)?
enum DropKind: Equatable {
/// File URLs (Finder) or web URLs (browser) — routed, never pasted.
case urls([URL])
/// Text only (a selection drag, text from another app) — the stock
/// NSTextView drop, which inserts text and nothing else.
case text
/// Raw image data, file promises — anything URL-less and text-less.
case none
}
/// The drag's URLs — or nil when it carries none.
static func droppedURLs(from pasteboard: NSPasteboard) -> [URL]? {
let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: nil) as? [URL] ?? []
return urls.isEmpty ? nil : urls
}
static func classify(_ pasteboard: NSPasteboard) -> DropKind {
if let urls = droppedURLs(from: pasteboard) {
return .urls(urls)
}
return pasteboard.types?.contains(.string) == true ? .text : .none
}
/// `classify`, memoized on the pasteboard's changeCount.
func dropKind(of pasteboard: NSPasteboard) -> DropKind {
if let dropProbe, dropProbe.changeCount == pasteboard.changeCount {
return dropProbe.kind
}
let kind = Self.classify(pasteboard)
dropProbe = (pasteboard.changeCount, kind)
return kind
}
override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation {
switch dropKind(of: sender.draggingPasteboard) {
case .urls: onFileDrop != nil ? .copy : [] // accept so a refusal stays LOUD
case .text: super.draggingEntered(sender)
case .none: []
}
}
override func draggingUpdated(_ sender: any NSDraggingInfo) -> NSDragOperation {
switch dropKind(of: sender.draggingPasteboard) {
case .urls: onFileDrop != nil ? .copy : []
case .text: super.draggingUpdated(sender)
case .none: []
}
}
override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
switch dropKind(of: sender.draggingPasteboard) {
case let .urls(urls): onFileDrop?(urls) ?? false
case .text: super.performDragOperation(sender)
case .none: false
}
}
/// Nothing to conclude — the ingest leaves the scroll stack as a
/// keystroke would.
override func concludeDragOperation(_: (any NSDraggingInfo)?) {}
}
+16 -6
View File
@@ -153,6 +153,20 @@ nonisolated enum FixCardStore {
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
}
/// #204: the anchor's exact span in `text` — the appliedText math WITHOUT
/// the edit: the quote's 1-based non-overlapping occurrence as an NSRange
/// a jump can select. nil for every case that must never land: a stale
/// anchor (quote gone or occurrence short) or an empty quote. The lane
/// never gates here — a demonstration card's anchor is still a real
/// place in the text; the palette decides what to offer.
static func anchorRange(of card: StoredFixCard, in text: String) -> NSRange? {
guard card.anchor.occurrence >= 1, !card.anchor.quote.isEmpty else { return nil }
return text.ranges(of: card.anchor.quote)
.dropFirst(card.anchor.occurrence - 1)
.first
.map { NSRange($0, in: text) }
}
// MARK: - Apply (pure)
/// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit
@@ -164,12 +178,8 @@ nonisolated enum FixCardStore {
/// issue and accept degrade to a loud no-match, never a wrong-span
/// patch. The caller owns the ask and the file write.
static func appliedText(of card: StoredFixCard, in text: String) -> String? {
guard card.lane == .mechanical,
card.anchor.occurrence >= 1,
!card.anchor.quote.isEmpty,
let range = text.ranges(of: card.anchor.quote).dropFirst(card.anchor.occurrence - 1).first
else { return nil }
return text.replacingCharacters(in: range, with: card.fix)
guard card.lane == .mechanical, let range = anchorRange(of: card, in: text) else { return nil }
return (text as NSString).replacingCharacters(in: range, with: card.fix)
}
// MARK: - Submit
+20 -11
View File
@@ -3,8 +3,8 @@
// Museion
//
// #25 (S3.3): the Fix Cards palette becomes the card work surface. Open
// cards lead with their actions — Apply (a blocking ask), Skip, Done —
// closed cards dim behind them. No apply-all, no batch, nothing applies
// cards lead with their actions — Apply (a blocking ask), Skip, Done,
// Promote (#26), Jump (#204) — closed cards dim behind them. No apply-all, no batch, nothing applies
// without the ask (S3.3). #23's show-only surface kept its bones.
//
@@ -106,9 +106,10 @@ private struct CardList: View {
/// One card: pattern title, problem + fix body, rank · pass · lane ·
/// emitter mono meta (ADR-0006). A stale anchor reads distinct — orange —
/// and never offers Apply. Closed cards dim, record their status in the
/// meta, and offer no actions. The blocking Apply ask is the ROW's own
/// sheet: one card asks at a time, by construction (S3.3).
/// and never offers Apply or Jump (#204). Closed cards dim, record their
/// status in the meta, and keep only Promote and Jump — a closed card that
/// is already promoted keeps neither (its row is gone). The blocking Apply
/// ask is the ROW's own sheet: one card asks at a time (S3.3).
private struct CardRow: View {
let card: FixCardStore.StoredFixCard
@Environment(AppGateState.self) private var gate
@@ -134,14 +135,22 @@ private struct CardRow: View {
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(stale ? .orange : DesignTokens.muted)
if open || card.promotedAt == nil {
// The actions this card offers (#25 S3.3, #26 S4.1):
// mechanical + valid → Apply (the blocking ask) and Skip;
// demonstration → Done and Skip (never Apply, ADR-0006);
// stale anchor → Skip only. Promote (its own ask) sits
// between the primary action and Skip, and outlives the
// card — closed cards keep it until promoted (#26: the
// The actions this card offers (#25 S3.3, #26 S4.1, #204):
// Jump on every card whose anchor still resolves (closed cards
// included — the span is still a real place; stale anchors offer
// none — nothing to land on); mechanical + valid → Apply (the
// blocking ask) and Skip; demonstration → Done and Skip (never
// Apply, ADR-0006); stale anchor → Skip only. Promote (its own
// ask) sits between the primary action and Skip, and outlives
// the card — closed cards keep it until promoted (#26: the
// Learning is the durable artifact).
HStack(spacing: 8) {
if !stale {
Button("Jump") { gate.posts.revealCard(card) }
.buttonStyle(.borderless)
.controlSize(.small)
.help("Select the anchored span in the piece")
}
if open, !stale {
if card.lane == .mechanical {
Button("Apply") { asking = true }
+15
View File
@@ -80,4 +80,19 @@ extension AppGateState {
nonisolated static func storeHome(_ home: URL, in defaults: UserDefaults) {
defaults.set(home.absoluteString, forKey: "museionHome")
}
/// brief-28 (home-repoint-retains-old-editor-target): the ONE repoint
/// entry at runtime — the departure gate runs FIRST (`posts.repoint`:
/// every open document lands, or nothing changes and `posts.lastError`
/// names the piece); the preference and its persistence (`museionHome`'s
/// didSet) commit only after. True = committed. WorkspaceView's Settings
/// binding routes through here; the root `.task(id: museionHome)` binds
/// the model after the commit, so `watchedHome` can never move past a
/// live session again.
@discardableResult
func repointMuseionHome(to newHome: URL) -> Bool {
guard posts.repoint(to: newHome) else { return false }
museionHome = newHome
return true
}
}
+10 -3
View File
@@ -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)
}
}
+110
View File
@@ -0,0 +1,110 @@
//
// 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 + a mono-11 meta line — origin, or
/// (#206) the piece's Micro.blog status in its place on a sent piece (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.
// #206: a piece with a Micro.blog status shows THAT here
// (origin stays in the accessibility label and one hover
// away) — the row's content is 178pt, too narrow for both.
Text(post.micropubStatus ?? post.origin.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
.help(post.origin.rawValue)
}
.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(accessibilityText)
}
/// VoiceOver reads every status the row carries — #206's Micro.blog
/// status included, since it takes the micro-label's place.
private var accessibilityText: String {
var parts = [post.title, post.passState.rawValue, "origin \(post.origin.rawValue)"]
if let status = post.micropubStatus {
parts.append(status)
}
return parts.joined(separator: ", ")
}
}
+27
View File
@@ -32,4 +32,31 @@ nonisolated enum LibrarySearch {
}
return titleHits + bodyHits
}
/// #144 (mounted half): the identity of one search sweep — the
/// trimmed query, the Home it ran under, and the library content
/// revision it saw (`PostsModel.contentRevision`). The column's
/// `.task(id:)` re-keys on ANY difference, so a keystroke, a Home
/// repoint, or a library write that landed after the last sweep
/// restarts it instead of serving the stale snapshot.
nonisolated struct SearchKey: Equatable {
var query: String
var homePath: String
var revision: Int
}
/// #144 (mounted half): one landed sweep — the results plus the key
/// that produced them. `isFresh` is the column's stale gate: results
/// render only under the key that computed them, so an archived,
/// trashed, renamed, or since-edited library drops to the recompute
/// state, never stale rows.
nonisolated struct Snapshot: Equatable {
var key: SearchKey
var results: [Post]
/// A snapshot renders only under its own key.
func isFresh(for key: SearchKey) -> Bool {
self.key == key
}
}
}
+6 -2
View File
@@ -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.
}
+255 -64
View File
@@ -11,7 +11,13 @@
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
// MicropubMedia.swift, the orchestration in micropubSend below.
// #206: a piece that remembers its post re-sends as an IN-PLACE
// update (action=update + replace name/content — never a second
// post), Publish is remembered on the piece (`micropub_published`),
// and a 404 forgets the link. Wire facts live-verified 2026-12-04
// (microblog.dev/api/posting): `replace` sets name and content;
// updates answer 200 with an empty body, 404 when the URL is gone.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -32,9 +38,17 @@ nonisolated enum Micropub {
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
case drafted(url: String, preview: String?)
/// #206: an in-place update landed — `url` is the post the piece
/// already remembered (a draft refreshed, a live post edited).
/// No second post, no new URL.
case updated(url: String)
case published
/// No open saved piece (model guard) — nothing went out.
case refused(String)
/// #206 (model-level): Micro.blog answered 404 — the post is gone
/// there. The piece has forgotten it (both stamps cleared); the
/// payload says so. The next send is a fresh draft.
case forgotten(String)
case authFailed(String)
case requestFailed(status: Int, detail: String)
case unreachable(String)
@@ -52,12 +66,19 @@ nonisolated enum Micropub {
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
/// The one JSON POST shape every request rides: the fixed endpoint,
/// Bearer token, 30 s, sorted keys.
private static func jsonPost(_ object: [String: Any], token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
return request
}
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
@@ -66,32 +87,40 @@ nonisolated enum Micropub {
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
jsonPost([
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], options: [.sortedKeys])
return request
], token: token)
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: [
jsonPost([
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
], token: token)
}
// MARK: The two steps
/// #206: refresh the post the piece remembers — title and content
/// replaced IN PLACE over the remembered URL (wire-verified
/// 2026-12-04: `replace` sets name and content, JSON-only). Never
/// a status flip: a draft stays a draft, a published post stays live.
static func makeUpdateRequest(url: String, title: String, body: String, token: String) -> URLRequest {
jsonPost([
"action": "update",
"url": url,
"replace": [
"name": [title],
"content": [body],
],
], token: token)
}
// MARK: The steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content; #34's uploaded
@@ -116,6 +145,25 @@ nonisolated enum Micropub {
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
}
/// #206: step 1 again, in place — the piece's current title and
/// body replace the remembered post's (a draft refreshed for
/// review; a live post edited). Needs the remembered URL.
static func update(
url: String,
title: String,
body: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let outcome = await run(makeUpdateRequest(url: url, title: title, body: body, token: token), transport: transport, decodeDraftURL: false)
// `run` has one success word for the URL-less steps; the update's
// carries the URL it touched.
if outcome == .published {
return .updated(url: url)
}
return outcome
}
/// One POST + the honest decode: 2xx → drafted/published (drafts
/// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create
@@ -152,10 +200,12 @@ nonisolated enum Micropub {
/// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
/// Format-only by design — ponytail: a well-formed foreign URL still
/// passes (the label shows its full text); host-allowlist when v2's
/// q=config surface names the blog's real domains.
/// and `Post.scan`'s read-back. Format-only by design — ownership is
/// settled upstream, not here: the import boundary drops the micropub
/// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
/// update a well-formed foreign URL would aim a content replace), so
/// only Museion or the writer's own hand writes one. ponytail:
/// host-allowlist stays the upgrade if another way in ever appears.
static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
@@ -166,15 +216,38 @@ nonisolated enum Micropub {
return true
}
/// The remembered post URL read from frontmatter — the ONE read the
/// scan and the send share, gated like the decode: a hand-written
/// broken value is no memory at all (an imported one never arrives —
/// the boundary drops the key).
static func rememberedURL(_ matter: [String: String]) -> String? {
guard let raw = matter["micropub_url"], trustworthyURL(raw) else { return nil }
return raw
}
/// #206: the short date the library row and the publish sheet both
/// show (`Dec 4, 2026`) — one format, so the two can't drift.
static func shortDate(_ date: Date) -> String {
FixCardStore.formatted(date, "MMM d, yyyy")
}
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
/// A 5xx is Micro.blog's side (their nginx front with the app not
/// answering behind it, or a rate limit) and arrives as an HTML page,
/// never Micropub JSON — so the fallback names the outage instead of
/// a bare `HTTP 503` (2026-12-04: a 503 in the sheet while the
/// endpoint answered its usual 400 to a tokenless probe minutes later).
static func decodeFailure(status: Int, body: Data) -> Outcome {
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)"
let described = (root["error_description"] as? String) ?? (root["error"] as? String)
if status == 401 || status == 403 {
return .authFailed(detail)
return .authFailed(described ?? "HTTP \(status)")
}
return .requestFailed(status: status, detail: detail)
let fallback = (500 ... 599).contains(status)
? "unavailable on their side — retry in a few minutes (status.micro.blog)"
: "HTTP \(status)"
return .requestFailed(status: status, detail: described ?? fallback)
}
}
@@ -232,43 +305,56 @@ nonisolated enum MicropubTokenStore {
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
// MARK: - #33 (S6.1) / #206 Micropub draft → publish
extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// as a draft (h=entry, name = Title, markdown content, post-status
/// draft — category frontmatter never travels). runPass's guard set
/// minus the engine gates (no engine involved); flush-first so the
/// wire carries the editor's latest. On success the piece remembers
/// the draft URL (`micropub_url` stamp) — a stamp failure never
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
/// The OPEN saved library piece as the micropub pair (id, Home) —
/// the identity guard both publish steps share. brief-28: the open
/// session must target THIS library's selected piece; the wire and
/// every stamp below act on the piece actually sent (Home, ID),
/// never the current Home's same-slug file. Nil = nothing to send.
private var openMicropubPiece: (id: String, home: URL)? {
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home),
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
else { return nil }
return (id, home)
}
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// (name = Title, markdown content — category frontmatter never
/// travels). runPass's guard set minus the engine gates (no engine
/// involved); flush-first so the wire carries the editor's latest.
/// #206: a piece that remembers no post is CREATED as a draft
/// (h=entry, post-status draft) and remembers its URL
/// (`micropub_url` stamp); a piece that remembers one UPDATES that
/// post in place — same URL, no second post — so a draft refreshes
/// for review and a published piece edits live. A stamp failure
/// never un-sends the draft.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSend(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard flushOrAbort(id) else {
guard flushOrAbort(piece.id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
// Disk is the truth post-flush — ONE read serves the wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name) and the frontmatter-stripped body (the stamp is
// name), the frontmatter-stripped body (the stamp is
// bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY). No scan dependency: the list can lag the open piece.
guard let home = watchedHome,
let dir = PostStore.folder(of: id, home: home),
// GLOSSARY), and the remembered URL. No scan dependency: the
// list can lag the open piece.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
@@ -289,25 +375,91 @@ extension PostsModel {
return outcome
}
}
let title = Post.title(of: raw)
// #206: the piece remembers its post → update THAT post in
// place (the remembered URL never moves; nothing new to stamp).
// A 404 means the post is gone on Micro.blog — the piece forgets
// it rather than fail forever against a dead URL.
if let remembered = Micropub.rememberedURL(PostFrontmatter.parse(raw)) {
let outcome = await Micropub.update(url: remembered, title: title, body: wireBody, token: token, transport: transport)
if case .requestFailed(404, _) = outcome {
return micropubPostGone(id: piece.id, home: piece.home)
}
return outcome
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
title: title,
body: wireBody,
token: token,
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. A stamp
// failure can't un-send the draft; the sheet still holds
// the URL for this session — the piece just loses the
// memory across a reopen (re-send the draft then). Kept
// quiet: lastError's setter stays PostsModel-file-private,
// and the same disk accepted the flush moments before.
try? PostStore.stampMicropubURL(id: id, url: url, home: home)
// Remember the draft's URL for the publish step and every
// later in-place update. A stamp failure can't un-send the
// draft; the sheet still holds the URL for this session —
// the piece just loses the memory across a reopen (it
// would create a second draft then). Kept quiet: the same
// disk accepted the flush moments before.
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// Step 2: flip the remembered draft to published. #206: the model
/// owns it — the sheet used to call the client directly, so nothing
/// remembered a publish. Success is the piece's publish record:
/// `micropub_published` stamped now (first publish wins — a later
/// in-place update of the live post never moves it) and
/// `micropub_url` healed in the same write should the send's stamp
/// have failed. A stamp failure never un-publishes. No flush: no
/// content travels, and the editor never writes frontmatter. The URL
/// is trust-gated HERE — it lands in frontmatter (the heal), and a
/// caller's value is external until proven.
func micropubPublish(
url: String,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard Micropub.trustworthyURL(url) else {
return .refused("That post address isn't a clean https URL — nothing was sent or remembered.")
}
let outcome = await Micropub.publish(url: url, token: token, transport: transport)
switch outcome {
case .published:
try? PostStore.stampMicropub(piece.id, home: piece.home, [
("micropub_url", url),
("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)),
])
case .requestFailed(404, _):
return micropubPostGone(id: piece.id, home: piece.home)
default:
break
}
return outcome
}
/// #206: Micro.blog answered 404 — the post is gone there, so the
/// piece is no longer on Micro.blog: it forgets both stamps and the
/// writer hears why (the next send is a fresh draft). A forget that
/// cannot land refuses instead — never a "cleared" the disk
/// contradicts: the link is still on the piece, so the sheet stays
/// on it and says what to do by hand.
private func micropubPostGone(id: String, home: URL) -> Micropub.Outcome {
do {
try PostStore.forgetMicropub(id: id, home: home)
} catch {
return .refused(
"Micro.blog no longer has this post — it was deleted there — but its link couldn't be cleared from this piece "
+ "(\(error.localizedDescription)). Delete the `micropub_url` line from its frontmatter, then send it as a draft.",
)
}
return .forgotten("Micro.blog no longer has this post — it was deleted there. Its link is cleared; send it as a draft again.")
}
/// #34 (S6.2): the illustration rail of `micropubSend`. The
/// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
@@ -336,11 +488,6 @@ extension PostsModel {
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
@@ -355,8 +502,36 @@ extension PostsModel {
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
}
/// One asset about to travel: its ref destination (the rewrite's
/// map key), its wire content type, its bytes.
private struct Payload {
let destination: String
let mimeType: String
let data: Data
}
/// #206: the piece's upload memo answers first — an image whose
/// bytes uploaded before rides that URL again (Micro.blog keeps
/// every copy, and their listing carries no hash to match against,
/// so the memory is local). Only what the memo lacks touches the
/// wire: q=config, then one upload per pending payload, each
/// remembered as it lands.
private func uploadRemembered(
_ payloads: [Payload],
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
var memo = Micropub.readUploadMemo(in: dir)
let remembered = uploadedDestinations(payloads, memo: memo)
let pending = payloads.filter { remembered[$0.destination] == nil }
guard !pending.isEmpty else {
return .ready(Micropub.rewritingIllustrations(body, uploaded: remembered))
}
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
@@ -364,8 +539,9 @@ extension PostsModel {
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
// The `where` skips a later payload with the same bytes as one
// uploaded earlier in this batch.
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
@@ -376,11 +552,26 @@ extension PostsModel {
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
// Remembered as it lands: a later failure in the batch
// keeps the earlier uploads (a retry never repeats them).
memo[Micropub.uploadKey(payload.data)] = url
Micropub.writeUploadMemo(memo, in: dir)
case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
}
}
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
// Every payload is memoized now — the earlier uploads and this batch's.
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploadedDestinations(payloads, memo: memo)))
}
/// The rewrite's map: each payload's ref destination → its upload URL.
private func uploadedDestinations(_ payloads: [Payload], memo: [String: String]) -> [String: String] {
var uploaded: [String: String] = [:]
for payload in payloads {
if let url = memo[Micropub.uploadKey(payload.data)] {
uploaded[payload.destination] = url
}
}
return uploaded
}
}
+40
View File
@@ -16,8 +16,11 @@
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`;
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
// #206: the upload memo — an image whose bytes uploaded before rides
// that URL again (`.museion-uploads.json` in the piece folder).
//
import CryptoKit
import Foundation
nonisolated extension Micropub {
@@ -194,6 +197,43 @@ nonisolated extension Micropub {
}
}
// MARK: #206 — the upload memo (a re-send never re-uploads)
/// `.museion-uploads.json` in the piece folder — the cursor
/// sidecar's posture: Finder-invisible, dies with the folder.
static let uploadMemoFile = ".museion-uploads.json"
/// The memo's key: the asset's exact bytes. Rename the file or
/// rewrite the alt and it is still the same upload; change one byte
/// and it uploads fresh.
static func uploadKey(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
/// `uploadKey → uploaded URL`. Disk is external data: a symlinked
/// memo never reads (the rail's planted-link posture) and only
/// trustworthy URLs come back — a memo URL lands in published
/// content. ponytail: an upload deleted on Micro.blog stays memoized
/// (a dead image URL) until the sidecar is removed; no liveness probe.
static func readUploadMemo(in pieceFolder: URL) -> [String: String] {
let url = pieceFolder.appendingPathComponent(uploadMemoFile)
guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey]),
values.isSymbolicLink != true,
let data = try? Data(contentsOf: url)
else { return [:] }
let memo = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
return memo.filter { trustworthyURL($1) }
}
/// Best-effort, like the cursor sidecar: a failed memo write only
/// costs a re-upload, never a send.
static func writeUploadMemo(_ memo: [String: String], in pieceFolder: URL) {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // a stable file: no churn across sends or syncs
guard let data = try? encoder.encode(memo) else { return }
try? data.write(to: pieceFolder.appendingPathComponent(uploadMemoFile), options: .atomic)
}
/// The one illustration-ref pattern both passes share (the parse
/// and the rewrite can never drift). The alt class is single-line
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
+151 -59
View File
@@ -7,9 +7,14 @@
// sheet owns the whole two-step flow over the OPEN piece: Send as
// Draft (h=entry, name, markdown content) → review on Micro.blog →
// Publish (the post-status update against the piece's remembered
// draft URL). The app token is entered here ONCE and lives in the
// Keychain (G11; re-offered only on an auth failure). Refusals show
// draft URL). The app token is entered here when none is saved and
// lives in the Keychain (G11; re-offered only on an auth failure —
// Settings → Micro.blog is the standing manager). Refusals show
// inline with the buttons kept (ApplyAskSheet posture).
// #206: the sheet opens on the piece's publish record. A published
// piece says so (and links its live post) and offers Update Live
// Post; a draft offers Publish / Update Draft. Both re-sends update
// the remembered post IN PLACE — never a second post.
//
import SwiftUI
@@ -20,17 +25,26 @@ struct MicropubPublishSheet: View {
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
/// Never sent — nothing on Micro.blog yet.
case idle
case drafting
/// A draft is on Micro.blog, not published (fresh or remembered).
case drafted
case updating
case updated
case publishing
/// The publish record — this session's Publish, or the piece's stamp.
case published
}
@State private var phase: Phase = .idle
/// The draft URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (a draft sent in an earlier session).
@State private var draftURL: String?
/// The post URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (sent in an earlier session) — a draft's
/// until it is published, the live post's after.
@State private var postURL: String?
/// #206: when the piece was published — its stamp, or this session's
/// Publish. Nil while it is a draft.
@State private var publishedAt: Date?
@State private var previewURL: String?
@State private var refusal: String?
@State private var tokenField = ""
@@ -42,16 +56,22 @@ struct MicropubPublishSheet: View {
reentry || MicropubTokenStore.read() == nil
}
private var busy: Bool {
phase == .drafting || phase == .updating || phase == .publishing
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?")
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
.font(.headline)
Text(pieceTitle)
.font(.callout.weight(.semibold))
.lineLimit(2)
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if phase == .idle {
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
if showsTokenField {
SecureField("App token", text: $tokenField)
@@ -60,20 +80,26 @@ struct MicropubPublishSheet: View {
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
} else {
// A stored token is in use — the field's absence alone
// never said which token a send carries.
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if phase == .drafting || phase == .publishing {
if busy {
ProgressView()
}
if let url = statusURL {
// The draft lives on Micro.blog — the preview link goes
// there for review; once published it's the post itself.
if let label = statusLabel {
// A published piece's link is the post itself; a draft's
// is its review page.
VStack(alignment: .leading, spacing: 4) {
Text(phase == .published ? "Published" : "Draft on Micro.blog")
Text(label)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) {
if let link = statusLink {
Link(destination: link) {
Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono))
@@ -90,24 +116,25 @@ struct MicropubPublishSheet: View {
}
HStack(spacing: 8) {
if phase == .published {
if publishedAt != nil {
// The piece is out: the only send left edits the live
// post, immediately — the label says so. A stamp with no
// remembered link (a hand-added key) has no post to
// update: that send is a fresh draft, and says so.
Button(postURL == nil ? "Send as Draft" : "Update Live Post") { send() }
.buttonStyle(.bordered)
.disabled(busy)
Button("Done") { dismiss() }
.buttonStyle(.borderedProminent)
} else {
Button("Publish") { publish() }
.buttonStyle(.borderedProminent)
.disabled(draftURL == nil || phase == .drafting || phase == .publishing)
if draftURL != nil {
// The piece changed since the draft — a fresh send
// replaces it (and the remembered URL).
Button("Send Again") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
} else {
Button("Send as Draft") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
}
.disabled(postURL == nil || busy)
// The piece changed since the draft — a re-send
// updates that same draft (never a second post).
Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
.buttonStyle(.bordered)
.disabled(busy)
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
@@ -117,17 +144,18 @@ struct MicropubPublishSheet: View {
.padding(16)
.frame(width: 340, alignment: .leading)
.onAppear {
// A draft sent in an earlier session is still publishable:
// the piece remembers its URL.
if draftURL == nil, let id = posts.session?.postID {
if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL {
draftURL = remembered
}
}
// A piece sent in an earlier session still has its record:
// the remembered URL, and (#206) its publish stamp.
guard postURL == nil, let id = posts.session?.postID,
let post = posts.posts.first(where: { $0.id == id })
else { return }
postURL = post.micropubURL
publishedAt = post.micropubPublished
phase = settledPhase
}
}
// MARK: Steps
// MARK: Status
/// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback).
@@ -135,10 +163,49 @@ struct MicropubPublishSheet: View {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
}
private var statusURL: String? {
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil
private var statusLabel: String? {
switch phase {
case .idle:
nil
case .drafting:
"Sending draft…"
case .drafted:
"Draft on Micro.blog — not published yet"
case .updating:
publishedAt == nil ? "Updating draft…" : "Updating live post…"
case .updated:
publishedAt.map { "Updated live — published \(Micropub.shortDate($0))" } ?? "Draft updated — not published yet"
case .publishing:
"Publishing…"
case .published:
publishedAt.map { "Published \(Micropub.shortDate($0))" }
}
}
/// A published piece links its live post; a draft links the review
/// page — only the send that created it carries one, so a draft
/// remembered from an earlier session shows no (dead) link.
private var statusLink: URL? {
if publishedAt != nil {
return postURL.flatMap { URL(string: $0) }
}
return previewURL.flatMap { URL(string: $0) }
}
/// Where the sheet rests on the piece's record: published, draft,
/// or never sent.
private var settledPhase: Phase {
if publishedAt != nil {
return .published
}
if postURL != nil {
return .drafted
}
return .idle
}
// MARK: Steps
/// Resolve the token: a freshly entered one is saved ONCE (rotation
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
/// a silent send.
@@ -153,29 +220,44 @@ struct MicropubPublishSheet: View {
return saved
}
private func sendDraft() {
/// A failed step: the message shows inline with the buttons kept, and
/// the sheet rests on the piece's record (a rejected token re-opens
/// entry — the entered-once token may be wrong).
private func fail(_ message: String, tokenRejected: Bool = false) {
if tokenRejected {
reentry = true
}
refusal = message
phase = settledPhase
}
/// Step 1 — the model decides create-vs-update by the piece's
/// remembered URL: a first send creates the draft, every later one
/// updates that post in place.
private func send() {
guard let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .drafting
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSendDraft(token: token) {
switch await posts.micropubSend(token: token) {
case let .drafted(url, preview):
draftURL = url
postURL = url
previewURL = preview
phase = .drafted
case let .updated(url):
postURL = url
phase = .updated
case let .authFailed(detail):
reentry = true // the entered-once token may be wrong
refusal = "Micro.blog rejected the token: \(detail)"
phase = draftURL == nil ? .idle : .drafted
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = draftURL == nil ? .idle : .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = draftURL == nil ? .idle : .drafted
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .published:
break
}
@@ -183,29 +265,39 @@ struct MicropubPublishSheet: View {
}
private func publish() {
guard let url = draftURL, let token = resolveToken() else {
guard let url = postURL, let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .publishing
Task {
switch await Micropub.publish(url: url, token: token) {
switch await posts.micropubPublish(url: url, token: token) {
case .published:
publishedAt = Date()
phase = .published
case let .authFailed(detail):
reentry = true
refusal = "Micro.blog rejected the token: \(detail)"
phase = .drafted
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = .drafted
case .drafted:
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .drafted, .updated:
break
}
}
}
/// #206: Micro.blog lost the post and the piece forgot it — the
/// sheet is back on a never-sent piece (a fresh draft is one click
/// away).
private func forgot(_ reason: String) {
refusal = reason
postURL = nil
publishedAt = nil
previewURL = nil
phase = .idle
}
}
+23 -5
View File
@@ -16,11 +16,9 @@ import SwiftUI
@MainActor
@Observable
final class AppGateState {
/// #141: the live prose text view — the window-level drop destination
/// (the ONLY destination that ever fires; nested editor-level SwiftUI
/// targets are never consulted, and AppKit views registered for file
/// drags are starved by it — field-verified 2026-11-02) routes image
/// drops to the editor through this handle.
/// #141: the live prose text view — the window-level SwiftUI destination
/// (drops landing OUTSIDE the editor) reaches it through this handle;
/// routing lives in `routeFileDrop`.
let proseDrop = ProseDropBridge()
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
@@ -67,6 +65,9 @@ final class AppGateState {
) {
// Explicit init: `Self` in a stored-property initializer trips
// @ObservationTracked's macro expansion (covariant Self).
// #200: the app delegate's quit gate reaches the one posts model
// (the WritingLockState.active precedent).
PostsModel.active = posts
if let stored = Self.fileHomeURL(in: defaults) {
museionHome = stored
return
@@ -115,6 +116,23 @@ final class AppGateState {
}
}
}
/// #91 + #141 — the ONE file-drop router. Two surfaces reach it, never
/// both for one drag (27.2 routing: the editor's text view when the
/// pointer is over it, the window-level SwiftUI destination elsewhere):
/// a PURE-markdown set opens as the guest; anything else goes to the
/// open piece's prose ingest, which refuses loudly (drafts, mixed
/// md+image sets, non-publishable or non-file URLs).
/// #162: no new buffers while a Cold Turkey block holds.
func routeFileDrop(_ urls: [URL]) -> Bool {
guard !writingLock.isLocked else { return false }
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
posts.openExternal(url)
return true
}
guard let textView = proseDrop.textView else { return false }
return textView.ingestDrop(urls)
}
}
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
+60 -44
View File
@@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter {
_ nodes: [OutlineNode], folded: Set<UUID>, 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).
+5 -2
View File
@@ -127,8 +127,11 @@ struct OutlineRowTextView: NSViewRepresentable {
}
}
/// The row NSTextView: structural key interception.
final class RowTextView: NSTextView {
/// The row NSTextView: structural key interception. `FileDropTextView`
/// base (27.2 routing): a file drag landing on a row bounces instead of
/// pasting the path — images don't ingest into outlines (#141); text
/// drags keep the stock drop.
final class RowTextView: FileDropTextView {
weak var bridge: OutlineRowTextView.Coordinator?
override func keyDown(with event: NSEvent) {
+86 -35
View File
@@ -47,9 +47,10 @@ struct PostEditorView: View {
/// #68: reading is a transient act of inspection — no persistence; a
/// fresh open always lands in editing.
@State private var reading = false
/// Flip-back caret (#68): source location + a token so repeated flips to
/// the same location re-apply. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: (location: Int, token: Int)?
/// Flip-back caret (#68) and #204 jump span: a zero-length range is a
/// bare caret landing, a non-zero range selects the anchor; the token
/// re-applies repeats. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: FixCardRevealRequest?
@State private var flipToken = 0
/// Reading scroll state (#68 mapping): entry caret + live top block.
@State private var readingState = ReadingStateBox()
@@ -108,6 +109,22 @@ struct PostEditorView: View {
}
}
}
// #204: a Fix Card jump (the palette's Jump) lands here — the model's
// reveal request rides the SAME caret rail as the reading flip-back,
// through the ONE token counter (two counters could collide and a
// jump would silently never land): the span selected, revealed, and
// the main window made key so the writer can type where the card
// pointed (the coordinator does that — it owns tv.window). A jump
// while READING leaves reading first — plain `reading = false`, not
// exitReading (which would stamp its own zero-length hint over the
// jump); the remounted coordinator applies the jump after the load.
// Outline pieces have no prose surface — the request is dropped.
.onChange(of: gate.posts.revealRequest) { _, request in
guard let request, !outline else { return }
flipToken += 1
flipBackCaret = FixCardRevealRequest(range: request.range, token: flipToken)
reading = false
}
.onAppear {
if draftMirror.isEmpty {
draftMirror = draftText ?? ""
@@ -182,6 +199,7 @@ struct PostEditorView: View {
focused: gate.isFocused,
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
@@ -196,6 +214,7 @@ struct PostEditorView: View {
},
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
@@ -218,7 +237,7 @@ struct PostEditorView: View {
flipToken += 1
// Toggle-back maps the reading scroll back (top visible block);
// click-to-edit lands at the clicked paragraph (survives always).
flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken)
flipBackCaret = FixCardRevealRequest(range: NSRange(location: caret ?? readingState.topSourceLocation ?? 0, length: 0), token: flipToken)
reading = false
}
@@ -338,8 +357,8 @@ private struct SaveStateDot: View {
// MARK: - TextKit2 surface (the lifted spike pane)
/// #141: the SwiftUI drop target's handle down to the live prose text
/// view (weak — dies with the editor surface).
/// #141: the window-level SwiftUI destination's handle down to the live
/// prose text view (weak — dies with the editor surface).
@MainActor
final class ProseDropBridge {
weak var textView: ProseListTextView?
@@ -348,8 +367,9 @@ final class ProseDropBridge {
/// NSTextView in a scroll view; attributes are presentation-only over a plain
/// store. Session mode: edits → session.edit (debounce), cursor → session,
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
/// #71: `caretHint` (location + token) lands the caret after a flip back
/// from reading — applied once per token, after any generation load.
/// #71/#204: `caretHint` (range + token) lands a bare caret after a flip
/// back from reading or SELECTS a card's anchor span after a Jump — applied
/// once per token, after any generation load.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
@@ -361,22 +381,24 @@ struct ProseTextView: NSViewRepresentable {
var spellChecking = false
/// #21: focus mode — the text ground joins the workspace background.
var focused = false
var caretHint: (location: Int, token: Int)?
var caretHint: FixCardRevealRequest?
/// #141: the piece folder dropped images ingest into — saved posts
/// only (drafts have no folder until first save; the external guest
/// isn't a piece). Nil = image drags refuse loudly.
var ingestFolder: URL?
/// #141: the drop bridge — the WINDOW-level SwiftUI drop target
/// reaches this text view through it (app-scoped, passed down from
/// the gate at both call sites — never optional).
/// #141: the window-level SwiftUI destination's handle to the live
/// view (drops landing OUTSIDE the editor); the gate's router for drops
/// landing ON it — both handed down from the gate at both call sites.
var dropBridge: ProseDropBridge
var routeDrop: ([URL]) -> Bool
init(
session: EditorSession,
spellChecking: Bool = false,
focused: Bool = false,
caretHint: (location: Int, token: Int)? = nil,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.session = session
@@ -386,6 +408,7 @@ struct ProseTextView: NSViewRepresentable {
self.onTextChange = onTextChange
ingestFolder = session.postID != nil ? session.folderURL : nil
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
init(
@@ -393,8 +416,9 @@ struct ProseTextView: NSViewRepresentable {
spellChecking: Bool = false,
focused: Bool = false,
onEdit: @escaping (String) -> Void,
caretHint: (location: Int, token: Int)? = nil,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.draft = draft
@@ -404,6 +428,7 @@ struct ProseTextView: NSViewRepresentable {
self.caretHint = caretHint
self.onTextChange = onTextChange
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
/// Cursor state snapshot from the live view (#66).
@@ -421,16 +446,30 @@ struct ProseTextView: NSViewRepresentable {
/// location 0 then rests inside the invisible 9pt blank fragment ABOVE
/// the title, rendering as a detached terracotta stroke at the canvas
/// top. Programmatic landings (cursor restore, reading flip-back) hop
/// over leading blanks to the first content line; interactive
/// placements (click, drag, typing) never route through here.
/// over leading blanks to the first content line — zero-length landings
/// only, a #204 span never hops (`landingSpan`); interactive placements
/// (click, drag, typing) never route through here.
static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int {
max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
}
/// Where a caret-hint lands, clamped to the text: a zero-length range
/// (#71 flip-back) is a bare caret and hops past leading blanks; a
/// non-zero range (#204 jump) SELECTS the anchor exactly where it
/// resolved — a quote that IS the leading blanks selects those blanks,
/// never the title (the load restore gates its hop the same way).
static func landingSpan(for hint: FixCardRevealRequest, in text: String) -> NSRange {
let length = (text as NSString).length
let start = hint.range.length == 0 ? caretPastLeadingBlanks(max(0, hint.range.location), in: text) : max(0, hint.range.location)
let loc = min(start, length)
return NSRange(location: loc, length: min(max(0, hint.range.length), length - loc))
}
func makeNSView(context: Context) -> NSScrollView {
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
dropBridge.textView = tv // #141: the SwiftUI drop target's handle
dropBridge.textView = tv // #141: the window destination's handle
tv.onFileDrop = routeDrop // #141: the view's own drag handlers route here
tv.isRichText = false // plain source of truth; attributes are presentation
tv.allowsUndo = true
tv.isAutomaticQuoteSubstitutionEnabled = false
@@ -485,6 +524,7 @@ struct ProseTextView: NSViewRepresentable {
tv.isContinuousSpellCheckingEnabled = spellChecking
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
dropBridge.textView = tv // #141: idempotent re-point
tv.onFileDrop = routeDrop // #141: idempotent re-point
// #21: the ground follows focus in/out without a remount.
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
tv.backgroundColor = ground
@@ -532,25 +572,9 @@ struct ProseTextView: NSViewRepresentable {
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
tv.refreshFolds() // #115: re-key folds over the swapped content
}
// #71: flip-back caret — apply once per token, after any load above.
// #71 flip-back caret / #204 jump span — apply once per token, after any load above.
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
context.coordinator.appliedCaretToken = hint.token
let length = (tv.string as NSString).length
// #ui-r1: same leading-blank hop as the load restore — a reading
// flip-back must never park the caret above the first content line.
let loc = min(Self.caretPastLeadingBlanks(max(0, hint.location), in: tv.string), length)
tv.setSelectedRange(NSRange(location: loc, length: 0))
// ponytail: same layout race as the cursor-restore scroll above —
// this was the click-to-edit "always lands at top" defect: the sync
// scrollRangeToVisible fired before the target region was laid out.
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
DispatchQueue.main.async { [weak tv] in
tv?.scrollRangeToVisible(NSRange(location: loc, length: 0))
tv?.window?.makeFirstResponder(tv)
}
if let session {
session.cursorUpdate(ProseTextView.cursorState(of: tv))
}
context.coordinator.applyCaretHint(hint, tv: tv, session: session)
}
}
@@ -576,6 +600,33 @@ struct ProseTextView: NSViewRepresentable {
onTextChange = representable.onTextChange
}
/// The caret rail's landing (#71 flip-back, #204 jump). Called by the
/// representable once per token.
func applyCaretHint(_ hint: FixCardRevealRequest, tv: NSTextView, session: EditorSession?) {
appliedCaretToken = hint.token
let landing = ProseTextView.landingSpan(for: hint, in: tv.string)
tv.setSelectedRange(landing)
// ponytail: same layout race as the cursor-restore scroll — this was
// the click-to-edit "always lands at top" defect: the sync
// scrollRangeToVisible fired before the target region was laid out.
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
DispatchQueue.main.async { [weak tv] in
guard let tv else { return }
// #204: a jump (span > 0) comes from the palette window, which
// holds key after the click — make the main window key or the
// first responder never sees keystrokes. The #71 flip-back
// (span 0) is already in the key window; untouched.
if landing.length > 0 {
tv.window?.makeKeyAndOrderFront(nil)
}
tv.scrollRangeToVisible(landing)
tv.window?.makeFirstResponder(tv)
// Recorded AFTER the scroll: the sidecar's scrollOffset must be
// the landed one, or a reopen restores an off-screen selection.
session?.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
let sel = tv.selectedRange()
+44 -13
View File
@@ -24,7 +24,9 @@ import Foundation
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
/// with our three owned keys winning in place (importFile, #95).
/// with our three owned keys winning in place (importFile, #95), and
/// Museion's Micro.blog bookkeeping dropped (#206 — a foreign file
/// carries no post of THIS library).
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
/// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss).
@@ -33,6 +35,19 @@ import Foundation
/// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order.
nonisolated enum PostFrontmatter {
/// The frontmatter timestamp shape (`stats_captured`, #31;
/// `micropub_published`, #206) — local time, lexically sortable. The
/// one home for the format: both stamp writers and the reader share it.
static let stampFormat = "yyyy-MM-dd'T'HH:mm:ss"
/// Museion's Micro.blog bookkeeping — written only by the app (or the
/// writer's own hand, the legacy migration), never trusted from
/// outside: the import boundary DROPS these keys and the 404 forget
/// removes them. #206: an imported `micropub_url` passes the format
/// gate and would steer the next send's content replace — under the
/// writer's token — onto whatever post it names.
static let micropubKeys: Set<String> = ["micropub_url", "micropub_published"]
/// The leniently-decoded identity triple — one home for the `?? default`
/// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this
@@ -139,8 +154,9 @@ nonisolated enum PostFrontmatter {
/// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the
/// pairs.
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
/// pairs. `dropping` removes those keys' lines outright, first (#206:
/// the import boundary and the 404 forget).
static func updating(text: String, with pairs: [(key: String, value: String)], dropping: Set<String> = []) -> String {
let (block, body) = split(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
@@ -159,17 +175,15 @@ nonisolated enum PostFrontmatter {
// the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// if nested frontmatter ever matters.
if !dropping.isEmpty {
lines.removeAll { key(ofLine: $0).map(dropping.contains) == true }
}
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
lines[index] = "\(key): \(value)"
seen.insert(key)
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
@@ -181,13 +195,30 @@ nonisolated enum PostFrontmatter {
/// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post). The update posture over the known-key table.
/// as post), and Museion's Micro.blog bookkeeping is dropped (#206: a
/// foreign file carries no post of this library — its `micropub_url`
/// would otherwise aim the next send's content replace). The update
/// posture over the known-key table.
///
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
/// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String {
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
updating(
text: text,
with: ownedKeys(type: .post, passState: .firstDraft, origin: origin),
dropping: micropubKeys,
)
}
/// A block line's key — the update posture's ONE key read (so the
/// drop and the walk can never disagree about a line): leading and
/// trailing whitespace trimmed, a trailing `\r` included (CRLF
/// files). Nil for the fences and blank lines.
private static func key(ofLine line: String) -> String? {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { return nil }
return String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
}
}
+38 -22
View File
@@ -28,10 +28,18 @@ nonisolated struct Post: Identifiable, Equatable {
var project: String
/// True when the piece lives under archive/ (#107).
var isArchived: Bool
/// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter
/// `micropub_url`) — set when a draft was sent, the target the
/// publish step updates. Inert to everything else.
/// #33 (S6.1): the remembered Micro.blog post URL (frontmatter
/// `micropub_url`) — set when a draft was sent; the target the
/// publish step updates and a re-send replaces in place (#206), and
/// half of the row's status. Inert to everything else.
var micropubURL: String?
/// #206: when Publish succeeded — frontmatter `micropub_published`,
/// the `stats_captured` stamp shape (local time). The Museion-side
/// publish record: the library answers "is this piece out, and
/// since when" from disk, never from a live query. Nil = never
/// published from here (a piece published before this stamp read
/// as a draft until its next Publish).
var micropubPublished: Date?
/// #32 (S5.2): the captured first-draft stats — present ONLY when
/// `captureFirstDraftStats` stamped the piece at a pass invocation
/// (writer origin, First Draft, post type, decided there against the
@@ -41,6 +49,15 @@ nonisolated struct Post: Identifiable, Equatable {
/// keys, and non-writer or outline pieces never render them.
var firstDraftStats: FirstDraftStats?
/// #206: the row's Micro.blog status — nil when the piece was never
/// sent; a remembered URL alone is a draft; the publish stamp wins.
var micropubStatus: String? {
if let micropubPublished {
return "published \(Micropub.shortDate(micropubPublished))"
}
return micropubURL == nil ? nil : "draft on Micro.blog"
}
/// New pieces land here when no project is selected (#107).
static let defaultProject = "posts"
@@ -58,7 +75,7 @@ nonisolated struct Post: Identifiable, Equatable {
/// reads "steady" in the verdict (finish-audit #32).
init?(frontmatter: [String: String]) {
guard
let captured = frontmatter["stats_captured"].flatMap(Self.parseCaptured),
let captured = frontmatter["stats_captured"].flatMap(Post.parseStamp),
let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite),
@@ -73,15 +90,6 @@ nonisolated struct Post: Identifiable, Equatable {
)
}
/// The symmetric read of the capture stamp (`FixCardStore.formatted`,
/// local time) — per-access formatter, the repo's no-static convention.
private static func parseCaptured(_ stamp: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: stamp)
}
/// Frontmatter is external data (hand-edits, imports): reject the
/// non-finite doubles Swift's `Double(String)` happily parses.
private static func finite(_ raw: String) -> Double? {
@@ -189,15 +197,12 @@ nonisolated struct Post: Identifiable, Equatable {
type: stamp.type,
project: project,
isArchived: isArchived,
// #33: the remembered Micro.blog draft URL —
// one flat key, read leniently like the rest.
// #33 audit: imported frontmatter rides
// verbatim, so the read-back gates on the same
// format guard the decode applies — a hostile
// value never pre-arms the publish sheet.
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #33: the remembered Micro.blog URL — one flat key
// through the ONE trust gate (an import drops the key,
// #206, so a hostile value never pre-arms the publish
// sheet); #206: the publish stamp beside it.
micropubURL: Micropub.rememberedURL(frontmatter),
micropubPublished: frontmatter["micropub_published"].flatMap(parseStamp),
// #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which
// legitimately advances after the capture. `stats_*`
@@ -210,6 +215,17 @@ nonisolated struct Post: Identifiable, Equatable {
)
}
/// The frontmatter timestamp reader — `yyyy-MM-dd'T'HH:mm:ss`, local
/// time (`FixCardStore.formatted`'s writer side); nil on anything
/// else. The symmetric read of the #31 capture stamp and the #206
/// publish stamp. Per-access formatter, the repo's no-static convention.
private static func parseStamp(_ stamp: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = PostFrontmatter.stampFormat
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: stamp)
}
/// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
+36 -13
View File
@@ -166,7 +166,9 @@ nonisolated enum PostStore {
/// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// verbatim with `type: post`, `pass_state: First Draft` and
/// `origin: <chosen>` set / overwritten (our three keys win); id = Title
/// `origin: <chosen>` set / overwritten (our three keys win) and the
/// Micro.blog bookkeeping dropped (#206 — a foreign file carries no
/// post of this library); id = Title
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
/// no mtime preservation (#96).
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
@@ -663,7 +665,7 @@ nonisolated extension PostStore {
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body)
let stamped = PostFrontmatter.updating(text: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_captured", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
@@ -675,22 +677,35 @@ nonisolated extension PostStore {
return true
}
// MARK: #33 (S6.1) — the remembered Micro.blog draft URL
// MARK: #33 (S6.1) / #206 — the remembered Micro.blog post
/// Stamp `micropub_url` in place on a successful draft send — the
/// publish step's target (a frontmatter-only change: the body and
/// Stamp micropub keys in place (`micropub_url`, the publish record
/// `micropub_published`) — a frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires). A vanished piece throws
/// (write-never-resurrects, `writeNew` is the only creator).
static func stampMicropubURL(id: String, url: String, home: URL) throws {
/// readBody-based echo check never fires, and every later editor
/// save re-reads the block (the stamps survive it). A vanished piece
/// throws (write-never-resurrects, `writeNew` is the only creator).
/// `dropping` removes those keys' lines outright (the forget).
static func stampMicropub(_ id: String, home: URL, _ pairs: [(key: String, value: String)], dropping: Set<String> = []) throws {
guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
try PostFrontmatter.updating(text: raw, with: pairs, dropping: dropping)
.write(to: file, atomically: true, encoding: .utf8)
}
/// #206: the piece forgets Micro.blog — both keys' lines removed
/// through the update posture's drop (no empty key left behind; an
/// absent key scans as no memory, and the next send inserts the line
/// fresh). Called when Micro.blog answers 404: the post is gone
/// there, so the piece is no longer on Micro.blog. Throws when the
/// write cannot land — the caller must not then claim the link is
/// gone.
static func forgetMicropub(id: String, home: URL) throws {
try stampMicropub(id, home: home, [], dropping: PostFrontmatter.micropubKeys)
}
}
// MARK: Cursor-state sidecar (#66)
@@ -756,6 +771,12 @@ struct IngestError: LocalizedError {
IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
}
/// A file the drag named but the disk can no longer stat — moved or
/// deleted between drag and drop (or a URL that never was a file).
static func missing(_ name: String) -> IngestError {
IngestError(message: "“\(name.prefix(40))” couldn’t be read — it may have moved since the drag began.")
}
/// assets/ exists as a symlink or a file — never write through it
/// (research/promote posture: the #34 rail would refuse the send).
static func hostileAssets() -> IngestError {
@@ -790,10 +811,12 @@ nonisolated extension PostStore {
// AS a link (finish-audit 2026-11-02), and the #34 rail then
// refuses the whole send — nothing enters assets/ that can't ship.
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard source.isFileURL, let values,
values.isDirectory != true, values.isSymbolicLink != true
else {
throw values?.isSymbolicLink == true ? IngestError.isLink(name) : IngestError.isFolder(name)
guard source.isFileURL, let values else { throw IngestError.missing(name) }
if values.isSymbolicLink == true {
throw IngestError.isLink(name)
}
if values.isDirectory == true {
throw IngestError.isFolder(name)
}
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
if FileManager.default.fileExists(atPath: assets.path) {
+524
View File
@@ -0,0 +1,524 @@
//
// 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<String> = []
/// #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)
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: 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()
}
}
+83 -478
View File
@@ -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,63 +33,32 @@ struct PostDraft {
let mountID = UUID()
}
/// Recursive FSEvents stream on one or more directories (#61): file-level
/// events, so nested `projects/<name>/<id>/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<PostsWatcher>.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
@Observable
final class PostsModel {
/// #200: the app's one model, for WritingLockAppDelegate's quit-time
/// departure gate (the WritingLockState.active reachability
/// precedent). Weak; registered by AppGateState's init — bare
/// hosted-test rigs never register, so the delegate's pins inject
/// their model through `quitReply(posts:)`.
weak static var active: 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
/// a scan sees the library change: a Post-list change OR any re-read
/// post.md (a body-only edit compares equal as a Post — #143's skip
/// 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.
/// #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.
@@ -112,11 +76,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
@@ -127,7 +93,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
@@ -173,68 +140,43 @@ final class PostsModel {
/// submitted; nil session (draft/guest/nothing) shows none.
/// #146: setter internal — the split-out domain extensions set it.
var openPieceCards: [FixCardStore.StoredFixCard] = []
/// #204: one jump-to-the-anchor request from the Fix Cards palette —
/// the anchor's span in the LIVE session text plus a token that
/// advances per jump (the editor column applies once per token, the
/// #71 flip-back caret pattern). Set by `revealCard`; never written
/// to disk — a jump is a view act.
var revealRequest: FixCardRevealRequest?
/// Last failed-op message surfaced in the editor (nil = clean).
/// #146: setter internal — the split-out domain extensions set it.
var lastError: String?
/// #179: the bound Home — the MODEL owns it. Construction (`bind`) and
/// the Settings repoint (bind again through `.task(id:)`) are the only
/// writers; 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()
/// #179: the bound Home — the MODEL owns it. `bind` is the only writer,
/// 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.
/// #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()
/// brief-28: the card scanner behind `refreshCards` — injectable so the
/// stale-result pin can HOLD an old-library scan past a repoint (a
/// detached disk read is otherwise faster than any test can arrange).
/// Per-model, never static (the hosted suite runs tests in parallel).
var scanPieceCards: @Sendable (URL) -> [FixCardStore.StoredFixCard] = FixCardStore.scan
/// brief-28 r1 (MF-1): the library scanner behind `rescan` — the same
/// injection shape, so the stale-Home pin can HOLD an old library's scan
/// past a repoint and watch its continuation land under the new binding.
var scanLibrary: @Sendable (URL, PostScanCache?) -> [Post] = Post.scan
/// #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
/// `.task(id: home)` — re-fires on Home repoint.
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
@@ -244,9 +186,15 @@ final class PostsModel {
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along). #96: quit also
/// flushes the external buffer — same posture, same moment.
/// #200: quit is a document departure — the flush half routes through
/// the departure gate (`documentsMayDepart`): an unanswered #67
/// conflict never writes over the foreign body, a failed flush or a
/// never-loaded retype lands its reason in lastError instead of
/// silently dropping the edits. The verdict itself is quitReply's, at
/// applicationShouldTerminate — this belt runs only at willTerminate.
/// Watchers stop either way — the process is leaving.
func shutdown() {
session?.flush()
externalSession?.flush()
documentsMayDepart()
watcher.stop()
externalWatcher.stop()
}
@@ -256,9 +204,7 @@ final class PostsModel {
/// target the default — new pieces are never born archived).
func newPost() {
let target = targetProject
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
@@ -272,9 +218,7 @@ final class PostsModel {
/// Title keeps prose semantics (raw first line).
func newOutline() {
let target = targetProject
dismissExternal()
session?.teardown(flushFirst: true)
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
@@ -283,16 +227,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).
/// #146: internal — the split-out domain extensions dismiss too.
func dismissExternal() {
externalSession?.teardown(flushFirst: true)
externalSession = nil
externalWatcher.stop()
}
/// 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.
@@ -336,16 +270,21 @@ final class PostsModel {
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
dismissExternal()
guard dismissExternal() else { return } // brief-25: the guest's edits land or the switch aborts
// A reselect of the already-open piece is a no-op — INCLUDING a
// guarded one: the piece is open under a prior answer, and firing
// the ask again would nil its session without teardown (the armed
// debounce would then flush mid-ask, outside any owned session).
if let session, session.postID == id {
// brief-28: identity, not id — only THIS library's piece counts as
// open; a session born under another Home departs below.
if let session, let home = watchedHome, session.targets(postID: id, home: home) {
return
}
if let session {
session.teardown(flushFirst: true)
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
if isGuardedOutline(id) {
outlineGuardPieceID = id
@@ -384,9 +323,10 @@ final class PostsModel {
if externalSession != nil {
return true
}
guard let session, session.postID == selectedPostID else { return false }
let outline = session.postID != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == session.postID })?.type == .outline)
// brief-28: this library's piece, by identity (Home, ID).
guard let session, let id = selectedPostID, openSessionTargets(id) else { return false }
let outline = id != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == id })?.type == .outline)
return !outline
}
@@ -400,280 +340,12 @@ final class PostsModel {
if let externalSession {
return externalSession.text
}
if let session, session.postID == selectedPostID {
if let session, let id = selectedPostID, openSessionTargets(id) { // brief-28: this library's piece, by identity
return session.text
}
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 }
// #114 audit: an unanswered #67 conflict means disk holds foreign
// text with the session's version unwritten — proceeding would act
// on the foreign body and discard the editor's. Abort; the alert
// stays up for the writer to answer, then the op retries.
if session.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
if !session.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
}
/// #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/<name>), − 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()
dismissExternal()
session?.teardown(flushFirst: true) // #92: the guest takes the column
session = nil
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 }
@@ -681,70 +353,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
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = Post.scan(home: home, cache: scanMemo)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
// #143: @Observable invalidates on assignment regardless of equality —
// skip the no-op so panes don't regroup on our own autosave echoes.
if scanned != posts {
posts = scanned
}
// 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 <piece>/cards/ writes too.
refreshCards()
}
}
+40 -7
View File
@@ -4,7 +4,8 @@
//
// #146: the fix-card extensions of PostsModel — stored-card surfacing
// (#23), apply/skip/done (#25, S3.2/S3.3), and promote (#26, S4.1) —
// moved from PostsModel.swift (file-length ceiling), code unchanged.
// moved from PostsModel.swift (file-length ceiling), code unchanged;
// #204: the jump-to-the-anchor reveal (`revealCard`, `FixCardRevealRequest`).
//
import Foundation
@@ -20,9 +21,14 @@ extension PostsModel {
/// transitions — the piece-roots watcher already fires on cards/ writes.
/// #122: the same pass also derives `openPieceHasSnapshot` (the Blind
/// Read's base) — one detached read of the open piece's disk facts.
/// brief-28: identity at BOTH ends. At launch the open session must
/// target (watchedHome, id) — a session born under another Home has no
/// cards here. At COMPLETION the re-check is identity too: the old
/// ID-only guard let a scan started under the previous library land its
/// cards on the new library's same-slug piece after a repoint.
func refreshCards() {
guard let id = session?.postID,
let home = watchedHome,
guard let session, let id = session.postID, let home = watchedHome,
session.targets(postID: id, home: home), // brief-28
let folder = PostStore.folder(of: id, home: home)
else {
openPieceCards = []
@@ -31,13 +37,15 @@ extension PostsModel {
}
// Plain disk reads re-run on every watcher burst (typing retriggers
// rescan) — keep the I/O off MainActor, same posture as rescan's
// Post.scan. The id re-check on hop-back drops a scan that raced a
// piece switch.
// Post.scan. The identity re-check on hop-back drops a scan that
// raced a piece switch or a Home repoint.
let scan = scanPieceCards // detached capture, not a property read
Task.detached { [weak self] in
let cards = FixCardStore.scan(pieceURL: folder)
let cards = scan(folder)
let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil
await MainActor.run { [weak self] in
guard let self, session?.postID == id else { return }
// brief-28: (Home, ID) at completion, never the id alone.
guard let self, self.session?.targets(postID: id, home: home) == true else { return }
openPieceCards = cards
openPieceHasSnapshot = hasSnapshot
}
@@ -126,6 +134,31 @@ extension PostsModel {
}
}
// MARK: Jump to the anchor (#204)
/// #204: one jump-to-the-anchor request — the anchor's span in the live
/// session text plus a token that advances per jump so the editor column
/// (which applies once per token) re-fires on a repeated jump. Ephemeral
/// view state: nothing here ever reaches disk.
struct FixCardRevealRequest: Equatable {
var range: NSRange
var token: Int
}
extension PostsModel {
/// #204: jump to a card's anchor — the palette's Jump. Resolves the
/// anchor against the LIVE session text (a dirty buffer still lands
/// where the writer sees it) and stamps one reveal request; the editor
/// column observes it and selects + reveals the span. A stale anchor
/// (quote gone, occurrence short) stamps nothing — the previous
/// request stands. Touches no text, no card, no disk: a jump is a view
/// act, the writer's hands stay on the wheel.
func revealCard(_ card: FixCardStore.StoredFixCard) {
guard let session, let range = FixCardStore.anchorRange(of: card, in: session.text) else { return }
revealRequest = FixCardRevealRequest(range: range, token: (revealRequest?.token ?? 0) + 1)
}
}
// MARK: Fix Card promote (#26, S4.1/S4.3)
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
+41
View File
@@ -0,0 +1,41 @@
//
// PostsModelIdentity.swift
// Museion
//
// brief-28 (home-repoint-retains-old-editor-target): document identity for
// the open session. Every "is this piece open" question in the model
// routes through here — select, the structural rail, the pass guard, the
// card refresh, Micropub. The bare `session.postID == id` comparison is
// retired: two libraries can hold the same slug, and the id alone matched
// a session retained from another library (the repoint finding's seam).
// #205: also the piece's on-disk path (`fileURL(for:)`) — the same
// (Home, ID) identity resolved to post.md for the row menus' Finder
// hand-off; nil when the piece is gone.
//
import Foundation
extension PostsModel {
/// brief-28: is the open session THIS library's piece `id`? Identity is
/// (Home, ID) — `watchedHome` is the Home half, so the answer is "the
/// buffer belongs to the piece the current library lists under that id".
/// A session born under another Home (or an external guest) is never
/// the open piece, whatever its id says; nothing bound = nothing open.
func openSessionTargets(_ id: String) -> Bool {
guard let session, let home = watchedHome else { return false }
return session.targets(postID: id, home: home)
}
/// #205: the piece's `post.md` on disk — the row menus' Reveal in
/// Finder / Copy Path target. The same (Home, ID) identity resolved to
/// a path: `watchedHome` is the Home half, `PostStore.folder(of:)` the
/// ONE id→folder resolver (never the scan snapshot — the folder is
/// what Finder opens). A pure read — nothing written, no strip. Nil
/// when the piece is gone, so the menu entries no-op instead of
/// revealing a stale path.
func fileURL(for post: Post) -> URL? {
guard let home = watchedHome,
let dir = PostStore.folder(of: post.id, home: home) else { return nil }
return dir.appendingPathComponent("post.md")
}
}
+116
View File
@@ -0,0 +1,116 @@
//
// 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. The disk read goes through
/// the shared external normalizer (brief-32): the session's text is
/// normalized on open, so a raw read raised a false conflict on every
/// directory event over an unchanged BOM/CRLF file. 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 = EditorSession.readExternalDocument(at: url) 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)
}
}
}
+13 -9
View File
@@ -66,12 +66,16 @@ extension PostsModel {
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String) {
guard let home = watchedHome else { return }
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts
// brief-28: identity — a session born under another Home is never
// "the same piece", whatever its id says; it departs here too.
if let session, !session.targets(postID: id, home: home) {
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
session = session?.targets(postID: id, home: home) == true ? session : EditorSession(postID: id, home: home)
draft = nil
pendingProject = nil
lastDraftWasOutline = false
@@ -99,7 +103,7 @@ extension PostsModel {
/// for prose typed since the last flush (#114 audit).
func stageConversion(_ post: Post) {
guard post.type == .outline else { return }
let body: String = if let session, session.postID == post.id {
let body: String = if let session, openSessionTargets(post.id) { // brief-28: identity
session.text
} else if let home = watchedHome {
PostStore.readBody(id: post.id, home: home) ?? ""
@@ -141,9 +145,9 @@ extension PostsModel {
}
performWrite { home in
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
if session?.postID == pending.id {
session?.teardown(flushFirst: false) // flushOrAbort already wrote
session = nil
if let session, openSessionTargets(pending.id) { // brief-28: identity
session.teardown(flushFirst: false) // flushOrAbort already wrote
self.session = nil
proseOverridePostID = pending.id
openUnguarded(pending.id)
}
+17 -15
View File
@@ -19,12 +19,13 @@ extension PostsModel {
/// Read, named honestly whichever runner asks), the mentor not
/// mid-reply with its engine ready, and an open SAVED piece (never a
/// draft, the external guest, or a held #111 guard ask). The refusal
/// lands in lastError naming the blocker; answers the open piece's id
/// and session — the run's target — or nil (refused).
func guardOpenPieceRun(
_ action: String,
mentor: MentorSessionModel,
) -> (id: String, session: EditorSession)? {
/// lands in lastError naming the blocker; answers the open piece's id,
/// session and Home — the run's target — or nil (refused).
/// brief-28: identity — the open session must target THIS library's
/// selected piece (Home, ID); a session born under another Home never
/// runs (its snapshot/stats/lint would land in the wrong library).
// swiftlint:disable:next large_tuple
func guardOpenPieceRun(_ action: String, mentor: MentorSessionModel) -> (id: String, session: EditorSession, home: URL)? {
guard runningPass == nil else {
lastError = "A pass is already running."
return nil
@@ -43,7 +44,9 @@ extension PostsModel {
}
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home), // brief-28
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
@@ -51,7 +54,7 @@ extension PostsModel {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session)
return (id, session, home)
}
}
@@ -64,7 +67,7 @@ extension PostsModel {
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, mentor: MentorSessionModel) async {
guard let (id, session) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
guard let (id, session, home) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings. Nothing has touched disk yet (the snapshot
// comes after this guard).
@@ -73,8 +76,8 @@ extension PostsModel {
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
// #179: the model owns the Home; an open piece implies a bound one.
guard let home = watchedHome else { return }
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity); every write below lands there.
do {
try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home)
} catch {
@@ -137,12 +140,11 @@ extension PostsModel {
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(mentor: MentorSessionModel) async {
guard let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
guard let (id, session, home) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
guard flushOrAbort(id) else { return }
// #179: the model owns the Home; an open piece implies a bound one.
guard let home = watchedHome,
let base = PostStore.latestPassSnapshot(id: id, home: home)
else {
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity).
guard let base = PostStore.latestPassSnapshot(id: id, home: home) else {
lastError = "No Pass snapshot yet — run a Pass first."
return
}
+203
View File
@@ -0,0 +1,203 @@
//
// 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/<name>/<id>/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<PostsWatcher>.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.
/// brief-28: the dumb binder — it flips `watchedHome` unconditionally.
/// A REPOINT reaches it only after `repoint(to:)` passed its departure
/// gate (the Settings binding runs the gate before committing the
/// preference; the `.task` fires after that commit).
func bind(home: URL) {
startWatching(home: home)
Task { await rescan() }
}
/// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is
/// a DOCUMENT DEPARTURE — the gate runs FIRST, the binding commits
/// after. The Settings path used to flip `watchedHome` under the open
/// session: the session's immutable target kept the OLD Home, a
/// same-slug piece in the new library made the ID-only reselect return
/// it, and autosave/Save/quit wrote the old library while structural
/// operations resolved against the new one (#198's departure gate never
/// saw this seam; a no-collision piece was torn down by the vanish
/// path with its dirty buffer dropped).
/// True = every open document landed through `sessionMayDepart` (the
/// three legs: unanswered #67, failed flush, never-loaded retype) and
/// the departed piece's state is cleared — the caller may bind the new
/// Home. False = `lastError` says why and NOTHING changed: the
/// preference stays A, `watchedHome` stays A, the session keeps its
/// (A, id) target and its buffer. No parallel gate — the same one
/// `select`/`newPost`/quit ride.
/// The in-memory draft survives: it has no Home until first save (#62)
/// and lands in the new library — the only alternative is dropping the
/// only copy. A running pass or Blind Read keeps its own completion
/// guard (#179: the advance refuses once `watchedHome` moved).
@discardableResult
func repoint(to newHome: URL) -> Bool {
guard newHome != watchedHome else { return true } // first bind / the same folder: nothing departs
guard departOpenDocuments() else { return false }
// The departed piece's state dies with it: a stale id under the new
// library is a ghost selection (a same-slug piece would read as
// open over an empty editor) and a stale ask would act on the new
// library's piece. Nothing auto-reopens — the writer picks from
// the new list (the reopen machinery stays where it is).
selectedPostID = nil
openPieceCards = []
openPieceHasSnapshot = false
outlineGuardPieceID = nil
proseOverridePostID = nil
pendingConversion = nil
lastDraftWasOutline = false
pendingProject = nil
return true
}
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).
// #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
// brief-28: the Home half of that identity — the open post's disk
// text is read from the session's OWN library. A session targeting
// another Home has no piece in this scan's tree; reading the
// current Home's same-slug file for it raised a spurious #67 on the
// old session.
let openPostID = openSession?.targets(home: home) == true ? openSession?.postID : nil
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 scan = scanLibrary // detached capture, not a property read
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = scan(home, scanMemo)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
// Stale-scan guard (#137 suite find / finish): the snapshot can
// PREDATE the current selection, and a scan that outlived a Home
// repoint speaks for the OLD tree — 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, and a
// pre-repoint scan would land the old library's list under the new
// binding. 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); the new Home's own rescan
// owns everything (brief-28: hoisted — the list, the revision and
// the #67 text ride the same verdict, not just the vanish check).
guard watchedHome == home 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
}
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), PostStore.folder(of: id, home: home) == nil {
selectedPostID = nil // the post vanished (deleted in Finder or here)
if let open = session, open.targets(postID: id, home: home) {
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 <piece>/cards/ writes too.
refreshCards()
}
}
+288
View File
@@ -0,0 +1,288 @@
//
// 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 openSessionTargets(post.id) { // brief-28: identity
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, openSessionTargets(post.id) { // brief-28: identity
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 {
// brief-28: identity — only THIS library's open piece flushes here; a
// session born under another Home is not the caller's piece.
guard let session, openSessionTargets(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
}
// #200 finish-audit (LOW): a never-loaded session's flush reports
// a vacuous success — its retyped words would die with the
// departure (quit AND navigation). Block instead: never silently
// drop the only copy.
if outgoing.loadFailed, outgoing.saveState == .changed {
lastError = "This piece's file never loaded — the retyped text in the editor can't be saved. Copy it out 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
}
/// #200 (gate quit-time flushes through the departure gate): the quit
/// run of the same gate — `shutdown`'s flush half, shared with
/// WritingLockAppDelegate's `applicationShouldTerminate` (willTerminate
/// can no longer refuse a quit). Both open documents route through
/// `sessionMayDepart`; false = the quit must not proceed, lastError
/// says why. The failed-flush-at-quit posture is BLOCK QUIT (the
/// WritingLock refusal precedent) — never silently drop the only copy
/// of the edits, never write over an unanswered #67 foreign body.
func documentsMayDepart() -> Bool {
var departed = true
if let guest = externalSession, !sessionMayDepart(guest) {
departed = false
}
if let open = session, !sessionMayDepart(open) {
departed = false
}
return departed
}
/// #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 openSessionTargets(post.id) { // brief-28: identity
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, openSessionTargets(post.id) { // brief-28: identity
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 openSessionTargets(post.id) { // brief-28: identity
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/<name>), − 2 = root.
guard let boundHome = watchedHome else { return }
func openPieceInArchivedProject() -> String? {
guard let id = session?.postID, openSessionTargets(id), // brief-28: identity
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()
}
}
}
}
+5 -577
View File
@@ -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
@@ -85,10 +87,6 @@ struct PostsPaneView: View {
}
}
}
.task(id: home) {
// Bind: initial off-main scan + (re)start the FSEvents watcher (#61).
model.bind(home: home)
}
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
@@ -185,573 +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<String> = []
/// #144: the library search — live title+body filter over the
/// non-archived pieces. nil = not searching (sections render).
@State private var query = ""
@State private var matches: [Post]?
/// 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)
}
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 {
if let matches {
if matches.isEmpty {
searchEmptyState
} else {
searchResults(matches)
}
} 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).
.task(id: trimmedQuery) {
guard !trimmedQuery.isEmpty else {
matches = nil
return
}
try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return }
let found = await librarySearch(
candidates: model.posts.filter { !$0.isArchived },
matching: trimmedQuery,
home: home,
)
guard !Task.isCancelled else { return }
matches = 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)")
}
}
+1 -3
View File
@@ -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
}
+37 -26
View File
@@ -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
+6 -1
View File
@@ -121,8 +121,13 @@ nonisolated enum ProseList {
let hiddenLineCount: Int
}
static func parents(in text: String) -> [ParentHint] {
/// `observeLines` (brief-24): reports how many lines the scan visited —
/// the typing-budget instrument. Nil in production; tests inject it to
/// pin that single-line typing edits scan ZERO lines (the #142 in-place
/// re-key) while full passes scan O(lines). Per-call, no shared state.
static func parents(in text: String, observeLines: ((Int) -> Void)? = nil) -> [ParentHint] {
let scanned = lines(in: text)
observeLines?(scanned.count)
var out: [ParentHint] = []
for (idx, line) in scanned.enumerated() where line.isList {
let bounds = blockBounds(scanned, from: idx, indent: line.indent)
+29 -13
View File
@@ -71,7 +71,7 @@ final class ProseChromeView: NSView {
}
}
final class ProseListTextView: NSTextView {
final class ProseListTextView: FileDropTextView {
/// A fold: the marker line's buffer position + its text (the re-key
/// identity when an edit above shifts offsets) + the hidden scope
/// (shift-maintained by the #142 cheap path; the full pass re-derives
@@ -90,6 +90,12 @@ final class ProseListTextView: NSTextView {
/// rejected, or none) → the full pass.
var pendingPlainEdit: (range: NSRange, delta: Int)?
/// Brief-24 typing-budget window for paths that call `refreshFolds()`
/// bare (the PostEditorView coordinator's textDidChange tail) — a
/// per-instance, test-owned hook; nil in production. The per-call
/// `observeScan` parameter takes precedence when both are set.
var onLineScan: ((Int) -> Void)?
override func shouldChangeText(in affectedRange: NSRange, replacementString: String?) -> Bool {
let accepted = super.shouldChangeText(in: affectedRange, replacementString: replacementString)
pendingPlainEdit = nil
@@ -202,7 +208,11 @@ final class ProseListTextView: NSTextView {
/// recorded single-line edit takes the in-place re-key (no rescan, no
/// storage swap); no folds → chrome-only refresh, everything else → the
/// full pass.
func refreshFolds() {
/// `observeScan` (brief-24): the typing-budget instrument — reports the
/// line count of every full-buffer scan this refresh performs. Nil in
/// production; the typing-budget pins inject it to prove single-line
/// edits take the in-place re-key (zero scans) at any buffer size.
func refreshFolds(observeScan: ((Int) -> Void)? = nil) {
defer { pendingPlainEdit = nil }
if let edit = pendingPlainEdit, !folds.isEmpty, rekeyAfterPlainEdit(edit) {
return
@@ -211,7 +221,7 @@ final class ProseListTextView: NSTextView {
chrome.refresh()
return
}
refreshFoldRendering()
refreshFoldRendering(observeScan: observeScan)
}
func toggleFold(_ parent: ProseList.ParentHint) {
@@ -227,8 +237,8 @@ final class ProseListTextView: NSTextView {
/// same marker text; no match → the fold dies), restyle the document,
/// re-hide every live scope, and park a caret that landed inside a
/// hidden scope at its parent's marker end.
func refreshFoldRendering() {
let parents = ProseList.parents(in: string)
func refreshFoldRendering(observeScan: ((Int) -> Void)? = nil) {
let parents = ProseList.parents(in: string, observeLines: observeScan ?? onLineScan)
// ponytail: nearest-same-marker re-key can move a fold across duplicate
// marker texts — track the edit delta in shouldChangeText if that bites.
var seenKeys = Set<Int>()
@@ -328,8 +338,10 @@ final class ProseListTextView: NSTextView {
return firstRect(forCharacterRange: NSRange(location: charIndex, length: 1), actualRange: nil).midY
}
/// #141's SwiftUI entry — the window `.dropDestination`'s perform
/// routes here after markdown forwarding is ruled out upstream.
/// #141's ingest entry — `AppGateState.routeFileDrop` routes here
/// from whichever surface took the drag (the text view's own drag
/// handlers over the editor, the window `.dropDestination` elsewhere)
/// after markdown forwarding is ruled out upstream.
/// The drop point is read from the live pointer (NSEvent.mouseLocation
/// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02).
/// Gates: saved piece, every file publishable (#34's mimeType set) —
@@ -344,8 +356,10 @@ final class ProseListTextView: NSTextView {
}
// The publish-able set IS #34's mimeType gate — nothing the rail
// can't ship ever enters assets/. A mixed md+image set refuses
// here too (only pure-markdown sets are forwarded upstream).
guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
// here too (only pure-markdown sets are forwarded upstream), and
// so does a web URL (a browser image drag): the extension may
// look publishable, but nothing is on disk to copy.
guard urls.allSatisfy({ $0.isFileURL && Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.")
return false
}
@@ -367,10 +381,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
}
@@ -409,7 +420,12 @@ final class ProseListTextView: NSTextView {
private var ingestNotice: NSTextField?
private var ingestNoticeHide: DispatchWorkItem?
/// The last refusal text — the observable the pins read (the strip
/// itself is private chrome).
private(set) var lastIngestNotice: String?
private func showIngestNotice(_ text: String) {
lastIngestNotice = text
let strip: NSTextField
if let ingestNotice {
strip = ingestNotice
+177 -102
View File
@@ -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<Substring>, 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<Int>] = []
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<Int>) -> 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<Int>], _ span: Range<Int>) -> Bool {
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
claimed.append(span)
return true
}
func dim(_ utf16: Range<Int>) {
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<Int>) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(ProseTypography.codeAttributes, range: range)
}
func attr(_ utf16: Range<Int>, _ 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<Int>, _ 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<Int>],
) {
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<Int>],
) {
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<Int>],
) {
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] {
+4 -2
View File
@@ -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
+3 -2
View File
@@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter {
// swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\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 {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head>" +
"<body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
}
static func escapeHTML(_ text: String) -> String {
+8 -3
View File
@@ -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
}
+41
View File
@@ -0,0 +1,41 @@
# Third-Party Notices
Museion is GPL-3.0-or-later. It bundles the two components below, both under
the MIT License; the full license text follows.
## apex 1.1.59 (`apex`)
Markdown → HTML converter, used for reading mode.
Copyright (c) 2026 Brett Terpstra — https://github.com/ApexMarkdown/apex
Redistributed as the arm64 slice of the v1.1.59 release binary (checksum
verified against the published `.sha256`), re-signed for Developer ID
distribution; rpath rewritten to load the libyaml beside it.
## libyaml 0.2.5 (`libyaml.bundle/libyaml-0.2.dylib`)
YAML parser linked by apex.
Copyright (c) 2017-2020 Ingy döt Net
Copyright (c) 2006-2016 Kirill Simonov — https://github.com/yaml/libyaml
Re-signed for Developer ID distribution (the hardened runtime's library
validation requires the team's own signature); shipped inside a `.bundle`
folder so Xcode copies it as a resource instead of linking it into the app.
## MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Binary file not shown.
Binary file not shown.
+80 -1
View File
@@ -6,7 +6,9 @@
// in-memory SettingsModel — one page per LLM surface (provider select,
// registry combobox with first-class free text, per-provider effort menu)
// and the Provider Keys page (endpoint, z.ai key-type toggle swapping the
// endpoint family, masked key + reveal). Visual contract: #130 prototype
// endpoint family, masked key + reveal). The Micro.blog page is the app
// token's home (saved status, replace, remove over the publish sheet's own
// Keychain slot). Visual contract: #130 prototype
// variant C, with variant B's current-model headline folded in.
//
@@ -340,6 +342,83 @@ private struct TestConnectionResult: View {
}
}
/// The Micro.blog page: the app token's home — saved status, replace,
/// remove. Writes the SAME Keychain slot the publish sheet reads
/// (`MicropubTokenStore`), so a token saved here is the one a send
/// carries; the sheet's own field stays the first-run path and its
/// 401/403 re-entry. `saved` is read back from the Keychain after every
/// write, never assumed — a locked keychain fails the save and the
/// status line says so.
struct MicroblogSettingsPage: View {
@State private var tokenField = ""
@State private var saved = MicropubTokenStore.read() != nil
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("Micro.blog")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Where the Micro.blog app token lives.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
form
.padding(.top, 12)
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 24)
.padding(.top, 17)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private var trimmedToken: String {
tokenField.trimmingCharacters(in: .whitespaces)
}
private var form: some View {
VStack(alignment: .leading, spacing: 6) {
SettingsFieldLabel("App Token")
HStack(spacing: 8) {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
Button("Save") {
let token = trimmedToken
MicropubTokenStore.save(token)
tokenField = ""
saved = MicropubTokenStore.read() == token
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(trimmedToken.isEmpty)
if saved {
Button("Remove") {
MicropubTokenStore.delete()
saved = MicropubTokenStore.read() != nil
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
}
}
// The standing state, in the Settings verdict idiom (Provider
// Keys' "✓ works"). The intro line is a description — a state
// swap there never read as a status.
status
Text("From micro.blog → Account → App Tokens. Stored in your Keychain — the publish sheet sends with this token.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
.padding(.top, 2)
}
}
/// Live: Save and Remove read the Keychain back, so this line is
/// both the confirmation that a write landed and the standing
/// answer to "is a token stored?".
private var status: some View {
Text(saved ? "✓ Token saved in your Keychain" : "No token saved — publishing will ask for one")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(saved ? DesignTokens.accent : DesignTokens.muted)
.padding(.top, 2)
}
}
/// The z.ai key-type toggle (prototype `.seg`): a two-segment capsule, the
/// selected segment filled with the foreground ink. Toggling swaps the
/// endpoint family (the model guards a custom endpoint).
+9 -4
View File
@@ -5,9 +5,9 @@
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
// #135 (Profiles S2): reworked to the #130 prototype's variant C verdict —
// a Settings sidebar + detail column (System Settings shape): destinations
// Content · Pass 1 · Pass 2 · Chat · Provider Keys. Content keeps the #17
// Home control unchanged; the surface and keys pages live in
// SettingsPagesView.swift.
// Content · Pass 1 · Pass 2 · Chat · Provider Keys · Micro.blog. Content
// keeps the #17 Home control unchanged; the surface, keys, and Micro.blog
// pages live in SettingsPagesView.swift.
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
// CLI/.env rail) and hydrates from the profiles at pane open.
//
@@ -109,6 +109,8 @@ struct SettingsPaneView: View {
SurfaceSettingsPage(model: model, surface: .chat)
case .keys:
ProviderKeysPage(model: model)
case .microblog:
MicroblogSettingsPage()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -116,13 +118,15 @@ struct SettingsPaneView: View {
}
/// The sidebar's destinations (#135): the #17 Content control, one page per
/// LLM surface (Sessions rides Chat — #126), and the provider keys.
/// LLM surface (Sessions rides Chat — #126), the provider keys, and the
/// Micro.blog app token (the one Keychain credential, ADR-0014).
enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
case content
case pass1
case pass2
case chat
case keys
case microblog
var id: String {
rawValue
@@ -135,6 +139,7 @@ enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
case .pass2: "Pass 2"
case .chat: "Chat"
case .keys: "Provider Keys"
case .microblog: "Micro.blog"
}
}
+138
View File
@@ -0,0 +1,138 @@
//
// WorkspaceChrome.swift
// Museion
//
// #193: the shared workspace chrome, moved from WorkspaceView.swift
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
// PaneHeader; every pane reuses them, code unchanged. #205 adds
// FinderHandOffButtons, #206 MicroblogHandOffButton (both born here).
//
import AppKit
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<Trailing: View>: 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)
}
}
}
/// #205: the row menus' Finder hand-off — Reveal in Finder + Copy Path,
/// one fragment for every surface that lists pieces (the library column,
/// the Archive pane). Both act on `model.fileURL(for:)` — the resolved
/// `post.md`; a nil URL (the piece is gone) no-ops.
struct FinderHandOffButtons: View {
let model: PostsModel
let post: Post
var body: some View {
Button("Reveal in Finder") {
if let url = model.fileURL(for: post) {
NSWorkspace.shared.activateFileViewerSelecting([url])
}
}
Button("Copy Path") {
if let url = model.fileURL(for: post) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(url.path, forType: .string)
}
}
}
}
/// #206: the row menus' Micro.blog hand-off — Open on Micro.blog, for a
/// piece that is published (a draft's final URL does not exist yet on
/// their side, so a draft shows no entry; neither does a never-sent
/// piece). The URL is the piece's remembered `micropub_url`, already
/// trust-gated at the scan.
struct MicroblogHandOffButton: View {
let post: Post
var body: some View {
if post.micropubPublished != nil, let url = post.micropubURL.flatMap({ URL(string: $0) }) {
Button("Open on Micro.blog") {
NSWorkspace.shared.open(url)
}
}
}
}
+49 -446
View File
@@ -7,8 +7,12 @@
// 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 AppKit
import SwiftUI
/// The post-gate main surface. Posts shows the full four-column workspace;
@@ -52,27 +56,14 @@ struct WorkspaceView: View {
}
}
}
// #91: drag a markdown file onto the window — same guest slot as
// File ▸ Open… Non-markdown drops are refused.
// #91/#141: drops landing OUTSIDE the editor (over the editor the
// text view takes the drag itself — FileDropTextView); one router.
.dropDestination(for: URL.self) { urls, _ in
// #162: no new buffers while a Cold Turkey block holds —
// the open Piece is the one being counted.
guard !gate.writingLock.isLocked else { return false }
// #141: the window destination is the only one that ever
// fires (field-verified 2026-11-02 — nested editor-level
// SwiftUI targets are never consulted, and AppKit views
// registered for file drags are starved by it).
// PURE-markdown sets keep #91's open-as-guest; a mixed
// md+image set falls through and ingestDrop refuses it
// loudly (images must not vanish silently behind the md).
// Nil text view: bounce.
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
gate.posts.openExternal(url)
let landed = gate.routeFileDrop(urls)
if landed {
selection = .posts
return true
}
guard let textView = gate.proseDrop.textView else { return false }
return textView.ingestDrop(urls)
return landed
}
// #21: left-edge hover slides rail+library back in as an overlay.
// Library only while the window width allows it (#17 verdict stands:
@@ -151,6 +142,13 @@ struct WorkspaceView: View {
}
}
}
// #179 follow-up: the model bind rides the ROOT task — the Archive
// pane and every root sheet (import / new project / convert) call
// library verbs from any pane; a pane-local bind left `watchedHome`
// stale after a Home repoint until Posts remounted.
.task(id: gate.museionHome) {
gate.posts.bind(home: gate.museionHome)
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #151: every failure arrival auto-expands the card — a fresh
@@ -238,6 +236,37 @@ struct WorkspaceView: View {
)
}
/// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a
/// document departure. The binding's setter IS the gate —
/// `repointMuseionHome` runs the departure gate first and commits the
/// preference (and its persistence) only when every open document
/// landed; the root `.task(id: museionHome)` binds the model after that
/// commit. A refusal keeps Home A and every buffer, and speaks the #198
/// reason the way #200's quit refusal does — the Posts strip that shows
/// `lastError` is not in sight from Settings.
private var homeRepointBinding: Binding<URL> {
Binding(
get: { gate.museionHome },
set: { newHome in
guard gate.repointMuseionHome(to: newHome) else {
presentRepointRefusal()
return
}
},
)
}
/// Hosted tests never present (the quit refusal's guard convention).
private func presentRepointRefusal() {
guard !AppGateState.hostedTestRun else { return }
let alert = NSAlert()
alert.messageText = "Home not changed — a piece needs you first"
alert.informativeText = gate.posts.lastError
?? "An open piece could not be saved. Tend to it, then choose the folder again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
/// #151: the pill/card state — the gate's phase machine plus the
/// provisioning failure verdict.
private var statusVisibility: EngineStatusSurface.Visibility {
@@ -249,7 +278,6 @@ struct WorkspaceView: View {
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate
switch selection {
case .posts:
// #14: mentor column hands in the app-scoped model + gate's winner.
@@ -293,8 +321,9 @@ struct WorkspaceView: View {
// #137 (S4): a committed Chat model change restarts the resident
// chat engine in place (slice A's engine-side API; deferred to
// turn end while streaming).
// brief-28: the Home control binds through the repoint gate.
SettingsPaneView(
home: $gate.museionHome,
home: homeRepointBinding,
binaryPath: gate.gateModel.currentBinaryPath,
onChatSurfaceWrite: { gate.mentor.requestRestart() },
)
@@ -348,346 +377,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<String> = []
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
@@ -754,89 +443,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<Trailing: View>: 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)
}
}
}
+189
View File
@@ -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()
}
}
}
+19 -8
View File
@@ -24,9 +24,9 @@ nonisolated enum WritingGoal: Equatable {
/// (typing, deleting, pasting, undo all land as whole-document
/// text), and `now` is injected, so the countdown can never be
/// paused or deferred from inside the engine. Word counting rides
/// `DraftStats.words` — the one tokenizer all text metrics share, so
/// net-words can never drift from first-draft stats ("writer's" is
/// two words there, headings are body text; frontmatter is not body
/// `DraftStats.words` — the one word-count rail all text metrics
/// share, so net-words can never drift from first-draft stats
/// ("writer's" is two words there, headings are body text; frontmatter is not body
/// text — the editor never shows it, so it never counts).
nonisolated struct WritingGoalRun: Equatable {
let goal: WritingGoal
@@ -35,7 +35,9 @@ nonisolated struct WritingGoalRun: Equatable {
let armedAt: Date
/// Whole-document word count at arm.
let baselineWords: Int
/// Whole-document word count as of the last `update(text:)`.
/// Whole-document word count as of the last `update(text:)` —
/// words goals only; a minutes run freezes at the arm-time
/// count (the verdict never reads it).
private(set) var currentWords: Int
init(goal: WritingGoal, armedAt: Date, body: String) {
@@ -46,10 +48,19 @@ nonisolated struct WritingGoalRun: Equatable {
currentWords = words
}
/// Record the live editor text. The caller passes the whole
/// document every time; the net falls out of the delta.
mutating func update(text: String) {
currentWords = DraftStats.words(in: text)
/// Record the live editor text — words goals only. The caller
/// passes the whole document every time; the net falls out of
/// the delta. A minutes run never re-counts: its verdict and
/// progress ride the clock alone, so the per-keystroke feed
/// does no word work at all (opt pass 2026-11-09 — the feed
/// once tokenized the whole document per keystroke for a count
/// nothing read). `countWords` is the injectable word rail —
/// the pins count rail trips through this seam (a global
/// counter would race the hosted suite's parallel DraftStats
/// calls).
mutating func update(text: String, countWords: (String) -> Int = DraftStats.words(in:)) {
guard case .words = goal else { return }
currentWords = countWords(text)
}
/// Net new words since arm. Deleting costs — net, not gross; a
+43 -3
View File
@@ -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
@@ -325,9 +332,19 @@ enum WritingLockKiosk {
/// unlocked quits proceed, a held block gets ONE modal ask — walk away
/// (the block dies quietly with the process, nothing kept — #158 settle
/// 3) or keep writing.
/// #200: quit is also a document departure — the posts gate runs FIRST
/// (never walk away from a block the quit then refuses to complete): an
/// open document that can't depart (unanswered #67 conflict, failed
/// flush) refuses termination with one spoken reason.
@MainActor
final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
// #200: the departure gate — before the lock ask, so a refusal
// never strands a walked-away block in a still-running app.
guard quitReply(posts: PostsModel.active) == .terminateNow else {
presentQuitRefusal()
return .terminateCancel
}
guard WritingLockState.active?.isLocked == true else { return .terminateNow }
let alert = NSAlert()
alert.messageText = "Walk away from the block?"
@@ -343,4 +360,27 @@ final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
}
return .terminateCancel
}
/// #200: the quit-time departure gate — the pure decision, no UI (the
/// pins' seam; the refusal alert below is hosted-guarded like the
/// kiosk). nil posts (no model alive) passes: nothing is open,
/// nothing to lose.
func quitReply(posts: PostsModel?) -> NSApplication.TerminateReply {
guard let posts else { return .terminateNow }
guard posts.documentsMayDepart() else { return .terminateCancel }
return .terminateNow
}
/// #200: the refusal speaks (#163's ruling — self-aware friction, not
/// silence): one alert naming the strip's reason. Hosted tests never
/// present (the startLaunchCheck guard convention).
private func presentQuitRefusal() {
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
let alert = NSAlert()
alert.messageText = "Quit stopped — a piece needs you first"
alert.informativeText = PostsModel.active?.lastError
?? "An open piece could not be saved. Tend to it, then quit again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
}
+17
View File
@@ -49,6 +49,13 @@ import Testing
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
/// the finish-audit interleaving pin's in-flight observable.
/// Mode `neverRead` (brief-27): execs /bin/sleep 30 without reading one
/// line — the inert non-reading child of the backpressure smokes (the
/// pipe fills, the client's writer blocks; the finding's probe shape).
/// Mode `serverPing` (brief-27): full behaviour PLUS one server→client
/// request (id 900) emitted at initialize — the client must answer -32601
/// over the wire; the fake logs our reply line to `<name>-reply-log`
/// (the reply-delivery pin).
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
@@ -69,6 +76,11 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
mode="full"
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran
if [[ "$mode" == "neverRead" ]]; then
# brief-27: /bin/sleep never reads stdin — the pipe fills and the client's writer blocks.
# exec keeps sleep the DIRECT child (close SIGTERMs it; no orphan holds the pipe open).
exec /bin/sleep 30
fi
card=$(print -- '\(fixCardB64)' | base64 -d)
research=$(print -- '\(researchB64)' | base64 -d)
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
@@ -80,7 +92,12 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
[[ -z "$line" ]] && continue
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$mode" == "serverPing" && "$rid" == "900" && -z "$method" ]]; then
print -r -- "$line" >> "${0:h}/\(name)-reply-log" # brief-27: the client's -32601 reply to our server request, on the wire
continue
fi
if [[ "$method" == "initialize" ]]; then
[[ "$mode" == "serverPing" ]] && echo '{"jsonrpc":"2.0","id":900,"method":"client/ping"}'
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then
+8 -6
View File
@@ -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.
@@ -31,18 +32,19 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched).
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates).
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import, image ingest + the 27.2 drag-routing seam (`DragInfoStub`, the suite's NSDraggingInfo mock: a Finder-shaped drag routes through the text view and never pastes the path; text-only drags keep the stock drop; outline rows bounce; the probe follows `changeCount`; web URLs and vanished files refuse with the right notice) + the one router's pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal).
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
- `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline.
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests`, `ProviderCredentialTests` — settings model, real CLI write path, probe decode + request builders, the #181 ONE credential resolution (pasted key wins, keyless fallback on the official endpoint, custom-endpoint and no-login refusals).
@@ -50,7 +52,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
+37
View File
@@ -75,3 +75,40 @@ import Testing
#expect(abs(DraftStats.compute(body: "Dog dog DOG").typeTokenRatio - 1.0 / 3.0) < 0.001)
#expect(abs(DraftStats.compute(body: "writer's note writer").typeTokenRatio - 3.0 / 4.0) < 0.001)
}
@Test func `word rail equals the split tokenizer over a mixed corpus`() {
/// The count-only word rail (opt pass 2026-11-09) must answer exactly
/// what the lowercased-token array answered: split on
/// !(isLetter || isNumber), empty subsequences omitted. The reference
/// IS the old implementation — the corpus (mixed scripts, emoji,
/// punctuation, numbers, empties) makes any semantic drift (e.g. a
/// whitespace count) fail here.
func reference(_ text: String) -> Int {
text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).count
}
let corpus = [
"",
" \t\n ",
"\n\n\n",
"— — !!!",
"one two three",
"writer's note",
"## Chapter Two — draft 3",
"abc123def",
"3.14 and 2,718,281",
"$5,000 USD",
"naïve café Zürich",
"Привет мир",
"日本語のテキストです",
"مرحبا بالعالم",
"emoji 👨‍👩‍👧‍👦 are not words",
"word—word, word; word: word",
"One two three. Four five! Six?",
]
for text in corpus {
#expect(
DraftStats.words(in: text) == reference(text),
"corpus mismatch for \(text.debugDescription)",
)
}
}
+172
View File
@@ -9,6 +9,11 @@
// Then exactly one real-process end-to-end smoke per surface (chat on museion,
// pass1, pass2) drives the real ACPEngineClient + the zsh fake — the only
// child-spawning tests left in the suite.
// brief-27 (acp-backpressure): plus the blocked-writer regression rig — a
// never-reading /bin/sleep child (the finding probe's shape) pins that a full
// stdin pipe cannot defeat the request deadline, Stop delivery, or a bounded
// reaping close; a serverPing fake pins the healthy contract (round trip,
// -32601 reply delivery, idempotent clean close).
//
import Foundation
@@ -214,4 +219,171 @@ struct EngineSmokeTests {
#expect(kill(chatPid, 0) == 0)
#expect(mentor.phase.isReady)
}
// MARK: - brief-27 backpressure smokes (blocked-writer regression rig)
/// brief-27: await an operation that may HANG on the unfixed transport
/// (the RED shape) and report what it answered — nil when the window leg
/// won. One deadline per call (the house rule). The bound is `window`
/// only in the green world: withTaskGroup awaits stragglers at scope
/// exit and `await task.value` is cancellation-blind, so a HUNG task
/// holds this helper until IT settles — the real RED-world watchdog is
/// the fake's `exec /bin/sleep 30` exit (~30 s, inside the rail's 60 s
/// per-test timeout). Keep the fake's sleep short.
@MainActor
private func awaitBounded<T: Sendable>(_ task: Task<T, Never>, window: TimeInterval) async -> T? {
await withTaskGroup(of: T?.self) { group in
group.addTask { await task.value }
group.addTask {
try? await Task.sleep(nanoseconds: UInt64(window * 1_000_000_000))
return nil
}
let first = await group.next() ?? nil
group.cancelAll()
return first
}
}
/// brief-27: run one request on a task and string-encode its outcome
/// ("returned" or the error) — the observable the pins match on.
@MainActor
private func requestOutcome(
_ client: ACPEngineClient, method: String, params: JSONValue?, timeout: TimeInterval,
) -> Task<String, Never> {
Task<String, Never> {
do {
_ = try await client.request(method, params: params, timeout: timeout)
return "returned"
} catch {
return String(describing: error)
}
}
}
/// brief-27: the blocked-writer rig — a real ACPEngineClient over the
/// zsh fake in `neverRead` mode, which execs /bin/sleep without ever
/// reading stdin (the finding's inert non-reading child; no real
/// profile is anywhere near it). The oversized prompt fills the 64 KB
/// pipe and wedges the writer.
@MainActor
private func makeBlockedWriterRig(label: String) throws -> (client: ACPEngineClient, pid: pid_t) {
let dir = acpTempDir(label)
let fake = makeFakeACP(at: dir, mode: "neverRead")
let client = ACPEngineClient(binaryPath: fake)
client.onMessage = { _, _ in }
try client.start()
return (client, client.childProcessIdentifier)
}
/// The pipe-filling payload: a 2,000,000-char prompt (the probe's size;
/// the pipe holds 64 KB).
private var blockedWriterPayload: JSONValue {
.object(["prompt": .string(String(repeating: "x", count: 2_000_000))])
}
/// brief-27 regression 1: the request deadline FIRES while the stdin
/// write is blocked. On the unfixed transport the deadline sits on the
/// same serial queue as the blocked send and never runs — the request
/// stays pending forever (the finding's executed probe).
@MainActor
@Test func `request deadline fires while the stdin write is blocked`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-deadline")
defer {
kill(pid, SIGKILL) // settle the blocked pipe FIRST — close's boundedness is the next smoke's pin, not this one's
client.close()
}
let outcome = requestOutcome(client, method: "session/prompt", params: blockedWriterPayload, timeout: 0.5)
let result = await awaitBounded(outcome, window: 5)
#expect(
result?.contains("timed out") == true,
"deadline did not fire while the write was blocked: \(result ?? "still blocked after 5 s")",
)
}
/// brief-27 regression 2: Stop/cancellation stays deliverable while the
/// write is blocked. The bytes cannot reach a non-reading child (the
/// pipe is full — physics), so deliverable means the seam ACCEPTS the
/// notification and lifecycle bookkeeping still answers: session/cancel
/// is taken (a blocking notify would never let this test reach its
/// assertion), and a follow-up request gets registered and reaches its
/// OWN deadline. On the unfixed transport the follow-up's registration
/// queues behind the stuck writer and never runs.
@MainActor
@Test func `stop notification and bookkeeping answer while the stdin write is blocked`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-stop")
defer {
kill(pid, SIGKILL)
client.close()
}
// Wedge the writer: the oversized prompt fills the pipe (outcome unobserved).
Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) }
// Let the oversized write reach the pipe and wedge the writer first.
try await Task.sleep(nanoseconds: 200_000_000)
client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")]))
let second = requestOutcome(
client,
method: "session/new",
params: .object(["cwd": .string("/tmp"), "mcpServers": .array([])]),
timeout: 0.5,
)
let result = await awaitBounded(second, window: 5)
#expect(
result?.contains("timed out") == true,
"bookkeeping starved behind the blocked writer: \(result ?? "no answer within 5 s")",
)
}
/// brief-27 regression 3: close RETURNS BOUNDED while the write is
/// blocked — child reaped, the SIGTERM→grace→SIGKILL escalation inside
/// close actually reachable — without waiting on the blocked writer.
/// On the unfixed transport close begins with a queue.sync behind the
/// stuck send and never returns (the probe's watchdog hang).
@MainActor
@Test func `close returns bounded while the stdin write is blocked and reaps the child`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-close")
defer {
kill(pid, SIGKILL)
client.close()
}
// Wedge the writer: the oversized prompt fills the pipe (outcome unobserved).
Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) }
// The write is in the pipe and the writer wedged before close runs.
try await Task.sleep(nanoseconds: 200_000_000)
let closeTask = Task<Void, Never> { client.close() }
let finished = await awaitBounded(closeTask, window: 5)
#expect(finished != nil, "close did not return within 5 s — the blocked writer defeats teardown")
#expect(try await pollReaped(pid), "child not reaped after the bounded close")
}
/// brief-27 regression 4: the healthy-child contract is unchanged —
/// round trip (initialize → version), reply delivery (the engine's
/// server→client request answered -32601 over the wire; the fake logs
/// our reply), and a clean idempotent close that reaps the child.
@MainActor
@Test func `healthy engine round trip, server request answered, clean close`() async throws {
let dir = acpTempDir("smoke-healthy-brief27")
let fake = makeFakeACP(at: dir, mode: "serverPing")
let client = ACPEngineClient(binaryPath: fake)
client.onMessage = { _, _ in }
try client.start()
let pid = client.childProcessIdentifier
defer { client.close() }
let version = try await client.request("initialize", params: nil, timeout: 5)
#expect(version?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9")
let replyLog = (dir as NSString).appendingPathComponent("hermes-acp-reply-log")
var reply: String?
for _ in 0 ..< 250 where reply == nil {
reply = try? String(contentsOfFile: replyLog, encoding: .utf8)
if reply == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(
reply?.contains("-32601") == true,
"our -32601 reply to the server request never reached the engine: \(reply ?? "no reply logged")",
)
client.close()
client.close() // idempotent
#expect(try await pollReaped(pid))
}
}
+107 -1
View File
@@ -14,6 +14,16 @@
// card closes applied), skip and done flip only the status, and the stale
// anchor selects and changes no text while the card flags itself stale.
//
// #204 — Scenario: the card points, the editor lands
// From issue #204: a Fix Card should let the writer jump to the relevant
// paragraph — the palette's Jump hands the editor the anchor's exact span.
// Given an open piece carrying a fix card whose anchor is valid,
// when the writer clicks Jump on that card,
// then the model stamps one reveal request carrying the anchor's NSRange
// resolved against the LIVE session text (a dirty buffer still lands),
// the request's token advances so repeated jumps re-fire, nothing is
// written (not text, not the card), and a stale anchor stamps nothing.
//
import Foundation
@testable import Museion
@@ -284,7 +294,103 @@ struct FixCardApplyTests {
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
}
// MARK: Promote (#26, S4.1)
// MARK: Jump to the anchor (#204)
/// #204: the pure anchor-span math — the appliedText occurrence rule
/// (1-based, non-overlapping) answered as a range, with every
/// must-never-land case nil.
@Test func `anchorRange resolves the nth occurrence and nils every unlandable case`() throws {
let piece = try makePiece()
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [
card(quote: "anchor sentence"),
card(quote: "anchor sentence", occurrence: 2),
card(quote: "vanished quote", occurrence: 1),
card(quote: "anchor sentence", lane: .demonstration),
],
)
// submit refuses an empty quote and occurrence 0 at the trust
// boundary — the unlandable-input cases are pinned through the
// stored shape directly.
let emptyQuote = FixCardStore.StoredFixCard(
id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p",
diagnosticQuestion: "", fix: "", anchor: .init(quote: "", occurrence: 1),
lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil,
)
let zeroOccurrence = FixCardStore.StoredFixCard(
id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p",
diagnosticQuestion: "", fix: "", anchor: .init(quote: "anchor", occurrence: 0),
lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil,
)
let text = "The anchor sentence. And the anchor sentence again."
let first = try #require(FixCardStore.anchorRange(of: written[0].card, in: text))
#expect((text as NSString).substring(with: first) == "anchor sentence")
#expect(first.location == 4) // 1-based, the FIRST match
let second = try #require(FixCardStore.anchorRange(of: written[1].card, in: text))
#expect(second.location == 29) // occurrence 2 — not the first
#expect(FixCardStore.anchorRange(of: written[2].card, in: text) == nil) // stale
// A demonstration card's anchor is still a real place in the text.
#expect(FixCardStore.anchorRange(of: written[3].card, in: text) != nil)
#expect(FixCardStore.anchorRange(of: emptyQuote, in: text) == nil)
#expect(FixCardStore.anchorRange(of: zeroOccurrence, in: text) == nil)
// The range is UTF-16 (NSTextView's unit), not Characters — a grapheme
// before the anchor is 2 units here; a Character-counted location would say 6.
let wide = FixCardStore.anchorRange(of: written[0].card, in: "✍️ The anchor sentence.")
#expect(wide?.location == 7)
}
/// #204: a jump selects the anchor exactly where it resolved; only a bare
/// caret (the #71 flip-back) hops past leading blanks — a quote that IS
/// the leading blanks must select those blanks, never the title. Both
/// shapes clamp to the text.
@Test @MainActor func `landingSpan hops only a bare caret and clamps both shapes to the text`() {
let text = "\n\n\nTitle line."
let jump = FixCardRevealRequest(range: NSRange(location: 0, length: 3), token: 1)
#expect(ProseTextView.landingSpan(for: jump, in: text) == NSRange(location: 0, length: 3)) // the blank run itself
let caret = FixCardRevealRequest(range: NSRange(location: 0, length: 0), token: 2)
#expect(ProseTextView.landingSpan(for: caret, in: text) == NSRange(location: 3, length: 0)) // hops to the title
let over = FixCardRevealRequest(range: NSRange(location: 10, length: 50), token: 3)
#expect(ProseTextView.landingSpan(for: over, in: text) == NSRange(location: 10, length: 4)) // clamped
}
/// #204: the model stamps ONE reveal request per jump — the range
/// resolved against the LIVE session text (dirty buffer included), the
/// token advancing so a repeated jump re-fires; a stale anchor stamps
/// nothing. No write of any kind.
@Test @MainActor func `revealCard stamps a reveal request against the live text and writes nothing`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(
piecePath: folder.path,
cards: [card(quote: "anchor sentence"), card(quote: "vanished quote")],
)
model.select(post.id)
let session = try #require(model.session)
// The writer typed since the last flush — the jump must resolve
// against the buffer, not disk (the range would otherwise drift).
session.edit("# Carded\n\nIntro line.\nThe anchor sentence.\n")
let before = try Data(contentsOf: folder.appendingPathComponent("post.md"))
model.revealCard(written[0].card)
let request = try #require(model.revealRequest)
#expect(request.range.location == (session.text as NSString).range(of: "anchor sentence").location)
#expect(request.range.length == ("anchor sentence" as NSString).length) // UTF-16 units — what NSTextView selects
let token = request.token
#expect(try Data(contentsOf: folder.appendingPathComponent("post.md")) == before) // no write
#expect(try FixCardStore.scan(pieceURL: folder).allSatisfy { $0.status == .open }) // card untouched
// A repeated jump re-fires (the editor applies once per token).
model.revealCard(written[0].card)
#expect(model.revealRequest?.token == token + 1)
// A stale anchor stamps nothing — the previous request stands.
model.revealCard(written[1].card)
#expect(model.revealRequest?.token == token + 1)
}
/// Scenario: the mentor remembers — promoting through the model writes
/// the Learning under the open piece's Home, refreshes the palette's
+248 -4
View File
@@ -25,6 +25,66 @@ import Foundation
@testable import Museion
import Testing
/// The smallest NSDraggingInfo the drag overrides read: only the
/// pasteboard matters (the stock text drop also wants a destination view,
/// which the hosted text view supplies itself).
@MainActor
final class DragInfoStub: NSObject, NSDraggingInfo {
let draggingPasteboard: NSPasteboard
init(_ pb: NSPasteboard) {
draggingPasteboard = pb
}
var draggingDestinationWindow: NSWindow? {
nil
}
var draggingSourceOperationMask: NSDragOperation {
[.copy]
}
var draggingLocation: NSPoint {
.zero
}
var draggedImageLocation: NSPoint {
.zero
}
var draggedImage: NSImage? {
nil
}
var draggingSource: Any? {
nil
}
var draggingSequenceNumber: Int {
0
}
func slideDraggedImage(to _: NSPoint) {}
override func namesOfPromisedFilesDropped(atDestination _: URL) -> [String]? {
nil
}
var draggingFormation: NSDraggingFormation = .none
var animatesToDestination = false
var numberOfValidItemsForDrop = 0
func enumerateDraggingItems(
options _: NSDraggingItemEnumerationOptions,
for _: NSView?,
classes _: [AnyClass],
searchOptions _: [NSPasteboard.ReadingOptionKey: Any],
using _: @escaping (NSDraggingItem, Int, UnsafeMutablePointer<ObjCBool>) -> Void,
) {}
var springLoadingHighlight: NSSpringLoadingHighlight {
.none
}
func resetSpringLoading() {}
}
@MainActor
struct ImageIngestTests {
/// Throwaway Home + a saved post standing in for the open editor
@@ -96,9 +156,10 @@ struct ImageIngestTests {
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
}
// MARK: - #141 drag-layer entry (ingestDrop — the SwiftUI drop
// MARK: - #141 drag-layer entry (ingestDrop — whichever surface took
// target's perform lands on the text view)
// the drag routes here: the text view's own handlers over the editor,
// the window SwiftUI destination elsewhere)
@Test func `ingestDrop copies lands the ref and selects alt`() throws {
let (_, folder) = try ingestHome()
@@ -129,6 +190,189 @@ struct ImageIngestTests {
#expect(try !draft.ingestDrop([imageSource("x.png")]))
}
// MARK: - 27.2 drag routing (a drag goes to the deepest destination:
// FileDropTextView owns drops that land on the editor — stock NSTextView
// handling would paste the file PATH)
/// A Finder-shaped drag pasteboard: `public.file-url` plus the legacy
/// filenames type NSTextView registers for.
private func finderDragPasteboard(_ urls: [URL]) -> NSPasteboard {
let filenames = NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")
let pb = NSPasteboard(name: .drag)
pb.declareTypes([.fileURL, filenames], owner: nil)
pb.setString(urls[0].absoluteString, forType: .fileURL)
pb.setPropertyList(urls.map(\.path), forType: filenames)
return pb
}
/// A live text view in a window (the stock text drop inserts only into
/// a hosted view). Caller orders the window out.
private func hostedView() -> (tv: ProseListTextView, win: NSWindow) {
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false)
let tv = ProseListTextView()
tv.string = "Body.\n"
win.contentView?.addSubview(tv)
win.makeFirstResponder(tv)
return (tv, win)
}
/// A temp markdown file standing in for a dragged guest.
private func markdownSource() throws -> URL {
let md = FileManager.default.temporaryDirectory.appendingPathComponent("imageingest-\(UUID().uuidString).md")
try "# Guest\n".write(to: md, atomically: true, encoding: .utf8)
return md
}
@Test func `a file drag landing on the text view routes, never pastes the path`() throws {
let (_, folder) = try ingestHome()
let (tv, win) = hostedView()
defer { win.orderOut(nil) }
tv.ingestFolder = folder
tv.onFileDrop = { [weak tv] in tv?.ingestDrop($0) ?? false } // the gate's router in miniature
let source = try imageSource("sketch.png")
let drag = DragInfoStub(finderDragPasteboard([source]))
#expect(tv.draggingEntered(drag) == .copy)
#expect(tv.draggingUpdated(drag) == .copy)
#expect(tv.performDragOperation(drag))
#expect(tv.string.contains("![alt](assets/sketch.png)"))
#expect(!tv.string.contains(source.path), "the stock path paste survived")
// Unrouted (no handler mounted): a Finder drag claims nothing and
// pastes nothing.
let (bare, bareWin) = hostedView()
defer { bareWin.orderOut(nil) }
let bareDrag = DragInfoStub(finderDragPasteboard([source]))
#expect(bare.draggingEntered(bareDrag) == [])
#expect(!bare.performDragOperation(bareDrag))
#expect(bare.string == "Body.\n")
}
@Test func `a text-only drag keeps the stock drop and never reaches the router`() {
let (tv, win) = hostedView()
defer { win.orderOut(nil) }
var routed: [URL]?
tv.onFileDrop = { routed = $0; return true }
let pb = NSPasteboard(name: .drag)
pb.declareTypes([.string], owner: nil)
pb.setString("dropped text", forType: .string)
#expect(FileDropTextView.classify(pb) == .text)
#expect(tv.draggingEntered(DragInfoStub(pb)) == .copy)
#expect(tv.performDragOperation(DragInfoStub(pb)))
#expect(tv.string.contains("dropped text"))
#expect(routed == nil)
// URL-less AND text-less (raw image data from Photos/Preview): bounces.
let png = NSPasteboard(name: .drag)
png.declareTypes([.png], owner: nil)
#expect(tv.draggingEntered(DragInfoStub(png)) == [])
#expect(!tv.performDragOperation(DragInfoStub(png)))
#expect(tv.string.contains("dropped text"))
}
@Test func `the drag probe follows the pasteboard contents, not its memory`() throws {
let (tv, win) = hostedView()
defer { win.orderOut(nil) }
let source = try imageSource("sketch.png")
let pb = finderDragPasteboard([source])
#expect(tv.dropKind(of: pb) == .urls([source]))
// Same pasteboard object, new contents (changeCount moved): follows.
pb.declareTypes([.string], owner: nil)
pb.setString("now text", forType: .string)
#expect(tv.dropKind(of: pb) == .text)
pb.clearContents()
#expect(tv.dropKind(of: pb) == .none)
}
@Test func `the outline rows bounce a file drag instead of pasting the path`() throws {
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false)
defer { win.orderOut(nil) }
let row = RowTextView()
row.string = "- item"
win.contentView?.addSubview(row)
let drag = try DragInfoStub(finderDragPasteboard([imageSource("sketch.png")]))
#expect(row.draggingEntered(drag) == [])
#expect(!row.performDragOperation(drag))
#expect(row.string == "- item")
}
@Test func `a web URL refuses loudly with the type notice and plants nothing`() throws {
// A browser image drag reaches the router as an https URL — the
// extension looks publishable, but nothing is on disk to copy. The
// sink would refuse it too; only the isFileURL gate names the type.
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
tv.ingestFolder = folder
let web = try #require(URL(string: "https://example.com/cat.jpg"))
#expect(!tv.ingestDrop([web]))
#expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true, "notice: \(tv.lastIngestNotice ?? "nil")")
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
}
@Test func `a file that vanished after the drag refuses as missing, not as a folder`() throws {
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
tv.ingestFolder = folder
let gone = try imageSource("ghost.png")
try FileManager.default.removeItem(at: gone)
#expect(!tv.ingestDrop([gone]))
let notice = try #require(tv.lastIngestNotice)
#expect(notice.contains("couldn’t be read"), "notice: \(notice)")
#expect(!notice.contains("folder"), "notice: \(notice)")
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
}
// MARK: - The one router (AppGateState.routeFileDrop)
@Test func `the router opens a pure-markdown set as the guest`() throws {
let gate = AppGateState()
let md = try markdownSource()
defer { try? FileManager.default.removeItem(at: md) }
#expect(gate.routeFileDrop([md]))
#expect(gate.posts.externalSession != nil)
}
@Test func `the router refuses everything while a Cold Turkey block holds`() throws {
let gate = AppGateState()
gate.posts.newPost()
gate.posts.draft?.text = "seed words here"
gate.startWritingLock(goal: .words(2))
defer {
gate.writingLock.feed(text: "seed words here plus two more")
gate.writingLock.tick()
}
let md = try markdownSource()
defer { try? FileManager.default.removeItem(at: md) }
#expect(gate.writingLock.isLocked)
#expect(!gate.routeFileDrop([md]))
#expect(gate.posts.externalSession == nil)
}
@Test func `the router hands non-markdown to the open piece's ingest`() throws {
let gate = AppGateState()
let (_, folder) = try ingestHome()
let source = try imageSource("sketch.png")
// No editor mounted: bounce.
#expect(!gate.routeFileDrop([source]))
let tv = ProseListTextView()
tv.string = "Body.\n"
tv.ingestFolder = folder
gate.proseDrop.textView = tv
#expect(gate.routeFileDrop([source]))
#expect(tv.string.contains("![alt](assets/sketch.png)"))
// A mixed md+image set reaches the ingest's loud refusal, never the guest.
let md = try markdownSource()
defer { try? FileManager.default.removeItem(at: md) }
#expect(try !gate.routeFileDrop([imageSource("second.png"), md]))
#expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true)
#expect(gate.posts.externalSession == nil)
}
// MARK: - #141 finish-audit pins
@Test func `a dropped symlink refuses with nothing planted`() throws {
@@ -149,8 +393,8 @@ struct ImageIngestTests {
}
@Test func `a mixed image and markdown set refuses loudly`() throws {
// The window destination forwards only PURE-markdown sets (#91);
// a mixed set must reach this refusal, not vanish behind the md.
// The router forwards only PURE-markdown sets (#91); a mixed set
// must reach this refusal, not vanish behind the md.
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
+86
View File
@@ -25,6 +25,16 @@ private func writeExternal(_ name: String, _ body: String) throws -> URL {
return url
}
/// brief-32: the guest-watch pins' own temp dir — `startExternalWatch`
/// observes the file's CONTAINING folder, so their guest must live where
/// no sibling test ever writes.
private func watchedDir() throws -> URL {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-watch-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir
}
@Suite(.serialized)
@MainActor
struct ImportExternalTests {
@@ -190,4 +200,80 @@ struct ImportExternalTests {
#expect(!session.conflictAlert)
#expect(session.text == "# C\n\nForeign edit.")
}
// MARK: - The guest watch (brief-32: the #67 compare's disk read)
@Test func `external watch raises no 67 conflict on an unchanged BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("watched.md")
// Windows-authored file: BOM + CRLF. The open read normalizes
// (readDocument's external branch); the watch must read in the
// SAME representation or every directory event reads as #67.
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
#expect(session.text == "# Title\n\nBody line.\n")
// Sibling directory events re-fire the compare (the watch observes
// the containing folder): representation alone must never raise.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch still conflicts on a real write and never re-arms after yes-reload`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("foreign.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
// A REAL external modification (different content, same BOM/CRLF
// representation): the departure gate must still see it.
try "\u{FEFF}# Title\r\n\r\nRewritten underneath.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// Yes-reload takes the foreign content, normalized:
session.reloadFromDisk()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nRewritten underneath.\n")
// The next directory event reads the same unchanged bytes — the
// false conflict must not re-arm.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch never re-arms after keep-local on a BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("kept.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
try "\u{FEFF}# Title\r\n\r\nForeign body.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// No: keep local — the disk state is seen, the local buffer stays
// and stays pending.
session.keepLocal()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nBody line.\n")
#expect(session.saveState == .changed)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
}
+19
View File
@@ -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
+124
View File
@@ -89,3 +89,127 @@ struct LibrarySearchTests {
#expect(byBody.map(\.id) == ["b-morning-pages"])
}
}
/// #144 (mounted half): the snapshot invalidation the pure seam can't
/// see — PostsLibraryColumn keys its `.task(id:)` to query + Home +
/// `PostsModel.contentRevision` and renders a landed snapshot only
/// 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, 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")
struct LibrarySearchSnapshotTests {
@Test func `a snapshot renders only under the key that computed it`() {
let swept = LibrarySearch.Snapshot(
key: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4),
results: [piece("a", title: "Quartz Harbor")],
)
#expect(swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "harbor", homePath: "/users/a/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/b/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 5)))
}
/// The sweep a mounted column would have landed before the archive:
/// key = (query, home, revision at sweep time), results from the
/// real seam + readBody rail.
@MainActor
private func standingSweep(_ model: PostsModel, home: URL, query: String) -> LibrarySearch.Snapshot {
LibrarySearch.Snapshot(
key: LibrarySearch.SearchKey(query: query, homePath: home.path, revision: model.contentRevision),
results: LibrarySearch.results(for: query, in: model.posts.filter { !$0.isArchived }) {
PostStore.readBody(id: $0.id, home: home)
},
)
}
@Test @MainActor func `archiving a result invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.map(\.id) == [post.id]) // the sweep found it
model.archivePost(post)
try await pollUntil { model.posts.contains { $0.id == post.id && $0.isArchived } }
// Same query, same Home — the library moved under the sweep.
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `trashing a result invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.map(\.id) == [post.id])
model.trash(post)
try await pollUntil { !model.posts.contains { $0.id == post.id } }
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `a same-query body edit invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quiet Study\n\nplain body", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.isEmpty) // nothing matches yet
// The body gains the needle with NO Post metadata change — the
// #143 equality skip's blind spot: the list itself never moves.
let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
try PostFrontmatter.stamped(
body: "# Quiet Study\n\nthe quartz lamp", passState: .firstDraft, origin: .writer, type: .post,
).write(to: file, atomically: true, encoding: .utf8)
let before = model.posts
await model.rescan()
#expect(model.posts == before) // metadata equal — the scan's skip held
let reswept = LibrarySearch.results(for: "quartz", in: model.posts.filter { !$0.isArchived }) {
PostStore.readBody(id: $0.id, home: home)
}
#expect(reswept.map(\.id) == [post.id]) // a fresh sweep WOULD find it now
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `an unchanged rescan keeps the revision`() async throws {
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 burst — all cache hits
#expect(model.contentRevision == settled)
}
}
+22 -37
View File
@@ -23,7 +23,7 @@ struct MicropubModelTests {
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
)
@@ -42,7 +42,7 @@ struct MicropubModelTests {
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
let (model, _) = try makeModelHome()
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -57,7 +57,7 @@ struct MicropubModelTests {
let (model, _) = try makeModelHome()
model.newPost() // staged draft — no folder, no session
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -76,7 +76,7 @@ struct MicropubModelTests {
model.select(post.id)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -99,7 +99,7 @@ struct MicropubModelTests {
.write(to: fileURL, atomically: true, encoding: .utf8)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
_ = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
)
@@ -116,7 +116,7 @@ struct MicropubModelTests {
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
_ = await model.micropubSend(
token: "tok",
transport: micropubCanned(500, body: "{}", log: log),
)
@@ -124,28 +124,11 @@ struct MicropubModelTests {
#expect(Post.scan(home: home).first?.micropubURL == nil)
}
@Test @MainActor func `re-drafting overwrites the remembered url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
)
_ = await model.micropubSendDraft(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
)
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second")
}
// MARK: #34 (S6.2) — illustrations travel with it
/// Plants a PNG beside the piece; returns the piece's post.md URL.
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
/// Shared with `MicropubStatusTests` (shared-helper convention).
@MainActor func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id)
let dir = try #require(PostStore.folder(of: post.id, home: home))
@@ -162,20 +145,21 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// The three hops, in order: q=config → upload → create.
#expect(log.requests.count == 3)
let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
let config = URLComponents(url: log.request(0)?.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
#expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media")
#expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
#expect(log.request(1)?.url?.absoluteString == "https://micro.blog/micropub/media")
#expect(log.request(1)?.httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
// The create: the ref REWRITTEN in place with its uploaded URL
// — exactly where the writer placed it (2026-11-01: the photo
// PROPERTY rendered at the bottom, position lost), alt in the
// markdown, NO photo property keys.
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
let create = try #require(log.request(2))
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
let expected = "# Inked\n\nProse before.\n\n![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after."
#expect(props["content"] as? [String] == [expected])
#expect(props["photo"] == nil)
@@ -197,7 +181,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -228,7 +212,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -246,13 +230,14 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// config + ONE upload + create — the FILE uploads once, not once per ref.
#expect(log.requests.count == 3)
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
let create = try #require(log.request(2))
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
let content = try #require((props["content"] as? [String])?.first)
// Both refs share the one uploaded URL.
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
@@ -266,7 +251,7 @@ struct MicropubModelTests {
) // path.png planted, ghost.png never
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -281,10 +266,10 @@ struct MicropubModelTests {
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// The #33 path unchanged: no config round-trip, straight to the create.
#expect(log.requests.count == 1)
#expect(log.requests[0].url == Micropub.endpoint)
#expect(log.request(0)?.url == Micropub.endpoint)
}
}
+423
View File
@@ -0,0 +1,423 @@
//
// MicropubStatusTests.swift
// MuseionTests
//
// #206: the Micro.blog publish record. Scenario:
//
// Given a saved Post the writer sent to Micro.blog (the piece
// remembers its post URL)
// When the writer publishes it, sends it again, or Micro.blog has
// lost the post
// Then the piece remembers the publish (frontmatter
// `micropub_published`, healing a link the send could not stamp)
// and the library row can say
// "published <date>"; a re-send UPDATES the remembered post in
// place — same URL, no second post, no second upload for an
// unchanged image — and leaves the publish date alone; a 404 (the
// post deleted on Micro.blog) clears the link so the piece can go
// out as a fresh draft. Nothing is stamped on any failure, and a forget that
// cannot land says so — never a "cleared" the disk contradicts.
//
// Wire facts (microblog.dev/api/posting, 2026-12-04):
// `action=update` with `replace` sets name and content; updates
// answer 200 with an empty body and 404 when `url` is not on the
// blog. The media listing carries no content hash, so upload dedup
// is a local memo keyed by the asset's bytes.
//
// A file from outside brings none of this: the import boundary drops
// Museion's micropub keys, so a foreign `micropub_url` can never aim
// a send at one of the writer's posts.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubStatusTests")
struct MicropubStatusTests {
/// A fresh piece with extra frontmatter lines planted after the
/// owned keys; returns its id.
private func piece(_ home: URL, frontmatter: String = "") throws -> String {
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
if !frontmatter.isEmpty {
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
let raw = try String(contentsOf: fileURL, encoding: .utf8)
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
.write(to: fileURL, atomically: true, encoding: .utf8)
}
return post.id
}
// MARK: The record on disk
@Test func `row status reads nil draft or published from the frontmatter`() throws {
let home = try storeHome()
defer { try? FileManager.default.removeItem(at: home) }
let live = try piece(
home,
frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2026-12-04T15:02:00\n",
)
let draft = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/draft\n")
let untouched = try piece(home)
// A stamp that isn't the stamp shape never reads as a publish.
let broken = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/broken\nmicropub_published: yesterday\n")
let posts = Post.scan(home: home)
#expect(posts.first { $0.id == live }?.micropubStatus == "published Dec 4, 2026")
#expect(posts.first { $0.id == draft }?.micropubStatus == "draft on Micro.blog")
#expect(posts.first { $0.id == untouched }?.micropubStatus == nil)
#expect(posts.first { $0.id == broken }?.micropubStatus == "draft on Micro.blog")
}
@Test func `an imported piece brings no micro.blog memory`() throws {
let home = try storeHome()
defer { try? FileManager.default.removeItem(at: home) }
let source = home.appendingPathComponent("guest.md")
try """
---
title: Guest
micropub_url: https://example.micro.blog/someone-elses-live-post
micropub_published: 2026-01-01T00:00:00
---
# Guest
Body.
""".write(to: source, atomically: true, encoding: .utf8)
// A foreign file's remembered URL would aim the next send's
// content replace at whatever post it names, under the writer's
// token — so Museion's bookkeeping is ours to set, never theirs
// to carry in (the way a foreign `origin` loses).
let post = try PostStore.importFile(at: source, origin: .writer, home: home)
let scanned = try #require(Post.scan(home: home).first { $0.id == post.id })
#expect(scanned.micropubURL == nil)
#expect(scanned.micropubPublished == nil)
#expect(scanned.micropubStatus == nil)
let matter = try PostFrontmatter.parse(readPost(home, post.id))
#expect(matter["title"] == "Guest") // every other external key still rides verbatim
#expect(matter["micropub_url"] == nil) // the line is gone, not merely emptied
}
@Test @MainActor func `publish remembers the date on the piece`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Stamped\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/stamped"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
#expect(Post.scan(home: home).first?.micropubPublished == nil) // a draft is not a publish
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(outcome == .published)
let scanned = try #require(Post.scan(home: home).first)
let published = try #require(scanned.micropubPublished)
#expect(abs(published.timeIntervalSinceNow) < 60) // stamped now, local time
#expect(scanned.micropubURL == url)
#expect(scanned.micropubStatus?.hasPrefix("published ") == true)
}
@Test @MainActor func `publish remembers a post whose send could not stamp it`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Unstamped\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/unstamped"
// The send lands, but its stamp cannot: the piece folder is
// read-only for the moment (the sheet still holds the URL for
// this session; the piece remembers nothing on disk).
let dir = try #require(PostStore.folder(of: post.id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let sent = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
#expect(sent == .drafted(url: url, preview: nil))
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
#expect(Post.scan(home: home).first?.micropubURL == nil)
// Publish writes the record AND heals the link the send couldn't.
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.micropubURL == url)
#expect(scanned.micropubPublished != nil)
}
@Test @MainActor func `a failed publish stamps nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Refused\n\nBody.", home: home)
model.select(post.id)
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/refused",
token: "tok",
transport: micropubCanned(500, log: MicropubRequestLog()),
)
guard case let .requestFailed(status, _) = outcome else {
Issue.record("expected requestFailed, got \(outcome)")
return
}
#expect(status == 500)
#expect(Post.scan(home: home).first?.micropubPublished == nil)
}
@Test @MainActor func `publish refuses a post address that is not a clean url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Injected\n\nBody.", home: home)
model.select(post.id)
let log = MicropubRequestLog()
// A newline in the address would close the frontmatter block on
// the heal write — so nothing travels and nothing is remembered.
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/live\nmicropub_published: 2020-01-01T00:00:00",
token: "tok",
transport: micropubCanned(200, log: log),
)
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.micropubURL == nil)
#expect(scanned.micropubPublished == nil)
}
// MARK: A re-send updates the remembered post in place
@Test func `update request is the in-place replace against the remembered url`() {
let request = Micropub.makeUpdateRequest(
url: "https://example.micro.blog/hello.html",
title: "The Title",
body: "The body.",
token: "tok",
)
#expect(request.url == Micropub.endpoint)
#expect(request.httpMethod == "POST")
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
let root = micropubJSON(request)
#expect(root["action"] as? String == "update")
#expect(root["url"] as? String == "https://example.micro.blog/hello.html")
let replace = root["replace"] as? [String: Any]
#expect(replace?["name"] as? [String] == ["The Title"])
#expect(replace?["content"] as? [String] == ["The body."])
// Never a status flip — a draft stays a draft, a live post stays live.
#expect(replace?["post-status"] == nil)
}
@Test @MainActor func `a re-send updates the remembered post and never creates a second`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nFirst body.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/again"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
model.session?.edit("# Again\n\nSecond body.")
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
let request = try #require(log.requests.first)
let root = micropubJSON(request)
#expect(root["action"] as? String == "update") // the create's `type`/`properties` never ride
#expect(root["type"] == nil)
#expect(root["url"] as? String == url)
let replace = try #require(root["replace"] as? [String: Any])
#expect(replace["content"] as? [String] == ["# Again\n\nSecond body."])
#expect(Post.scan(home: home).first?.micropubURL == url) // the remembered URL never moves
}
@Test @MainActor func `a live update leaves the publish date alone`() async throws {
let (model, home) = try makeModelHome()
let live = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2025-01-15T08:00:00\n")
model.select(live)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(outcome == .updated(url: "https://example.micro.blog/live"))
#expect(Post.scan(home: home).first?.micropubStatus == "published Jan 15, 2025")
}
// MARK: A re-send never re-uploads an unchanged image
/// An illustrated piece, opened in the model; returns its folder
/// (`MicropubModelTests` owns the planting — shared-helper convention).
@MainActor private func illustratedPiece(_ model: PostsModel, _ home: URL) throws -> URL {
try MicropubModelTests()
.plantIllustratedPiece(model, home, body: "# Inked\n\n![A winding path.](assets/path.png)\n\nProse.")
.deletingLastPathComponent()
}
@Test @MainActor func `an unchanged illustration rides its earlier upload`() async throws {
let (model, home) = try makeModelHome()
_ = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // config + upload + create
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// ONE request — the in-place update. No q=config, no upload.
#expect(outcome == .updated(url: "https://example.micro.blog/inked"))
#expect(log.requests.count == 1)
let resent = try #require(log.request(0))
let replace = try #require(micropubJSON(resent)["replace"] as? [String: Any])
#expect((replace["content"] as? [String])?.first?.contains("![A winding path.](https://micro.blog/uploads/2026/ink.png)") == true)
}
@Test @MainActor func `a changed illustration uploads again`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
// The writer replaces the image — same name, new bytes.
let fresh = micropubPNG() + Data([0x7F])
try fresh.write(to: dir.appendingPathComponent("assets/path.png"))
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
// config → upload → update, and the upload carries the NEW bytes.
#expect(log.requests.count == 3)
#expect(log.request(1)?.httpBody?.firstRange(of: fresh) != nil)
}
@Test @MainActor func `an untrustworthy memo url never rides the wire`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
// The sidecar is disk, so external data: a planted http URL is
// no memory at all.
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
var memo = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: memoURL))
let key = try #require(memo.keys.first)
memo[key] = "http://evil.example/swap.png"
try JSONEncoder().encode(memo).write(to: memoURL, options: .atomic)
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(log.requests.count == 3) // re-uploaded rather than trusted
let last = try #require(log.request(2))
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
let content = try #require((replace["content"] as? [String])?.first)
#expect(!content.contains("evil.example"))
#expect(content.contains("https://micro.blog/uploads/2026/ink.png"))
}
@Test @MainActor func `a symlinked upload memo is no memory at all`() async throws {
let (model, home) = try makeModelHome()
let dir = try illustratedPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // the real memo lands
// Planted: the sidecar becomes a link to a memo OUTSIDE the piece
// that names this image's bytes with an attacker-chosen URL.
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
try FileManager.default.removeItem(at: memoURL)
let outside = home.appendingPathComponent("planted-memo.json")
let planted = [Micropub.uploadKey(micropubPNG()): "https://micro.blog/uploads/2026/planted.png"]
try JSONEncoder().encode(planted).write(to: outside, options: .atomic)
try FileManager.default.createSymbolicLink(at: memoURL, withDestinationURL: outside)
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
#expect(log.requests.count == 3) // config → a fresh upload → the update
let last = try #require(log.request(2))
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
let content = try #require((replace["content"] as? [String])?.first)
#expect(!content.contains("planted.png"))
}
// MARK: A post Micro.blog lost
@Test @MainActor func `a post micro.blog lost is forgotten named and sendable again`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Gone\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/gone"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
// The writer deleted the draft on Micro.blog; the next send hears 404.
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case let .forgotten(reason) = outcome else {
Issue.record("expected forgotten, got \(outcome)")
return
}
#expect(reason.contains("deleted"))
let forgotten = try #require(Post.scan(home: home).first)
#expect(forgotten.micropubURL == nil) // no dead link left on the piece
#expect(forgotten.micropubStatus == nil)
// Recovery: with nothing remembered, the next send is a fresh draft.
let log = MicropubRequestLog()
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: log))
let created = try #require(log.request(0))
#expect(micropubJSON(created)["action"] == nil) // a create, not an update
#expect(Post.scan(home: home).first?.micropubURL == url)
}
@Test @MainActor func `a lost live post takes the publish record with it`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Vanish\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/vanish"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
#expect(Post.scan(home: home).first?.micropubPublished != nil) // the record exists
// The post is deleted on Micro.blog; the next word there is 404.
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case .forgotten = outcome else {
Issue.record("expected forgotten, got \(outcome)")
return
}
#expect(Post.scan(home: home).first?.micropubURL == nil)
#expect(Post.scan(home: home).first?.micropubPublished == nil)
}
@Test @MainActor func `publish refuses a piece that is not the open one`() async throws {
let (model, home) = try makeModelHome()
_ = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never selected
let log = MicropubRequestLog()
let outcome = await model.micropubPublish(
url: "https://example.micro.blog/unopened",
token: "tok",
transport: micropubCanned(200, log: log),
)
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty) // nothing went out
#expect(Post.scan(home: home).first?.micropubPublished == nil) // and nothing was remembered for it
}
@Test @MainActor func `a forget that cannot write says so instead of claiming the link is cleared`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Stuck\n\nBody.", home: home)
model.select(post.id)
let url = "https://example.micro.blog/stuck"
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
// The piece folder goes read-only: the forget cannot land.
let dir = try #require(PostStore.folder(of: post.id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.contains("couldn't be cleared"))
#expect(Post.scan(home: home).first?.micropubURL == url) // still on the piece — and said to be
}
}
+35 -4
View File
@@ -43,6 +43,18 @@ final class MicropubRequestLog: @unchecked Sendable {
defer { lock.unlock() }
return items
}
/// The request at `index`, nil when fewer traveled. Read recorded
/// requests through here, never `requests[index]`: an out-of-range
/// subscript TRAPS, one trap kills the hosted runner, and every
/// queued test reports `Crash:` beside it (#206 flip cycle). A nil
/// here fails the pin's OWN expectation — `#require` it when the
/// value feeds a non-optional parameter.
func request(_ index: Int) -> URLRequest? {
lock.lock()
defer { lock.unlock() }
return index < items.count ? items[index] : nil
}
}
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
@@ -214,6 +226,25 @@ struct MicropubTests {
}
}
@Test func `a 5xx names micro.blog's outage not a bare status`() {
// Their errors arrive as HTML pages, so the JSON decode finds
// nothing — a 503 over that body names their side; a 4xx keeps
// the bare status; a described 5xx keeps the description.
let html = Data("<html><body>503 Service Unavailable</body></html>".utf8)
let outage = Micropub.decodeFailure(status: 503, body: html)
guard case let .requestFailed(status, detail) = outage else {
Issue.record("expected requestFailed, got \(outage)")
return
}
#expect(status == 503)
#expect(detail.contains("their side"))
let bare = Micropub.decodeFailure(status: 422, body: html)
#expect(bare == .requestFailed(status: 422, detail: "HTTP 422"))
let described = Micropub.decodeFailure(status: 502, body: Data(#"{"error_description":"upstream timeout"}"#.utf8))
#expect(described == .requestFailed(status: 502, detail: "upstream timeout"))
}
@Test func `publish outcome is published on 2xx`() async {
let log = MicropubRequestLog()
let outcome = await Micropub.publish(
@@ -247,7 +278,7 @@ struct MicropubTests {
// MARK: The stamp + scan (the remembered draft URL)
@Test func `stampMicropubURL stamps in place and scan reads it back`() throws {
@Test func `stampMicropub stamps in place and scan reads it back`() throws {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
@@ -273,7 +304,7 @@ struct MicropubTests {
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
let before = try String(contentsOf: fileURL, encoding: .utf8)
try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home)
try PostStore.stampMicropub(post.id, home: home, [("micropub_url", "https://example.micro.blog/hello.html")])
let after = try String(contentsOf: fileURL, encoding: .utf8)
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
@@ -286,11 +317,11 @@ struct MicropubTests {
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
}
@Test func `stampMicropubURL throws on a vanished piece`() throws {
@Test func `stampMicropub throws on a vanished piece`() throws {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
#expect(throws: (any Error).self) {
try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home)
try PostStore.stampMicropub("ghost", home: home, [("micropub_url", "https://x.example/")])
}
}
+2 -2
View File
@@ -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)
+2 -1
View File
@@ -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")
}
+264
View File
@@ -0,0 +1,264 @@
//
// PostsModelDepartureTests.swift
// MuseionTests
//
// brief-25 (failed-flush-discarded-on-document-switch): document
// departure is guarded. A navigation whose outgoing flush fails (write
// error, or an unanswered #67 conflict) aborts and retains the dirty
// session — teardown used to discard the flush result and drop the only
// retained copy of unsaved prose. Both navigation families (saved-post
// session, external guest) pinned with injected write failures: a
// read-only piece folder / read-only guest directory (atomic writes
// stage their temp file beside the destination), the permission-
// injection convention of FixCardApplyTests.
//
// #200 (gate quit-time flushes through the departure gate): quitting is
// the one departure that used to bypass the gate — shutdown() flushed
// both sessions best-effort. Pins: a quit-time shutdown with an
// unanswered #67 conflict leaves the foreign disk body untouched (the
// #114 harm); the open external guest's edits ride the shutdown flush;
// a never-loaded session with retyped words refuses (its flush would
// report a vacuous success and drop the only copy — finish-audit LOW).
// The block-quit posture itself (applicationShouldTerminate's refusal)
// is pinned in WritingLockTests at the delegate seam.
//
import Foundation
@testable import Museion
import Testing
@Suite("PostsModelDepartureTests")
@MainActor
struct PostsModelDepartureTests {
private func denyWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
}
private func allowWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
}
@Test func `new post aborts when the dirty session flush fails and keeps its text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
model.select(post.id)
model.session?.edit("# Keeper\n\nunique failed-flush paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newPost()
// The switch aborted: the dirty session is retained, not replaced
// by the draft — its text is the only copy of the edits.
#expect(model.session?.postID == post.id)
#expect(model.session?.text == "# Keeper\n\nunique failed-flush paragraph")
#expect(model.session?.saveState == .failed)
#expect(model.draft == nil)
#expect(model.selectedPostID == post.id)
#expect(model.lastError != nil)
// Writability restored → the retry lands the edits, then switches.
try allowWrites(to: pieceDir)
model.newPost()
#expect(model.draft != nil)
#expect(model.session == nil)
#expect(model.lastError == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nunique failed-flush paragraph")
}
@Test func `new outline aborts when the dirty session flush fails`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newOutline()
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.newOutline()
#expect(model.draft?.type == .outline)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `switching pieces aborts when the outgoing session flush fails`() throws {
let (model, home) = try makeModelHome()
let postA = try PostStore.writeNew(body: "# A\n", home: home)
let postB = try PostStore.writeNew(body: "# B\n", home: home)
model.select(postA.id)
model.session?.edit("# A\n\noutgoing paragraph")
let dirA = try #require(PostStore.folder(of: postA.id, home: home))
try denyWrites(to: dirA)
defer { try? allowWrites(to: dirA) }
model.select(postB.id)
// The switch aborted before replacing the session (select's own
// teardown AND the second one through openUnguarded both gated).
#expect(model.session?.postID == postA.id)
#expect(model.session?.text == "# A\n\noutgoing paragraph")
#expect(model.selectedPostID == postA.id)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n")
try allowWrites(to: dirA)
model.select(postB.id)
#expect(model.session?.postID == postB.id)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `open external aborts when the dirty session flush fails`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
model.select(post.id)
model.session?.edit("# Host\n\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
// The guest did not take the column: the switch aborted with the
// dirty session retained.
#expect(model.session?.postID == post.id)
#expect(model.externalSession == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.openExternal(extFile)
#expect(model.externalSession != nil)
#expect(model.session == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Host\n\noutgoing paragraph")
}
@Test func `select aborts when the dirty guest flush fails and keeps the guest`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
defer { try? allowWrites(to: extDir) }
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
model.externalSession?.edit("# Foreign\n\nguest paragraph that must survive")
try denyWrites(to: extDir)
model.select(post.id)
// The guest stays: its buffer is the only copy of the edits.
#expect(model.externalSession != nil)
#expect(model.externalSession?.text == "# Foreign\n\nguest paragraph that must survive")
#expect(model.session == nil) // the switch aborted before opening the post
#expect(model.selectedPostID == nil)
#expect(model.lastError != nil)
try allowWrites(to: extDir)
model.select(post.id)
#expect(model.externalSession == nil)
#expect(model.session?.postID == post.id)
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest paragraph that must survive")
}
@Test func `new post aborts while the conflict alert is unanswered`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlocal paragraph")
// #67: a foreign disk body arrived — the alert is up, unanswered.
model.session?.diskDidChange(diskText: "foreign body from disk")
model.newPost()
// Departure mirrors flushOrAbort: the unanswered conflict holds the
// navigation (and never overwrites the foreign disk body).
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n")
}
@Test func `quit-time shutdown leaves the foreign disk body untouched while the conflict alert is unanswered`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlocal paragraph")
// #67, for real this time: the foreign body is ON disk (quit's
// flush() never held for a conflict — only the debounce did, so
// shutdown used to write the local text over it, #114's harm).
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
model.session?.diskDidChange(diskText: "foreign body from disk")
model.shutdown()
// AC #200: the foreign disk body survives the quit-time flush and
// the strip says why instead of pretending it saved.
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
#expect(model.lastError != nil)
}
@Test func `quit-time shutdown flushes a clean dirty session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlast words before quitting")
model.shutdown()
// No conflict, no failure: the edits land and quit proceeds clean.
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown flushes the open external guest`() throws {
let (model, _) = try makeModelHome()
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
defer { try? allowWrites(to: extDir) }
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
model.externalSession?.edit("# Foreign\n\nguest words that must land before quitting")
model.shutdown()
// The guest leg of the quit gate: its edits ride the shutdown
// flush, exactly as the old best-effort shutdown did.
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest words that must land before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown refuses over a never-loaded session with retyped text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
// The file turns unreadable between scan and open: the session
// opens empty (loadFailed), the writer retypes into it.
let file = try #require(PostStore.folder(of: post.id, home: home))
.appendingPathComponent("post.md")
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) }
model.select(post.id)
#expect(model.session?.loadFailed == true)
model.session?.edit("# Retyped words over a file that never loaded")
model.shutdown()
// flush() reports a vacuous success for a never-loaded session —
// the gate must refuse instead of letting the retype die quietly.
#expect(model.lastError != nil)
#expect(model.session?.text == "# Retyped words over a file that never loaded")
}
}
+351
View File
@@ -0,0 +1,351 @@
//
// PostsModelRepointTests.swift
// MuseionTests
//
// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a
// document departure. Settings used to commit the new Home and flip
// `watchedHome` (bind → startWatching) without departing the open
// session: the session's immutable target kept the OLD Home, a same-slug
// piece in the new library made the ID-only reselect return it, and
// autosave/Save/quit wrote the old library while structural operations
// resolved against the new one (#198's departure gate never saw this
// seam). Pins: the gate runs BEFORE anything changes (a refused repoint
// leaves Home A, the binding, the session's (Home, ID) target and its
// buffer untouched — all three `sessionMayDepart` legs), an accepted
// repoint lands the edits on A first and leaves no live session targeting
// an A piece under B, the same-slug piece opens from B and saves there
// (flush AND quit), a no-collision repoint tears down cleanly (the old
// vanish path dropped the dirty buffer), a card scan from the old library
// never lands on the new library's piece (identity re-check at
// COMPLETION — the scan seam holds it past the repoint), and a pass
// started after the repoint runs against the new library.
//
// Two-Home rig: `projects/posts/shared/post.md` in BOTH libraries — the
// collision shape the finding names; differing bodies so a wrong-library
// read is observable. The Settings path in these pins is the model's two
// steps — `repoint(to:)` (the gate) then `bind` (the commit) — exactly as
// WorkspaceView's binding and root `.task(id:)` drive them.
// r1 (athena MF-1/N-1): the hoisted stale-Home verdict in `rescan` (the
// library-scan sibling of the card hop-back — the per-model `scanLibrary`
// seam holds it past the repoint) and the draft-survives decision are
// pinned too.
//
import Foundation
@testable import Museion
import Testing
/// brief-28 rig: a Sendable one-shot flag the stale card-scan pin's park
/// probe reads (the detached scanner sets it from off-main; pollUntil's
/// per-iteration probe must not consume anything).
private final class ParkedFlag: @unchecked Sendable {
private let lock = NSLock()
private var value = false
var isSet: Bool {
lock.withLock { value }
}
func set() {
lock.withLock { value = true }
}
}
@Suite("PostsModelRepointTests")
@MainActor
struct PostsModelRepointTests {
private func denyWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
}
private func allowWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
}
/// Two Homes holding the SAME slug — `writeNew` derives `shared` from
/// the `# Shared` title in both (a non-Shared bodyA makes a unique
/// slug instead: the no-collision shape). The model is bound to A.
// swiftlint:disable:next large_tuple
private func makeTwoHomes(bodyA: String, bodyB: String) throws -> (model: PostsModel, homeA: URL, homeB: URL) {
let base = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true)
let homeA = base.appendingPathComponent("A", isDirectory: true)
let homeB = base.appendingPathComponent("B", isDirectory: true)
for home in [homeA, homeB] {
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
}
_ = try PostStore.writeNew(body: bodyA, home: homeA)
_ = try PostStore.writeNew(body: bodyB, home: homeB)
let model = PostsModel()
model.bind(home: homeA)
return (model, homeA, homeB)
}
@Test func `a same-slug piece opens from the new library after a repoint and saves there, never the old one`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
#expect(model.session?.text == "# Shared\n\nA body\n")
model.session?.edit("# Shared\n\nA body, typed in A\n")
// The Settings repoint: the gate first, the binding after.
#expect(model.repoint(to: homeB))
// Ordering: the departure landed on A and NOTHING has moved yet —
// watchedHome is still A until the binding commits, and no live
// session targets an A piece.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
#expect(model.watchedHome == homeA)
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
model.bind(home: homeB)
#expect(model.watchedHome == homeB)
model.select("shared")
// B's piece opened from B — not the retained A session (whose
// ID-only reselect used to return it under the new UI).
#expect(model.session?.text == "# Shared\n\nB body\n")
#expect(model.session?.targets(postID: "shared", home: homeB) == true)
model.session?.edit("# Shared\n\nB body, typed in B\n")
model.session?.flush() // ⌘S — the debounce's own sink
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B\n")
// A holds exactly what the departure flushed — never B's edits.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
model.session?.edit("# Shared\n\nB body, typed in B again\n")
model.shutdown() // quit rides the departure gate (#200)
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B again\n")
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
}
@Test func `repoint refuses when the open piece's flush fails and changes nothing`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
model.session?.edit("# Shared\n\nA body, typed in A\n")
let pieceDir = try #require(PostStore.folder(of: "shared", home: homeA))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
// The Settings repoint — refused: the gate fires before any change.
#expect(model.repoint(to: homeB) == false)
// ORDERING: the gate fired before ANY state changed — the binding,
// the selection, the session's (Home, ID) target and its buffer.
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.postID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.text == "# Shared\n\nA body, typed in A\n")
#expect(model.session?.saveState == .failed)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n")
// Writability restored → the edits land on A first (watchedHome
// still A until the binding commits), then the repoint departs.
try allowWrites(to: pieceDir)
#expect(model.repoint(to: homeB))
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
#expect(model.watchedHome == homeA)
model.bind(home: homeB)
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
#expect(model.watchedHome == homeB)
}
@Test func `repoint refuses while the conflict alert is unanswered`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
model.session?.edit("# Shared\n\nA body, typed in A\n")
// #67: a foreign disk body arrived — the alert is up, unanswered.
model.session?.diskDidChange(diskText: "foreign body from disk")
// The Settings repoint — refused.
#expect(model.repoint(to: homeB) == false)
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.postID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.conflictAlert == true)
#expect(model.session?.text == "# Shared\n\nA body, typed in A\n")
#expect(model.lastError != nil)
// Never over the foreign body, never into the new library.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body\n")
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n")
}
@Test func `repoint refuses over a never-loaded session with retyped text`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
// The file turns unreadable between scan and open: the session
// opens empty (loadFailed), the writer retypes into it (#200's leg).
let file = try #require(PostStore.folder(of: "shared", home: homeA))
.appendingPathComponent("post.md")
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) }
model.select("shared")
#expect(model.session?.loadFailed == true)
model.session?.edit("# Retyped words over a file that never loaded")
// The Settings repoint — refused: the retype is the only copy.
#expect(model.repoint(to: homeB) == false)
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.text == "# Retyped words over a file that never loaded")
#expect(model.lastError != nil)
}
@Test func `a no-collision repoint lands the open piece's edits first and tears it down cleanly`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Unique\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("unique")
model.session?.edit("# Unique\n\nA body, typed in A\n")
// The Settings repoint — accepted: the old session's edits landed
// on A BEFORE anything moved (the vanish path used to tear it down
// without a flush).
#expect(model.repoint(to: homeB))
#expect(PostStore.readBody(id: "unique", home: homeA) == "# Unique\n\nA body, typed in A\n")
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
model.bind(home: homeB)
// No ghost: the new library's rescan leaves nothing selected, nothing open.
try await pollUntil { model.posts.contains { $0.id == "shared" } }
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
#expect(model.watchedHome == homeB)
}
@Test func `a card scan from the old library never lands on the new library's same-slug piece`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
let folderA = try #require(PostStore.folder(of: "shared", home: homeA))
let folderB = try #require(PostStore.folder(of: "shared", home: homeB))
_ = try FixCardStore.submit(piecePath: folderA.path, cards: [card(pattern: "Hedging", quote: "A body")])
_ = try FixCardStore.submit(piecePath: folderB.path, cards: [card(pattern: "Telling", quote: "B body")])
// HOLD the old library's scan past the repoint: the injected scanner
// parks on A's folder until the test releases it (a detached disk
// read is otherwise faster than any arrangement); B's scans run
// free. The park probe is a flag, never a consuming semaphore wait —
// pollUntil re-evaluates its condition per iteration.
let parked = ParkedFlag()
let release = DispatchSemaphore(value: 0)
model.scanPieceCards = { url in
if url == folderA {
parked.set()
_ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread
}
return FixCardStore.scan(pieceURL: url)
}
model.select("shared") // the A scan parks inside the detached read
try await pollUntil { parked.isSet }
// The repoint, then B's same-slug piece opens and ITS scan lands.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
model.select("shared")
try await pollUntil { model.openPieceCards.map(\.pattern) == ["Telling"] }
#expect(model.openPieceCards.map(\.pattern) == ["Telling"])
// Release the stale A scan: its continuation completes AFTER the new
// library's piece is open — identity at completion, never the id.
release.signal()
release.signal() // a second A scan, if one ever queued, must not park the teardown
try await Task.sleep(nanoseconds: 200_000_000) // let the hop-back land
#expect(model.openPieceCards.map(\.pattern) == ["Telling"]) // never A's cards
}
@Test func `a pass started after the repoint runs against the new library`() async throws {
let (model, homeA, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
_ = try PostStore.writeNew(body: "# Shared\n\nA body\n", home: homeA)
let homeB = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-pass-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true)
_ = try PostStore.writeNew(body: "# Shared\n\nB body\n", home: homeB)
model.select("shared")
#expect(model.session?.text == "# Shared\n\nA body\n")
// The Settings repoint: gate, then binding.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
model.select("shared")
#expect(model.session?.text == "# Shared\n\nB body\n")
await model.runPass(.pass1, mentor: mentor)
// Snapshot and the advance landed on B's piece with B's body — the
// retained A session used to hand its text to the new library.
let snapshot = try String(
contentsOf: homeB.appendingPathComponent("projects/posts/shared/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot.contains("B body"))
let onDiskB = try String(contentsOf: homeB.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8)
#expect(onDiskB.contains("pass_state: Pass-1 Done"))
let onDiskA = try String(contentsOf: homeA.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8)
#expect(onDiskA.contains("pass_state: First Draft"))
#expect(!FileManager.default.fileExists(atPath: homeA.appendingPathComponent("projects/posts/shared/passes/pass-1.md").path))
}
/// r1 (MF-1): the hoisted stale-Home verdict in `rescan` — the sibling
/// continuation of the card hop-back, and the one guard still observable
/// in production after the gate. A scan started under A sits in its
/// detached hop while the gate passes and `bind` flips to B; landing
/// after B's own scan it would put A's list under the B binding until
/// the next B-side event — which, with nothing open, can be never.
@Test func `a library scan from the old Home lands nothing under the new binding`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Alpha\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// The rig's first rescan lands first: posts is A's list, steady state.
try await pollUntil { model.posts.map(\.id) == ["alpha"] }
// HOLD the next A scan past the repoint (the card pin's shape).
let parked = ParkedFlag()
let release = DispatchSemaphore(value: 0)
model.scanLibrary = { home, cache in
if home == homeA {
parked.set()
_ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread
}
return Post.scan(home: home, cache: cache)
}
Task { await model.rescan() } // parks inside the detached scan
try await pollUntil { parked.isSet }
// The Settings repoint: gate, then binding; B's own scan lands.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
try await pollUntil { model.posts.map(\.id) == ["bravo"] }
let revision = model.contentRevision
// Release the stale A scan: its continuation completes AFTER B's scan
// — the hoisted verdict applies nothing it found (list, revision).
release.signal()
release.signal() // a second A scan, if one ever queued, must not park the teardown
try await Task.sleep(nanoseconds: 200_000_000) // let the continuation land
#expect(model.posts.map(\.id) == ["bravo"]) // never A's list under the B binding
#expect(model.contentRevision == revision) // and no revision bump for it
}
/// r1 (N-1): the draft-survives decision, pinned — a draft has no Home
/// until first save (#62), so the repoint leaves its buffer alone and
/// the lazy folder lands under B, in the draft's OWN project even when
/// B does not have it yet (materialize creates with intermediates).
@Test func `an in-memory draft survives a repoint and first-saves into the new library only`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Piece\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// A holds `projects/alpha/in-alpha` — a project B does not have.
let alphaPiece = try PostStore.writeNew(body: "# In Alpha\n\nA body\n", project: "alpha", home: homeA)
try await pollUntil { model.posts.contains { $0.id == alphaPiece.id } } // the list must know the piece (targetProject reads it)
model.select(alphaPiece.id)
model.newPost() // targets the selected piece's project
#expect(model.draft?.project == "alpha")
model.updateDraft("# Draft Words\n\nTyped in A, saved in B")
// The Settings repoint: gate, then binding — the draft rides along.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
#expect(model.draft?.text == "# Draft Words\n\nTyped in A, saved in B") // intact
model.saveDraft()
#expect(PostStore.readBody(id: "draft-words", home: homeB) == "# Draft Words\n\nTyped in A, saved in B")
#expect(PostStore.readBody(id: "draft-words", home: homeA) == nil) // never A
#expect(Post.scan(home: homeB).contains { $0.id == "draft-words" && $0.project == "alpha" }) // B-absent project created
#expect(model.session?.targets(postID: "draft-words", home: homeB) == true) // and it opens there
#expect(model.draft == nil)
}
}
+37 -1
View File
@@ -8,6 +8,8 @@
// #179: the write-rail pins — one seam pairs every library store write
// with exactly one rescan and owns the error strip; the model owns the
// Home (no method takes one).
// #205: the row menus' Reveal in Finder / Copy Path target — the piece's
// post.md resolved on disk; a vanished piece answers nil.
//
import Foundation
@@ -68,6 +70,37 @@ func makeModelHome() throws -> (PostsModel, URL) {
#expect(model.lastError == nil)
}
@Test @MainActor func `reveal and copy path resolve the post file on disk`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Find Me\n", project: "essays", home: home)
let url = model.fileURL(for: post)
let expected = home.appendingPathComponent("projects/essays/\(post.id)/post.md")
#expect(url == expected)
#expect(FileManager.default.fileExists(atPath: url?.path ?? ""))
}
@Test @MainActor func `reveal and copy path answer nil for a vanished piece`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Ghost\n", home: home)
try PostStore.trash(post, home: home)
#expect(model.fileURL(for: post) == nil)
}
@Test @MainActor func `reveal and copy path resolve an archived piece off the archive root`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Shelved\n", project: "essays", home: home)
try PostStore.archive(post, home: home)
let url = model.fileURL(for: post)
let expected = home.appendingPathComponent("archive/essays/\(post.id)/post.md")
#expect(url == expected)
#expect(FileManager.default.fileExists(atPath: url?.path ?? ""))
}
@Test @MainActor func `new project draft lands in the named project`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home)
@@ -579,7 +612,10 @@ struct PostsModelWriteRailTests {
let homeB = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true)
rig.model.bind(home: homeB) // the Settings repoint, mid-pass
// the Settings repoint, mid-pass — brief-28: gate first (the open
// piece departs cleanly), then the binding commits.
#expect(rig.model.repoint(to: homeB))
rig.model.bind(home: homeB)
// Release the held turn as a NORMALLY ended one — .ended + no refusal.
// Poll for the PARK first: runningPass flips before the one-shot
// engine spawns, so ending the hold in that window false-fails
@@ -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")))
+64 -32
View File
@@ -44,8 +44,8 @@ struct SeedSkill {
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// 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 <name>` 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 <profile>` global flag
/// (#23, #134): `mcp list` prints "museion-tools" iff
/// `<binaryDir>/mcp-registered-<profile>` 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 `<binaryDir>/mcp-add-invocation-<profile>`, drops the
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` / `config-unset-fails`
/// force the matching failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
/// #136: `config set` also records KEY=VALUE into
/// `<binaryDir>/config-store-<profile>` (dedup per key), and the fake speaks
/// `config get <key>` (store value, or the not-set line on stderr exit 1)
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// 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
"""
+2 -1
View File
@@ -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))
}
}
+5 -1
View File
@@ -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
+106
View File
@@ -261,3 +261,109 @@ struct ProseRekeyMathTests {
#expect(result.park == 15) // caret parks at the marker line's content end
}
}
// MARK: - #142 typing budget (brief-24: fold-typing-budget-pin)
/// The typing-cost guard the landed re-key optimization never had: a quiet
/// regression that routes single-line typing edits back to the full pass
/// would keep every correctness pin above green (the full pass re-derives
/// CORRECT folds — it is only O(buffer) per keystroke). These pins count
/// scanned LINES through the real keystroke pipeline (shouldChangeText →
/// storage mutate → refreshFolds) — an operation count, never wall-time —
/// and hold the budget flat as the buffer doubles: the cheap path's cost
/// rides the fold count, not the document size.
extension ProseFoldRekeyTests {
/// One folded list + `filler` plain lines below it. Plain filler lines
/// are not list markers, so they add buffer without adding parents.
private func budgetText(filler: Int) -> String {
"intro\n\n- parent\n - child\n" + (0 ..< filler).map { "filler line \($0)\n" }.joined()
}
/// Type one character through the real pipeline at N and 2N filler lines
/// and return each run's scanned-line total.
private func typingScans(filler: Int) -> Int {
let text = budgetText(filler: filler)
let textView = makeView(text)
guard let parent = ProseList.parents(in: text).first else {
preconditionFailure("fixture must arm a parent")
}
textView.toggleFold(parent)
var scanned = 0
// The coordinator's keystroke tail with the budget instrument armed.
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x")
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x")
textView.refreshFolds { scanned += $0 }
return scanned
}
@Test func `typing beside a fold scans zero lines at N and 2N`() {
let atN = typingScans(filler: 200)
let at2N = typingScans(filler: 400)
#expect(atN == 0, "single-line typing edit took the full pass at N: \(atN) lines scanned")
#expect(at2N == 0, "single-line typing edit took the full pass at 2N: \(at2N) lines scanned")
// The budget itself: doubling the buffer must not move it.
#expect(atN == at2N)
}
@Test func `coordinator keystroke pipeline scans zero lines beside a fold`() throws {
// The through-seam pin (aegis ruling): the REAL entry — insertText
// through the PostEditorView coordinator's delegate tail
// (shouldChangeText → storage → textDidChange → refreshFolds) —
// never a direct test call. The instance hook (onLineScan) is the
// budget window for paths that call refreshFolds() bare.
let text = budgetText(filler: 200)
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
var scanned = 0
textView.onLineScan = { scanned += $0 }
let session = EditorSession(
target: .externalFile(URL(fileURLWithPath: "/dev/null")),
debounce: .seconds(3600),
)
let coordinator = ProseTextView.Coordinator(
representable: ProseTextView(session: session, dropBridge: ProseDropBridge(), routeDrop: { _ in false }),
)
textView.delegate = coordinator // production wiring (PostEditorView)
textView.setSelectedRange(NSRange(location: 0, length: 0))
textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
#expect(scanned == 0, "real keystroke took the full pass: \(scanned) lines")
#expect(textView.folds.count == 1) // and the fold survived the real pipeline
// Liveness in the same harness: a structural insert through the same
// coordinator MUST scan the whole buffer (206 — see the control's
// arithmetic) — proving the instance window counts real work.
scanned = 0
textView.setSelectedRange(NSRange(location: 0, length: 0))
textView.insertText("y\n\n", replacementRange: NSRange(location: 0, length: 0))
#expect(scanned == 206, "instance window lost exact accounting: \(scanned)")
}
@Test func `full pass scans scale with the buffer at N and 2N`() {
/// The control that keeps the zero-pin honest: route the SAME edit
/// shape to the full pass (a multi-line replacement — structural
/// edits never take the cheap path) and the instrument must report
/// the whole buffer, growing with it. If the observer ever goes
/// dead (unwired, wrong seam), this fails — the zero-pin above can
/// never pass vacuously.
func fullPassScans(filler: Int) -> Int {
let text = budgetText(filler: filler)
let textView = makeView(text)
guard let parent = ProseList.parents(in: text).first else {
preconditionFailure("fixture must arm a parent")
}
textView.toggleFold(parent)
var scanned = 0
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x\n\n")
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n")
textView.refreshFolds { scanned += $0 }
return scanned
}
let atN = fullPassScans(filler: 200)
let at2N = fullPassScans(filler: 400)
// 4 fixture lines + filler + 2 from the split intro line ("x\n\n"
// turns intro into three lines) — exactly the buffer's line count.
#expect(atN == 206, "control lost exact line accounting: \(atN)")
#expect(at2N == 406, "control lost exact line accounting: \(at2N)")
#expect(at2N > atN, "the instrument must scale with the buffer")
}
}
+2 -1
View File
@@ -27,7 +27,8 @@ struct ReadingPresenterTests {
@Test
func `stamper rewrites attributes`() {
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>")
let expected = "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>"
#expect(ReadingPresenter.stampHTML(html) == expected)
}
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
+35
View File
@@ -103,6 +103,41 @@ struct WritingGoalTests {
#expect(block.secondsRemaining(now: Self.arm.addingTimeInterval(60)) == 29 * 60)
}
@Test
func `a minutes update takes zero word-rail trips`() {
// Opt pass 2026-11-09 (unticketed digest finding): a minutes
// verdict rides the clock alone, so the per-keystroke feed must
// not count — let alone tokenize — the whole document. One long
// feed, zero rail trips through the injectable seam.
var block = Self.run(.minutes(30))
var railTrips = 0
block.update(
text: String(repeating: "word ", count: 2000),
countWords: { _ in
railTrips += 1
return 0
},
)
#expect(railTrips == 0)
}
@Test
func `a words update takes exactly one word-rail trip`() {
// The skip boundary: words goals keep live accounting — exactly
// one rail trip per update, and the count lands.
var block = Self.run(.words(500))
var railTrips = 0
block.update(
text: "one two three four five six seven",
countWords: { _ in
railTrips += 1
return 7
},
)
#expect(railTrips == 1)
#expect(block.currentWords == 7)
}
@Test
func `an absurd minutes goal never traps the countdown`() {
// Int() traps past Int.max — the clamp at the conversion seam is the pin
+38
View File
@@ -253,6 +253,44 @@ struct WritingLockTests {
#expect(delegate.applicationShouldTerminate(NSApplication.shared) == .terminateNow)
}
// MARK: - #200: the quit-time departure gate
@Test @MainActor
func `quit refuses while an open piece cannot depart and proceeds once it can`() throws {
// The failed-flush-at-quit posture, pinned: block quit (this
// delegate's own refusal precedent) — never silently drop the
// only copy of the edits. quitReply is the pure decision seam;
// the refusal ALERT itself is hosted-guarded like the kiosk.
let delegate = WritingLockAppDelegate()
// No model alive → nothing open, nothing to lose.
#expect(delegate.quitReply(posts: nil) == .terminateNow)
// A dirty-but-clean-writable session departs: quit proceeds and
// the flush lands.
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlast words before quitting")
#expect(delegate.quitReply(posts: model) == .terminateNow)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
// An unanswered #67 conflict refuses termination — the foreign
// disk body must survive the quit attempt.
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
model.session?.diskDidChange(diskText: "foreign body from disk")
#expect(delegate.quitReply(posts: model) == .terminateCancel)
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
// A failed flush refuses termination too — the pinned posture.
model.session?.keepLocal() // #67 No: the writer keeps their words
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: pieceDir.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: pieceDir.path) }
#expect(delegate.quitReply(posts: model) == .terminateCancel)
#expect(model.lastError != nil)
}
/// Bounded poll for the watched scan to surface a piece (the
/// PostsModelTests poll pattern — the FSEvents latency window).
@MainActor
+66
View File
@@ -0,0 +1,66 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
macos
## Users
v1 is Alexander himself — scratch-own-itch, the Helm ADE pattern: personal, local-first, GPL, zero audience risk while the category is invented. Dogfood until the loop earns more. The vertical it proves: essay/blog writers who want to get better, not ghostwritten — unoccupied (AI-writing competitors are fiction-only). The decision to publish for others is post-v1, informed by actual use.
## Product Purpose
Museion is the Agentic Writing Environment (AWE) — the IDE for long-form writing, where the text, the library, and a resident AI mind work under one native macOS roof. Named for the Mouseion of Alexandria: the one place in history where they already did.
v1 ships the Mentor Loop: a minimal editor surface + one fierce agent + persistent critique memory + library-light + plain markdown + a real publish path. The workflow is not hypothetical — it already runs daily (Hermes + the serif-writing skill stack); Museion formalizes a validated workflow into an app, it does not invent the mentor. Success means the daily loop holds up as an app and the writer measurably improves at craft.
## Positioning
Every AI writing tool on the market makes text faster; none is built to make the *writer* better. Museion's defensible mechanism is the discipline apparatus — manuscript context plus persistent memory of recurring weaknesses — which a plugin bolted to a notes app cannot own. Fierceness alone is a system prompt; memory is the moat.
- vs Obsidian + Copilot: agent-first and native, manuscript-shaped with the AI as resident, with memory of the writer.
- vs Ulysses/Scrivener: real AI depth — their structure is the ceiling, here it is the floor.
- vs Paper: Paper's calm without giving up depth.
- vs Sudowrite Story Coach / Fictionary / AutoCrit: an environment aimed at essays/blogs (unoccupied vertical), not fiction coaching.
## Operating Context
- All writing lives in one **Museion Home** folder as plain markdown (default `iCloud Drive/Museion`, silent `~/Documents/Museion` fallback at first run; repoint-only — Museion never moves content). Finder, Textastic-class editors, and iCloud.com all reach it.
- The engine is user-installed **Hermes**, spawned as a child process over **ACP** under dedicated profiles — one per LLM surface: `museion` (chat/sessions), `museion-pass1`, `museion-pass2`. Isolated config, skills, credentials, memory; writing and coding learnings never mix.
- Model/provider per surface, edited in-app; `zai/glm-5.3` is the research-validated default pin.
- Mentor methodology ships as bundled markdown skills seeded additively into the profiles (Serif stack, deslop, pass/session personas, demonstrator doctrine, craft canon, drill packs) — the profile's self-improved skills are never overwritten.
- Publishing goes to Micro.blog via Micropub: draft first, then publish; illustrations travel with alt text.
- GLOSSARY.md is the binding shared vocabulary (Mentor, Engine, Pass, Fix Card, Learning, Home, Piece…).
## Capabilities and Constraints
- v1 scope locked to the seven milestones M0–M6 (bridge spike, editor surface, edit passes + fix cards, critique memory, measurable improvement, research/library-light, Micropub publish). M4–M6 shed in that order under scope pressure.
- v1 non-goals: long-form structure tools (binder/compile), multi-mind agents, vault depth (backlinks/graph), native Swift agent loop, app-managed Hermes install, publish targets beyond Micro.blog, non-macOS platforms, App Store distribution, AI-draft wizards/templates, mentor judgment of illustration style.
- Hard product rules: stats are computed on unaided writer-origin first drafts only; a Learning is promoted only by explicit confirmation (one confirm = one entry) with output-clock decay (resurface after 10 passes, doubling per re-dismiss); no batch apply-all; trust defaults are fixed (apply/promote/keep/publish = ask-before; delete/outside-Home/shell/git = never-do); no one-button publish of mentor prose — the writer's hand ships every piece.
- Technical: native SwiftUI, macOS 26.5+, Swift 6 (ADR-0001); GPL-3.0-or-later (ADR-0002); no bespoke store — plain files only; app sandbox off (the app spawns the user-installed `hermes` binary); the engine never owns Museion state (ADR-0007) — sessions are expendable, learnings/pieces/stats are Museion-owned.
- UI constraint: `ref/Web-Prototype/museion-workspace.html` (+ `DESIGN-HANDOFF.md`, `DESIGN-MANIFEST.json`) is the workspace visual contract — build from its tokens and layout geometry, not a loose reinterpretation.
## Brand Commitments
- Name **Museion**, for the Mouseion of Alexandria; in-app displayed name/tagline come from `AppMetadata` (single source).
- The Alexandria family: *Classis sails, Pharos guides, Museion holds knowledge* — shared native-SwiftUI craft and a coherent brand story.
- License GPL-3.0-or-later; distribution never via the App Store.
- Mentor voice is constant: fierce, never flattering — the Knife never leaves the room; warm-but-firm by persona blend, never a mood adjective.
## Evidence on Hand
- `PRD.md` — build-ready PRD, two stress-test reshapes applied (audit trail G1–G14 inside).
- `GLOSSARY.md`, `docs/adr/` (ADR-0001…0014), `docs/devlog/` session logs, `docs/research/` provider factsheets, `docs/sample-pass.md` (worked sample Pass), `CHANGELOG.md`.
- Validated methodology evidence: daily Hermes + serif-writing editing workflow; session docs under `docs/brainstorming-output/`.
- Visual contract: `ref/Web-Prototype/` (OpenDesign handoff).
- No testimonials, customers, or benchmarks exist — v1 has one user; future work must not fabricate any.
## Product Principles
1. Make the writer better, not the text faster — a feature either deepens the critique or gets out of its way.
2. The writer's hand stays on the wheel — the mentor critiques, demonstrates, and remembers; nothing ships without explicit acceptance.
3. Plain files, local-first, writer-owned — no bespoke store, no backend; the Home is portable markdown Museion never moves.
4. The engine is a swappable organ, never the body — Museion owns all durable state; the engine's own memory is expendable by design.
5. Friction where it guards craft, calm everywhere else — fix cards are first-class surfaces, never toasts; the editor disappears so the writing can lead.
+134 -16
View File
@@ -1,40 +1,158 @@
# Museion
The Agentic Writing Environment (AWE): where scholars, texts, and AI minds work under a single roof — named for the Mouseion of Alexandria, the one place in history where they already did.
**The Agentic Writing Environment** — a native macOS app where your text, your library, and a resident AI mentor work under one roof. Named for the Mouseion of Alexandria, the one place in history where they already did.
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE)
An Obsidian-and-Copilot-class tool for long-form AI-assisted writing, with Ulysses/Scrivener depth and Paper elegance. Native macOS, built in SwiftUI.
Museion is built for long-form writers who want to get *better*, not ghostwritten. The mentor critiques, demonstrates, and remembers your recurring weaknesses — and nothing ships without your hand on it. Everything you write is plain markdown in a folder you own.
## Features
### Writing
- **Native prose editor** (TextKit 2) with styled markdown source — headings scale, syntax dims, the plain file stays the truth. Autosaves about a second after you stop typing; `⌘S` saves now. The dot in the toolbar tells the truth: changed, saved, or failed.
- **Reading mode** (`⌘R`) renders the piece for reading. Click anywhere to drop back into editing at that spot.
- **Focus mode** (`⌥⌘F`) recesses the library, the mentor, and the toolbar; they return on edge hover.
- **Cold Turkey** — a writing lock inside focus mode. Set a goal (net new words, or minutes) and Museion goes into a fullscreen kiosk until you meet it. Quitting asks once. Nothing persists.
- **Drop an image** into prose: it is copied into the piece's `assets/` and a markdown reference lands at the drop point with the alt text selected.
- **Lists** — `Tab` / `⇧Tab` indents and outdents, `⌥↑` / `⌥↓` moves the item with its subtree. Nested lists fold behind a gutter chevron.
- **External files** — `⌘O` opens any `.md` file in place as a guest (never converted, never moved). `⇧⌘O` imports `.md` files as posts (copies; the originals stay put).
- An edit from outside (Finder, iCloud, another editor) raises a **Reload / Keep Local** alert — never a silent overwrite. Cursor and scroll position come back on reopen.
### Outlines
Outline pieces are plain nested bullets with LogSeq-style keys: `⌘↑` / `⌘↓` fold, `Enter` splits at the caret, double-click a bullet to zoom into its branch with breadcrumbs back out. Drag blocks to reorder or nest. **Convert to Post…** turns an outline into prose — verbatim bullets, or a headings ladder. One-way in v1.
### Library
- Pieces live under **projects** and fold into an **archive**. The library column groups by project and Pass State, with collapse toggles and counts.
- **Search** across titles and bodies (frontmatter excluded), title matches first.
- Rename (retitles and moves the folder), move to project, archive, restore, trash — all from the row's menu. A folder move flushes pending edits first; a failed write aborts the move with nothing relocated.
- The library mirrors the folder live: a recursive file watcher picks up Finder edits, new pieces, and deletes.
### The Mentor
- The mentor is a resident **[Hermes](https://hermes-agent.nousresearch.com/docs)** engine you install yourself, spawned as a child process over ACP under three isolated profiles — `museion` for Chat and Sessions, `museion-pass1` and `museion-pass2` for the passes. Model, provider, and reasoning effort are set per surface in Settings and written through Hermes' own config rail. z.ai, Anthropic, OpenAI, and Nous Portal are wired up; **Test Connection** says in plain words what is wrong.
- **Passes** — Pass 1 critiques structure, argument, and flow (paragraph level and up); Pass 2 works at sentence level and below. Each pass streams live and ends in a verdict plus **Fix Cards**.
- **Fix Cards** are a first-class surface, never toasts. A mechanical card offers **Apply** behind a sheet showing the exact edit (anchored quote → replacement) — one card at a time, there is no apply-all. A demonstration card shows one annotated example on your own text and closes Done or Skip. A stale anchor (the text moved) flags the card instead of editing.
- **Deslop lint** runs natively in Swift at every pass invocation — banned-vocabulary tiers and em-dash density land as cards before the engine even sees the piece. Override the tables with `<Home>/deslop-lint.json`.
- **Learnings** — promote a card into a per-writer, per-content-type memory of your recurring weaknesses. Plain markdown files in the Home; every later pass consults them. Dismiss a Learning and it fades, resurfacing after 10 completed passes (doubling on each re-dismiss).
- **Sessions** — freeform conversations: new, resume, fork, compact, Stop. **New Post** turns a reply into a piece (stamped `origin: ai`, never stats-eligible). A Brainstorm is a session with an opener.
- **Blind Read** — an advisory A/B judgment of the current text against the pass-start snapshot, by a fresh session that never saw the history. Records nothing; you stay the judge.
- **Research notes** — mid-pass findings arrive as candidate cards with provenance. Keep lands a note in the piece's `research/`; Reject vanishes.
- **Drill offers** — two-minute craft drills riding the finding that motivates them. Declined drills vanish; drill output never touches the draft.
- The methodology ships as markdown skills seeded into the profiles (the Serif stack, deslop, pass and session personas, demonstrator doctrine, craft canon, the VOICE payload). Your own skills are never overwritten.
### Measuring progress
Running a pass on an unaided first draft captures four style metrics — burstiness, type-token ratio, sentence variation, trigram repetition — before the mentor sees the text. The **Trends** pane charts them across captures with an honest *improving / steady / slipping* verdict per metric.
### Publishing
**[Micro.blog](https://micro.blog) via Micropub:** Publish ▸ **Send as Draft** ▸ review on Micro.blog ▸ **Publish**. The app token lives in your login keychain. Illustrations upload first and ride inline where you placed them; a picture without alt text never ships. The piece on disk never changes. The library row shows where each piece stands — `draft on Micro.blog` or `published <date>` — and its menu opens the live post. Sending again updates the same post in place (never a second post) and reuses images that haven't changed.
### Rails
- Hardened runtime on; sandbox off (the app spawns your `hermes` binary).
- Daily backup of the three Hermes profiles, last seven kept — Help ▸ Open Backup Folder.
- Quit, navigation, and Home changes all pass one departure gate: an unanswered conflict or a failed save blocks the move. Edits are never dropped.
## Requirements
- macOS 26.5+ — developed against the latest Xcode (26.x) and Swift (6.3.x); no backward compatibility
- [SwiftFormat](https://github.com/nicklockwood/SwiftFormat) and [SwiftLint](https://github.com/realm/SwiftLint) for linting (`brew install swiftformat swiftlint`)
- **macOS 27 or later** (Apple Silicon).
- **Hermes engine** — needed for Passes and Sessions. The editor, library, outlines, and publishing work without it. Install with `curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash` ([installation guide](https://hermes-agent.nousresearch.com/docs)).
- A provider API key for the model the mentor should run on (Settings ▸ Provider Keys).
- A [Micro.blog](https://micro.blog) account — only if you publish.
## Getting started
### Fonts
```bash
git clone https://git.babylondreams.de/AlexKucera/museion.git
cd museion
Museion's typography is set in Matthew Butterick's typefaces. They are commercial, so the app does not ship them — install them yourself (open each `.otf` in Font Book):
open Museion.xcodeproj # develop in Xcode
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build # build
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # test (unit + UI)
swiftformat . && swiftlint . # lint
```
- **[Valkyrie OT](https://practicaltypography.com/valkyrie.html)**, the B cut — body text, document titles, the mentor's prose.
- **[Concourse OT](https://practicaltypography.com/concourse.html)** — headings and your side of the conversation.
- **[Ubuntu Mono Nerd Font](https://www.nerdfonts.com/font-downloads)** — code and syntax dimming (free).
Full Xcode project at the repo root — `open Museion.xcodeproj` and run.
Without them Museion still works: the editor falls back to the system font (SF Pro), Reading mode to Georgia. The spacing is calibrated on the real faces, so install them for the intended look.
## Install
Download `Museion-<version>.dmg` from [Releases](https://git.babylondreams.de/AlexKucera/museion/releases), open it, drag Museion to **Applications**.
The app is signed with a Developer ID and notarized with Apple, so it opens like any other app.
## Quick start
1. **First launch** picks your **Museion Home** — the folder everything lives in. Fresh installs get `iCloud Drive/Museion` when iCloud Drive is on, otherwise `~/Documents/Museion`. Settings ▸ Content shows the path; repoint any time (Museion never moves files).
2. **Install Hermes** (one-liner above). Museion finds it on the next launch, creates the three profiles, and seeds the writing skills — nothing else to set up. The rail pill and the Mentor header show engine state; the status card carries **Re-check**.
3. **Add a provider key** under Settings ▸ Provider Keys and hit **Test Connection**.
4. **Write.** `⌘N` for a new post, `⇧⌘N` for an outline. The first line is the title.
5. **Run a Pass** from the Mentor pane. Read the verdict, work the Fix Cards one at a time, promote the patterns worth remembering into Learnings.
6. **Publish** when the piece is yours.
## Support Museion
Museion is free and open source. It is one of a suite of apps I build and publish, and together they are my only income.
Every feature above took hours to build. Those hours have to come from somewhere. If Museion has become part of how you write, a coffee at **[buymeacoffee.com/babylondreams](https://buymeacoffee.com/babylondreams)** keeps them coming, for this app and the rest of the suite.
Thank you for writing with it.
## Keyboard shortcuts
| Action | Keys |
| --- | --- |
| New Post · New Outline · New Project… | `⌘N` · `⇧⌘N` · `⌥⌘N` |
| Open a file as a guest · Import files | `⌘O` · `⇧⌘O` |
| Save | `⌘S` |
| Toggle Reading Mode | `⌘R` |
| Toggle Focus Mode | `⌥⌘F` |
| Start Cold Turkey… | View menu (inside focus mode) |
| Check Spelling While Typing | Edit menu (off by default) |
| Prose list: indent · outdent · move item | `Tab` · `⇧Tab` · `⌥↑` `⌥↓` |
| Outline: fold · move subtree · select blocks · split | `⌘↑` `⌘↓` · `⌥↑` `⌥↓` · `⇧↑` `⇧↓` · `Enter` |
| Composer: send · newline | `Return` · `⇧Return` |
## Your Museion Home
Everything you write lives in one folder — the **Museion Home** — as plain markdown you can reach from anywhere.
```
<Home>/
projects/<project>/<piece-id>/post.md one piece, one folder
assets/ illustrations (drop an image)
research/ kept research notes
cards/ the piece's fix cards
passes/ pass-start snapshots
archive/<project>/<piece-id>/post.md finished work, Finder-visible
learnings/<content-type>/… promoted patterns, one markdown file each
deslop-lint.json optional lint-table override
```
- **Default for new Homes: `iCloud Drive/Museion`** — `~/Library/Mobile Documents/com~apple~CloudDocs/Museion`, resolved dynamically. When iCloud Drive is unavailable at first run, Museion silently falls back to `~/Documents/Museion` — no dialog; the Settings Home field shows the resolved path. An existing `~/Documents/Museion` Home is never silently moved — it stays your Home until you migrate it yourself (#169).
- **Migrating an existing Home:** Museion is repoint-only — it never moves content. Move the `Museion` folder in Finder (e.g. `~/Documents/Museion` → `iCloud Drive/Museion`), then repoint via **Settings ▸ Content ▸ Museion Home ▸ Choose…** (Museion/SettingsPaneView.swift:199).
- **Migrating an existing Home:** Museion is repoint-only — it never moves content. Move the `Museion` folder in Finder (e.g. `~/Documents/Museion` → `iCloud Drive/Museion`), then repoint via **Settings ▸ Content ▸ Museion Home ▸ Choose…**.
- **Avoid eviction stalls:** right-click the `Museion` folder in Finder and choose **Keep Downloaded**. Pinning keeps files local, so opening a piece never waits on a download (#168).
- **iCloud quirks are substrate, not bugs:** editing the same file on two devices yields numbered duplicate siblings — iCloud keeps both, it never merges. An evicted file keeps its real name and size, but its first read blocks while the data downloads (#168).
- **Companions:** Textastic-class editors open and edit pieces in place on iPhone/iPad via the Files app / document picker; iCloud.com and iCloud for Windows reach the Home too (#168, #169).
## Development
SwiftUI, Swift 6 (language mode 6, default MainActor isolation), macOS 27+, latest Xcode only — no backward compatibility, no pinned toolchains.
```bash
git clone https://git.babylondreams.de/AlexKucera/museion.git
cd museion
open Museion.xcodeproj # develop in Xcode
./scripts/build-and-run.sh # build + launch (⌘R equivalent)
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build
./scripts/full-test.sh start && ./scripts/full-test.sh status # full unit suite (verify rail)
swiftformat . && swiftlint . # lint (brew install swiftformat swiftlint)
./scripts/deploy.sh # Release build → /Applications
./scripts/release.sh # Developer ID-signed, notarized DMG → dist/
```
`AGENTS.md` is the binding work contract for agents and humans alike; `GLOSSARY.md` pins the vocabulary; decisions live in `docs/adr/`; one session log per task in `docs/devlog/`.
## License
GPL-3.0-or-later — see [LICENSE](LICENSE).
GPL-3.0-or-later — see [LICENSE](LICENSE). The bundled reading renderer (apex) and its libyaml are MIT; see [Museion/Resources/THIRD-PARTY-NOTICES.md](Museion/Resources/THIRD-PARTY-NOTICES.md).
+2
View File
@@ -14,6 +14,7 @@ Owned by the root AGENTS.md contract.
- ADR format follows the domain-modeling skill's `ADR-FORMAT.md`: short title + 1–3 sentences; optional Considered Options / Consequences only when they earn their place.
- `docs/agents/` holds the engineering-skills config (issue tracker, triage labels, domain-docs consumer rules) written by `setup-matt-pocock-skills` — edit directly, no child doc needed.
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7, #11, #123, and #58 verification artifacts); card shape follows GLOSSARY.md (lane and emitter fields included), anchors follow ADR-0006.
- `docs/releases/<version>.md` holds the release notes, one file per released version, written for humans: highlights, the milestones it closes, install, known limits. It distills that version's `CHANGELOG.md` section (which stays the entry-by-entry record with issue numbers); the Gitea release body is pasted from it.
## Work Guidance
@@ -31,3 +32,4 @@ Owned by the root AGENTS.md contract.
| `agents/` | Agent-skills config — issue-tracker, triage-label, domain conventions (written by `/setup-matt-pocock-skills`) |
| `brainstorming-output/` | Transient brainstorming session records — working artifacts, not durable decisions; durable outcomes flow into PRD/ADRs |
| `research/` | Verified research artifacts (provider/API factsheets) feeding ADRs — source-cited and probe-dated, not decisions |
| `releases/` | Release notes per version — human-readable distillation of the CHANGELOG section; the Gitea release body |
+1 -1
View File
@@ -9,7 +9,7 @@ Reading mode renders markdown through apex (MIT, unified dialect) as an HTML fra
## Consequences
- **Bundling:** the prebuilt apex binary ships in app resources, signed + notarized. No source build in CI, no user install gate — a renderer must not grow a gate.
- **Bundling:** the prebuilt apex binary (arm64 slice) and a vendored libyaml ship in app resources, Developer ID–signed at commit time (apex with the hardened runtime), apex's rpaths replaced by the single `@executable_path/../Resources`, which resolves in the bundle and in the checkout alike; Xcode copies and seals both as resources untouched. The vendored copy lives in `Resources/libyaml.bundle/` ON PURPOSE: Xcode's synced-folder classifier sniffs Mach-O content and silently adds any bare dylib (extension or not) to the app's link phase; a `.bundle` folder is an opaque resource. apex's release build links libyaml through CI/Homebrew rpaths, so alone it only ever ran on developer machines — reading mode silently fell back to source for everyone else (surfaced by the 0.1.0 notarization, which also rejects an unsigned Mach-O in Resources). Re-sign both when the Developer ID certificate rotates (`codesign -f -s "<identity>" --options runtime --timestamp Resources/apex`; `codesign -f -s "<identity>" --timestamp Resources/libyaml.bundle/libyaml-0.2.dylib`). No source build in CI, no user install gate — a renderer must not grow a gate. Licenses: `Resources/THIRD-PARTY-NOTICES.md`.
- **One WKWebView, reloaded in place.** Remounting per document (`.id(sel)`) was the dominant switch cost — hundreds of ms of web-process respawn; `loadHTMLString` on a retained view feels instant.
- **`--no-mixed-lists` is required**, not tuning: apex's default merges an ordered list following a bullet list into one `<ul>`, killing `1. 1. 1.` auto-renumbering.
- **Early handoff:** stdout EOF is conversion done; apex's ~65 ms teardown is reaped async via `terminationHandler` (the error path still waits for exit status).
@@ -0,0 +1,26 @@
# PostsModel bind rides the WorkspaceView root task — #179 follow-up
> **Date:** 2026-11-10
> **Type:** follow-up fix
> **Reference:** #179 (landed as 5bf0955); supersedes/closes PR #185
## Goal
The #179 finish-audit (run on PR #185) found one real bug that also lived in main's landed implementation: the model bind rode `PostsPaneView.task(id: home)`, which unmounts with the Posts pane — after a Settings Home repoint, the Archive pane and every root sheet (import / new project / convert) kept writing through the stale `watchedHome` until Posts remounted. Port that single fix to main's `performWrite` rail.
## Context — the duplicate implementation
PR #185 (`fix/postsmodel-write-rail`, opened 04:14) and main's 5bf0955 (08:45) turned out to be two complete, independent #179 implementations (three named `railWrite` entries + `boundHome` vs single `performWrite` seam + `watchedHome`). 5bf0955 closed the issue and carries six stacked commits (#180–#184). A merge attempt auto-resolved every Swift file — a semantic collision git cannot see — so per owner decision PR #185 is closed as superseded and the audit findings that still apply to main were ported here instead.
## What Was Done
- **Bind hoisted** — `PostsPaneView`'s pane-local `.task(id: home)` removed; `WorkspaceView` gains the root `.task(id: gate.museionHome) { gate.posts.bind(home: gate.museionHome) }`: first frame + every repoint, whichever pane is showing. Stacks cleanly with the rail's existing mid-pass repoint refusal (that guards the pass advance's minutes-long turn; this closes the global window).
- **Comments corrected** — `watchedHome`'s doc, `bind`'s doc, and the `Museion/AGENTS.md` PostsModel bullet no longer claim "construction + the Settings repoint" as two writers; they name the one root task.
Not ported (already resolved differently on main): dead `home:` sheet params (5bf0955 cut them), failure observability (main's five pins + sheet-AND-strip createProject routing cover it).
## Verification
- Full unit suite on this branch: `test-without-building -only-testing:MuseionTests` → executed 681 / passed 681 / failed 0 / skipped 0.
- swiftformat 0 dirty on the touched files; swiftlint 279 violations / 60 serious in 141 files — identical to main's pre-change baseline.
- Unpinned delta: the hoist is view wiring (no render harness for WorkspaceView) — verified by build + suite; the bind seam itself is model-level and pinned by the nil-Home refusal pin.
@@ -0,0 +1,27 @@
# Library search snapshots invalidated by library writes — the #144/#157 mounted gap
> **Date:** 2026-11-11
> **Type:** fix (finding `museion/library-search-stale-after-mutation`; no Gitea ticket)
> **Reference:** #144 (library search), #157 (LibrarySearch seam + pure suite — mounted invalidation explicitly unpinned), #179 (the write rail this extends), #143 (the equality-gated `posts` assignment whose blind spot this closes)
## Goal
PostsPaneView's search stored a snapshot in `matches` but its only task identity was `trimmedQuery` (`.task(id: trimmedQuery)` at PostsPaneView.swift:333 on 5915178). Library mutations never re-keyed the task, so the sweep never re-ran: after Archive/Trash from a result row's own context menu, the archived post REMAINED in the non-archived search results even after `model.posts` rescanned; new, renamed, and externally edited matching pieces never entered or left the results until the query changed or the view remounted. Body-only changes had no signal at all — #143's equality-gated assignment keeps `posts` still when a rewritten post.md parses to an equal Post.
## What Was Done
- **The rail extension** (PostsModel.swift): `rescan()` now bumps `contentRevision` whenever a scan sees the library change — a Post-list change OR any re-read post.md (the scan cache's miss counter deltas across the detached scan; a miss is one disk read + parse). Archive/trash/rename arrive as list changes; a body-only edit arrives as a cache miss (metadata-equal — the #143 skip keeps the panes still; the bump alone re-keys the search). The `posts`-assignment skip is untouched: panes never regroup on autosave echoes, and an unchanged rescan (all cache hits) does not bump — pinned.
- **The mounted key + gate** (LibrarySearch.swift, pure seam): `LibrarySearch.SearchKey` (query, homePath, revision) and `LibrarySearch.Snapshot` (key + results) with `isFresh(for:)` — a landed sweep renders only under the key that computed it.
- **The view rewiring** (PostsPaneView.swift): the column's `.task(id:)` keys on the full `searchKey` (trimmed query + Home + `model.contentRevision`), so library writes and Home repoints restart the sweep; the task captures its key at start and lands the snapshot under it; body renders a snapshot only while `isFresh(for: searchKey)` — stale rows drop to the recompute spinner instead of lingering. A mid-sweep key change cancels at the existing `Task.isCancelled` guards, and even a raced assignment cannot render — the body-side gate refuses it.
- **Tests** (MuseionTests/LibrarySearchTests.swift, new `LibrarySearchSnapshotTests` suite): the pure key/gate pin, plus controller-level pins over the real rescan rail (`makeModelHome` + `pollUntil` convention) proving archive, trash, and a same-query body edit each move the revision through the standing-snapshot `isFresh` gate; a guard pin that an unchanged rescan keeps the revision. The three rail pins were committed red first (c0cd60b: 3 failed / 2 passed) and turned green with the fix (becad45: 5/5).
Not done (out of scope): a render harness for the SwiftUI column itself — no UI automation per house style; the invalidation is observable at controller level, which is what the view consumes.
## Verification
- Baseline on pristine 5915178 (before any edit, after a stash): `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -derivedDataPath <scratch>/dd-base -resultBundlePath <scratch>/base.xcresult -only-testing:MuseionTests test` → ** TEST SUCCEEDED **, exit 0; xcresult summary: totalTestCount 681, result Passed.
- RED @ c0cd60b: same invocation with `-only-testing:MuseionTests/LibrarySearchSnapshotTests` → ** TEST FAILED **, exit 65; failedTests 3 (archive, trash, body-edit — exactly the briefed failure set), passedTests 2.
- GREEN focused @ becad45: same focused invocation → ** TEST SUCCEEDED **, exit 0; 5/5 passed, 0 failed.
- GREEN full @ becad45 (code head; the later docs commit adds no compiled code): full `-only-testing:MuseionTests` → ** TEST SUCCEEDED **, exit 0; xcresult summary: totalTestCount 686, passedTests 686, failedTests 0, skippedTests 0 (baseline 681 + the 5 new pins, zero confounds).
- swiftlint: 279 violations / 60 serious in 141 files at base; identical counts at the fix head (the two PostsModel warnings and one PostsPaneView file-length warning pre-exist, only their line counts grew). swiftformat: 0 files require formatting, touched and whole-tree.
- Known flake EditorSessionTests/debounce not encountered in either full run on this base.
@@ -0,0 +1,51 @@
# Cold Turkey live tokenization — minutes skip + count-only word rail
> **Date:** 2026-11-13
> **Type:** opt
> **Reference:** unticketed digest finding `cold-turkey-full-tokenization` (argus opt pass 2026-11-09, scanned at efbde25c; branch `opt/cold-turkey-full-tokenization` off main 5915178)
## Goal
Kill the O(document) per-keystroke tokenization on the focused writing surface: Cold Turkey feeds every editor edit through whole-document word counting even for minutes blocks whose verdict and progress ignore words entirely, and the word count itself builds a lowercased `[String]` token array just to return `.count`. Behavior byte-stable, cost down.
## What Was Done
- Re-derived the defect live at base 5915178 (tip unmoved from the scan-era drift check; the ~10 commits since efbde25c never touched the seam): `PostEditorView.onTextChange` → `WritingLockState.feed` → `WritingGoalRun.update` → `DraftStats.words` → `tokens(in:)` — `text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map { $0.lowercased() }`, full array materialized per keystroke, main actor, for every goal type. Minutes consumers (`isMet`, `progress`, `readout`, `completionNoteText`) never read the count.
- RED first: injected a per-call word-rail seam on `update(text:countWords:)` (default `DraftStats.words`) and pinned `a minutes update takes zero word-rail trips` — failed at base exactly as designed (base takes one trip per update); companion `a words update takes exactly one word-rail trip` pins the skip boundary; both sides of the boundary in one suite.
- Semantic equivalence pin: `word rail equals the split tokenizer over a mixed corpus` (DraftStatsTests) — the old split expression kept alive as an inline reference over a corpus covering empty, whitespace-only, punctuation-only, mixed scripts (Latin/diacritics/Cyrillic/CJK/Arabic), emoji ZWJ, punctuation, decimal/comma numbers, contiguous alnum runs. Green at base by design — it is the equivalence proof, not a RED.
- Fix (9f4d9ef): `update` guards on `.words` — a minutes run does no word work on feed at all (its accounting freezes at the arm-time baseline; `currentWords` was dead state for minutes runs); `DraftStats.words` becomes a count-only Character pass over maximal `isLetter`/`isNumber` runs — identical count by construction (split with omitted empty subsequences yields exactly the maximal runs), no array, no lowercasing. Arm-time baseline still counts once per arm through the same rail, now allocation-free. All callers unchanged.
- Gates: focused WritingGoalTests RED 12/13 → GREEN 13/13; full unit target 684 executed / 684 passed / 0 failed / 0 skipped (681 base + 3 new); swiftformat 0 dirty; swiftlint 279 violations / 60 serious in 141 files — byte-identical to pristine base 5915178 (all pre-existing, spike/prototypes noise).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Per-call injectable rail seam over a global tokenizer counter | The hosted suite runs Swift Testing tests in parallel — a shared static counter would race concurrent `DraftStats.compute` calls (which legitimately tokenize) and false-RED the zero-trips pin. The per-call closure counts exactly the production path (default argument = the real rail) with no shared state. Precedent: `spawnsTicker`, injectable `at:` — the repo's established seam style. |
| Minutes accounting freezes at baseline rather than being deleted | `WritingGoalRun`'s documented shape keeps `baselineWords`/`currentWords` as arm-time facts; nothing reads `currentWords` for a minutes run (readout/isMet/progress/note all ride the clock), so freezing is observationally identical to the old live tracking for every consumer — the smallest diff that removes the work. |
| `words(in:)` stays the ONE word-count rail (count-only inside it) | Museion/AGENTS.md contract: net-words and first-draft stats can never drift. The count-only pass uses the exact same per-Character predicates as the tokenizer; the corpus pin holds the equivalence forever. Explicitly NOT a whitespace count. |
| `DraftStats.compute`'s sentence-length `tokens(...).count` left alone | Store-time (once per pass at capture), not the per-keystroke seam — one finding per branch; folding it in would scope-creep the opt. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| RED build failed: "Unprintable ASCII character" at DraftStatsTests:91 | The patch layer's JSON escaping wrote a raw TAB (0x09) inside the `" \t\n "` corpus literal — Swift forbids raw tabs inside string literals (the neighboring `\n` escapes landed correctly, masking the asymmetry) | Byte-level replace with proper `\t` escape; scanned all touched files for stray mid-line control bytes; amended into the RED commit (dde99c8, force-with-lease — branch unreviewed at that point, disclosed) |
| 02:27 gateway drop killed the turn between the seam patch and the test patches | Dead turn discarded; the applied seam patch survived on disk, the two unapplied test patches were lost | Re-derived state from `git status`/diff before redoing anything (no double-apply); RED milestone committed + pushed on resume per push-at-first-commit |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/WritingGoal.swift` | `update` guards on `.words` (minutes: no word work on feed); injectable `countWords` rail seam; `currentWords`/header docs updated to the frozen-minutes truth |
| `Museion/DraftStats.swift` | `words(in:)` count-only Character pass — no token array, no lowercasing; equivalence documented |
| `MuseionTests/WritingGoalTests.swift` | Pins: minutes zero rail trips (RED at base), words exactly one rail trip + count lands |
| `MuseionTests/DraftStatsTests.swift` | Corpus equivalence pin: word rail vs the old split expression over mixed scripts/emoji/punctuation/numbers/empties |
| `CHANGELOG.md` | [Unreleased] › Changed entry |
## Open Items & Next Steps
- [ ] None on this seam. Observation for @aegis (NOT folded in): `DraftStats.compute`'s sentence-length `.map { tokens(in: String($0)).count }` still allocates per sentence chunk at store-time — same count-only treatment would apply there if it ever shows up hot, separate finding.
---
*Log written by hand on the brief-23 branch (daedalus).*
@@ -0,0 +1,60 @@
# Fold typing budget — operation-count pin at N/2N
> **Date:** 2026-11-13
> **Type:** opt (test-only instrument + pins; zero production behavior change)
> **Reference:** brief-24 `fold-typing-budget-pin` (unticketed instrument-audit commitment; #142 referenced as context only — CLOSED, no Fixes footer). Base `7ed3041` (museion main tip at claim, re-verified via ls-remote). **Incident:** the brief was dual-dispatched (aegis one-shot spawn + discussion announcement); the sibling session began implementing in this worktree concurrently and was dispatcher-terminated at zero commits per @aegis ruling — this branch is the ruling's surviving implementation, with the sibling's coordinator-seam idea folded in as the through-seam pin. Takeover is recorded in the ack file; every gate below ran AFTER hunk-level decontamination of the tree.
## Goal
The landed #142 in-place re-key (`rekeyAfterPlainEdit` — single-line typing edits re-key folds with per-fold O(1) math, no rescan, no storage swap) has correctness coverage (`ProseFoldRekeyTests`) but no typing-cost guard: a quiet regression that routes single-line edits back to the full pass would keep every correctness pin green — the full pass re-derives CORRECT folds, it is only O(buffer) per keystroke. Ship the missing pin: an operation-count instrument through the real editor seam, budget held flat as the buffer doubles. Explicitly NOT a wall-time benchmark.
## What Was Done
- Instrument (production diff, default-nil, zero behavior change): `ProseList.parents(in:observeLines:)` reports the line count it scanned; `refreshFolds(observeScan:)` / `refreshFoldRendering(observeScan:)` thread a per-call observer to it; `refreshFoldRendering` also consults a per-instance `onLineScan` hook (`observeScan ?? onLineScan`) — the window for production paths that call `refreshFolds()` bare, i.e. the PostEditorView coordinator's textDidChange tail. Per-call and per-instance only, no shared/static state — the brief-23 lesson (parallel hosted suite races a global counter). Precedent: `WritingGoal.update(text:countWords:)`, PostScanCache's counted miss/hit seams.
- Pin 1 `typing beside a fold scans zero lines at N and 2N`: one folded list + 200 plain filler lines (N) and 400 (2N); type "x" in the intro line through the keystroke pipeline (`shouldChangeText` → storage mutate → `refreshFolds(observeScan:)`). Scanned lines == 0 at both sizes, equal across sizes — the cheap path's cost rides the fold count, not the document.
- Pin 2 (control) `full pass scans scale with the buffer at N and 2N`: the same edit shape routed to the full pass (multi-line replacement — structural edits never take the cheap path) must report EXACTLY the buffer's line count: 206 at N, 406 at 2N (4 fixture lines + filler + 2 from the split intro line). A dead/unwired instrument passes pin 1 vacuously but fails pin 2.
- Pin 3 (through-seam, the ruling's addition) `coordinator keystroke pipeline scans zero lines beside a fold`: real `insertText` on a real `ProseListTextView` whose delegate is a REAL `ProseTextView.Coordinator` (constructed like production: `ProseTextView(session:dropBridge:)`) — insertText → shouldChangeText → storage → coordinator `textDidChange` (paragraph reattribute, caret centering, edit feed) → `refreshFolds()` bare → in-place re-key. Zero scans, fold survives; then a structural insert through the same live harness must report exactly 206 — the instance window is non-vacuous in the same test. Headless-safe by construction: `centerCaretWhileTyping` guards on `textView.window`.
- Mutation check (the pin-brief RED equivalent — pins of existing good behavior cannot fail at base): severing the single `observeLines?(scanned.count)` firing → pin 2 AND pin 3 fail (both instruments proven live, both zero-pins exposed as vacuous-green without their controls); wiring restored → green.
## Incident & Decontamination (ruling steps 1–2)
- Sibling session `local-8a52f739…` (aegis one-shot) claimed the ack at 17:02:32 and wrote `MuseionTests/ProseTypingBudgetTests.swift` (untracked, compile-broken — pins a `typingBudget` member that existed nowhere; test-first, production edit never landed) into this worktree at 17:09:46, mid-implementation, while the owner's background suite ran. Dispatcher-terminated; the file was removed by the sibling mid-rewrite and verified absent.
- Takeover ack block appended to `brief-24-fold-typing-budget-pin-ack.txt` (owner session id, ruling attribution, sibling id + termination).
- Hunk-level decontamination: every modified line in `ProseList.swift`, `ProseListTextView.swift`, `ProseRekeyTests.swift`, `docs/devlog/INDEX.md` matched the surviving owner's known hunks; zero deletions outside the two changed signatures; no other tracked or untracked paths in the tree. All pre-interleave gate numbers were voided per the ruling and re-run below.
## Gates (all fresh, post-decontamination, `-derivedDataPath /tmp/b24-dd2`)
- Focused: MuseionTests/ProseFoldRekeyTests **11/11 passed**, `** TEST SUCCEEDED **` (8 pre-existing + 3 new pins).
- Mutation run: firing severed — `** TEST FAILED **`; exactly `full pass scans scale with the buffer at N and 2N` and `coordinator keystroke pipeline scans zero lines beside a fold` failed, other 9 passed. Wiring restored, count re-verified present.
- Full unit target: xcresult `Test-Museion-2026.11.13_17-19-25-+0100.xcresult`, `xcresulttool` summary: **result Passed, 692 passed / 0 failed / 0 skipped, totalTestCount 692** (689 trunk + 3 new pins), `** TEST SUCCEEDED **`, exit 0.
- swiftformat: `0/3 files require formatting`. swiftlint (3 touched files): 4 violations — identical count to pristine base `7ed3041` (all pre-existing: two file_length, one opening_brace, one type_body_length); net zero added.
- One vacuous-run trap hit and discarded during development: `-only-testing` with an underscore-mangled test name matched ZERO tests and exited 0 — the #134-class lesson; class-level filters only.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Per-call observer + per-instance hook, never a global counter | Brief-23 lesson: the hosted suite runs Swift Testing tests in parallel; shared counters race. The per-instance hook lives on a view one test exclusively owns. |
| Exact line counts (206/406), not `> 0` | An exact count proves the instrument reads the real buffer through the real seam — `> 0` passes on any accidental firing. |
| Through-seam pin self-controls in one test | The instance window needs its own liveness proof; folding the structural 206-assert into the same test keeps the ruling's "one pin" while closing the vacuous loop. |
| Coordinator harness: real `ProseTextView.Coordinator` + `EditorSession(target: .externalFile)` | Production wiring (`tv.delegate = context.coordinator`) reproduced with the lightest session; sessionRef stays nil so the edit feed no-ops and the tail reaches `refreshFolds()`. |
| No CHANGELOG entry | Test-only change plus default-nil parameters and a nil-default property; nothing user-facing. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Control initially pinned 205/405 | Counted the split intro line as +1 — "x\n\n" at location 0 turns `intro` into THREE lines | Recomputed from `lines(in:)` semantics: 206/406 — confirmed by the green exact-count runs |
| Underscore `-only-testing` filter exited 0 with no test lines | Backtick/space test names don't match underscore-mangled identifiers — zero tests, vacuous green (#134 class) | Class-level `-only-testing:MuseionTests/ProseFoldRekeyTests` everywhere |
| First post-format build broke | Not formatting — the sibling's untracked test file had landed mid-flight (see Incident) | Suspend-edits, read-only forensics, report-for-ruling; sibling terminated, tree proven clean, gates voided and re-run |
| xcresulttool "doesn't exist" on first full-run query | Shell quoting produced a `/.`-suffixed path against a pruned bundle list | Re-list bundles, query the run's own bundle; counts always from `xcresulttool`, never the build-log tail |
## Open Items & Next Steps
- [ ] None on this seam. Two observations for @aegis (NOT folded in, one finding per branch):
1. `rebuildChromeLayers` re-derives `ProseList.parents(in:)` — a full line scan — on every chevron refresh in a laid-out view, one async main-queue tick after each cheap-path edit; `skipIfParentsAbove` skips only rect queries, not the scan. Headless tests never see it (`chrome.refresh` early-returns at zero bounds). Candidate: consult the freshly re-keyed fold keys before scanning.
2. The coordinator's `textDidChange` calls `ProsePresenter.fenceDelimCount(storage.string)` on EVERY keystroke — a whole-buffer character pass per keystroke, independent of folds (seen while building the through-seam harness). Same class of typing-cost item as the seam this branch pins.
---
*Log written by hand on the brief-24 branch (daedalus).*
@@ -0,0 +1,62 @@
# Document departure guard — a failed flush aborts navigation
> **Date:** 2026-11-16
> **Type:** fix
> **Reference:** brief-25 `failed-flush-discarded-on-document-switch` (unticketed; argus cycle-4 dedicated bugs pass, finding 1 — evidence `~/argus-audits/audit/2026-11-16/museion-bugs.md`). Base `11b196d68a23d10fdbe474848b9472c523ae0279` (main tip re-verified via `tea api repos/AlexKucera/museion/branches/main` at claim, 20:03 CET — no drift).
## Goal
`EditorSession.flush()` returns false after a write failure (saveState `.failed`), but `teardown(flushFirst:)` discarded the result — so every document departure (New Post, New Outline, piece switch, open external, guest dismissal) tore down the outgoing session even when its flush FAILED, then navigation replaced the only retained copy of the unsaved prose. Structural ops (move/archive/rename/convert) already aborted through `flushOrAbort`; ordinary departure did not. Make departure report failure and abort navigation while retaining the dirty session — one shared guard at every site, placed before any document-specific state clears.
## Site re-derivation (mandate — from root cause, not the seed list)
All production `teardown(` call sites re-enumerated at the pinned base:
| Site | Location | Verdict |
|------|----------|---------|
| `newPost` | PostsModel.swift:271 | exposed — guarded |
| `newOutline` | PostsModel.swift:287 | exposed — guarded |
| `dismissExternal` | PostsModel.swift:302 | exposed — guarded (guest half) |
| `select` | PostsModel.swift:359 | exposed — guarded (session half) |
| `openExternal` | PostsModel.swift:620 | exposed — guarded |
| `openUnguarded` | PostsModelOutline.swift:72 | exposed — guarded |
| trash:451, archivePost:550, convert:145, rescan:762 | — | `flushFirst: false` behind `flushOrAbort` or a vanished post — correctly unguarded |
Six sites, matching the seed list exactly; no seventh. `select`'s potential second teardown through `openUnguarded` is covered by gating both members of the pair. No seeded site disproved.
## What Was Done
- **`sessionMayDepart(_:)`** (PostsModel.swift): the departure gate for ONE outgoing session — `flushOrAbort`'s two gates (unanswered #67 conflict holds; failed flush holds) lifted to document departure, message strings byte-identical. `flushOrAbort` now routes through it (pure refactor, same contract).
- **`dismissExternal() -> Bool`**: the guest departs only when its flush lands; on failure the guest, its buffer, AND its watcher stay live; returns false so callers abort.
- **`departOpenDocuments()`**: the full-switch composition (guest + post session, each gated then torn down `flushFirst: false` — the gate already flushed) behind `newPost` / `newOutline` / `openExternal`.
- **`select` / `openUnguarded`**: gate the guest unconditionally at head (reselect-as-return still dismisses it, now guarded) and gate their same-id-conditional session teardowns through `sessionMayDepart` directly.
- **Disclosed semantic addition:** departure now also aborts on an *unanswered #67 conflict* (mirroring `flushOrAbort`). Previously, departing while the alert was up silently overwrote the foreign disk body via the teardown flush — the alert promises the writer chooses. Pinned by `new post aborts while the conflict alert is unanswered` (asserts disk NOT overwritten).
- **Tests** (`PostsModelDepartureTests.swift`, 6 pins): both navigation families with injected write failures (read-only piece folder / guest directory — atomic writes stage their temp beside the destination; FixCardApplyTests' permission-injection convention), the conflict hold, and retry-after-writability-restored proving the edits land and the switch then completes.
## Gates
- **RED at base:** `-only-testing:MuseionTests/PostsModelDepartureTests` at `11b196d` + tests-only commit — 6/6 failed, per-case lines printed, `** TEST FAILED **` (xcresult `Test-Museion-2026.11.16_20-13-27-+0100.xcresult`, dd `$TMPDIR/b25-dd`).
- **GREEN focused:** same filter at the fix tree — 6/6 passed, `** TEST SUCCEEDED **`.
- **Full suite ×2** (repo runner `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test`, same dd, post-commit tree `250a662`): xcresult summaries **699 passed / 1 failed / 0 skipped** both runs — the 1 is `MuseionUITests-Runner` failing at INIT ("Timed out while enabling automation mode"), a System Failure node with zero test assertions executed; xcresults `Test-Museion-2026.11.16_20-18-05-+0100.xcresult` and `Test-Museion-2026.11.16_20-20-18-+0100.xcresult`. 699 = 693 trunk executions + 6 new pins.
- **Environmental wall, disclosed:** a third full run (fresh dd) failed the UI runner identically, then the hosted unit runner wedged at session init (log frozen, killed per the wedge protocol; `b25-full-test3.log`, `b25-unit-clean.log` kept). `killall -9 testmanagerd` between runs 1 and 2 did not clear it — the machine's automation mode is wedged machine-wide (reboot-class, the #134 lesson). All hosted/UI test INIT was blocked after ~20:20; every green number above predates the wedge. The UI smoke (single XCUITest, no seam touched by this model-layer diff) is UNVERIFIED on this machine tonight — re-run post-reboot.
- **swiftformat:** 1/3 touched files rewrapped. **swiftlint:** net zero — `file_length` 775→809 and `type_body_length` 327→342 both pre-existing at base; no new rule fires; two `identifier_name` errors in the first test draft (`a`/`b`) fixed before commit.
- **gitnexus:** impact (owner index `f49e4b6`, 20 commits stale — disclosed): `dismissExternal`/`openUnguarded`/`flushOrAbort` CRITICAL, `newPost` HIGH (transitive closure through the `@Observable` model into the view tree — the direct callers are the enumerated sites above). `detect-changes` on a fresh worktree index: 3 files / 23 symbols / 15 flows / risk high — exactly the intended symbols, nothing unexpected. The analyze step's root-AGENTS.md gitnexus marker rewrite was reverted (brief-15 lesson).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| One gate engine (`sessionMayDepart`) shared by `flushOrAbort` and departure | One contract at the flush-or-abort seam; the coupled `home-repoint` brief (held behind this merge) rebases onto exactly this "flush-or-abort before committing" shape. |
| Guard placed before ANY document-specific state clears | The failure path must leave selection, draft, session, and watcher byte-identical — the retry is then a clean re-entry. |
| `departOpenDocuments` for the three full switches; primitives under same-id rules in `select`/`openUnguarded` | Reselect-as-return still dismisses the guest (existing #92 contract) but must not gate a session that is not departing. |
| Conflict-alert abort included (not just write failure) | Mirrors `flushOrAbort`; without it, departure resolves an unanswered #67 by silently overwriting the foreign body — the exact class of loss the guard exists to prevent. |
| Teardown flags flipped to `flushFirst: false` behind the gate | `flushOrAbort` precedent comment ("already flushed"); avoids a redundant second flush attempt. |
| Guest watcher stays live on a held guest | The retained guest must keep its #67 disk-change check — it is still the open document. |
## Docs
`Museion/AGENTS.md` PostsModel bullet carries two clause edits (guest held by the departure gate; document departure rides `sessionMayDepart`). AGENTS.md writes are consent-gated in this environment — shipped as an owner-apply patch beside the handoff: `~/daedalus-builds/museion/brief-25-agents-md-owner-apply.patch` (`git apply` verified CLEAN against the branch). PR body to carry: `git apply brief-25-agents-md-owner-apply.patch`.
## Coupling
`museion/home-repoint-retains-old-editor-target` is HELD behind this PR's merge and rebases onto this branch — `sessionMayDepart` / `departOpenDocuments` are its departure seam.
@@ -0,0 +1,53 @@
# ACP backpressure — a blocked stdin writer can no longer defeat deadlines, Stop, or close
> **Date:** 2026-11-17
> **Type:** fix (availability — APP-DOWN class)
> **Reference:** brief-27 `museion/acp-backpressure-defeats-timeout-and-shutdown` (unticketed; argus cycle-4 dedicated bugs pass, finding 3 — `~/argus-audits/audit/2026-11-16/museion-bugs.md`). Base `bb4bfa2675c3fd2776bd0235c01010baec2290df` (museion main tip at claim, re-verified via tea api + fetch). Scan SHA `11b196d6` — both touched source files byte-identical between scan SHA and base.
## Finding
A hung engine that stops reading stdin fills the 64 KB pipe, and `ACPEngineClient.send`'s synchronous `fileHandleForWriting.write` blocked the client's ONE serial queue — the same queue that carries request-id allocation, pending-registration, the `asyncAfter` deadline, and `close()`'s opening `queue.sync` barrier. A blocked writer therefore defeated the request timeout (the deadline sat queued behind the stuck send), starved Stop/lifecycle calls (a follow-up request hung at id-allocation `queue.sync`), and made `close()` block behind the write before SIGTERM/SIGKILL was ever reachable. `EngineHost`'s close callers (`killChat`, `withOneShot` defer, `shutdownAll`) run on MainActor — engine backpressure became an app-wide unbounded hang on restart/quit. Argus executed the repro standalone: complete HEAD `ACPEngineClient.swift` in an isolated process, child argv swapped to `/bin/sleep 30` (inert non-reading child), 2M-char request at timeout 0.1 s — no request completion, and an independent watchdog's `close()` never returned (probe killed at 12 s).
## What Was Done
- **Fix** (`Museion/ACPEngineClient.swift`, +34/−8): stdin writes — and the stdin write-handle's own close — moved off the state queue onto a dedicated serial `writerQueue`. `request`/`notify`/`dispatch`'s server-reply all funnel through it (wire order preserved: one serial FIFO queue, same enqueue-order semantics as before). The state queue is now I/O-free: id allocation, registration, deadlines, and `close()`'s bookkeeping barrier always run; `close()` then does SIGTERM → 1 s grace → SIGKILL → reap without ever queueing behind the writer. The stdin write-handle close rides the writer queue (a blocked write may still own the handle — closing under a live write would race Foundation); it unblocks with EPIPE once the child's read end died, which the kill just arranged. Reader handles close on the caller as before (handlers off first, no writers exist for them).
- **Rig** (`MuseionTests/ACPClientTests.swift`): two new zsh-fake modes. `neverRead` — execs `/bin/sleep 30` without reading a line (the probe's inert non-reading child; exec keeps sleep the DIRECT child so close's SIGTERM reaches it and no orphan holds the pipe); `serverPing` — full behaviour plus one server→client request (id 900) emitted at initialize, logging our reply line to `<name>-reply-log` (the reply-delivery observable).
- **Smokes** (`MuseionTests/EngineSmokeTests.swift`, +4): (1) request deadline fires while the stdin write is blocked (0.5 s deadline, 2M-char prompt, 5 s bounded window); (2) Stop accepted + bookkeeping answers while blocked (`session/cancel` notify returns, a follow-up request registers and reaches its OWN deadline); (3) close returns bounded while blocked (5 s window) and reaps the child; (4) healthy contract unchanged — round trip (initialize → 9.9.9), -32601 reply delivery over the real wire, idempotent clean close with reap. `awaitBounded` helper = the bounded window (house one-deadline rule); teardown in every blocked-writer smoke SIGKILLs the rig child FIRST so the base tree also settles without hanging the runner.
## Site-class enumeration (mandate — re-derived, seed not ceiling)
Included (fixed): all four `send` call sites (request L177-ish, notify L197-ish, dispatch server-reply L317-ish — the seeded set) plus the deadline scheduling and both `request`-path `queue.sync`s and `close()`'s barrier — all healed by the same writer-queue separation; the direct server-request reply path rides the same `send` (no second site to mint, as the brief noted).
Disproved with evidence:
- `EngineGate.execute` pre-spawn stdin write (EngineGate.swift:99-110): not queue-bound, and the write lands BEFORE `process.run()` — the reader does not exist yet, so it cannot block behind a hung engine; the in-source ceiling note (keep payloads well under 64 KB) plus the watchdog own it.
- `EngineGate.terminateAndReap` (EngineGate.swift:145-155): SIGTERM → grace → SIGKILL → reap with NO preceding queue.sync — nothing can block before it.
- `ReadingPresenter` apex render (ReadingPresenter.swift:137-154): a one-shot synchronous render helper (write → closeFile → waitUntilExit is the operation itself); no transport/lifecycle queue, no deadline machinery being defeated — adjacent, out of class.
- `MCPServer` fflush(stdout) (MCPServer.swift:39): the app IS the child there; no engine pipe parenting — out of class.
- `ScriptedEngine` (MuseionTests): mirrors the client's queue shape exactly, but performs zero FileHandle I/O (in-process) — its `queue.sync`s can never block on a pipe.
- `EngineHost` seeded sites (killChat 175-178, withOneShot defer 204-207, shutdownAll 223-227): synchronous close callers; post-fix they call a bounded close (bookkeeping sync on an I/O-free queue; ≤1 s SIGTERM-grace worst case + reap). No EngineHost change required — see Decisions.
## Gates
- Focused serialized `EngineSmokeTests` at base (RED commit `33b7fe0`): **6 executed / 3 passed / 3 failed** — exactly the three blocked-writer smokes failed, on mechanism (deadline expectation nil after 5 s; bookkeeping expectation nil; `finished != nil` false). Healthy-contract smoke + both existing surface smokes passed at base.
- Focused serialized `EngineSmokeTests` at fix (`89cd377`): **6 executed / 6 passed / 0 failed** (exit 0). Per-test: deadline 0.539 s, stop/bookkeeping 0.733 s, close bounded 0.232 s, healthy 0.195 s.
- Full suite at fix head via the rail (run dir `20261117T212755Z-Museion-serialized`): **697 executed / 697 passed / 0 failed / 0 skipped, xcodebuild exit 0** (xcresult-authoritative; the four new smokes' started/passed lines verified in the run log).
- swiftformat `0/149 files formatted`; swiftlint zero violations (repo gate is zero, not net-zero — base was clean).
- GitNexus: `analyze --skip-agents-md` in the worktree (AGENTS.md untouched); impact on every edited symbol — `send` LOW (5), `dispatch` LOW (3), `notify` LOW (0), `close` LOW (0), `request` UNKNOWN/0 (callers ride the EngineTransport existential; graph doesn't connect protocol witnesses) — no HIGH/CRITICAL, no user warning owed; detect-changes at the fix: 1 file / 8 symbols / 1 affected process (the transport), medium, expected.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Dedicated serial writer queue, blocking writes kept | Boring over clever: nonblocking fd + DispatchSourceWrite drain would add partial-write buffering and source lifecycle for zero additional contract (the API-level guarantees all hold once the state queue is I/O-free). A blocked writer now wedges only itself — it cannot pin a deadline, Stop, or close. |
| stdin write-handle closes ON the writer queue | After kill+reap a blocked write may still be in `write(2)` (unblocks on read-end death); Foundation FileHandle is not safe under concurrent write+close. The close job queues behind the last write — close() itself has already returned. Residual: a pathologic grandchild holding the pipe's read end past the child's death pins one writer-queue worker until it exits; the client is closed and reaped regardless. |
| `exec /bin/sleep` in neverRead (not `sleep 30` as a zsh child) | exec makes sleep the direct child: close's SIGTERM reaches it, and no orphan holds the pipe open — the smoke's teardown leaves nothing behind on either tree. |
| Case (2) pinned as accepted+unstarved, not bytes-delivered | The bytes cannot reach a non-reading child — the pipe is full; that is physics, identical before and after. "Deliverable" means the seam accepts the notification and lifecycle bookkeeping still answers; the RED leg (follow-up request registration starving at `queue.sync`) is the un-fixed behavior. |
| EngineHost left untouched; close stays synchronous but bounded | The fix direction's "no MainActor-blocking close path remains" read against the finding (backpressure → unbounded hang): the writer can no longer defeat close, and close is bounded (ms when the child honors SIGTERM; ≤ ~1 s grace + reap worst case). Making killChat/shutdownAll hop off MainActor would drop the reaped-before-return guarantee the teardown smokes pin (and the quit path relies on) — an EngineHost API change out of this finding's scope, disclosed to the dispatcher instead. |
| Zsh fake modes, never a real profile | Brief's probe discipline: the only child ever spawned by the dead-child tests is our own zsh fake execing /bin/sleep (pre-validated standalone: ps shows `/bin/sleep`, a 2 MB stdin write blocks, serverPing round-trips the -32601 reply). |
## Disclosures
- First focused RED run died at COMPILE (my `Task<String?, Never>` made `awaitBounded`'s `T?` a double optional — two `error:` lines, zero tests executed, the rail's vacuous guard caught it as 0-executed/exit 65). Fixed to `Task<String, Never>`; the recorded RED run is the second, clean one.
- No testmanagerd wedge encountered this brief (the known hazard did not fire; runs sequenced behind @athena's classis brief-26 verify, which finished 22:21:15 exit 0 before my first xcodebuild).
- AGENTS.md DOX updates (Museion/AGENTS.md ACP-bridge bullets, MuseionTests/AGENTS.md suite-map lines) are consent-gated → owner-apply patch beside the handoff, `git apply --check` clean vs branch head; the root AGENTS.md session-log 10-row window is left for the write-log tooling (INDEX.md carries the durable row).
- Docs commit (CHANGELOG + devlog + INDEX) is docs-only; the 697/697 suite ran at its parent (the fix commit) — code identical.
@@ -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*
@@ -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 <file>` 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*
@@ -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 — <owner>` 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*
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more