Compare commits

..
51 Commits
Author SHA1 Message Date
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 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
92 changed files with 6563 additions and 1890 deletions

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
.build/
.swiftpm/
DerivedData/
_build/
dist/
**/xcuserdata/
.DS_Store
CLAUDE.md
+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
+30 -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,7 @@ When the user requests a durable behavior change, record it here or in the relev
| `Museion/AGENTS.md` | App target — SwiftUI app shell, assets, entitlements |
| `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) |
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
| `scripts/` | Verify rail + hooks + build/deploy/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 |
| `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 +133,24 @@ 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.
- A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162)
- Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30)
- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134)
- `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178)
- Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197)
- A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178)
- Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33); the race persists in a chained read one command later — read the bundle from a LATER terminal invocation and retry the identical read once before diagnosing (#179)
- A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177)
- Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177)
- `test-without-building` tests the BUILT PRODUCTS, not the sources — a rename/edit landing after `build-for-testing` (e.g. while a long suite runs in background) leaves the green detached from the tree; rebuild + rerun for the definitive gate (#182)
- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33)
- An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151)
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
@@ -207,15 +173,15 @@ 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) |
| --- | --- |
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](docs/devlog/20261201-release-010-readme-notes-packaging_log.md) |
| 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](docs/devlog/20261123-home-repoint-retains-old-editor-target_log.md) |
| 2026-11-19 | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) |
| 2026-11-17 | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](docs/devlog/20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) |
| 2026-11-17 | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) |
| 2026-11-17 | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) |
| 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) |
| 2026-11-17 | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) |
| 2026-11-16 | [20261116-failed-flush-discarded-on-document-switch_log.md](docs/devlog/20261116-failed-flush-discarded-on-document-switch_log.md) |
| 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) |
<!-- write-log: window-end -->
+15
View File
@@ -4,12 +4,27 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
## [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.
+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.0;
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.0;
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.0;
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.0;
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.0;
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.0;
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
+15 -7
View File
@@ -23,20 +23,28 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in `docs/devlog/`.
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller).
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`.
- `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108).
- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them.
- `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<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.
- `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).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #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.
@@ -45,7 +53,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- 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.
- 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)
@@ -76,10 +84,10 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## 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).
- 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
+176
View File
@@ -0,0 +1,176 @@
//
// ArchivePaneView.swift
// Museion
//
// #193: the #108 Archive pane, moved from WorkspaceView.swift
// (file-length ceiling), code unchanged (private → internal:
// WorkspaceView instantiates it cross-file now).
//
import SwiftUI
/// #108: the Archive pane — archive/ as a rail destination (prototype
/// verdict: a destination, not a library disclosure). List-only: clicking a
/// piece selects it and hops to Posts, where the editor column lives.
struct ArchivePaneView: View {
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
let onOpenPiece: () -> Void
@State private var renamingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted
/// (mirrors the library column).
@State private var collapsed: Set<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)
}
}
+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
+18
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
+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)
}
}
+94
View File
@@ -0,0 +1,94 @@
//
// LibraryPostRow.swift
// Museion
//
// #193: the shared post row, moved from PostsPaneView.swift
// (file-length ceiling) — the Archive pane reuses it, code
// unchanged.
//
import SwiftUI
/// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
/// Archive pane reuses it.
struct LibraryPostRow: View {
let post: Post
let selected: Bool
let select: () -> Void
@State private var hover = false
var body: some View {
// `.vB .post-row { border-left: 2px solid transparent;
// border-radius: 0 8px 8px 0 }` — every row: leading corners square
// (the 2px strip below), trailing rounded 8. Only the strip's
// VISIBILITY changes on selection.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) {
HStack(spacing: 0) {
// The leading strip is always 2px wide so hover/selection
// never shifts the title. r6 (mercury#49/52, argon#13):
// the shared SelectedRowStrip capsule — accent, radius-1
// ends, vertically inset 6pt (was 3) so it sits INSIDE
// the card, never pasted on its square leading edge.
SelectedRowStrip()
.opacity(selected ? 1 : 0)
VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text(post.title)
if post.type == .outline {
Text(" ✳")
.foregroundStyle(DesignTokens.muted)
}
}
// ui-polish r8: serif-13 per the row contract — `.callout`
// was the system sans design (the r6/r7 councils pixel-
// verified sans glyphs on the Archive rows).
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
// Origin only — the Pass State already rides the uppercase
// group label above (it stays in the accessibility label).
// r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge.
Text(post.origin.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
}
.clipShape(shape)
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.background {
if selected || hover {
// r8 (mercury#11): the selected row DROPS its gray outline —
// fill + accent capsule read as ONE shape; stacking fill +
// outline + capsule competed. Hover keeps its borderless
// 0.06 wash exactly as before.
shape
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
}
}
// r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
// leads at the PRIMARY inset (x14, the 'Posts' header text's
// edge); its INNER content (title + status micro-label, strip
// 2 + padding 12) lands at x28 — the ONE indent step, shared
// with the head text and the group labels. No other x-axis
// exists in the column. Vertical padding stays the content
// VStack's constant 10 whether or not the row shows its strip.
.padding(.horizontal, 14)
.onHover { hover = $0 }
// help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
}
}
+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.
}
+8 -2
View File
@@ -250,9 +250,16 @@ extension PostsModel {
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
// brief-28: identity — the open session must target THIS library's
// selected piece (Home, ID); the wire below reads the session's OWN
// library, never the current Home's same-slug file. The completion
// stamp targets the same captured pair — the piece actually sent,
// wherever the writer has since pointed the app.
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home),
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
@@ -267,8 +274,7 @@ extension PostsModel {
// name) and 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),
guard let dir = PostStore.folder(of: id, home: home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
+3
View File
@@ -67,6 +67,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
+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).
+521
View File
@@ -0,0 +1,521 @@
//
// PostsLibraryColumn.swift
// Museion
//
// #193: the Posts library column, moved from PostsPaneView.swift
// (file-length ceiling) — PostsLibraryColumn with its rename/move
// sheets, the file-scope librarySearch mount (#144), and
// LaunchFocusReset (r8), code unchanged.
//
import AppKit
import SwiftUI
/// #21: the library column, shared by the unfocused layout and the focus-mode
/// left reveal overlay — one implementation, both surfaces. Owns the rename +
/// move sheets and the context menu (they travel with the post rows).
/// #108 variant B: sections per project, Pass-State groups inside.
struct PostsLibraryColumn: View {
let home: URL
var model: PostsModel
@State private var renamingPost: Post?
@State private var movingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted (a
/// fresh open shows everything; the prototype behaved the same).
@State private var collapsed: Set<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)
}
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()
}
}
+77 -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
@@ -176,65 +143,34 @@ final class PostsModel {
/// 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 +180,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 +198,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 +212,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 +221,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 +264,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 +317,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 +334,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 +347,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()
}
}
+13 -6
View File
@@ -20,9 +20,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 +36,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
}
+25
View File
@@ -0,0 +1,25 @@
//
// 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).
//
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)
}
}
+113
View File
@@ -0,0 +1,113 @@
//
// PostsModelImports.swift
// Museion
//
// #193: the external guest (#91–#93) and the import batch (#94/#95),
// moved from PostsModel.swift (file-length ceiling) — openExternal,
// dismissExternal, the guest watch, and stageImport/cancelImport/
// importFiles, code unchanged.
//
import Foundation
extension PostsModel {
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change). brief-25: the dismissal is GUARDED — a guest
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
/// buffer and watcher live: teardown would drop the only retained
/// copy of the unsaved edits. Callers abort their navigation on
/// false, before clearing anything.
/// #146: internal — the split-out domain extensions dismiss too.
@discardableResult
func dismissExternal() -> Bool {
guard let guest = externalSession else {
externalWatcher.stop()
return true
}
guard sessionMayDepart(guest) else { return false }
guest.teardown(flushFirst: false) // the gate already flushed
externalSession = nil
externalWatcher.stop()
return true
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
/// #91/#92: open an external markdown file in the guest slot — one at a
/// time; opening anything else (file, Post, draft) flushed and replaced
/// it first. A Post session/draft stands down while the guest is up
/// (the editor column is the guest's; the selection stays for return).
/// Local files only (a dragged web link is not a document) and symlinks
/// resolve to their real target so the in-place write never severs the
/// link (rename over a symlink replaces it).
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
externalSession = nil
return
}
wireSession()
startExternalWatch(url: target)
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. PostsWatcher fires on the
/// main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(urls: [url.deletingLastPathComponent()])
}
/// #94: stage a multi-file import — the ONE Origin ask presents; the
/// sheet's answer runs the batch.
func stageImport(_ urls: [URL]) {
guard !urls.isEmpty else { return }
pendingImportURLs = urls
}
/// #94: dismiss the ask without an answer — the batch drops.
func cancelImport() {
pendingImportURLs = nil
}
/// #94/#95: run the batch after the Origin answer — copy each file in as
/// a Post; a per-file failure continues the batch into lastError (stated
/// default, reversible; never an alert, never an abort). The last
/// imported post opens; a failure anywhere keeps its message up even
/// when other files landed. #107: the batch lands in the selected
/// post's project (newPost's target rule). #179: the batch rides the
/// rail — the strip was cleared up front, so the per-file failure
/// messages the loop sets survive the rail's success tail.
func importFiles(origin: Post.Origin) {
guard let urls = pendingImportURLs else { return }
pendingImportURLs = nil
let project = targetProject
var last: Post?
performWrite { home in
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
} catch {
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
}
}
}
if let last {
select(last.id)
}
}
}
+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)
+15 -8
View File
@@ -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>()
@@ -367,10 +377,7 @@ final class ProseListTextView: NSTextView {
guard let scalar = Unicode.Scalar(Int(char)) else { return false }
return CharacterSet.whitespacesAndNewlines.contains(scalar)
}
if index > 0, index < length,
!isGap(buffer.character(at: index - 1)),
!isGap(buffer.character(at: index))
{
if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) {
while index < length, !isGap(buffer.character(at: index)) {
index += 1
}
+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.58 (`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.58 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.
+96
View File
@@ -0,0 +1,96 @@
//
// WorkspaceChrome.swift
// Museion
//
// #193: the shared workspace chrome, moved from WorkspaceView.swift
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
// PaneHeader; every pane reuses them, code unchanged.
//
import SwiftUI
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
/// reservation keeps layout constant.
struct SelectedRowStrip: View {
var body: some View {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 6)
}
}
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
/// Choose…). 36pt tall by default — a real hit target, not a text-size
/// pill; pass a smaller `minHeight` where the row is compact.
struct BorderedSecondaryButtonStyle: ButtonStyle {
var minHeight: CGFloat = 36
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.foreground)
.padding(.horizontal, 12)
.frame(minHeight: minHeight)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border),
),
)
.opacity(configuration.isPressed ? 0.7 : 1)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<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)
}
}
}
+44 -428
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;
@@ -151,6 +155,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 +249,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 +291,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 +334,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 +390,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 +456,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
+5 -3
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,12 +32,13 @@ 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).
- `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` — publish wire contract, model flow, media/illustration surface.
- `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.
@@ -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))
}
}
+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)
}
}
+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)
}
}
+4 -1
View File
@@ -579,7 +579,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()),
)
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.
+116 -16
View File
@@ -1,40 +1,140 @@
# 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.
### 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
## Install
```bash
git clone https://git.babylondreams.de/AlexKucera/museion.git
cd museion
Download `Museion-<version>.dmg` from [Releases](https://git.babylondreams.de/AlexKucera/museion/releases), open it, drag Museion to **Applications**.
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
```
The app is signed with a Developer ID and notarized with Apple, so it opens like any other app.
Full Xcode project at the repo root — `open Museion.xcodeproj` and run.
## 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.
## 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*
@@ -0,0 +1,72 @@
# Close out: repo-wide swiftlint green becomes the documented lint contract (#197)
> **Date:** 2026-11-17
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/197
## Goal
With #195 and #196 done, make the docs and code comments honest about repo-wide lint being green: refresh the pre-push hook's stale "pre-existing violations" rationale (gate semantics unchanged), prune/replace the stale #190 learning in AGENTS.md, confirm the root lint line is literally true — and land a green full unit suite.
Tree composition note: the working tree also carries the uncommitted #194/#195/#196 batches (lint policy, test renames + `.swiftformat` name-format pin, warning-fix sweep) from earlier sessions today; this session implemented #197 on top, then ran a three-reviewer finish-audit over the whole 27-file diff.
## What Was Done
- `scripts/hooks/pre-push` — all three stale rationale blocks refreshed (header "pre-existing findings", gate block "a bare `swiftlint .` gate can never pass", NEW-ref note "pre-existing violations could never clear it") to the settled #190 design wording. Comment-only; gate logic byte-identical (reviewer grep-verified).
- `AGENTS.md` — the Tooling & gates learning rewritten to the true contract: repo-wide lint green (#194 policy, #195/#196 cleared every finding, `spike/` excluded as unbuilt), bare `swiftlint .` = 0 violations + `swiftformat .` reformats nothing, gates stay push-scoped. Root lint line confirmed literally true by execution.
- `MuseionTests/LibrarySearchTests.swift` — hardened `an unchanged rescan keeps the revision` against a pre-existing watcher-race flake: two FSEvent-burst rescans can snapshot the shared `PostScanCache` miss count before either stamps it, double-counting one first read → `contentRevision` double-bump (benign over-invalidation). The test now quiesces the burst (bounded 20 × 0.5 s stability loop, own deadline, post-loop `#expect`) before snapshotting. Suite scenario header names the fourth pin.
- Finish-audit (3 parallel reviewers: ponytail / security / general over the full uncommitted diff):
- Reviewer's "dead symlink clause" bug in `LearningsIndex.isPlainDirectory` **disproved by scratch probes** — `&&` out-binds `??` (`a ?? false && b` parses as `(a ?? false) && b`; second `??`/`&&` precedence claim probe-settled in this repo, see #26) and `URL.resourceValues` is lstat-style (symlink-to-dir → `isDirectory=false`). Kept parens + doc as readability hygiene; the expression had fooled a capable reviewer.
- `Museion/LearningsPaneView.swift` — guard reordered so the cheap rejections (`isPlainDirectory`, dot-prefix) short-circuit before the directory listing.
- `MuseionTests/LearningsPaneTests.swift` — new pin `a symlinked type dir never surfaces` (the documented "same skip posture as Post.scan" contract was unpinned). Flip-verified: the contract is **defended in depth** (lstat guard AND `contentsOfDirectory`'s own refusal of a symlinked entry URL) — the pin fails only when both go traversal-shaped (fileExists guard + resolved-URL listing failed the pin + a sibling pin; restored green).
- `Museion/MentorSessionModel.swift` — pre-existing `sessions.json` world-readable sub-second window (atomic write → 0o600 chmod) parked with a `ponytail:` ceiling comment naming the upgrade path (createFile-0600 + rename).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Fix the LibrarySearchTests race in the TEST, not the model | The model's revision over-bump only over-invalidates a search snapshot (conservative-safe); serializing rescans or making the miss counter race-free is real machinery for a signal that tolerates false positives. The test's timing assumption was the bug (#147 family). |
| Keep parens in `isPlainDirectory` despite the finding being disproved | Behavior-identical, two characters, and the bare form demonstrably costs reviewer time — this audit burned a slot misreading it. |
| Symlink pin added although no behavior changed | The documented contract was unpinned; the flip cycle showed it is held up by two accidental mechanisms, exactly the kind of seam a future "simplification" breaks silently. |
| Chmod window parked, not fixed | Pre-existing, local-only, single-user workstation threat model; from-creation 0600 changes a pinned write path — ceiling comment names the trigger (hostile local account). |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Full suite failed 1/692 on first run (`an unchanged rescan keeps the revision`, `contentRevision 2 ≠ 1`) | Two FSEvent-burst rescans double-count one shared `PostScanCache` miss; the test snapshotted mid-burst | Quiesce loop before snapshotting; verified in isolation (7/7), full (693/693) |
| Flip cycle "passed" with the guard flipped — twice | **xcodebuild served stale binaries**: a source edit made seconds before invocation was not compiled (zero `SwiftCompile` lines, suite start 3 s after invocation) | `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green; with that, guard-flip green → both-belts flip red → restored green |
| Reviewer precedence claim contradicted the code's comment | `a ?? b && c` precedence is genuinely easy to misread (this repo's second such dispute) | Scratch probes settle it empirically — never rewrite comments on a reviewer's word |
| `swiftlint` line_length (187 chars) after the guard reorder | swiftformat merges adjacent guards into one long condition list | Wrap the call arguments inside the condition (the shape the same function already uses for its root listing); format-stable on re-run |
| Rail scoped reruns looked green during the flip | Stale-build hazard above | Always confirm compile lines in the run log for rapid edit→test cycles |
## Files Changed
| File | Change Summary |
|------|---------------|
| `scripts/hooks/pre-push` | Three stale rationale comment blocks refreshed; logic untouched |
| `AGENTS.md` | Tooling & gates learning rewritten to the true lint contract |
| `MuseionTests/LibrarySearchTests.swift` | Quiesce loop hardening + scenario header names the settled-state pin |
| `Museion/LearningsPaneView.swift` | Guard reorder, parens + doc on `isPlainDirectory` |
| `MuseionTests/LearningsPaneTests.swift` | New symlink-skip pin with flip-verified doc |
| `Museion/MentorSessionModel.swift` | Ceiling comment on the roster chmod window |
(The commit also carries the #194/#195/#196 batches from earlier sessions: `.swiftlint.yml`, `.swiftformat`, `MuseionTests/AGENTS.md`, `PolishSeamTests.swift`, and the #196 warning-fix sweep across 11 app files + test files + `prototypes/GateUIPrototype.swift`.)
## Open Items & Next Steps
- [ ] User: commit + push (carries `Closes #197`; #194–#196 already closed on the tracker), verify auto-close
- [ ] Candidate project learning: xcodebuild can skip recompiling a source edited seconds before invocation — flip/edit-test cycles must `touch` and verify `SwiftCompile` lines in the run log
- [ ] Parked: roster 0600-from-creation if a hostile local account ever matters (`Museion/MentorSessionModel.swift` ceiling comment)
## Verification
- `swiftlint .` — 0 violations / 130 files, exit 0
- `swiftformat .` — 0/141 formatted, tree unchanged
- `./scripts/test-full-test.sh` — 23/23 hook acceptance checks
- `./scripts/full-test.sh` — **693 executed / 693 passed / 0 failed** (run `20261117T151013Z-Museion`; no source file newer than the run — the green attaches to the committed bytes)
- GitNexus: `detect-changes` risk **critical** (breadth: 100+ symbols across the four-ticket mechanical batch — affected-scope checked by the 3-reviewer fanout, probes, and the suite); `analyze` reindexed (7,035 nodes / 34,056 edges)
---
*Log written by write-log skill*
@@ -0,0 +1,99 @@
# #200 — Gate quit-time flushes through the departure gate
> **Date:** 2026-11-19
> **Type:** issue
> **Reference:** AlexKucera/museion#200 (follow-up from the PR #198 finish audit)
## Goal
Quitting was the one document departure that bypassed the brief-25 gate:
`PostsModel.shutdown()` flushed both sessions best-effort and ignored the
results. Two harms: quitting with an unanswered #67 conflict wrote local text
over the foreign disk body (`flush()` holds for conflicts only in the debounce,
not itself — the #114 harm), and a failed quit-time flush silently dropped the
only copy of the edits. Deliver the conflict hold at quit, plus an explicit
pinned product decision for the failed-flush-at-quit posture.
## What Was Done
- `PostsModel.shutdown()` (PostsModel.swift) now routes both sessions through
the departure gate via `documentsMayDepart()` and is `void` — the verdict
channel is `quitReply`'s, at `applicationShouldTerminate` (finish-audit
ponytail finding: a `-> Bool` shutdown had no production reader).
- `documentsMayDepart()` (PostsModelWrites.swift, beside `sessionMayDepart` /
`departOpenDocuments`): the gate's quit run — external guest then post
session, both through `sessionMayDepart`, no early exit (a clean sibling
still saves while a conflicted one holds).
- BLOCK-QUIT at `WritingLockAppDelegate.applicationShouldTerminate`
(WritingLockState.swift): new pure seam `quitReply(posts:)` (nil model
passes; the pins inject here) runs BEFORE the Cold Turkey lock ask — never
walk away from a block the quit then refuses to complete. The refusal
speaks once via a hosted-guarded alert (startLaunchCheck/kiosk convention)
naming `lastError`.
- `PostsModel.active` weak static (the `WritingLockState.active`
reachability precedent), registered ONLY by `AppGateState.init`
(MuseionApp.swift) — bare test rigs never register, so parallel suites
can't flake the delegate through the static.
- Finish-audit fixes: `sessionMayDepart` refuses a never-loaded session's
retyped words (`loadFailed && saveState == .changed` — its `flush()` is a
vacuous success; the security reviewer's LOW data-loss gap, closed for quit
AND navigation at the one shared seam); guest quit-flush pin added (the
guest leg of `documentsMayDepart` was unpinned — deleting it kept the rail
green).
- Pins (5 total): conflict hold at shutdown (foreign body on disk, byte
unchanged), clean dirty session flushes, guest flushes, never-loaded
refusal (PostsModelDepartureTests), delegate refusal/proceed across all
phases incl. chmod-injected flush failure (WritingLockTests).
- DOX: Museion/AGENTS.md (WritingLock delegate bullet, PostsModel bullet,
PostsModelWrites bullet, Wiring bullet), MuseionTests/AGENTS.md suite map
(also added the PR #198 gap: PostsModelDepartureTests had never been
listed).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| BLOCK QUIT (vs silently drop / rescue file) | The ticket's three options. Drop keeps the audited harm; rescue strands a buffer in a recovery file with no discovery UX. Block quit reuses both existing seams (`sessionMayDepart` + the `applicationShouldTerminate` refusal precedent) and is the only posture that never silently destroys the only copy — "edits land or the departure aborts" extended to termination. |
| `quitReply(posts:)` injectable pure seam, static written only by `AppGateState.init` | The delegate needs model reachability (`WritingLockState.active` precedent), but a static written by every `PostsModel` init would let parallel test rigs flake the delegate pin. Registration at the real construction site keeps hosted tests deterministic; pins inject the model directly. |
| Gate before the Cold Turkey ask | Refusing AFTER "walk away" would strand a walked-away block in a still-running app. |
| Never-loaded guard in `sessionMayDepart` (not in `flush()` or callers) | The vacuous success is `flush()`'s correct safety rule (a failed read must never become a destructive write); the gap is the gate trusting it. One guard at the shared seam closes quit AND navigation. |
| `shutdown()` void, willTerminate stays as belt | The belt double-flush is idempotent (clean no-op); the Bool return had no production reader. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Flip cycle: the guest pin passed with its guard "off" | The `, false` suffix on `if let guest = externalSession, !sessionMayDepart(guest), false` still CALLS `sessionMayDepart` — the flush is a side effect inside the condition, so the pin's observable survived; only the verdict assignment was skipped | Flip by deleting the block, which models the actual threat ("the leg is gone"); then the pin failed by name. Restore re-inserted the block byte-exact. |
| `git log` piped output hid merge commits / phantom staged file | The rtk terminal wrapper mangles piped git output (known trap) | Settled facts with `git show -s --format`, `git diff --cached --name-only` direct reads, and count-only greps. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostsModel.swift` | `shutdown()` void + routes through the gate; `PostsModel.active` weak static |
| `Museion/PostsModelWrites.swift` | `documentsMayDepart()`; never-loaded guard in `sessionMayDepart` |
| `Museion/WritingLockState.swift` | `quitReply(posts:)` pure seam; gate-first quit; hosted-guarded refusal alert |
| `Museion/MuseionApp.swift` | `AppGateState.init` registers `PostsModel.active` |
| `MuseionTests/PostsModelDepartureTests.swift` | 5 quit-time pins (conflict, clean, guest, never-loaded + navigation family) |
| `MuseionTests/WritingLockTests.swift` | Delegate pin: refuses while a piece can't depart, proceeds once it can |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass (quit-gate contracts, suite map) |
## Open Items & Next Steps
- [ ] #201 (consented brief-25 AGENTS.md sentences) — open, promoted, next in line.
- [ ] Follow-ups from PR #198's audit are otherwise exhausted.
## Verification
- Full verify rail (`./scripts/full-test.sh`): **708 executed / 708 passed /
0 failed** (706 pre-audit + the 2 audit pins), xcodebuild exit 0.
- swiftformat 0/150 reformatted; swiftlint 0 violations in 139 files.
- Finish-audit flips: both new pins fail by name on their guards
(loadFailed `, false` suffix; guest-leg block deletion), 8 siblings green,
restored byte-exact, 28/0 on both suites post-restore.
- GitNexus: analyze 7,134 nodes; detect-changes HIGH = the gate's deliberate
fan-in (every departure flow), all affected flows covered by the rail.
---
*Log written by write-log skill*
@@ -0,0 +1,255 @@
# brief-28 — Home repoint rides the departure gate (document identity is (Home, ID))
> **Date:** 2026-11-23
> **Type:** fix (unticketed)
> **Reference:** finding `museion/home-repoint-retains-old-editor-target` (argus cycle-5 bugs pass, `museion-bugs.md` finding 1; HIGH, certain) — branch `fix/home-repoint-retains-old-editor-target` off `main` at `ca265d3bd359e663216aa91d4778e2bdef8a36eb`
## Goal
Settings → Content → Choose… committed the new Home (preference + UserDefaults
through `AppGateState.museionHome.didSet`) and the root `.task(id:)` → `bind` →
`startWatching` flipped `watchedHome` WITHOUT departing the open session. The
session's immutable `SessionTarget` kept the OLD Home, so under the new UI:
- a same-slug piece in the new library made `select`'s ID-only reselect return
the retained A session — autosave/Save/quit wrote A while structural
operations resolved against B;
- the new library's rescan read B's same-slug `post.md` for the A session and
raised a spurious #67 on it (differing bodies);
- a no-collision piece was torn down by the vanish path with its dirty buffer
dropped (data loss);
- a card scan started under A landed its cards on B's same-slug piece when it
completed after a reselect (the ID-only hop-back guard).
#198's departure gate never saw this seam (it guards navigations, not the
Home binding). Fix direction (argus, binding): repoint = a GUARDED DOCUMENT
DEPARTURE before any commit; identity (Home, ID) everywhere, re-checked at
async COMPLETION.
## What Was Done
**The gate (gate-first, commit-after):**
- `PostsModel.repoint(to:) -> Bool` (PostsModelWatcher.swift, beside `bind`):
`guard newHome != watchedHome` (first bind / same folder: nothing departs)
→ `departOpenDocuments()` (the brief-25 gate — `sessionMayDepart`'s three
legs: unanswered #67, failed flush, never-loaded retype; NO parallel gate)
→ on true, the departed piece's state dies with it (`selectedPostID`,
`openPieceCards`, `openPieceHasSnapshot`, `outlineGuardPieceID`,
`proseOverridePostID`, `pendingConversion`, `lastDraftWasOutline`,
`pendingProject`). On false NOTHING changed: `lastError` says why (#198's
strings), the preference/binding/target/buffer are untouched.
- `AppGateState.repointMuseionHome(to:)` (HomeResolution.swift): `guard
posts.repoint(to:)` FIRST, `museionHome = newHome` (its `didSet` persists)
only after. The ONE runtime repoint entry.
- WorkspaceView: the Settings Home control binds through `homeRepointBinding`
— the binding's setter IS the gate (`repointMuseionHome`, then nothing
else: the root `.task(id: museionHome)` binds the model after the commit).
`$gate.museionHome` and the now-dead `@Bindable var gate` are gone from
`paneContent`. A refusal presents one hosted-guarded `NSAlert` carrying
`posts.lastError` (#200's quit-refusal posture — the Posts strip that shows
it is not in sight from Settings).
- `bind` stays the dumb binder by design (see Decisions).
**Document identity is (Home, ID) — the pattern-exhaustive sweep:**
- `EditorSession.targets(postID:home:)` / `targets(home:)` — the pair; the
target is immutable, so a session born under another Home is a foreign
document to a model whose `watchedHome` moved past it.
- `PostsModelIdentity.swift` (new): `openSessionTargets(_:)` — the model's ONE
"is this piece open" question (`session.targets(postID: watchedHome, id)`).
- Every model-side ID-only session comparison converted:
| Site | Was | Now |
|------|-----|-----|
| `PostsModel.select` reselect no-op | `session.postID == id` | `session.targets(postID: id, home: watchedHome)` — a foreign session departs below |
| `PostsModel.canArmWritingLock` / `editorBodyText` | `session.postID == selectedPostID` | `openSessionTargets(id)` |
| `PostsModelOutline.openUnguarded` (depart test + reuse test) | `postID != id` / `id == postID` | `!targets(postID:home:)` / `targets(postID:home:)` |
| `PostsModelOutline.stageConversion` / `convertToPost` | `session.postID == post.id` | `openSessionTargets` |
| `PostsModelWrites.flushOrAbort` | `session.postID == postID` | `openSessionTargets(postID)` |
| `PostsModelWrites` rename / trash / moveToProject / archivePost / restorePost / `unarchiveProject`'s `openPieceInArchivedProject` | `session?.postID == post.id` | `openSessionTargets(post.id)` |
| `PostsModelPasses.guardOpenPieceRun` | `id == selectedPostID` (+ callers re-read `watchedHome`) | `session.targets(postID: id, home: watchedHome)`; the answer carries the validated `home` (3-tuple, callers stop re-reading) |
| `Micropub.micropubSendDraft` launch | `id == selectedPostID`, then `watchedHome` + `folder(of:)` | identity at launch; the wire reads the session's OWN library |
| `PostsModelCards.refreshCards` launch | `session?.postID` + `watchedHome` | `session.targets(postID:home:)` |
**Async continuations re-validate at COMPLETION:**
- `refreshCards` hop-back: `self.session?.targets(postID: id, home: home)` —
the seeded site (PostsModelCards:24-42). The scanner is now the per-model
injectable `scanPieceCards` (never static — the hosted suite runs in
parallel) so the deterministic stale-result pin can HOLD an old-library scan
past a repoint.
- `rescan` (PostsModelWatcher): the stale-Home verdict is HOISTED — `guard
watchedHome == home` right after the detached scan, so a scan that outlived
a repoint applies NOTHING (list, revision, vanish check, #67 text), not
just the vanish check as before; the #67 disk read runs only for a session
targeting the scan's own Home (`openPostID` is identity-gated); the vanish
teardown matches identity and still tears down the CURRENT session.
- `Micropub`'s completion stamp (`stampMicropubURL(id:home:)` after the
awaits) keeps the CAPTURED pair — the piece actually sent — by construction;
re-validating against the live session would skip a correct write after a
mid-send repoint. Disclosed, left as is.
**Tests:** `PostsModelRepointTests` (9, new file) over a two-Home same-slug
rig (`projects/posts/shared/post.md` in both, differing bodies); the #179
mid-pass repoint pin (`PostsModelWriteRailTests`) now drives the real Settings
path (`repoint(to:)` then `bind`). r1 (athena) added the two the review
asked for: the hoisted `rescan` verdict (MF-1, via the `scanLibrary` seam)
and the draft-survives decision (N-1).
## Identity checks — evidence classes (r1, athena N-2)
"Identity everywhere" is NOT "every site test-verified". Three classes:
| Class | Sites | Proof |
|-------|-------|-------|
| **Pinned** (failing-test / mutation proof) | `refreshCards` hop-back (the seeded site); `rescan`'s hoisted stale-Home verdict; the #179 mid-pass advance guard (pre-existing, its `lastError ==` line) | Mutation checks: ID-only card guard → `openPieceCards → ["Hedging"]`; hoist removed → `posts → ["alpha"]` + `contentRevision → 3` vs `2`. Both restored byte-exact. |
| **Correct by construction** | Micropub's completion stamp — the captured (Home, ID) of the piece actually sent | Not independently pinnable: a re-validate against the live session would SKIP a correct write after a mid-send repoint. Disclosed, left as is. |
| **Invariant-equivalent defensive depth** — never independently observable under the gate-first invariant | The whole synchronous sweep: `select` reselect, `openUnguarded`×2, `stageConversion`, `convertToPost`, `flushOrAbort`, the six structural ops, `guardOpenPieceRun`, Micropub launch, `refreshCards` launch, `canArmWritingLock`/`editorBodyText`, the vanish teardown, AND `rescan`'s `openPostID` identity gate (the #67 read) | None possible while the gate holds: a live session always targets `watchedHome`, so the id-only and identity forms agree on every reachable state (athena's run removed `openPostID`'s gate and reverted `select` to ID-only — the rail stayed green). They are belt to the gate's suspenders: any future path that bypasses `repoint` (a direct `bind` under a live session — what the mid-pass pin used to do) falls through to a departure instead of matching across libraries. Correct as design; not test-verified; say so. |
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Gate in the Settings binding's setter + `repointMuseionHome`, NOT in `bind` | The gate must precede the preference commit (`museionHome.didSet` persists immediately). A gate inside `bind` would leave `museionHome` = B while `watchedHome` = A — the UI showing a Home the model isn't watching. `bind` is reached only after a passed gate (or the same Home / first frame), so it stays unconditional. |
| `sessionMayDepart` via `departOpenDocuments` — no parallel gate | The brief's acceptance (1) and brief-25's contract: one gate, three legs, #198's strings. The refusal tests prove the composition (PostsModelDepartureTests 10/10 stay green beside the new suite). |
| Nothing auto-reopens after an accepted repoint | The brief left it to the implementer within existing machinery. Auto-reopening B's same-slug piece would be a NEW UX (the writer never chose it) and cannot even be decided at gate time — B isn't scanned until `bind` + rescan land. `selectedPostID = nil` is the #198 departure semantics (newPost/openExternal do the same); the writer picks from the new list. |
| The in-memory draft survives a repoint | A draft has no Home until first save (#62); it lands in the new library. The only alternatives — dropping it (the only copy) or refusing the repoint (new UX) — are worse. Disclosed; `pendingProject` (a stale A project name) IS cleared. |
| A running pass / Blind Read is not cancelled by the repoint | `sessionMayDepart` flushes; the session departs; the engine turn keeps its own completion guard (#179: the advance refuses once `watchedHome` moved) — pinned by the mid-pass test. Cancelling would desync the pass bar's Cancel ↔ Run state. |
| `pendingImportURLs` / `askNewProject` left alone | Both are sheet-modal (OriginAsk / NewProject) — a repoint cannot be requested while either is up, and neither is piece-specific. An import batch landing in B after a repoint is the writer's chosen library. |
| Refusal = one `NSAlert` (the #200 posture), not a Settings strip | Settings shows no `lastError` strip (PostsPaneView owns it); a silent Choose… is the dishonest outcome. The alert carries the exact #198 `lastError` string; hosted-guarded like the quit refusal. |
| `openSessionTargets` on the model + `targets` on the session (two helpers) | The session owns the pair (it knows its target); the model owns "which Home is current". `rescan` needs the scan's captured `home`, not `watchedHome`, so the session-level predicate is public within the module. |
| Rescan hoist of `watchedHome == home` | The old inline guard covered only the vanish check; a stale list could still land under the new binding (and bump `contentRevision`). One verdict at the top covers everything the continuation writes. |
| View-layer `session.postID == selectedPostID` (PostsPaneView:125) NOT converted | A render gate on the same pair; with the model invariant (the open session always targets `watchedHome`) it is correct by construction, and the view has no Home-identity vocabulary. Other view reads are nil-checks (`session?.postID != nil`) or title lookups, not comparisons. Disclosed, not exposed. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Stale-scan pin's park probe never passed (5 s poll timeout) | `pollUntil` re-evaluates its `where !condition()` per iteration WITHOUT sleeping when true, and `DispatchSemaphore.wait` consumes — two parked scans drained the count in two iterations, the final `#expect(condition())` saw zero | A non-consuming `ParkedFlag` (NSLock box, `@unchecked Sendable`); the park itself is a bounded `release.wait(timeout: .now() + 30)` so a failed test never leaks a parked cooperative thread |
| `-only-testing:MuseionTests/PostsModelTests` matched ZERO tests in a filtered run (17 executed, not more) | The filter names a FILE, not a suite: `PostsModelTests.swift` holds free-function `@Test`s (unfilterable by suite) AND the `@Suite("write rail #179") struct PostsModelWriteRailTests`; "PostsModelTests" matches neither, and the rail's zero-match guard stays silent when sibling filters match | Filter by SUITE name (`grep '@Suite(' <file>`), never by file name. The mid-pass pin ran in the FULL rail (715) under its suite; no verification claim was taken from the filtered run for it |
| Vanish-path rewrite first tore down the CAPTURED session | `openSessionTargets(id)` reads `session` now while `openSession?.teardown` hit the pre-scan object — a same-id reopen mid-scan would leave the live session armed | `if let open = session, open.targets(postID: id, home: home)` — the original shape (current session), identity-matched |
| `swiftlint:disable:next large_tuple` flagged superfluous | The return type sat on the `) ->` line, not the `func` line the `:next` covers | Signature on one line so the tuple starts on the covered line (PostStore.swift:259 precedent) |
| A context-fuzzy patch duplicated "The refusal" in a doc comment | The edit span started mid-line | Re-read and re-patched the two lines |
| Regenerating the owner-apply patch from FRESH scratch copies kept only the r1 edits (9 changed lines vs the reviewed 19) | The regeneration script carries the full edit set; a partial re-run silently drops the earlier anchors | Re-ran the FULL pair set from fresh `a/` copies and compared hunk count/line count against the reviewed patch (69 lines / 5 hunks) before trusting it |
| `full-test.sh status` reported the MUTATION run's `9 / 8 / 1` while the full rail was in flight | `status` reads `current`, which a newer launch repoints; the loop broke on a finished-but-stale verdict | Read each run's OWN `summary.json` by run dir — the per-dir numbers are the record (full: Passed / 717) |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostsModelWatcher.swift` | `repoint(to:)` (the gate); `bind` documented as the dumb binder; rescan: identity-gated #67 read, hoisted stale-Home verdict, identity vanish teardown |
| `Museion/PostsModelIdentity.swift` (new) | `openSessionTargets(_:)` |
| `Museion/EditorSession.swift` | `targets(postID:home:)` / `targets(home:)` |
| `Museion/HomeResolution.swift` | `AppGateState.repointMuseionHome(to:)` |
| `Museion/WorkspaceView.swift` | `homeRepointBinding` (gate in the setter) + hosted-guarded refusal alert; `import AppKit`; dead `@Bindable` removed |
| `Museion/PostsModel.swift` | `select` reselect by identity; `canArmWritingLock`/`editorBodyText` by identity; `scanPieceCards` + `scanLibrary` (r1) seams |
| `Museion/PostsModelWrites.swift` | `flushOrAbort` + the six structural ops by identity |
| `Museion/PostsModelOutline.swift` | `openUnguarded`, `stageConversion`, `convertToPost` by identity |
| `Museion/PostsModelCards.swift` | identity at launch AND completion; scanner through the seam |
| `Museion/PostsModelPasses.swift` | `guardOpenPieceRun` identity + returns the validated Home; callers consume it |
| `Museion/Micropub.swift` | identity at launch |
| `MuseionTests/PostsModelRepointTests.swift` (new) | 9 pins (7 + r1's two) |
| `MuseionTests/PostsModelTests.swift` | mid-pass pin drives `repoint(to:)` + `bind` |
| `CHANGELOG.md`, `docs/devlog/INDEX.md`, this log | docs |
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | OWNER-APPLY patch only (see Open Items) — never written by this session |
## Open Items & Next Steps
- [ ] AGENTS.md DOX pass ships as an owner-apply patch:
`~/daedalus-builds/museion/brief-28-agents-owner-apply.patch` — `git
apply --check` clean at the r1 head (3 files, 5 hunks: the
PostsModel/Watcher/Writes/Editor-core/Settings/WorkspaceView bullets, the
`AppGateState.museionHome` bullet, the MuseionTests suite map row with the
r1 pins and the `scanLibrary` seam, and the root 10-most-recent window
row). Apply from the branch head with
`git apply ~/daedalus-builds/museion/brief-28-agents-owner-apply.patch`.
- [ ] GitNexus `impact`/`detect_changes` were NOT run: `.gitnexus/run.cjs` is
absent at base and no GitNexus capability is exposed (the argus cycle-5
audit hit the same wall). The blast radius was traced by hand instead — the
table above IS the caller trace. The root AGENTS.md index-count line
(`7133 symbols …`) is therefore NOT refreshed in the patch.
- [ ] Coupled (HELD behind this PR's merge, per the brief):
`museion/external-watch-compares-unnormalized-text` dispatches from the
merged state. This diff touched `rescan`'s :94-98 (identity-gated read) and
the vanish block (:135-146 → hoisted verdict), NOT the normalization seam
itself (`readBody`'s representation at the former :107 and
PostsModelImports.swift:69-70 are untouched) — the two changes are
disjoint in mechanism.
- [ ] Not in scope, observed while tracing: `newProjectPending(named:)` sets
`pendingProject` BEFORE `newPost()` and leaves it set when the departure
gate refuses the new post (a stale pending target with no draft). Reported
to @aegis as an observation; `repoint` clears `pendingProject` on its own
path regardless.
## Verification
- **Base / pin:** `ca265d3bd359e663216aa91d4778e2bdef8a36eb` = live `main` tip
at claim (`tea api repos/AlexKucera/museion/branches/main`, 20:05 CET) and
still at r1 handoff (`git ls-remote`, 22:36 CET). Zero drift. Round 1
(athena) reviewed `97712fb`; this round appends `92344e2` (code) and the
docs commit on top — 4 linear commits kept, no force-push.
- **r1 (athena MF-1/N-1), full rail at `92344e2`** (tree pristine vs the
commit, watcher blob sha256 prefix `d86ce09d6b7e6bd2`): run dir
`_build/full-test/20261123T213424Z-Museion` → `717 executed / 717 passed /
0 failed / 0 skipped (xcodebuild exit 0)`, `summary.json` `Passed / 717`,
`** TEST SUCCEEDED **`; 717 = 715 + the two r1 pins; `PostsModelRepointTests`
9/9 (both r1 pins named passed), `PostsModelDepartureTests` 10/10,
`PostsModelWriteRailTests` 5/5. Filtered GREEN (repoint + departure) →
run dir `…T213313Z` `19 / 19`.
- **r1 mutation check (MF-1):** hoisted `guard watchedHome == home` removed
→ run dir `…T213345Z` `9 executed / 8 passed / 1 failed (exit 65)`, ONLY
`a library scan from the old Home lands nothing under the new binding`,
`posts.map(\.id) → ["alpha"]` and `contentRevision → 3` vs `revision → 2`;
restored byte-exact (prefix `d86ce09d6b7e6bd2` before and after), zero
`MUTATION-CHECK` tokens repo-wide. Lint at `92344e2`: `swiftformat --lint .`
0/152, `swiftlint` 0.
- **r1 owner-apply patch regenerated** for the seam + the two pins (N-3):
69 lines / 5 hunks — the reviewed patch's shape — `git apply --check` CLEAN
at the new head (re-checked after the docs commit).
- **Round 0 (first report) follows.**
- **RED first** at the pin (commit `bce6abb`), rail-filtered
`./scripts/full-test.sh start -- -only-testing:MuseionTests/PostsModelRepointTests`:
`6 executed / 0 passed / 6 failed / 0 skipped (xcodebuild exit 65)`, zero
compile errors — each on the finding's signature: `session.text → "A body,
typed in A"` under the B binding, `targets(postID: "shared", home: homeB)
→ false`, B's edits landing on A's disk, `watchedHome → …/B` despite a
refused flush / unanswered conflict / never-loaded retype, and the
no-collision vanish path dropping the dirty buffer (`readBody(A) → "# Unique
\n\nA body\n"`).
- **GREEN, full rail** at `8b0d43a` (the fix commit; tree clean at start):
`./scripts/full-test.sh start` → `./scripts/full-test.sh status` →
`715 executed / 715 passed / 0 failed / 0 skipped (xcodebuild exit 0)`;
`summary.json` → `result: Passed, totalTestCount: 715`; `** TEST SUCCEEDED **`;
715 = the cycle-5 baseline 708 + the 7 new pins, all 7 named passed in the
log; `PostsModelDepartureTests` 10/10 (#198 + #200 matrix green beside the
new suite — the gates compose); the mid-pass `PostsModelWriteRailTests` pin
passed on its new path.
- **Mutation check** (the stale card-scan pin's honest RED — its seam cannot
exist at base, so it is GREEN-only there): completion guard reverted to the
ID-only base form → rail-filtered `7 executed / 6 passed / 1 failed`, ONLY
that pin, `openPieceCards → ["Hedging"]` (A's cards on B's piece); restored
byte-exact (sha256 prefix `9c8fb55264f5ac1c` before and after), zero
`MUTATION-CHECK` tokens repo-wide.
- **Lint:** `swiftformat --lint .` → `0/152 files require formatting`;
`swiftlint lint --quiet` → zero violations (both at `8b0d43a`; the pre-push
hook's scoped gate passed on both pushes).
- **Evidence types:** see "Identity checks — evidence classes" above —
pinned (card hop-back, rescan hoist, #179 guard) vs by-construction
(Micropub stamp) vs invariant-equivalent defensive depth (the synchronous
sweep and `openPostID`'s gate). The preference leg is NOT unit-pinned:
`AppGateState`'s `didSet` writes the REAL `UserDefaults.standard`
(MuseionTests/AGENTS.md: never touch the machine), so driving a repoint
through `AppGateState` in a hosted test would point the owner's next launch
at a temp dir. The view wiring is structural proof only
(`homeRepointBinding` → `repointMuseionHome` → `posts.repoint` precedes
`museionHome = newHome`). Unverified by design; disclosed.
- **Not run:** the MuseionUITests smoke (outside the rail by design); no GUI
reproduction of the Settings flow (same posture as the scan — static trace
+ model-level pins).
- `pool: 0 in flight` at handoff — no subagents spawned (Z.ai draws: this
main only).
---
*Log written by daedalus (brief-28, profile daedalus) — format per the write-log skill*
@@ -0,0 +1,98 @@
# Release 0.1.0 — version bump, README rewrite, release notes, DMG packaging
> **Date:** 2026-12-01
> **Type:** milestone
> **Reference:** tag `v0.1.0` at `d470615` (local; push + Gitea release pending Alexander's go)
## Goal
Cut the first release: bump to 0.1.0 with a git tag, a DMG shareable on Gitea, a human-readable
release-notes document (CHANGELOG.md is too dense for a release page), and a README with a real
feature list and usage instructions now that the codebase is stable.
## What Was Done
- `Museion.xcodeproj/project.pbxproj`: `MARKETING_VERSION` 1.0 → 0.1.0 on all three targets (six
configs). `CURRENT_PROJECT_VERSION` stays 1. Verified in a real Release archive: Info.plist reads
`0.1.0` / `1`, `LSMinimumSystemVersion` 27.0, binary arm64 only.
- `CHANGELOG.md`: `## [0.1.0] - 2026-12-01` heading over the former Unreleased entries, empty
`[Unreleased]` above, pointer to the release notes.
- `README.md`: rewritten. Intro → features (Writing, Outlines, Library, The Mentor, Measuring
progress, Publishing, Rails) → requirements → install → quick start → shortcut table → the
Museion Home (kept, plus a folder-layout block) → development commands → license. Every feature
line grounded in `MuseionApp.swift` (menus/shortcuts), `Museion/AGENTS.md`, and CHANGELOG entries;
nothing from the PRD's ambitions.
- `docs/releases/0.1.0.md`: the distilled notes — what's in it, the milestones closed (M0–M6 plus
the post-v1 extensions), install, known limits, numbers. This is the Gitea release body.
- `scripts/release.sh`: archive → `-exportArchive` with `method: developer-id` → UDZO DMG
(`diskutil image create from`) → `notarytool --wait` → `stapler staple` → `spctl` assessment.
Preflight refuses before any build when no `Developer ID Application` identity is in the
keychain. `NOTARIZE=0` skips notarize+staple. Output `dist/Museion-<MARKETING_VERSION>.dmg`
(version read from build settings, not from the pbxproj text). `.gitignore` gains `dist/`.
- DOX: root `AGENTS.md` commands block + scripts index row + Stack line (macOS 27+, see gotchas);
`docs/AGENTS.md` Local Contract for `docs/releases/<version>.md` + Child DOX Index row.
- Three commits (`docs(readme)`, `build(release)`, `chore(release)`) and annotated tag `v0.1.0` on
the last.
- Verification: `scripts/full-test.sh` at the tagged commit — 717 executed / 717 passed / 0 failed;
`shellcheck scripts/release.sh` clean; `bash -n` clean; preflight refusal exercised; archive step
ran (38 s); DMG step proven on the dev-signed archive app (3.3 MB UDZO, mounts, signature
verifies inside).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| No wayfinder map — direct session | The skill's own test: no fog, one session. The only real decision (signing) was a question for Alexander, not a ticket. |
| `v0.1.0` tag with the `v` | The convention Gitea release pages expect; annotated so it carries a message. |
| Tag AFTER the docs commits | The tagged tree must contain the README and release notes it describes. |
| DMG, no zip | Same effort with `diskutil image create`; DMG is what Mac users expect. |
| `docs/releases/<version>.md` over a root `RELEASE_NOTES.md` | Scales per release, lives under the docs contract, reviewable in the commit; the Gitea release body is pasted from it. |
| `archive` + `-exportArchive` (method `developer-id`) over a plain Release build with `CODE_SIGN_IDENTITY` overrides | The Xcode-sanctioned distribution path — identical to Organizer's export, so a GUI fallback matches. Preflight guarantees no portal-side surprise from `-allowProvisioningUpdates`. |
| arm64 only | `MACOSX_DEPLOYMENT_TARGET = 27.0`; macOS 27 does not run on Intel, so a universal binary is dead weight. |
| Developer ID + notarization | Alexander has a Developer ID (not yet on this Mac). Without notarization Gatekeeper still blocks on Sequoia+ regardless of the signing cert, so Developer ID alone buys nothing for the downloader. |
| `diskutil image create from` over `hdiutil create` | hdiutil create is deprecated on macOS 27 (warning on every run); the replacement produced an identical UDZO image. |
| Stale README "macOS 26.5+" → 27+ | pbxproj `MACOSX_DEPLOYMENT_TARGET = 27.0` on all six configs and `Museion/AGENTS.md` already said 27.0; the root Stack line was corrected to match. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `codesign -dv` prints no `Authority=` lines — the script's Developer-ID check would have false-failed on the real run | Authority chain needs `-dvv` | `codesign -dvv` in both the check and the diagnostic echo |
| `hdiutil create` warns "deprecated. Please use 'diskutil image create…'" on macOS 27 | Apple moved image creation under diskutil | `diskutil image create from --format UDZO --volumeName … <stage> <dmg>`; kept `hdiutil detach` for the busy-volume guard (not deprecated) |
| `security find-identity -v -p codesigning` showed only `Apple Development` despite Alexander having a Developer ID | A Developer ID private key exists only on the Mac that generated the CSR; the portal copy is useless without it | Preflight names the Xcode path (Settings ▸ Accounts ▸ Manage Certificates ▸ + ▸ Developer ID Application) or a `.p12` import from the other Mac |
| `git log --oneline` hid the merge commit `3bb1782` and read as if HEAD were `cac66f6` | This machine's log config suppresses merges in short logs | Trust `git status --branch` and `git show -s` for ancestry; the snapshot's "ahead 2" was the merge + one chore commit |
| AGENTS.md session-log window was one log stale (11-23 missing) | The 11-23 write-log did not refresh the window | Window rebuilt from INDEX's 10 newest rows |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion.xcodeproj/project.pbxproj` | `MARKETING_VERSION = 0.1.0` ×6 |
| `CHANGELOG.md` | `[0.1.0] - 2026-12-01` heading + notes pointer |
| `README.md` | Full rewrite: features, requirements, install, quick start, shortcuts, Home layout, development |
| `docs/releases/0.1.0.md` | New — distilled release notes (Gitea release body) |
| `scripts/release.sh` | New — Developer ID export → notarized DMG |
| `.gitignore` | `dist/` |
| `AGENTS.md` | Stack line → macOS 27+; commands block `release.sh`; scripts index row; session-log window |
| `docs/AGENTS.md` | `docs/releases/<version>.md` contract + index row |
## Open Items & Next Steps
- [ ] Alexander: create the Developer ID Application identity on this Mac (Xcode ▸ Settings ▸
Accounts ▸ Manage Certificates… ▸ + ▸ Developer ID Application — Account Holder only) or
import the `.p12` from the Mac that holds the private key.
- [ ] Alexander (for notarization): `xcrun notarytool store-credentials museion-notary --apple-id …
--team-id 3M7APDAAC5 --password <app-specific password>` — the secret never leaves his hands.
- [ ] Then `./scripts/release.sh` → `dist/Museion-0.1.0.dmg`; mount test, `spctl` should read
`accepted, source=Notarized Developer ID`.
- [ ] Only on explicit go: `git push origin main v0.1.0`, then the Gitea release with the DMG
attached and `docs/releases/0.1.0.md` as the body.
- [ ] README's "signed and notarized" sentence is true only after the step above lands — revert
to the Gatekeeper-workaround wording if notarization is skipped.
- [ ] Optional: a screenshot for the README (launch the archive build, `screencapture -l <window>`).
- [ ] Pre-existing, not touched: Release build emits `Text +` deprecation warnings in
`TrendsPaneView.swift:389–391`.
---
*Log written by write-log skill*
+13
View File
@@ -5,6 +5,19 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-12-01 | milestone | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) | Release 0.1.0: version bump + tag, README feature/usage rewrite, distilled release notes, release.sh (Developer ID DMG, notarize); rail 717/717; Developer ID cert pending |
| 2026-11-23 | fix | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) | Unticketed fix (brief-28, argus cycle-5): a Home repoint is a guarded document departure — the gate runs before the preference/binding commit, the refusal keeps Home A and the buffers; document identity is (Home, ID) across the model and re-checked at async completion (card scan, rescan — both mutation-checked); RED-first 6/6 at ca265d3b, review r1 +2 pins (rescan hoist, draft survives); rail 717/717 |
| 2026-11-19 | fix | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) | Quit routes through the departure gate (#200): conflict-held shutdown, BLOCK-QUIT at applicationShouldTerminate, never-loaded-retype guard; finish-audit fixes; rail 708/708 |
| 2026-11-17 | fix | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) | Unticketed fix (brief-27, argus cycle-4): stdin writes move to a dedicated writer queue — engine backpressure can no longer defeat the request deadline, Stop, or a bounded reaping close; neverRead/serverPing fake modes, 3 RED-first smokes + healthy-contract pin, suite 697/697 |
| 2026-11-17 | issue | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | Three most-re-read files split into 8 domain-extension files, move-only (three audits concur); 693/693 |
| 2026-11-17 | issue | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | Root gate-running learnings collapse into the full-test.sh pointer; 8 deletions mapped to script/hook behavior; authoring rules retained; 693/693 |
| 2026-11-17 | issue | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | Lint-green doc truth (#197) + finish-audit; watcher-race test quiesced, symlink pin flip-verified, stale-xcodebuild hazard found; 693/693 |
| 2026-11-17 | feat | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) | Classis full-test.sh ported as the verify rail + pre-push hook; 4-round finish-audit; suite 692/692 via the rail, hook rig 23/23 |
| 2026-11-16 | fix | [20261116-failed-flush-discarded-on-document-switch_log.md](20261116-failed-flush-discarded-on-document-switch_log.md) | Unticketed fix (brief-25, argus cycle-4): document departure aborts on a failed flush — one sessionMayDepart gate (flushOrAbort's conflict+flush gates) behind dismissExternal/departOpenDocuments and select/openUnguarded; both navigation families pinned RED-first (6 pins); unit suite 699 green ×2 |
| 2026-11-13 | opt | [20261113-fold-typing-budget-pin_log.md](20261113-fold-typing-budget-pin_log.md) | Unticketed pin (brief-24): typing-cost guard for the #142 re-key — per-call line-scan observer through the real keystroke pipeline; zero scans beside a fold at N/2N, exact-count control 206/406, mutation-checked |
| 2026-11-13 | opt | [20261113-cold-turkey-full-tokenization_log.md](20261113-cold-turkey-full-tokenization_log.md) | Unticketed opt (argus digest): minutes feeds skip word counting entirely; DraftStats.words count-only — no token array per keystroke; +3 pins (RED-first rail-trip seam, corpus equivalence), suite 684 |
| 2026-11-11 | fix | [20261111-fix-library-search-stale-after-mutation_log.md](20261111-fix-library-search-stale-after-mutation_log.md) | Search snapshots re-key on Home + a rescan-rail content revision (list change OR re-read post.md — body-only edits included); stale rows drop to the recompute spinner (#144/#157 mounted gap) |
| 2026-11-10 | follow-up | [20261110-issue179-followup-bind-root-task_log.md](20261110-issue179-followup-bind-root-task_log.md) | Bind hoisted to the WorkspaceView root task (stale watchedHome after repoint); PR #185 closed as superseded by 5bf0955 |
| 2026-11-10 | issue | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) | PR #184 finish-audit: dead Equatable cut, restart-race ceiling named, titled-apply pin + hangOnPromptLoad rig mode |
| 2026-11-10 | issue | [20261110-issue182-profilelayout-config-set-rail_log.md](20261110-issue182-profilelayout-config-set-rail_log.md) | ProfileLayout owns every profile path; HermesConfigRail owns the config-set CLI contract; audited, 684 green (#182) |
| 2026-11-10 | issue | [20261110-issue181-provider-descriptor-pass-readiness_log.md](20261110-issue181-provider-descriptor-pass-readiness_log.md) | Provider facts one table on the enum; one credential rail serves probe + readiness; readiness module; shared run guard (#181) |
+55
View File
@@ -0,0 +1,55 @@
# Museion 0.1.0
*Released 2026-12-01 · the first release. Entry-by-entry detail with issue numbers: [CHANGELOG.md](../../CHANGELOG.md).*
Museion is the Agentic Writing Environment: a native macOS app where your text, your library, and a resident AI mentor work under one roof. It 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.
0.1.0 is the complete v1 loop, three months in the making and dogfooded along the way: write, get critiqued, remember what keeps going wrong, measure whether it stops, publish.
## What is in it
**The Mentor Loop.** A user-installed [Hermes](https://hermes-agent.nousresearch.com/docs) engine runs as a child process under three isolated profiles. **Pass 1** critiques structure, argument, and flow; **Pass 2** works at sentence level. Each pass ends in a verdict and a set of **Fix Cards** — mechanical ones apply behind a sheet that shows the exact edit, one card at a time, never all at once; demonstration ones show a single annotated example on your own text. A native deslop lint lands its findings as cards before the engine even sees the piece. Promote a card into **Learnings** and every later pass consults it; dismiss one and it fades, resurfacing on an output clock. **Sessions** are freeform conversations with resume, fork, and compact; a reply can become a new post. **Blind Read** judges the current text against the pass-start snapshot without knowing which is which.
**A real editor.** A TextKit 2 prose surface with styled markdown source, sub-second autosave, an honest save-state dot, cursor and scroll restored across restarts, and an explicit *Reload / Keep Local* alert when the file changes underneath you — never a silent overwrite. Reading mode, focus mode, image drops that copy into the piece and reference in place, list indentation and folding, and spellcheck on request.
**Cold Turkey.** A writing lock nested inside focus mode: pick net words or minutes, and Museion holds a fullscreen kiosk until you meet the goal. Quitting asks once. Nothing persists.
**Outlines.** Nested-bullet outline pieces with LogSeq-style keys, drag-to-reorder and nest, zoom into a branch, and a one-way Convert to Post.
**A library that is a folder.** Pieces live under projects and fold into an archive, all plain markdown under your **Museion Home** (iCloud Drive by default on fresh installs, `~/Documents/Museion` otherwise; repoint-only, never moved). Grouping by project and Pass State, search across titles and bodies, rename/move/archive/trash from the row menu, and a live file watcher so Finder edits show up without a refresh. Open any `.md` in place as a guest; import `.md` files as posts.
**Measurable improvement.** Running a pass on an unaided first draft captures four style metrics before the mentor sees anything. The Trends pane charts them across captures with an honest *improving / steady / slipping* verdict per metric.
**Publishing.** Micro.blog via Micropub: Send as Draft, review, Publish. Illustrations upload and ride inline; a picture without alt text never ships.
## Milestones
- **M0 — ACP bridge.** The app spawns Hermes, opens a session, streams replies, cancels, and tears down cleanly on quit.
- **M1 — Editor surface.** Posts list over the Home folder, post lifecycle (new, save, rename, trash), the TextKit 2 prose editor with autosave and external-change guard.
- **M2 — Passes and Fix Cards.** Pass 1 / Pass 2, the in-app MCP server that receives cards, the Fix Cards palette with ask-before Apply, the native deslop lint.
- **M3 — Critique memory.** Learnings: promote with one confirm, consult on every pass, dismiss with decay.
- **M4 — Measurable improvement.** First-draft stats capture and the Trends pane.
- **M5 — Research and library-light.** Mid-pass research notes kept into the piece with provenance; drill offers; the bundled skill set (Serif stack, deslop, craft canon, VOICE).
- **M6 — Micropub publish.** Draft → publish to Micro.blog, illustrations included.
- **After v1 scope.** Projects and archive, the outliner, library search, image drops, Cold Turkey, per-surface engines with in-app model settings and Test Connection, Nous Portal, gateless launch, iCloud-default Home, the editorial two-color chrome.
## Install
Download `Museion-0.1.0.dmg` below, open it, drag Museion to Applications.
- **macOS 27 or later**, Apple Silicon.
- **Hermes** is needed for Passes and Sessions — `curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash`. Museion provisions the profiles and seeds its skills on the next launch. The editor, library, outlines, and publishing work without it.
- A provider API key (z.ai, Anthropic, OpenAI, or Nous Portal) under Settings ▸ Provider Keys.
The app is Developer ID-signed and notarized.
## Known limits
- Long-form structure tools (binder, compile), backlinks and graph views, multi-mind setups, and publish targets beyond Micro.blog are out of v1 scope — see `PRODUCT.md` for the full non-goal list.
- Convert to Post is one-way. Opening a mixed-content outline asks how to proceed; opening as an outline normalizes on save.
- The Mentor methodology is a bundled skill set, not a trained model — fierce or gentle is a persona blend, not a setting.
- One user so far. No testimonials, customers, or benchmarks exist yet, and none are claimed.
## Numbers
74 Swift files, about 23,000 lines in the app target; a unit suite of over 700 tests, run through `scripts/full-test.sh`; SwiftFormat and SwiftLint clean repo-wide.
+8 -2
View File
@@ -240,7 +240,11 @@ struct MockWorkspace: View {
}
private var previewText: String {
String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6)
String(
repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. "
+ "Sentences shorten. Claims retreat. ",
count: 6,
)
}
}
@@ -316,7 +320,9 @@ struct VariantA: View {
switch model.phase {
case .checking: "Running hermes acp --check."
case .passed: "Hermes \(model.version) answered the health check. The mentor is available."
case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available."
case .failed:
"The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions " +
"without it — the editor below stays available."
}
}
}
+594
View File
@@ -0,0 +1,594 @@
#!/usr/bin/env bash
# full-test.sh — detached, xcresult-authoritative full-suite runner.
#
# Ported from classis scripts/full-test.sh (matured through classis
# #649–#729, source commit 071966e) and adapted to Museion (#190). Encodes
# the session learnings so sessions stop re-deriving them — the 2026-11-16
# retro measured this loop at 29% of all terminal calls (77 xcodebuild +
# 76 hand-rolled xcresult reads in ≥8 incantation variants):
# #177 — run xcodebuild DETACHED and poll; the full suite can exceed a
# tool call's timeout budget (the #177 build-for-testing /
# test-without-building split existed only to dodge that cap —
# and detached runs make it unnecessary).
# #31/#178 — pass/fail counts are authoritative ONLY in the completed
# .xcresult (`xcresulttool get test-results summary`), never in
# grepped output; #178: totalTestCount counts a parameterized
# @Test as ONE test — reconcile executed counts from the summary,
# never from log lines.
# #31/#134 — an -only-testing filter that matches ZERO executed tests
# FAILS the run: single-name filters and suite names with
# spaces/backticks match zero Swift Testing tests and "pass"
# vacuously. A zero-executed summary exits nonzero, always.
# #30/#147 — a parallel-load flake settles via a serialized rerun
# (-parallel-testing-enabled NO); that green is the record (each
# rerun allocates its own run dir and becomes `current`).
# #134 — per-test execution-time allowances are enforced by the runner
# (-test-timeouts-enabled YES): a wedged test FAILS at its
# allowance — host killed, restarted, named in the xcresult —
# instead of holding the run silent (the machine-wedge family:
# testmanagerd / IDE-session hangs). The runner rounds the
# DEFAULT allowance UP to whole minutes (60s stays 60s).
# EngineSmokeTests' real child processes (one wire smoke per LLM
# surface) sit well inside the 60s default — raise via
# --test-timeout if that ever changes.
# #33/#179 — every launch pins its own result bundle (-resultBundlePath)
# into an ATOMICALLY allocated run dir, and `run` polls ITS OWN
# dir: never "newest .xcresult" (the #33 bundle race), never
# `current` (a same-second twin launch repoints it — the #179
# pin). Concurrent sessions can never race for a bundle.
# Wedge observability (classis #716 machinery, ported): live `status`
# names the last test event + its exact age, what is IN FLIGHT,
# flags STOPPED (state T) descendants immediately, and separates
# advisory "no test progress" from the hard STALLED warning.
#
# Usage:
# scripts/full-test.sh run [--serialized] [--workers N] [--scheme S] [--stall-min N] [--test-timeout N] [--no-test-timeouts] [-- xcodebuild-args...]
# scripts/full-test.sh start [same flags] # spawn detached, print run dir, exit
# Detached via nohup + setsid-when-available (escapes the caller's process
# group, so a tool-call timeout cannot take the run down). Without setsid,
# agent callers should prefer `setsid nohup ./scripts/full-test.sh run … > log 2>&1 < /dev/null &`.
# scripts/full-test.sh status # live: last test event + age, wedge/stall warnings; exits 3
# # finished: final summary
# scripts/full-test.sh summary [run-dir] # print a finished run's summary
#
# run blocks until done — only from a caller with enough timeout budget;
# otherwise use start + status (the #177-safe pattern).
# status exits 3 while the run is live, so callers can poll in a loop.
#
# Default test selection is the hosted unit bundle (-only-testing:MuseionTests);
# forward your own -only-testing to take over selection (multiple -only-testing
# flags UNION, so the default is dropped the moment you bring one). The UI
# smoke target stays out of the rail. No parallel flags are passed by default
# (single hosted bundle — worker pinning buys nothing); --workers N opts in.
#
# Do NOT lint concurrently with a live run (#30 — real-process fake-ACP tests
# flake under concurrent load).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# Acceptance harnesses point FT_BASE_DIR at an isolated directory. Run-dir
# allocation is unique per launch, but the bases must stay disjoint: a stub
# launch must never repoint the real base's `current` file under a live
# agent's polling loop. Absolute-path requirement enforced below die().
BASE="${FT_BASE_DIR:-$ROOT/_build/full-test}"
CURRENT="$BASE/current"
# Per-test timeouts bound a wedged test at --test-timeout; the stall warning
# is the BACKSTOP (non-test silence: build, host launch, post-phases). 10 min
# comfortably exceeds the 5-min maximum allowance plus kill/restart overhead.
# Keep it above --test-timeout if you raise that.
STALL_MIN_DEFAULT=10
# Per-test allowance seconds. The runner rounds the DEFAULT allowance UP to
# whole minutes; the maximum caps any per-test raise (XCTest
# executionTimeAllowance / Swift Testing .timeLimit). EngineSmokeTests spawns
# real child processes per LLM surface — seconds, well inside 60s.
TEST_TIMEOUT_DEFAULT=60
TEST_TIMEOUT_MAX=300
POLL_SECS=15
die() { echo "full-test.sh: $*" >&2; exit 2; }
[[ -z ${FT_BASE_DIR:-} || $FT_BASE_DIR == /* ]] \
|| die "FT_BASE_DIR must be an absolute path, got: ${FT_BASE_DIR:-}"
# Numeric flag values feed bash arithmetic downstream — a crafted value like
# `x[$(cmd)]` or a leading-zero octal literal would be EVALUATED there, not
# compared. Accept only plain decimal integers (≤9 digits, so arithmetic
# can't overflow either); zero is legal only where the caller allows it.
valid_int() { [[ $1 =~ ^(0|[1-9][0-9]{0,8})$ ]]; }
require_int() { # $1=flag-name $2=value — positive only
valid_int "$2" && [[ $2 != 0 ]] || die "$1 must be a positive integer (no leading zeros), got: $2"
}
require_nonneg_int() { # $1=flag-name $2=value — zero allowed (--stall-min)
valid_int "$2" || die "$1 must be a non-negative integer (no leading zeros), got: $2"
}
usage() { local last; last=$(awk '/^set -euo pipefail/{print NR - 2; exit}' "$0"); sed -n "2,${last}p" "$0" | sed 's/^# \{0,1\}//'; exit 2; }
MODE="${1:-run}"
case "$MODE" in
run | start | status | summary) if [[ $# -gt 0 ]]; then shift; fi ;;
*) usage ;;
esac
SCHEME=Museion
SERIALIZED=0
STALL_MIN=$STALL_MIN_DEFAULT
TIMEOUT_ENABLED=1
TEST_TIMEOUT=$TEST_TIMEOUT_DEFAULT
# 0 = pass NO explicit parallel flags (the historical Museion invocation;
# single hosted bundle — bundle-worker parallelism buys nothing). --workers N
# opts in; --serialized is the #30/#147 flake rerun hatch.
WORKERS=0
FORWARD=()
POSITIONAL=()
# The run dir allocated by THIS invocation's start_run. `run` mode polls its
# own directory — a same-second twin launch repoints `current` at its own
# run, which must not steal this poll loop (#179).
THIS_RUN=""
while [[ $# -gt 0 ]]; do
case "$1" in
--serialized) SERIALIZED=1 ;;
--workers) [[ $# -ge 2 ]] || die "--workers needs a value"; require_int --workers "$2"; WORKERS="$2"; shift ;;
--scheme) [[ $# -ge 2 ]] || die "--scheme needs a value"; [[ $2 == */* ]] && die "--scheme must be a bare scheme name (no path separators), got: $2"; SCHEME="$2"; shift ;;
--stall-min) [[ $# -ge 2 ]] || die "--stall-min needs a value"; require_nonneg_int --stall-min "$2"; STALL_MIN="$2"; shift ;;
--test-timeout) [[ $# -ge 2 ]] || die "--test-timeout needs a value (seconds)"; require_int --test-timeout "$2"; TEST_TIMEOUT="$2"; shift ;;
--no-test-timeouts) TIMEOUT_ENABLED=0 ;;
--) shift; FORWARD=("$@"); break ;;
-*) die "unknown flag: $1" ;;
*) POSITIONAL+=("$1") ;;
esac
shift
done
[[ ${#POSITIONAL[@]} -le 1 ]] || die "unexpected arguments: ${POSITIONAL[*]:1}"
SUFFIX=""
if [[ $SERIALIZED == 1 ]]; then SUFFIX="-serialized"; fi
start_run() {
local run_id run_dir timeout_max n cand merr have_only=0 a
# The enforced maximum never sits below the default, so a large
# --test-timeout stays coherent (computed once; used by args + banner).
timeout_max=$(( TEST_TIMEOUT > TEST_TIMEOUT_MAX ? TEST_TIMEOUT : TEST_TIMEOUT_MAX ))
# Allocate the run dir by ATOMIC test-and-create. The bare second-granular
# id is tried first (ids unchanged in the common case); a same-second
# launch of the same scheme+mode finds it taken and walks a serial tail
# (-2, -3, … — unbounded: every taken name was allocated by a real
# launch, so the walk always terminates). Each attempt is itself atomic —
# bare mkdir fails EEXIST under POSIX, so concurrent starts can never
# both win one candidate; there is no check-then-create window. A mkdir
# failure whose path does NOT then exist is a real error (e.g.
# permissions), not a collision, and dies loudly. The tail only ever
# follows the timestamp+scheme base, so ids stay sorted by start time.
run_id="$(date -u +%Y%m%dT%H%M%SZ)-$SCHEME$SUFFIX"
run_dir=""
mkdir -p "$BASE"
n=1
while :; do
if (( n == 1 )); then
cand="$BASE/$run_id"
else
cand="$BASE/$run_id-$n"
fi
if mkdir "$cand" 2>/dev/null; then
run_dir="$cand"
break
fi
if [[ ! -e $cand && ! -L $cand ]]; then
merr="$(mkdir "$cand" 2>&1)" || true
die "could not create run dir $cand${merr:+ — $merr}"
fi
n=$((n + 1))
done
THIS_RUN="$run_dir"
local args=(
-allowProvisioningUpdates
-project "$ROOT/Museion.xcodeproj"
-scheme "$SCHEME"
-destination 'platform=macOS'
test
-resultBundlePath "$run_dir/result.xcresult"
)
if [[ $SERIALIZED == 1 ]]; then args+=(-parallel-testing-enabled NO)
elif (( WORKERS > 0 )); then args+=(-parallel-testing-enabled YES -parallel-testing-worker-count "$WORKERS"); fi
# Runner-enforced per-test allowances — a wedged test fails at its
# allowance (host killed + restarted, named in the xcresult). The maximum
# never sits below the default, so a large --test-timeout stays coherent.
if [[ $TIMEOUT_ENABLED == 1 ]]; then
args+=(
-test-timeouts-enabled YES
-default-test-execution-time-allowance "$TEST_TIMEOUT"
-maximum-test-execution-time-allowance "$timeout_max"
)
fi
# Default test selection: the hosted unit bundle (#190). Multiple
# -only-testing flags UNION — a bundle-level default beside a finer
# forwarded filter would make the filter a no-op — so the default is
# dropped the moment the caller forwards any -only-testing of their own.
if [[ ${#FORWARD[@]} -gt 0 ]]; then
for a in "${FORWARD[@]}"; do [[ $a == -only-testing* ]] && have_only=1; done
fi
if (( have_only == 0 )); then args+=(-only-testing:MuseionTests); fi
if [[ ${#FORWARD[@]} -gt 0 ]]; then args+=("${FORWARD[@]}"); fi
# nohup + stdin </dev/null: survives this script's (and its caller's) exit.
# setsid (when present) also escapes the process group, so a tool-timeout
# group-kill of the launching call cannot take the run down with it.
# The pidfile holds the WRAPPER's pid: it dies only after exit-code is
# written, so "pid gone" always means "run fully finished".
# Output is piped through stamp_stream (exported below — wall-clock prefix
# per line, so `status` can age the last test-progress event exactly);
# pipefail keeps $? xcodebuild's own exit code, not the stamp function's.
DETACHER=()
command -v setsid >/dev/null 2>&1 && DETACHER=(setsid)
( cd "$ROOT" && nohup ${DETACHER[@]+"${DETACHER[@]}"} bash -c '
log="$1"; exitf="$2"; shift 2
set -o pipefail
xcodebuild "$@" 2>&1 < /dev/null | stamp_stream >"$log"
echo $? >"$exitf"
' _ "$run_dir/xcodebuild.log" "$run_dir/exit-code" "${args[@]}" >/dev/null 2>&1 &
echo $! >"$run_dir/pid"
)
# Publish `current` ATOMICALLY. A truncating `>` from two same-second
# launches can interleave — the shorter write lands over a longer earlier
# one and leaves trailing bytes, corrupting current for every reader.
# Write a per-launch temp and rename(2) it into place (same directory ⇒
# one filesystem ⇒ atomic).
printf '%s\n' "$run_dir" >"$BASE/.current.tmp.$$"
mv "$BASE/.current.tmp.$$" "$CURRENT"
echo "run dir : $run_dir"
echo "pid : $(cat "$run_dir/pid")"
echo "scheme : $SCHEME$SUFFIX"
if [[ $SERIALIZED == 1 ]]; then echo "parallel: NO (--serialized)"
elif (( WORKERS > 0 )); then echo "parallel: YES ($WORKERS workers)"
else echo "parallel: default (no flags)"; fi
if (( have_only == 0 )); then echo "tests : MuseionTests (default)"
else echo "tests : caller -only-testing filter"; fi
if [[ $TIMEOUT_ENABLED == 1 ]]; then echo "timeout : ${TEST_TIMEOUT}s per test (max ${timeout_max}s)"; else echo "timeout : DISABLED (--no-test-timeouts)"; fi
if [[ ${#FORWARD[@]} -gt 0 ]]; then echo "forwarded: ${FORWARD[*]}"; fi
}
current_run_dir() {
[[ -f $CURRENT ]] || die "no run recorded — call 'start' first"
local d
d="$(cat "$CURRENT")"
[[ -d $d ]] || die "recorded run dir missing: $d"
printf '%s' "$d"
}
pid_alive() { kill -0 "$1" 2>/dev/null; }
# --- wedge observability -----------------------------------------------------
# Test-progress lines are the test phase's heartbeat. The wrapper stamps every
# log line "YYYY-MM-DD HH:MM:SS ", so the last progress line carries an exact
# event time; unstamped (legacy) logs fall back to the log mtime for its age.
# Stamp every stdin line with a local wall-clock prefix "YYYY-MM-DD HH:MM:SS ".
# Runs inside the detached wrapper's shell via `export -f` — exported bash
# functions travel through nohup to the `bash -c` child, keeping the runner
# self-contained (no stamper file whose absence would silently empty the log).
# `date` is cached per second: stamps are second-granular anyway, so the fork
# cost is one date per wall-clock second of output. The `|| [[ -n $line ]]`
# arm keeps a final unterminated line. Verified: bash's printf builtin writes
# through per invocation — no stdio buffering — so the log's mtime tracks
# real output for stall detection.
stamp_stream() {
local line stamp='' last_sec=-1
while IFS= read -r line || [[ -n $line ]]; do
if (( SECONDS != last_sec )); then
last_sec=$SECONDS
stamp="$(date '+%Y-%m-%d %H:%M:%S')"
fi
printf '%s %s\n' "$stamp" "$line"
done
}
export -f stamp_stream
fmt_age() { # seconds → "45s" / "12m 03s"
local s="$1"
if (( s >= 60 )); then printf '%dm %02ds' $(( s / 60 )) $(( s % 60 ))
else printf '%ds' "$s"; fi
}
age_since() { # $1=epoch seconds → age in seconds, clamped at 0 (clock-skew guard)
local a=$(( $(date +%s) - $1 ))
(( a < 0 )) && a=0
printf '%s' "$a"
}
describe_progress_line() { # $1=line → TP_DESC, TP_EPOCH (stamp epoch; empty when unstamped)
local rest="$1"
TP_DESC=""; TP_EPOCH=""
if [[ $rest =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2})\ (.*)$ ]]; then
TP_EPOCH="$(date -j -f '%Y-%m-%d %H:%M:%S' "${BASH_REMATCH[1]}" +%s 2>/dev/null || true)"
rest="${BASH_REMATCH[2]}"
fi
if [[ $rest =~ [Tt]est\ [Ss]uite\ \'([^\']+)\'\ (started|passed|failed) ]]; then
TP_DESC="suite '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}"
elif [[ $rest =~ [Tt]est\ [Cc]ase\ \'([^\']+)\'\ (passed|failed) ]]; then
TP_DESC="test '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}"
elif [[ $rest =~ [Tt]est\ [Cc]ase\ (.+)\ started\.$ ]]; then
TP_DESC="test ${BASH_REMATCH[1]} started"
elif [[ $rest =~ [Ss]uite\ ([A-Za-z0-9_.]+)\ (started|passed|failed) ]]; then
# Swift Testing verbose (serialized logs, glyph-prefixed): "Suite NAME passed after …"
TP_DESC="suite '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}"
elif [[ $rest =~ [Tt]est\ ([A-Za-z0-9_.]+\(\))\ (started|passed|failed) ]]; then
# Swift Testing verbose: "Test fnName() started."
TP_DESC="test '${BASH_REMATCH[1]}' ${BASH_REMATCH[2]}"
elif [[ $rest =~ [Tt]est\ run\ with\ ([0-9]+)\ tests?\ in\ ([0-9]+)\ suites?\ (passed|failed) ]]; then
TP_DESC="run (${BASH_REMATCH[1]} tests) ${BASH_REMATCH[3]}"
elif [[ $rest == "Testing started" ]]; then
TP_DESC="testing started"
else
TP_DESC="progress: ${rest:0:80}"
fi
return 0
}
last_progress_event() { # $1=log → TP_DESC, TP_EPOCH; rc 1 = no progress line yet
local line
TP_DESC=""; TP_EPOCH=""
line="$(grep -iE "test suite|test case|test run with|testing started|suite .* (started|passed|failed)|test .*\(.*\) (started|passed|failed)" "$1" 2>/dev/null | tail -n 1)" || true
[[ -n $line ]] || return 1
describe_progress_line "$line"
}
# What is IN FLIGHT right now: the suite each host is currently in, plus the
# last started per-test line when the log shape provides one (classic/
# serialized modes, where a started line has no matching completion). This is
# the "last-started test" the wedge report names. Closing rules match the
# real log shapes: parallel hosts run suites SEQUENTIALLY and never emit
# suite-finished lines — a new suite-start on a host closes its previous one —
# while classic/serialized logs close suites explicitly. Ages come from the
# wrapper stamps; unstamped legacy logs report "?".
open_flights() { # $1=log → lines "kind<TAB>name<TAB>host<TAB>stamp"
awk '
function stampof(s) {
split(s, w, " ")
if (w[1] ~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/ && w[2] ~ /^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/) return w[1] " " w[2]
return ""
}
function close_suite(h, n) { if (h in openName && openName[h] == n) { delete openName[h]; delete openStamp[h] } }
{
st = stampof($0)
body = st == "" ? $0 : substr($0, 21)
sub(/^[^A-Za-z]*/, "", body) # strip Swift Testing glyph prefixes
if (body ~ /^(Test|Suite) /) {
split(body, a, "\047") # single-quote split: a[2] = quoted name
if (body ~ /^Test [Ss]uite/ && body ~ / started/) {
host = (a[3] ~ / on $/) ? a[4] : "-"
openName[host] = a[2]; openStamp[host] = st # sequential host: supersedes
} else if (body ~ /^Test [Ss]uite/ && body ~ /passed|failed/) {
host = (a[3] ~ / on $/) ? a[4] : "-"
close_suite(host, a[2])
inflDone = 1 # suite finished ⇒ its last started test did too
} else if (body ~ /^Suite/ && body ~ / started/) {
# Swift Testing verbose (serialized logs): "Suite NAME started."
split(body, sw, " "); openName["-"] = sw[2]; openStamp["-"] = st
} else if (body ~ /^Suite/ && body ~ /passed|failed/) {
split(body, sw, " "); close_suite("-", sw[2]); inflDone = 1
} else if (body ~ /^Test/ && body ~ /started\.$/) {
# classic quoted cases, Swift "Test case passing …" and "Test fn() started."
if (body ~ /^Test [Cc]ase /)
inflN = (a[2] != "") ? a[2] : substr(body, 11, length(body) - 19)
else {
inflN = substr(body, 6); sub(/ started\.$/, "", inflN)
}
inflS = st; inflDone = 0
} else if (body ~ /^Test run with/ && body ~ /passed|failed/) {
inflDone = 1 # Swift Testing bundle finished
} else if (body ~ /^Test/ && body ~ /passed|failed/) {
if (inflN != "" && index(body, inflN)) inflDone = 1
}
}
}
END {
for (h in openName) if (openName[h] != "") print "suite\t" openName[h] "\t" h "\t" openStamp[h]
if (inflN != "" && !inflDone) print "test\t" inflN "\t-\t" inflS
}
' "$1"
}
# Every live descendant of $1 whose ps state is T (stopped). A SIGSTOPed test
# host is the recorded wedge simulation; real machine wedges (#134
# testmanagerd/IDE-session family) go silent instead and surface through the
# progress-age tiers.
stopped_descendants() { # $1=root pid → "pid<TAB>command" lines
local root="$1" seen=" " pid st kids k n=0
local front=("$root")
while (( ${#front[@]} > 0 )); do
pid="${front[0]}"
front=(${front[@]+"${front[@]:1}"})
[[ $seen == *" $pid "* ]] && continue
seen+="$pid "
(( n += 1 )); (( n > 500 )) && return 0
st="$(ps -o stat= -p "$pid" 2>/dev/null | tr -d ' ')"
if [[ $st == T* ]]; then
printf '%s\t%s\n' "$pid" "$(ps -o command= -p "$pid" 2>/dev/null | cut -c 1-100)"
fi
kids="$(pgrep -P "$pid" 2>/dev/null || true)"
for k in $kids; do front+=("$k"); done
done
return 0
}
summarize_run() {
local run_dir="$1"
local result="$run_dir/result.xcresult"
local exit_code_file="$run_dir/exit-code"
[[ -f $exit_code_file ]] || die "run not finished (no exit-code in $run_dir) — use 'status'"
local xc_exit
xc_exit="$(cat "$exit_code_file")"
if [[ ! -d $result ]]; then
{
echo "full-test.sh: result bundle missing in $run_dir (xcodebuild exit $xc_exit)"
echo " A run killed mid-write corrupts the bundle (#177). Rerun; if the first"
echo " run wedged, add --serialized (#30/#147)."
} >&2
exit 2
fi
xcrun xcresulttool get test-results summary --path "$result" >"$run_dir/summary.json" ||
die "xcresulttool could not read $result"
python3 - "$run_dir" "$xc_exit" <<'PY'
import json, sys
run_dir, xc_exit = sys.argv[1], int(sys.argv[2])
s = json.load(open(f"{run_dir}/summary.json"))
def count(key):
return int(s.get(key) or 0)
passed, failed, skipped = count("passedTests"), count("failedTests"), count("skippedTests")
executed = passed + failed # skipped tests were selected, not executed
# #31/#134: a filter matching zero executed tests must FAIL, never pass
# vacuously (single-name / spaces / backticks match zero Swift Testing tests).
if executed == 0:
print(f"result : VACUOUS — 0 tests executed, {skipped} skipped (xcodebuild exit {xc_exit}) — summary.json beside the log")
print(" Nothing executable matched (#31/#134); fix the -only-testing value.")
sys.exit(1)
print(f"result : {executed} executed / {passed} passed / {failed} failed / {skipped} skipped "
f"(xcodebuild exit {xc_exit}) — summary.json beside the log")
sys.exit(0 if xc_exit == 0 and failed == 0 else 1)
PY
}
case "$MODE" in
start)
start_run
;;
run)
start_run
# Poll THIS launch's dir, not `current` — a same-second twin launch
# repoints `current` at its own run mid-loop (#179).
run_dir="$THIS_RUN"
pid="$(cat "$run_dir/pid")"
echo "polling every ${POLL_SECS}s…"
while pid_alive "$pid"; do sleep "$POLL_SECS"; done
summarize_run "$run_dir"
;;
status)
run_dir="$(current_run_dir)"
pid="$(cat "$run_dir/pid")"
if pid_alive "$pid"; then
log="$run_dir/xcodebuild.log"
elapsed="$(ps -p "$pid" -o etime= | tr -d ' ')"
if [[ ! -f $log ]]; then
# launch window: wrapper wrote pid but not the first log line yet
echo "live : pid $pid, elapsed $elapsed, log not yet written"
exit 3
fi
last_write="$(stat -f '%Sm' -t '%H:%M:%S' "$log")"
stall_age=$(( $(date +%s) - $(stat -f '%m' "$log") ))
echo "live : pid $pid, elapsed $elapsed, log last written $last_write ($(wc -l < "$log" | tr -d ' ') lines)"
tp_desc=""; tp_age=0; have_progress=0
if last_progress_event "$log"; then
have_progress=1
tp_desc="$TP_DESC"
tp_when="${TP_EPOCH:-$(stat -f '%m' "$log")}"
tp_age="$(age_since "$tp_when")"
echo "last : $tp_desc $(fmt_age "$tp_age") ago"
fi
# In-flight work — open suites (parallel logs) and the last started
# test without a completion (classic/serialized logs). This is what a
# wedge report names; the heartbeat only says when progress last
# HAPPENED. Collected once, reused by the display and the warnings.
FL_KIND=(); FL_NAME=(); FL_HOST=(); FL_AGE=()
fk= fn= fh= fs= fep= fage=
while IFS=$'\t' read -r fk fn fh fs; do
[[ -n $fk ]] || continue
fage="?"
if [[ -n $fs ]]; then
fep="$(date -j -f '%Y-%m-%d %H:%M:%S' "$fs" +%s 2>/dev/null || true)"
[[ -n $fep ]] && fage="$(fmt_age "$(age_since "$fep")")"
fi
FL_KIND+=("$fk"); FL_NAME+=("$fn"); FL_HOST+=("$fh"); FL_AGE+=("$fage")
done < <(open_flights "$log")
# Drop in-flight entries whose HOST has exited: parallel logs never emit
# suite-finished lines, and a dead test host's suite is finished — only
# a live host can be genuinely stuck. Host-less entries ("-", classic
# logs) and entries whose host text carries no "(pid)" are kept.
fl_keep=()
for i in "${!FL_KIND[@]}"; do
if [[ ${FL_HOST[$i]} =~ \(([0-9]+)\) ]] && ! pid_alive "${BASH_REMATCH[1]}"; then
continue
fi
fl_keep+=("$i")
done
if (( ${#fl_keep[@]} != ${#FL_KIND[@]} )); then
FL_K=(); FL_N=(); FL_H=(); FL_A=()
for i in ${fl_keep[@]+"${fl_keep[@]}"}; do
FL_K+=("${FL_KIND[$i]}"); FL_N+=("${FL_NAME[$i]}"); FL_H+=("${FL_HOST[$i]}"); FL_A+=("${FL_AGE[$i]}")
done
# bash 3.2: unguarded "${FL_K[@]}" on an empty array aborts under set -u
# (all hosts exited while the wrapper lives → fl_keep empty → status dies
# instead of reporting the live run). Same guard idiom as fl_keep above.
FL_KIND=(${FL_K[@]+"${FL_K[@]}"}); FL_NAME=(${FL_N[@]+"${FL_N[@]}"}); FL_HOST=(${FL_H[@]+"${FL_H[@]}"}); FL_AGE=(${FL_A[@]+"${FL_A[@]}"})
fi
open_desc=""
for i in "${!FL_KIND[@]}"; do
fdisp="${FL_HOST[$i]}"; fdisp="${fdisp#My Mac - }"
[[ $fdisp == "-" ]] && fdisp="" || fdisp=" (host: $fdisp)"
open_desc+="${open_desc:+; }${FL_KIND[$i]} '${FL_NAME[$i]}' ${FL_AGE[$i]}$fdisp"
done
[[ -n $open_desc ]] && echo "open : $open_desc"
# A STOPPED (state T) descendant is a wedge signature that is
# detectable immediately — no stall-min wait. Name the in-flight work
# on that host (hosts appear in the log as "(pid)") plus its last
# event (#134 machine-wedge family).
while IFS=$'\t' read -r wpid wcmd; do
[[ -n $wpid ]] || continue
wopen=""
for i in "${!FL_KIND[@]}"; do
if [[ ${FL_HOST[$i]} == *"($wpid)"* ]]; then
wopen+="${wopen:+ and }${FL_KIND[$i]} '${FL_NAME[$i]}' ${FL_AGE[$i]}"
fi
done
wlast=""
wline="$(grep -F "($wpid)" "$log" 2>/dev/null | tail -n 1)" || true
if [[ -n $wline ]]; then
describe_progress_line "$wline"
wlast="$TP_DESC"
if [[ -n $TP_EPOCH ]]; then
wage="$(age_since "$TP_EPOCH")"
wlast="$wlast $(fmt_age "$wage") ago"
fi
fi
{
echo "CANDIDATE WEDGE : descendant pid $wpid is STOPPED (state T) — #134 machine-wedge family.${wopen:+ Stuck in: $wopen.}"
[[ -n $wlast ]] && echo " last event on that host: $wlast"
[[ -n $wcmd ]] && echo " process: $wcmd"
} >&2
done < <(stopped_descendants "$pid")
# No test progress past stall-min while the log is still being written
# is NOT silence — advisory only, never the STALLED warning (from
# outside, a healthy slow test looks exactly like a wedged worker).
if (( have_progress )) && (( tp_age > STALL_MIN * 60 )) && (( stall_age <= STALL_MIN * 60 )); then
{
echo "CANDIDATE WEDGE : no test progress for $(fmt_age "$tp_age") (last: $tp_desc), but the"
echo " log is still being written $(fmt_age "$stall_age") ago — one worker may be"
echo " wedged (#134 family); a healthy slow test looks the same."
} >&2
fi
# True silence (no writes at all) keeps the stall-min semantics, now
# naming the last test event whenever the test phase was reached.
if (( stall_age > STALL_MIN * 60 )); then
{
echo "STALLED : no log output for $(( stall_age / 60 )) min — #134 machine-wedge family."
echo " Wait, or kill $pid and rerun with --serialized (#30/#147)."
if (( have_progress )); then
echo " last test progress: $tp_desc $(fmt_age "$tp_age") ago"
fi
} >&2
fi
exit 3
fi
summarize_run "$run_dir"
;;
summary)
if [[ ${#POSITIONAL[@]} -ge 1 ]]; then run_dir="${POSITIONAL[0]}"; else run_dir="$(current_run_dir)"; fi
summarize_run "$run_dir"
;;
esac
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# pre-push — lint gate + no-push-while-testing guard + autofix-tree guard (#190).
#
# Ports the classis pre-push (classis #679/#684 classes) to Museion:
# 1. no push while a full-test run is live — concurrent load flakes the
# real-process suites (#30), and pushing mid-verification defeats the run;
# 2. lint gate scoped to the push's own Swift files — failing closed on
# violations there (settled #190 design: the gate guards what the
# push itself carries, not the whole tree);
# 3. autofix guard — a lint autofix pass that rewrites files AFTER
# verification must not ride the push untested: the push fails, the
# rewrite gets reviewed and re-verified via scripts/full-test.sh.
# Pre-existing unrelated dirt only warns.
#
# Installed via scripts/install-hooks.sh (git config core.hooksPath scripts/hooks).
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
# GUI git clients (Xcode, …) inherit launchd's sparse PATH, which lacks
# Homebrew — resolve the lint tools from the standard tool dirs.
# Append-only: the caller's PATH keeps priority.
for dir in /opt/homebrew/bin /usr/local/bin; do
if [[ -d "$dir" && ":$PATH:" != *":$dir:"* ]]; then
PATH="$PATH:$dir"
fi
done
export PATH
# 1. Never push while ANY full-test run is live: concurrent load flakes the
# real-process suites (#30), and pushing mid-verification defeats the run.
# Concurrent runs each pin their own dir (#190) — `current` only names the
# newest, so scan every run dir for a live pid.
live=""
for d in _build/full-test/*/; do
[[ -f "${d}pid" ]] || continue
p="$(cat "${d}pid")"
kill -0 "$p" 2>/dev/null && live="$live $d(pid $p)"
done
if [[ -n $live ]]; then
echo "pre-push: full-test run(s) live:$live — wait for them, then push." >&2
exit 1
fi
# 2. Lint gate, scoped to THIS PUSH's Swift files (#190): the gate guards
# what the push itself carries — settled #190 design, kept even now
# that bare `swiftlint .` runs green repo-wide (#195/#196 cleared the
# last findings). No Swift in the push → nothing to gate.
before="$(git status --porcelain)"
zero=0000000000000000000000000000000000000000
# Default-branch base for NEW-ref scoping: the project's default branch at
# origin, as a FULL ref — short names resolve refs/tags/ first, so a fetched
# tag "origin/main" would shadow the remote ref. Hardcoded, not $1-derived:
# pushes to other remotes or by URL are still scoped against origin/main,
# which is correct for this project's delta. A remote with a divergent
# default would need its own scoping — add per-remote resolution then.
default_ref="refs/remotes/origin/main"
swift_files=()
while read -r lref lsha rref rsha; do
[[ "$lsha" == "$zero" ]] && continue # ref deletion — no content to lint
if [[ "$rsha" == "$zero" ]]; then
# NEW ref: lint the delta against the default branch, never the whole
# tree (the gate is the push's delta, not the repo). No resolvable
# base FAILS CLOSED — a silent skip is a vacuous pass (#31/#134 class).
base="$(git merge-base "$lsha" "$default_ref" 2>/dev/null || true)"
[[ -n "$base" ]] || {
echo "pre-push: no common history with $default_ref — cannot scope the lint gate (orphan branch or missing default ref); refusing." >&2
exit 1
}
range=("$base" "$lsha")
else
range=("$rsha" "$lsha")
fi
while IFS= read -r f; do swift_files+=("$f"); done < <(git diff --name-only --diff-filter=ACMR "${range[@]}" -- '*.swift')
done
# NOTE: lints the WORKING-TREE copies of the pushed files, not the pushed
# blobs — a local uncommitted fix lints clean while the broken blob ships.
# Inherent to worktree pre-push hooks; blob-lint via `git show` if it bites.
if [[ ${#swift_files[@]} -gt 0 ]]; then
if ! { swiftformat "${swift_files[@]}" && swiftlint lint --quiet "${swift_files[@]}"; }; then
echo "pre-push: linters failed — fix the violations above, then push again." >&2
exit 1
fi
fi
# 3. Autofix guard: if the pass MODIFIED anything, the pushed commits no
# longer match the verified tree. Review, re-verify (scripts/full-test.sh),
# commit, push again. Pre-existing unrelated dirt only warns.
after="$(git status --porcelain)"
if [[ $before != "$after" ]]; then
echo "pre-push: linters MODIFIED the working tree:" >&2
git status --short >&2
echo "Review these, re-run scripts/full-test.sh, commit the results, push again." >&2
exit 1
fi
if [[ -n $after ]]; then
echo "pre-push: note — unrelated uncommitted changes present (not blocked):" >&2
git status --short >&2
fi
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# install-hooks.sh — activate the repo-versioned git hooks (#190).
# Idempotent; safe to re-run after cloning or when hooks go missing.
# Trust note: versioned hooks mean repo content executes at push time —
# install only in repos whose code you already build and run.
set -euo pipefail
cd "$(dirname "$0")/.."
git config core.hooksPath scripts/hooks
echo "core.hooksPath -> scripts/hooks (pre-push lint gate active)"
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
# Release packaging: archive → Developer ID export → DMG → notarize → staple.
#
# Contract:
# - Bumps nothing and tags nothing. Run from the commit that already carries
# the version in MARKETING_VERSION; the git tag is the caller's job.
# - Refuses BEFORE building when no valid "Developer ID Application" identity
# is in the keychain. Create it at developer.apple.com ▸ Certificates ▸ + ▸
# Developer ID Application from a Keychain Access ▸ Certificate Assistant CSR —
# Xcode's Manage Certificates refuses this even for the Account Holder (stale
# role cache). The private key lives only on the Mac that made the CSR — a
# portal-side certificate without it is not an identity.
# - Notarizes through the `museion-notary` notarytool keychain profile, created
# once by the Account Holder:
# xcrun notarytool store-credentials museion-notary \
# --apple-id <apple-id> --team-id <team-id> --password <app-specific-password>
# NOTARIZE=0 skips notarize+staple (a Developer-ID-signed DMG Gatekeeper still warns on).
# - Output: dist/Museion-<MARKETING_VERSION>.dmg (gitignored). The version is
# read from build settings, never from the pbxproj text. Apple Silicon only —
# the deployment target is macOS 27, which does not run on Intel.
set -euo pipefail
PROJECT="Museion.xcodeproj"
SCHEME="Museion"
APP_NAME="Museion.app"
CONFIGURATION="Release"
IDENTITY="Developer ID Application"
NOTARY_PROFILE="museion-notary"
DIST="dist"
DESTINATION='platform=macOS,arch=arm64'
cd "$(dirname "$0")/.." # repo root — PROJECT is relative (same guard as deploy.sh)
if ! security find-identity -v -p codesigning | grep -q "\"$IDENTITY:"; then
echo "No valid \"$IDENTITY\" identity in the keychain." >&2
echo "Create it once: developer.apple.com ▸ Certificates ▸ + ▸ $IDENTITY (CSR from Keychain Access ▸ Certificate Assistant)" >&2
exit 1
fi
SIGNER=$(security find-identity -v -p codesigning | sed -n 's/.*"\('"$IDENTITY"':[^"]*\)".*/\1/p' | head -1)
VERSION=$(xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
-destination "$DESTINATION" -showBuildSettings 2>/dev/null \
| awk -F'= ' '/MARKETING_VERSION = / {print $2; exit}')
if [[ -z "$VERSION" ]]; then
echo "MARKETING_VERSION not found in build settings" >&2
exit 1
fi
TEAM=$(xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
-destination "$DESTINATION" -showBuildSettings 2>/dev/null \
| awk -F'= ' '/DEVELOPMENT_TEAM = / {print $2; exit}')
DMG="$DIST/Museion-$VERSION.dmg"
echo "Packaging $SCHEME $VERSION"
# xcodebuild -quiet prints nothing on success; keep the log to show on failure.
log=$(mktemp -t museion-release)
trap 'rm -f "$log"' EXIT
run() { echo "→ $*"; if ! "$@" >"$log" 2>&1; then echo "Failed: $*" >&2; cat "$log" >&2; exit 1; fi; }
rm -rf "$DIST"
mkdir -p "$DIST"
run xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
-destination "$DESTINATION" -archivePath "$DIST/Museion.xcarchive" -quiet archive
cat >"$DIST/export-options.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>method</key><string>developer-id</string>
<key>signingStyle</key><string>automatic</string>
<key>teamID</key><string>$TEAM</string>
<key>destination</key><string>export</string>
</dict></plist>
EOF
run xcodebuild -exportArchive -archivePath "$DIST/Museion.xcarchive" \
-exportOptionsPlist "$DIST/export-options.plist" -exportPath "$DIST/export" \
-allowProvisioningUpdates -quiet
APP="$DIST/export/$APP_NAME"
if [[ ! -d "$APP" ]]; then
echo "Export did not produce $APP" >&2
exit 1
fi
run codesign --verify --deep --strict "$APP"
# Capture first: `codesign -dvv | grep -q` SIGPIPEs codesign under pipefail (grep
# quits at the first Authority line while codesign still writes its Info.plist dump).
SIGNATURE=$(codesign -dvv "$APP" 2>&1)
grep -q '^Authority=Developer ID Application' <<<"$SIGNATURE" \
|| { echo "Export is not Developer ID signed:" >&2; grep '^Authority=' <<<"$SIGNATURE" >&2; exit 1; }
# The bundled renderer must run from the SHIPPED layout (rpath → Resources/libyaml.bundle), and
# the app must not link libyaml — a bare dylib in the synced Resources folder becomes a link target
# silently (Xcode sniffs Mach-O content), which is why the vendored copy sits in a .bundle.
if otool -L "$APP/Contents/MacOS/$SCHEME" | grep -q libyaml; then
echo "The app links libyaml — it must only be apex's dependency, never the app's" >&2; exit 1
fi
run "$APP/Contents/Resources/apex" --version
# A mounted leftover from an earlier run makes the create fail with a busy volume.
hdiutil detach "/Volumes/$SCHEME $VERSION" -quiet 2>/dev/null || true
STAGE="$DIST/stage"
mkdir -p "$STAGE"
ditto "$APP" "$STAGE/$APP_NAME" # ditto preserves the bundle's signature and xattrs
ln -s /Applications "$STAGE/Applications"
# diskutil image create replaces the deprecated `hdiutil create` (macOS 27).
run diskutil image create from --format UDZO --volumeName "$SCHEME $VERSION" "$STAGE" "$DMG"
rm -rf "$STAGE" "$DIST/export"
# Gatekeeper's open-assessment needs the IMAGE signed too; the notary ticket is stapled onto this signature.
run codesign --timestamp --sign "$SIGNER" "$DMG"
if [[ "${NOTARIZE:-1}" == "1" ]]; then
# `--wait` exits 0 on Invalid too — the status FIELD is the verdict. (JSON goes to
# stdout only; notarytool has no output-path option.)
echo "→ xcrun notarytool submit $DMG --keychain-profile $NOTARY_PROFILE --wait"
if ! xcrun notarytool submit "$DMG" --keychain-profile "$NOTARY_PROFILE" --wait --output-format json >"$DIST/notary.json" 2>"$log"; then
echo "Failed: notarytool submit" >&2; cat "$log" >&2; exit 1
fi
if ! grep -Eq '"status" *: *"Accepted"' "$DIST/notary.json"; then
echo "Notarization not accepted — Apple's log:" >&2
xcrun notarytool log --keychain-profile "$NOTARY_PROFILE" \
"$(awk -F'"' '/"id" *:/ {print $4; exit}' "$DIST/notary.json")" >&2
exit 1
fi
# The ticket can reach the CDN a few seconds after "Accepted"; stapler 404s in that window.
for attempt in 1 2 3 4 5 6; do
xcrun stapler staple "$DMG" && break
[[ "$attempt" == 6 ]] && { echo "Stapling failed after 6 attempts; retry: xcrun stapler staple $DMG" >&2; exit 1; }
echo " ticket not on the CDN yet, retrying in 10 s ($attempt/6)…"
sleep 10
done
# The Gatekeeper verdict a downloader's Mac will reach.
spctl -a -t open --context context:primary-signature -v "$DMG"
fi
echo "Built: $DMG"
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env bash
# test-full-test.sh — pre-push acceptance rig (#190 AC7; finish-audit rounds 1-3).
# Builds a DISPOSABLE bare remote + clone, installs the REAL hook, and pushes
# every ref shape the gate must handle: clean/autofix/lint-fail/live-run
# blocks, docs-only skip, endpoint scoping (in-range block, out-of-range
# pass), new-branch delta gating, delete pushes, orphan/shadow-tag refusals,
# non-origin and by-URL pushes. Run: ./scripts/test-full-test.sh (no args; a
# throwaway mktemp dir under /tmp is kept after the run for post-mortem).
# Exits nonzero on any FAIL or on an unexpected executed-check count.
set -uo pipefail
H="$(mktemp -d /tmp/museion-hook-rig.XXXXXX)" # kept after the run for post-mortem
REPO="$(cd "$(dirname "$0")/.." && pwd)"
fails=0; n_checks=0
check() { # $1=label $2=expected $3=actual
n_checks=$((n_checks + 1))
if [[ "$2" == "$3" ]]; then echo "PASS: $1"; else echo "FAIL: $1 — expected [$2] got [$3]"; fails=$((fails+1)); fi
}
EXPECTED_CHECKS=23 # executed-count guard: a deleted/dead check fails loudly (#31)
cd "$H"
git init -q --bare remote.git
git clone -q remote.git work
cd work
git config user.email t@t; git config user.name t
mkdir -p scripts/hooks
cp "$REPO/scripts/hooks/pre-push" scripts/hooks/
cp "$REPO/scripts/install-hooks.sh" scripts/
cp "$REPO/.swiftlint.yml" .
cp "$REPO/.swiftformat" .
# bootstrap: seed the remote's main BEFORE activating hooks (a fresh remote
# has no default ref for the gate to scope against — first push is --no-verify
# by definition, like any repo bootstrap)
printf 'let ok = 1\n' >Good.swift
git add -A; git commit -qm bootstrap
git push -q --no-verify origin HEAD:refs/heads/main 2>/dev/null
bash scripts/install-hooks.sh >/dev/null
check "AC7 install-hooks sets core.hooksPath" "scripts/hooks" "$(git config core.hooksPath)"
push_out() { git push origin HEAD:refs/heads/main 2>&1; }
# clean tree → push passes
printf 'let ok2 = 2\n' >Good2.swift
git add -A; git commit -qm clean
out="$(push_out)"; rc=$?
check "AC7 clean tree pushes" 0 "$rc"
# committed MISFORMAT → swiftformat rewrites the working tree → BLOCK
printf 'let bad=1\n' >Bad.swift
git add Bad.swift; git commit -qm misformat
out="$(push_out)"; rc=$?
[[ "$out" == *"linters MODIFIED the working tree"* ]]; check "AC7 autofix rewrite blocks push" 0 $?
check "AC7 autofix block exits nonzero" 1 "$rc"
git rm -qf Bad.swift; git commit -qm drop-bad
# committed LINT VIOLATION (>180-char line) → swiftlint fails → BLOCK
{ printf 'let long = "'; printf 'A%.0s' {1..190}; printf '"\n'; } >Long.swift
git add Long.swift; git commit -qm violation
out="$(push_out)"; rc=$?
[[ "$out" == *"linters failed"* ]]; check "AC7 lint violation blocks push" 0 $?
check "AC7 lint block exits nonzero" 1 "$rc"
git rm -q Long.swift; git commit -qm drop-long
# LIVE full-test run → BLOCK
mkdir -p _build/full-test/run1
sleep 30 & livepid=$!
echo "$livepid" >_build/full-test/run1/pid
printf '%s\n' "$PWD/_build/full-test/run1" >_build/full-test/current
out="$(push_out)"; rc=$?
[[ "$out" == *"full-test run(s) live"* ]]; check "AC7 live run blocks push" 0 $?
check "AC7 live block exits nonzero" 1 "$rc"
# regression (#190 review): a live run that `current` does NOT name (concurrent
# runs repoint it) must still block — the hook scans all run dirs.
mkdir -p _build/full-test/run2; echo 999999 >_build/full-test/run2/pid
printf '%s\n' "$PWD/_build/full-test/run2" >_build/full-test/current
out="$(push_out)"; rc=$?
[[ "$out" == *"run1"* ]]; check "AC7 live run outside current blocks push" 0 $?
check "AC7 outside-current block exits nonzero" 1 "$rc"
kill "$livepid" 2>/dev/null
# docs-only commit (no Swift in the push) → passes (lint has nothing to gate;
# the skip itself is not directly observable here — every Swift file is clean)
printf '# Doc\n' >DOC.md
git add DOC.md; git commit -qm docs
out="$(push_out)"; rc=$?
check "AC7 docs-only push passes" 0 "$rc"
# pre-existing violation OUTSIDE the push range must NOT block (endpoint diff)
{ printf 'let old = "'; printf 'B%.0s' {1..190}; printf '"\n'; } >Old.swift
git add Old.swift; git commit -qm add-old
out="$(push_out)"; rc=$? # Old.swift IS in range → blocked
[[ "$out" == *"linters failed"* ]]; check "AC7 in-range violation still blocks" 0 $?
git rm -q Old.swift; git commit -qm drop-old
out="$(push_out)"; rc=$? # endpoints no longer contain Old.swift; the range's only
# entry is its deletion (ACMR excludes D) — genuine out-of-tree scoping is
# pinned by the new-branch case below (Remote.swift outside the delta)
check "AC7 deleted-in-range file does not block" 0 "$rc"
# plant a violating file on the remote default branch (pushed around the gate)
{ printf 'let remote = "'; printf 'C%.0s' {1..190}; printf '"\n'; } >Remote.swift
git add Remote.swift; git commit -qm remote-violation
git push --no-verify -q origin HEAD:refs/heads/main 2>/dev/null
# NEW branch (zero rsha), clean delta → passes despite the remote's violation
git checkout -qb feat
printf 'let feat = 1\n' >Feat.swift
git add Feat.swift; git commit -qm feat
out="$(git push origin HEAD:refs/heads/feat 2>&1)"; rc=$?
check "AC7 new-branch push gated on delta only" 0 "$rc"
# NEW branch carrying a violation → still blocked (gate applies to the delta)
git checkout -qb featbad
{ printf 'let fb = "'; printf 'D%.0s' {1..190}; printf '"\n'; } >FeatBad.swift
git add FeatBad.swift; git commit -qm featbad
out="$(git push origin HEAD:refs/heads/featbad 2>&1)"; rc=$?
[[ "$out" == *"linters failed"* ]]; check "AC7 new-branch violation blocks" 0 $?
git checkout -q main
# DELETE push (zero lsha) → no fatal noise, passes
out="$(git push origin :refs/heads/feat 2>&1)"; rc=$?
[[ "$out" != *"fatal:"* ]]; check "AC7 delete push no fatal noise" 0 $?
check "AC7 delete push passes" 0 "$rc"
# push to a NON-origin remote (alt; its alt/main tracking ref deleted):
# still scoped against origin/main — the project's delta — and passes
git remote add alt "$PWD/../remote.git"; git fetch -q alt
git update-ref -d refs/remotes/alt/main
git checkout -qb feat2
printf 'let f2 = 1\n' >F2.swift
git add F2.swift; git commit -qm feat2
out="$(git push alt HEAD:refs/heads/feat2 2>&1)"; rc=$?
check "AC7 non-origin push scoped via origin/main passes" 0 "$rc"
# push BY URL ($1 is the URL, not a remote name): still scoped and passes
out="$(git push "$PWD/../remote.git" HEAD:refs/heads/byurl 2>&1)"; rc=$?
check "AC7 URL push scoped via origin/main passes" 0 "$rc"
# orphan-history branch → fails closed (silent skip would be a vacuous pass)
git checkout -q main
git checkout -q --orphan orph
git rm -qrf . >/dev/null 2>&1
printf 'let orph = 1\n' >Orph.swift
git checkout -q main -- scripts .swiftlint.yml .swiftformat # keep the hook in the orphan tree
git add -A; git commit -qm orphan
out="$(git push origin HEAD:refs/heads/orph 2>&1)"; rc=$?
[[ "$out" == *"no common history"* ]]; check "AC7 orphan push fails closed with message" 0 $?
check "AC7 orphan push blocked" 1 "$rc"
# shadow tag: a LOCAL tag named origin/main pointing at the branch tip must
# NOT choose the lint base (short-ref resolution consults refs/tags/ first)
git checkout -q main
git checkout -qb shadow
{ printf 'let sh = "'; printf 'E%.0s' {1..190}; printf '"\n'; } >Shadow.swift
git add Shadow.swift; git commit -qm shadow
git tag -f origin/main shadow >/dev/null
out="$(git push origin HEAD:refs/heads/shadow 2>&1)"; rc=$?
[[ "$out" == *"linters failed"* ]]; check "AC7 shadow tag cannot void the lint base" 0 $?
check "AC7 shadow-tag push blocked" 1 "$rc"
git tag -d origin/main >/dev/null; git checkout -q main
echo "----"
if [[ "$fails" -eq 0 && "$n_checks" -eq "$EXPECTED_CHECKS" ]]; then
echo "ALL HOOK ACCEPTANCE CHECKS PASSED ($n_checks/$EXPECTED_CHECKS)"
else echo "$fails CHECK(S) FAILED, $n_checks/$EXPECTED_CHECKS executed"; exit 1
fi