Compare commits

..
7 Commits
Author SHA1 Message Date
AlexKucera a3ef007562 test(session): finish-audit closeout for #184
CI / ci (pull_request) Canceled after 0s
CI / ci (push) Canceled after 0s
Three-reviewer fanout over PR #184's deferred nil-scope fix:

- pin the titled drain's APPLY half (unpinned suite-wide) over a new
  hangOnPromptLoad rig mode (prompt parks, load answers);
  flip-verified against a nil-only drain guard
- cut the dead Equatable on PendingScope (converged finding)
- name the same-turn pendingRestart ceiling on the drain: respawn's
  .starting window drops the consumed scope; consume-at-apply is the
  upgrade path (follow-up ticket)
- changelog + devlog for the PR; AGENTS.md rails refreshed

Suite 654 executed / 0 failed; swiftformat clean; swiftlint
unchanged (both warnings pre-exist on main).
2026-11-10 16:25:58 +01:00
AlexKucera 704e7a83fd fix(session): drain a deferred nil scope as an explicit clear
pendingScopePieceTitle: String? conflated 'no pending request' with a
pending request whose target is nil (the writer left the piece — New
Post, unsaved draft, external guest, nothing open). Both deferral
branches stored the target and the drain guarded on the optional, so a
deferred nil target was silently dropped: at turn end (sendPrompt,
runOneShot) or replay completion (resumeSession) the old piece's
activeEntry survived under a nothing-open context, contrary to the
scope contract (#176 class).

Pending-ness now rides PendingScope (none | scope(String?)) — a nil
target drains through scopeHostedSession like any titled target and
clears activeEntry. Titled deferrals and the immediate path are
unchanged.

Verified: SessionScopeTests 4/4 green (both RED pins now green in
45 ms — the clear lands at the drain, not a deadline); full unit bundle
653/653 green; swiftformat 0 files; swiftlint exit 0 (two pre-existing
warnings in MentorSessionModel.swift, unchanged kind).
2026-11-10 16:25:01 +01:00
AlexKucera 1b56b0d779 test(session): pin deferred nil scope lost at stream and replay drain
Leaving the piece mid-stream (New Post over a streaming reply) or
mid-replay defers a nil scope request like any switch, but the drain
guards on the optional title — an explicit nil target (clear) is
indistinguishable from no pending request, so activeEntry survives on
the old piece under a nothing-open context.

Two RED pins over the scripted rig: hangOnPrompt (stream parks, cancel
ends it, drain at sendPrompt turn end) and loadReplayHold (replay parks,
releaseHeldLoad completes it, drain at resume). Both fail on this base:
executed 4 / passed 2 / failed 2 (the two new pins).
2026-11-10 16:24:30 +01:00
AlexKucera a8b158ca26 refactor(profiles): one layout + config-set rail
CI / ci (push) Canceled after 0s
#182: ProfileLayout owns the profile root default and every per-profile
path (dir, .env, configured marker, gateway pid, skills dir) — the five
scattered profile-root literals are gone; the provisioner, the settings
writer, and backup/restore derive paths only through it, pinned once in
ProfileLayoutTests. RESTORE.md prose and the ps-scan grep keep their
literal text deliberately (doc text and argv matching, not paths).

HermesConfigRail owns the config set/unset contract once: argv shape
(+--force), provider-first hoisting (switching providers clears a stale
inherited base_url — a caller can no longer order it wrong), ✓-line
verification, unset-idempotence. The provisioner seeds provider/default/
max_tokens; the writer edits provider/default/effort/base_url — each
keeps its own key list, only the mechanism and ordering rule unify. The
rail's Failure carries key/profile/excerpt for both error surfaces.

Audit hardenings folded in: a leading-dash value refuses before any
spawn (free-text model/endpoint fields cannot reach the child CLI as
options), whitespace-only endpoints read as empty at both writer gates,
the deliberate 500-char excerpt cap is pinned not just commented, and
the failed-unset branch is pinned (the fake hermes grew a
config-unset-fails knob).

Full suite 684 passed / 0 failed; dash + whitespace pins flip-verified.

Closes #182
2026-11-10 11:32:47 +01:00
AlexKucera f49e4b6ca0 refactor(settings): provider facts as data
CI / ci (push) Canceled after 0s
#181: ModelProvider is the provider-descriptor table — label, effort
ladder, flagship, endpoint, env var joined by wire dialect (chat/models
paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's
header pair), keyless (nous rides the Portal login), and the ONE
trailing-slash endpoint trim. The probe's URL builders, auth headers,
and stream-decoder picks select by data; the per-dialect bodies and
decoders stay separate functions, not switch clothing.

ProviderCredential.resolve is the ONE credential rail (provider key,
else the shared Portal session key for keyless providers — official
endpoint ONLY, never a user-set URL). Settings' Test Connection and the
new PassReadiness module both call it; the twice-implemented #175
fallback can no longer drift. One deliberate tightening, reviewer-
blessed: a nous pass profile on a custom base_url with no pasted key now
reads missingKey where the old session-model fallback said ready — the
old copy had no endpoint gate at all.

Pass readiness leaves the session model (PassReadiness.swift maps each
pass surface to ready/missingKey/unknown over the descriptor;
MentorSessionModel stores the verdicts and reads no keys or auth
files). runPass and blindRead run their guards through one shared rail
(guardOpenPieceRun) — identical refusal strings, blockers named
honestly. No app-side model-settings store (ADR-0014 red line).

Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt
before releasing the held turn — runningPass flips before the one-shot
engine parks its prompt, so firing into that window false-failed under
parallel-suite load.

Full suite 668/668 (xcresult executed count). Finish-audit: three
reviewers (ponytail/security/general), zero findings above LOW; two
ponytail trims and one pin tightening applied.

Closes #181
2026-11-10 10:58:29 +01:00
AlexKucera 218e2db397 refactor(posts): one frontmatter read/write codec
CI / ci (push) Canceled after 0s
#180: one PostFrontmatter module now owns the lenient read
(parse/split/decoded) and every write posture — fresh stamp,
merge-import, update-keys — behind one known-key table (type,
pass_state, origin; one insertion order). The three near-twin walkers
are deleted byte-identically: PostStore.stamped/splitFrontmatter/
mergedFrontmatter, LearningDecay.stampingFrontmatter,
Post.frontmatter(of:) — 21 call sites swept across seven production
files and eight test files.

The Unaided First Draft eligibility is named once and consumed by both
gates: isUnaidedFirstDraftPair (writer ∧ post — the scan's read-back
gate) and isCaptureEligible (pair ∧ First Draft — the capture gate at
pass invocation). The lenient ?? default stamp decode is extracted
with it (the third copy's deferred extraction).

One deliberate divergence from the absorbed writer, doc-commented and
pinned: mergingImport now preserves hand-edit lines above the opening
--- on import where the old split-first shape silently dropped them —
lossless through every posture is the ticket's contract. Seven codec
pins (PostFrontmatterTests) cover the posture round-trip (foreign keys
verbatim through import → save → advance → micropub), the lenient
unknown-type decode, and the predicates' truth table.

Existing pieces are untouched on disk: every posture moved verbatim
and the full suite pins the byte shapes (664/664 green; the one
under-load flake in the #179 repoint pin is pre-existing on main,
proven by a stashed-tree control run).

Closes #180
2026-11-10 10:21:32 +01:00
AlexKucera 5bf09552f6 refactor(posts): route every library write through one rail
CI / ci (push) Canceled after 0s
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00
58 changed files with 2029 additions and 851 deletions

No files matched your search

+7 -4
View File
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (6752 symbols, 31140 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (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).
@@ -181,22 +181,25 @@ This project is indexed by GitNexus as **museion** (6752 symbols, 31140 relation
- 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)
- 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)
- 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)
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — avoid the wrap (nested ifs / a hoisted helper), don't fight the formatter (#142)
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — and the nested-if escape ALSO fails (swiftformat collapses it into one long line; line_length flags that). Hoist a predicate helper; that's the only stable shape (#142, #179)
- swiftformat's self-remove strips a load-bearing `self.` when a local hoists a property for a detached capture (`let x = self.x` becomes the self-referential `let x = x`) — rename the local so nothing shadows (#143)
- A `//` note sitting between a `///` doc block and its declaration detaches the doc (swiftlint orphaned_doc_comment) — fold such notes into the `///` block (#143)
- Sequential bounded-poll loops each arm their OWN deadline — a shared one starves the later loop, which then fails on the earlier flush's stale observable (zeros, never nil) (#147)
- A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147)
- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180)
- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181)
### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
- Post.frontmatter is LINE-BOUNDED on read — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (stampingFrontmatter), so gate external data before it reaches a stamp, not at scan (#33)
- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33)
## Session Logs
+10 -7
View File
@@ -25,8 +25,9 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the immutable pair (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.
- `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 `stampingFrontmatter` — 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 read from the file's own frontmatter (writer/First Draft/post); 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.
- `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.
@@ -35,14 +36,14 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). `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 (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal". `blindRead` mirrors the guards; 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`; 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).
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
- 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` — `ModelProvider` slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship `anthropic/claude-sonnet-5`, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). 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: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `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); 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot).
- 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.
- `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.
@@ -56,12 +57,14 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## Profile provisioning
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the engine's own CLI, provider first; success WIRE-VERIFIED `✓ Set` on stdout; marker-gated by `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
- `ProfileLayout.swift` — #182: the ONE owner of the Hermes profile layout: `defaultRoot` (`~/.hermes/profiles`) and the per-profile path builders (`profileDir`, `envFile(in:)`, `configuredMarker(in:)`, `gatewayPID(in:)`, `skillsDir(in:)`). The provisioner, the settings writer, and backup derive every path through it — no literal profile-root string lives outside (RESTORE.md prose and the ps-scan grep pattern are text, not paths; pinned in ProfileLayoutTests).
- `HermesConfigRail.swift` — #182: the ONE owner of the `hermes -p <profile> config set/unset` contract: argv shape (set value + `--force`), provider-first ordering (switching providers clears a stale inherited `model.base_url` — the rail hoists `model.provider` first, callers can't order it wrong), ✓-line verification (exit 0 AND `✓ Set`/`✓ Unset` on stdout; unset-of-absent = idempotent success). Callers hand it their own key lists: the provisioner seeds provider/default/max_tokens, the settings writer edits provider/default/effort/base_url. `Failure` carries key/profile/excerpt for both error surfaces; secrets never ride it (argv only carries non-secret keys).
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the HermesConfigRail — provider first, wire-verified; marker-gated by the layout's `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/`. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
## Profile backup
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours; profile + pid paths via ProfileLayout, #182); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
## museion-tools MCP server
@@ -74,7 +77,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `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.
- `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: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
- `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).
+2 -2
View File
@@ -422,7 +422,7 @@ nonisolated enum FixCardStore {
.sorted()
return files.compactMap { name in
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8),
LearningDecay.passesHidden(Post.frontmatter(of: markdown), currentPass: currentPass) == nil
LearningDecay.passesHidden(PostFrontmatter.parse(markdown), currentPass: currentPass) == nil
else { return nil }
return (file: name, markdown: markdown)
}
@@ -444,7 +444,7 @@ nonisolated enum FixCardStore {
for _ in 0 ..< 4 {
home.deleteLastPathComponent()
}
return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post)
return (home, PostFrontmatter.decoded(PostFrontmatter.parse(text)).type)
}
// MARK: - Promote (#26, S4.1/S4.3)
+5 -6
View File
@@ -149,7 +149,7 @@ private struct CardRow: View {
.controlSize(.small)
} else {
Button("Done") {
gate.posts.doneCard(card, home: gate.museionHome)
gate.posts.doneCard(card)
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -174,11 +174,11 @@ private struct CardRow: View {
// Apply = ask-before, a BLOCKING ask: the sheet is the only path
// from the Apply button to a write.
.sheet(isPresented: $asking) {
ApplyAskSheet(card: card, posts: gate.posts, home: gate.museionHome)
ApplyAskSheet(card: card, posts: gate.posts)
}
// #26: Promote is its own blocking ask — one confirm, one Learning.
.sheet(isPresented: $promoting) {
PromoteAskSheet(card: card, posts: gate.posts, home: gate.museionHome)
PromoteAskSheet(card: card, posts: gate.posts)
}
}
@@ -217,7 +217,7 @@ private struct SkipButton: View {
var body: some View {
Button("Skip") {
gate.posts.skipCard(card, home: gate.museionHome)
gate.posts.skipCard(card)
}
.buttonStyle(.borderless)
.controlSize(.small)
@@ -232,7 +232,6 @@ private struct SkipButton: View {
private struct ApplyAskSheet: View {
let card: FixCardStore.StoredFixCard
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
@State private var wentStale = false
@@ -289,7 +288,7 @@ private struct ApplyAskSheet: View {
}
private func apply() {
switch posts.applyCard(card, home: home) {
switch posts.applyCard(card) {
case .applied:
dismiss()
case .stale:
+94
View File
@@ -0,0 +1,94 @@
//
// HermesConfigRail.swift
// Museion
//
// #182: the ONE owner of the `hermes -p <profile> config set/unset` CLI
// contract — argv shape, provider-first ordering (switching providers
// clears stale inherited values — live-probed), and ✓-line verification.
// The provisioner (seeds provider/default/max_tokens) and the settings
// writer (edits provider/default/effort/base_url) hand the rail their own
// key lists; the mechanism and ordering rule live only here (pinned once
// in HermesConfigRailTests over the shared fake-hermes double).
//
// Secrets never ride this rail (`ps` reads live command lines) — it only
// ever carries provider/model/effort/base_url values.
//
import Foundation
nonisolated enum HermesConfigRail {
/// One CLI write: a set (key/value, `--force` for keys some engine
/// versions don't recognize), or an unset.
enum Write: Sendable {
case set(key: String, value: String, force: Bool)
case unset(key: String)
}
/// A wire-verified write that failed — structured so each caller keeps
/// its own error surface (the provisioner's Outcome excerpt; the
/// writer's `lastWriteError` text).
struct Failure: Error, Sendable, LocalizedError {
let verb: String
let key: String
let profile: String
let excerpt: String
var errorDescription: String? {
"couldn't \(verb) \(key) on \(profile): \(excerpt)"
}
}
/// Executes the ops provider-first, each wire-verified: exit 0 AND the
/// `✓ Set <key>` / `✓ Unset <key>` line on stdout — a CLI that exits 0
/// while writing nothing must not count as configured. An unset of an
/// absent key is idempotent success (exit 1 + the not-set line).
static func apply(_ writes: [Write], profile: String, binary: String, timeout: TimeInterval) throws {
// Provider first, relative order otherwise preserved: `config set
// model.provider` clears a stale inherited `model.base_url`, so
// everything after it sees the new provider.
let ordered = writes.filter(isProviderSet) + writes.filter { !isProviderSet($0) }
for write in ordered {
switch write {
case let .set(key, value, force):
// Trust boundary: free-text fields (model IDs, endpoints)
// feed this rail, and a leading `-` is an option to the
// child CLI, never a value — no legitimate value starts
// with a dash (learning #6's class: gate at the seam).
guard !value.hasPrefix("-") else {
throw Failure(verb: "set", key: key, profile: profile, excerpt: "value starts with '-' — not written")
}
var arguments = [binary, "-p", profile, "config", "set", key, value]
if force {
arguments.append("--force")
}
let run = EngineProbe.execute(arguments, timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw Failure(verb: "set", key: key, profile: profile, excerpt: excerpt(run))
}
case let .unset(key):
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw Failure(verb: "unset", key: key, profile: profile, excerpt: excerpt(run))
}
}
}
}
private static func isProviderSet(_ write: Write) -> Bool {
if case let .set(key, _, _) = write {
key == "model.provider"
} else {
false
}
}
/// Errors carry CLI output only — key-bearing text never reaches error
/// surfaces. #180 audit: the rail absorbed the two callers' excerpts and
/// keeps the provisioner's 500-char cap (the more-lossless twin; the
/// writer's old 300 was the outlier), a deliberate divergence.
static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
}
}
+27 -55
View File
@@ -79,7 +79,7 @@ struct NoopSettingsWriter: SettingsWriting {
struct HermesSettingsWriter: SettingsWriting {
let hermesBinary: String?
var profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath
var profileRoot: String = ProfileLayout.defaultRoot
struct WriteError: LocalizedError, Equatable {
let message: String
@@ -100,18 +100,24 @@ struct HermesSettingsWriter: SettingsWriting {
}
let binary = hermesBinary, profile = surface.profileName
try await Task.detached(priority: .utility) {
// Provider first (switching clears a stale base_url — probed),
// then the model, then effort, then the z.ai endpoint family.
try Self.setKey("model.provider", config.provider.rawValue, profile: profile, binary: binary, timeout: 30)
try Self.setKey("model.default", config.model, profile: profile, binary: binary, timeout: 30)
// The rail owns the mechanism and the provider-first rule (#182):
// provider (switching clears a stale base_url — probed), then the
// model, then effort (set or unset), then the z.ai endpoint family.
var ops: [HermesConfigRail.Write] = [
.set(key: "model.provider", value: config.provider.rawValue, force: false),
.set(key: "model.default", value: config.model, force: false),
]
if let effort = config.effort {
try Self.setKey("model.reasoning_effort", effort.rawValue, profile: profile, binary: binary, timeout: 30)
ops.append(.set(key: "model.reasoning_effort", value: effort.rawValue, force: false))
} else {
try Self.unsetKey("model.reasoning_effort", profile: profile, binary: binary, timeout: 30)
ops.append(.unset(key: "model.reasoning_effort"))
}
if let zaiEndpoint, !zaiEndpoint.isEmpty {
try Self.setKey("model.base_url", zaiEndpoint, profile: profile, binary: binary, timeout: 30)
// Whitespace-only = empty (learning #6: mirror the trimmed
// emptiness the model side validates, not raw isEmpty).
if let zaiEndpoint, !zaiEndpoint.trimmingCharacters(in: .whitespaces).isEmpty {
ops.append(.set(key: "model.base_url", value: zaiEndpoint, force: false))
}
try HermesConfigRail.apply(ops, profile: profile, binary: binary, timeout: 30)
}.value
}
@@ -128,7 +134,9 @@ struct HermesSettingsWriter: SettingsWriting {
config: ProviderKeyConfig,
profiles: [ProfileSurface],
) async throws {
let writesBaseURL = provider == .zai && !config.endpoint.isEmpty
// Whitespace-only endpoint/key = empty (learning #6: trimmed
// emptiness, never raw isEmpty, at free-text gates).
let writesBaseURL = provider == .zai && !config.endpoint.trimmingCharacters(in: .whitespaces).isEmpty
if writesBaseURL, hermesBinary == nil {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
@@ -137,14 +145,19 @@ struct HermesSettingsWriter: SettingsWriting {
let binary = hermesBinary
try await Task.detached(priority: .utility) {
for surface in ProfileSurface.allCases {
let dir = (root as NSString).appendingPathComponent(surface.profileName)
let dir = ProfileLayout.profileDir(surface.profileName, root: root)
if !key.isEmpty {
try Self.upsertEnvFile(varName: varName, value: key, profileDir: dir, profile: surface.profileName)
}
}
if let endpoint, let binary {
for surface in profiles {
try Self.setKey("model.base_url", endpoint, profile: surface.profileName, binary: binary, timeout: 30)
try HermesConfigRail.apply(
[.set(key: "model.base_url", value: endpoint, force: false)],
profile: surface.profileName,
binary: binary,
timeout: 30,
)
}
}
}.value
@@ -185,8 +198,7 @@ struct HermesSettingsWriter: SettingsWriting {
let root = profileRoot, varName = provider.envVarName
return await Task.detached(priority: .utility) { () -> String? in
for surface in ProfileSurface.allCases {
let envPath = ((root as NSString).appendingPathComponent(surface.profileName) as NSString)
.appendingPathComponent(".env")
let envPath = ProfileLayout.envFile(in: ProfileLayout.profileDir(surface.profileName, root: root))
guard let text = try? String(contentsOfFile: envPath, encoding: .utf8) else { continue }
for line in text.split(separator: "\n") where line.hasPrefix("\(varName)=") {
let value = line.dropFirst("\(varName)=".count).trimmingCharacters(in: .whitespaces)
@@ -199,46 +211,6 @@ struct HermesSettingsWriter: SettingsWriting {
}.value
}
// MARK: CLI rail (wire-verified, the provisioner's posture) — nonisolated:
// they run inside Task.detached, off the actor.
private nonisolated static func setKey(
_ key: String,
_ value: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "set", key, value], timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw WriteError(message: "couldn't set \(key) on \(profile): \(excerpt(run))")
}
}
private nonisolated static func unsetKey(
_ key: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
// Absent already = the desired state (idempotent; exit 1 + not-set line).
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw WriteError(message: "couldn't unset \(key) on \(profile): \(excerpt(run))")
}
}
/// Secrets never ride argv (`ps` reads live command lines) — this rail
/// only ever carries provider/model/effort/base_url. Errors keep the
/// same guarantee: excerpt content is CLI output, key text never
/// reaches `lastWriteError`.
private nonisolated static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))
}
// MARK: .env edit
/// Upsert `VAR=value` preserving every other line (hermes' own .env
@@ -272,7 +244,7 @@ struct HermesSettingsWriter: SettingsWriting {
}
envWriteLock.lock()
defer { envWriteLock.unlock() }
let envPath = (profileDir as NSString).appendingPathComponent(".env")
let envPath = ProfileLayout.envFile(in: profileDir)
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
let updated = upsertEnv(varName: varName, value: value, in: existing)
do {
+5 -47
View File
@@ -160,7 +160,7 @@ nonisolated enum LearningDecay {
throw FixCardStore.CardError(message: "learning not found: \(file)")
}
let frontmatter = Post.frontmatter(of: text)
let frontmatter = PostFrontmatter.parse(text)
let clock = passCounts(home: home)[typeDir] ?? 0
if let remaining = passesHidden(frontmatter, currentPass: clock) {
throw FixCardStore.CardError(message: "already dismissed — resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes")")
@@ -168,8 +168,10 @@ nonisolated enum LearningDecay {
// Clamped before +1 — an absurd hand-edited dismiss_count must not
// trap the stamp.
let count = min(dismissCount(in: frontmatter), valueCeiling)
let stamped = stampingFrontmatter(
of: text,
// #180: the codec's update-keys posture (the mechanical walk this
// file used to own); the Learning document shape is unchanged.
let stamped = PostFrontmatter.updating(
text: text,
with: [
("dismissed", FixCardStore.formatted(now, "yyyy-MM-dd")),
("dismiss_count", "\(count + 1)"),
@@ -178,48 +180,4 @@ nonisolated enum LearningDecay {
)
try stamped.write(to: url, atomically: true, encoding: .utf8)
}
/// The surgical frontmatter rewrite (mergedFrontmatter's line-walk,
/// generalized to ordered pairs): set-overwrite the keys in place,
/// insert absent ones before the closing `---`, preserve every other
/// line verbatim (leading hand-edit lines above the opening `---`
/// included), keep the block's trailing newline. No frontmatter
/// block at all → prepend a fresh one. Internal since #31: the
/// first-draft stats capture is the third caller.
// ponytail: PostStore.mergedFrontmatter's line-walk duplicated and
// generalized — extraction would grow PostStore at its type-body
// ceiling; #31's capture is the third caller and it STILL isn't
// extracted (LearningDecay + PostStore stay the two owners; the
// type-body ceilings named above are unchanged).
static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String {
let (block, body) = PostStore.splitFrontmatter(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
}
// Lines ABOVE the opening `---` (a hand-edit blank line —
// Post.frontmatter tolerates one) fall in neither block nor
// body; keep them verbatim so the rewrite loses nothing (#27 review).
let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? ""
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return prefix + lines.joined(separator: "\n") + "\n" + body
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ nonisolated enum LearningsIndex {
let resurfacesIn: Int?
init(file: String, text: String, currentPass: Int? = nil) {
let frontmatter = Post.frontmatter(of: text)
let frontmatter = PostFrontmatter.parse(text)
id = file
pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file)
problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 }
+5 -6
View File
@@ -92,7 +92,7 @@ struct MentorPaneView: View {
// Pass 2 selector replaced the mode picker; the transcript +
// composer below are the conversation surface, chat is not a
// mode.
PassBarView(posts: posts, home: home, model: model, onOpenSettings: onOpenSettings)
PassBarView(posts: posts, model: model, onOpenSettings: onOpenSettings)
Divider()
if let posts, !posts.openPieceCards.isEmpty {
// #23 follow-up + #156 ruling: a plain mono row — a link,
@@ -385,7 +385,6 @@ private struct PassBarView: View {
/// The selected pass — the bar's own state (nothing outside reads it).
@State private var kind: PassKind = .pass1
let posts: PostsModel?
let home: URL?
let model: MentorSessionModel
/// #137 (S4): the missing-key line's way out — WorkspaceView's pane hop.
let onOpenSettings: (() -> Void)?
@@ -547,8 +546,8 @@ private struct PassBarView: View {
}
private func runPass() {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
guard let posts else { return }
Task { await posts.runPass(kind, mentor: model) }
}
/// #122: the Blind Read — one purposeful click judges the current
@@ -560,8 +559,8 @@ private struct PassBarView: View {
style: .secondary,
disabled: blindReadBlocked != nil,
) {
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
guard let posts else { return }
Task { await posts.blindRead(mentor: model) }
}
.help(
blindReadBlocked
+22 -61
View File
@@ -289,13 +289,17 @@ final class MentorSessionModel {
}
private var pendingScope: PendingScope = .none
/// #137: per-pass readiness (refreshPassReadiness, same-file #137
/// extension) + the injectable read seam (tests). Stored in the class
/// body — extensions carry no stored state.
/// #137: per-pass readiness — refreshed at pane entry (re-entry
/// re-fires the pane's .task — the key-added-in-Settings re-enable
/// path). #181: computed in the PassReadiness module over the provider
/// descriptor (the model reads no keys and no auth files); stored here
/// because the pane observes it. `passReadinessWriter` is the
/// injectable read seam (tests).
private(set) var passReadiness: [PassKind: PassReadiness] = [:]
var passReadinessWriter: (any SettingsWriting)?
/// #175: the shared Portal auth store for the nous keyless readiness
/// fallback — injectable so tests never read the machine's real login.
/// #175: the shared Portal auth store — handed to the readiness
/// module's credential resolution; injectable so tests never read the
/// machine's real login.
var portalAuthPath: String = PortalAuth.defaultAuthPath
/// The gate's winning binary path (no re-probe — map decision). Set by
@@ -720,69 +724,26 @@ extension MentorSessionModel {
host.isOneShotRunning
}
/// #137 (S4): the Run Pass posture — is the pass profile's provider
/// keyed? .unknown NEVER blocks (our own read failure — the spawn's
/// honest failure row owns that path); .missingKey names the provider
/// so the pane can say what's missing and link to Settings.
enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
}
// Per-pass readiness (stored in the class body), refreshed at pane
// entry (re-entry re-fires the pane's .task — the key-added-in-
// Settings re-enable path). `passReadinessWriter` is the injectable
// read seam; nil at refresh time → an ad-hoc HermesSettingsWriter
// over the gate's binary (profileRoot default).
// #137 (S4): the Run Pass posture — is the pass profile's provider
// keyed? .unknown NEVER blocks (our own read failure — the spawn's
// honest failure row owns that path); .missingKey names the provider
// so the pane can say what's missing and link to Settings.
// #181: the enum and the refresh live in the PassReadiness module.
func readiness(for kind: PassKind) -> PassReadiness {
passReadiness[kind] ?? .unknown
}
/// Read each pass profile's provider (readSurface, one task group),
/// then each DISTINCT provider's key (readProviderKey). A surface we
/// can't read maps .unknown; a non-empty key maps .ready; no key maps
/// .missingKey with the provider's label. No binaryPath and no
/// injected writer → readiness stays empty (.unknown everywhere).
/// #181: thin delegate — the reads and the keyless fallback live in
/// the PassReadiness module over the provider descriptor. No
/// binaryPath and no injected writer → readiness stays empty
/// (.unknown everywhere).
func refreshPassReadiness() async {
guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return }
var providers: [ProfileSurface: ModelProvider] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in [ProfileSurface.pass1, .pass2] {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
providers[surface] = read?.config.provider
}
}
var keys: [ModelProvider: String] = [:]
for provider in Set(providers.values.compactMap(\.self)) {
var key = await (try? writer.readProviderKey(provider: provider)) ?? ""
// #175: nous runs on the shared Portal login — an empty `.env`
// key is not a blocker when the session's agent_key exists (the
// engine's own credential; API key and subscription bill the
// same account credits).
if provider == .nous, key.isEmpty {
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
}
keys[provider] = key
}
for surface in [ProfileSurface.pass1, .pass2] {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let provider = providers[surface] else {
passReadiness[kind] = .unknown
continue
}
if let key = keys[provider], !key.isEmpty {
passReadiness[kind] = .ready
} else {
passReadiness[kind] = .missingKey(providerLabel: provider.label)
}
}
passReadiness = await PassReadiness.refresh(
writer: writer,
portalAuthPath: portalAuthPath,
)
}
/// Send a prompt and stream the reply into the ACTIVE session's
+5 -3
View File
@@ -244,8 +244,9 @@ extension PostsModel {
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
home: URL,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
@@ -266,12 +267,13 @@ 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 dir = PostStore.folder(of: id, home: home),
guard let home = watchedHome,
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.")
}
let body = PostStore.splitFrontmatter(raw).body
let body = PostFrontmatter.split(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
+1 -2
View File
@@ -17,7 +17,6 @@ import SwiftUI
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
@@ -162,7 +161,7 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = .drafting
Task {
switch await posts.micropubSendDraft(home: home, token: token) {
switch await posts.micropubSendDraft(token: token) {
case let .drafted(url, preview):
draftURL = url
previewURL = preview
+79
View File
@@ -0,0 +1,79 @@
//
// PassReadiness.swift
// Museion
//
// ## Scenario: pass readiness over the provider descriptor
// From #181
//
// Given the pass profiles' providers read through the settings seam
// When pass readiness refreshes
// Then each pass surface maps to ready / missingKey / unknown through the
// ONE credential resolution (provider key, else the Portal session key
// for keyless providers) — the session model stores the verdicts and
// itself reads no keys and no auth files.
import Foundation
/// #181: per-pass readiness — ready / missingKey / unknown, computed
/// over the provider descriptor. Formerly the session model's #137
/// nested enum: the profile reads (surface provider, `.env` key, Portal
/// auth store) live HERE now; MentorSessionModel stores the verdicts its
/// pane observes.
nonisolated enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
/// Read each pass surface's provider (readSurface, one task group),
/// then resolve each DISTINCT provider's credential through the ONE
/// rail (ProviderCredential — provider key, else the Portal session
/// key for keyless providers). A surface we can't read maps .unknown
/// (our own read failure never blocks — the spawn's honest failure row
/// owns that path); a refused credential maps .missingKey naming the
/// provider. Nil/empty `base_url` means the provider's default family
/// (the family the session key is allowed to ride).
static func refresh(
writer: any SettingsWriting,
portalAuthPath: String,
) async -> [PassKind: PassReadiness] {
let surfaces = [ProfileSurface.pass1, .pass2]
var reads: [ProfileSurface: (config: SurfaceModelConfig, baseURL: String?)] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in surfaces {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
if let read {
reads[surface] = read
}
}
}
var envKeys: [ModelProvider: String] = [:]
for provider in Set(reads.values.map(\.config.provider)) {
envKeys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? ""
}
var verdicts: [PassKind: PassReadiness] = [:]
for surface in surfaces {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let read = reads[surface] else {
verdicts[kind] = .unknown
continue
}
let provider = read.config.provider
let endpoint = read.baseURL.flatMap { $0.isEmpty ? nil : $0 } ?? provider.defaultEndpoint
switch await ProviderCredential.resolve(
provider: provider,
envKey: envKeys[provider] ?? "",
endpoint: endpoint,
portalAuthPath: portalAuthPath,
) {
case .key:
verdicts[kind] = .ready
case .refused:
verdicts[kind] = .missingKey(providerLabel: provider.label)
}
}
return verdicts
}
}
+193
View File
@@ -0,0 +1,193 @@
//
// PostFrontmatter.swift
// Museion
//
// #180: the Post frontmatter codec — the ONE lenient read and the three
// write postures (fresh / merge-import / update-keys) behind one
// known-key table and one insertion-order rule. Absorbs and deletes the
// near-twin writers: PostStore.stamped (fresh), PostStore.mergedFrontmatter
// (merge-import), LearningDecay.stampingFrontmatter (update-keys) — each
// posture is byte-identical to the writer it replaced (merge-import's
// documented prefix-preservation divergence excepted), so existing pieces
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
// of scope (#180); their dismiss stamp rides the generic update posture
// without redesigning its shape.
//
import Foundation
/// #180: one engine for the flat `---`-delimited block every post.md
/// carries. Read leniently (absent or unknown keys decode to their
/// defaults — a bare legacy corpus post is a normal piece), written
/// through exactly three postures:
///
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
/// with our three owned keys winning in place (importFile, #95).
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
/// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss).
///
/// The known-key table and its stamp order (`type`, `pass_state`,
/// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order.
nonisolated enum PostFrontmatter {
/// The leniently-decoded identity triple — one home for the `?? default`
/// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this
/// fourth caller).
struct Stamp: Equatable {
let type: Post.ContentType
let passState: Post.PassState
let origin: Post.Origin
}
// MARK: - Read
/// The `---`-delimited frontmatter block's keys if present; empty
/// otherwise. Quoted scalar values (`origin: "ai"`) are unquoted —
/// lenient YAML. Values are line-bounded by construction (#33).
static func parse(_ text: String) -> [String: String] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] }
var map: [String: String] = [:]
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard let colon = trimmed.firstIndex(of: ":") else { continue }
let key = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func split(_ text: String) -> (block: String, body: String) {
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
all[open].trimmed() == "---",
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
else { return ("", text) }
let block = all[open ... close].joined(separator: "\n") + "\n"
return (block, all[(close + 1)...].joined(separator: "\n"))
}
/// The lenient stamp decode: absent or unknown keys read as their
/// defaults (post / First Draft / writer) — the same verdicts
/// `Post.scan`, `existingStamp`, and the capture gate must agree on.
static func decoded(_ matter: [String: String]) -> Stamp {
Stamp(
type: Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
passState: Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
origin: Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
)
}
// MARK: - Eligibility (#180: named once, consumed twice)
/// The Unaided First Draft immutable pair — writer origin ∧ post type
/// (CONTEXT.md). Never pass_state: that legitimately advances after a
/// capture. This is the pair the scan's read-back gate re-gates on, so
/// `stats_*` keys arriving by import on an ai or outline piece never
/// render, while a migrated writer piece keeps its real arc (#32).
static func isUnaidedFirstDraftPair(_ matter: [String: String]) -> Bool {
let stamp = decoded(matter)
return stamp.origin == .writer && stamp.type == .post
}
/// Unaided First Draft capture eligibility — the immutable pair ∧
/// Pass State First Draft. What the capture gate checks at pass
/// invocation against the file's own frontmatter (#31).
static func isCaptureEligible(_ matter: [String: String]) -> Bool {
let stamp = decoded(matter)
return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft
}
// MARK: - Write postures
/// The known-key table: Museion's three owned keys in stamp order —
/// the ONE insertion-order rule every posture shares.
static func ownedKeys(
type: Post.ContentType, passState: Post.PassState, origin: Post.Origin,
) -> [(key: String, value: String)] {
[
("type", type.rawValue),
("pass_state", passState.rawValue),
("origin", origin.rawValue),
]
}
/// Posture 1 — fresh: the #59 v1 block (+ `type`, #107). Flat keys,
/// the exact shape `parse` reads. Any existing block is replaced by
/// design (writeNew births, bare files normalize, convert rebuilds).
static func stamped(
body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post,
) -> String {
"---\n"
+ ownedKeys(type: type, passState: passState, origin: origin)
.map { "\($0.key): \($0.value)" }.joined(separator: "\n")
+ "\n---\n" + body
}
/// Posture 3 — update-keys: the surgical line-walk. Set-overwrite the
/// pairs in place, insert absent ones before the closing `---` (pair
/// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the
/// pairs.
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
let (block, body) = split(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
}
// Lines ABOVE the opening `---` (a hand-edit blank line — parse
// tolerates one) fall in neither block nor body; keep them verbatim
// so the rewrite loses nothing.
let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? ""
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
// ponytail: flat keys only — an indented `key: value` inside a
// nested YAML block scalar is matched and rewritten unindented;
// the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// if nested frontmatter ever matters.
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return prefix + lines.joined(separator: "\n") + "\n" + body
}
/// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post). The update posture over the known-key table.
///
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
/// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String {
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
}
}
+11 -31
View File
@@ -179,15 +179,14 @@ nonisolated struct Post: Identifiable, Equatable {
/// kept this a pure function of (text, location); the cache memoizes
/// its output, nothing else).
private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post {
let frontmatter = frontmatter(of: text)
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
let frontmatter = PostFrontmatter.parse(text)
let stamp = PostFrontmatter.decoded(frontmatter)
return Post(
id: id,
title: title(of: text),
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
origin: origin,
type: type,
passState: stamp.passState,
origin: stamp.origin,
type: stamp.type,
project: project,
isArchived: isArchived,
// #33: the remembered Micro.blog draft URL —
@@ -199,37 +198,18 @@ nonisolated struct Post: Identifiable, Equatable {
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #32 read-back gate: the capture gate's immutable
// pair (origin writer, type post) — NOT pass_state,
// which legitimately advances after the capture.
// `stats_*` keys can arrive by import (external YAML
// rides verbatim), so an imported ai piece or outline
// #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which
// legitimately advances after the capture. `stats_*`
// keys can arrive by import (external YAML rides
// verbatim), so an imported ai piece or outline
// carrying hand-stamped keys still never renders;
// a migrated writer piece keeps its real arc.
firstDraftStats: origin == .writer && type == .post
firstDraftStats: PostFrontmatter.isUnaidedFirstDraftPair(frontmatter)
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
)
}
/// The `---`-delimited frontmatter block if present; empty otherwise.
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
static func frontmatter(of text: String) -> [String: String] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] }
var map: [String: String] = [:]
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard let colon = trimmed.firstIndex(of: ":") else { continue }
let key = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
+31 -95
View File
@@ -154,7 +154,7 @@ nonisolated enum PostStore {
origin: Post.Origin = .writer, home: URL,
) throws -> Post {
try materialize(
text: stamped(body: body, passState: .firstDraft, origin: origin, type: type),
text: PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: origin, type: type),
title: Post.title(of: body),
origin: origin,
project: project,
@@ -181,11 +181,10 @@ nonisolated enum PostStore {
raw.removeFirst()
}
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let (block, body) = splitFrontmatter(raw)
let text = mergedFrontmatter(keeping: block, origin: origin) + body
let text = PostFrontmatter.mergingImport(text: raw, origin: origin)
return try materialize(
text: text,
title: Post.title(of: body),
title: Post.title(of: PostFrontmatter.split(raw).body),
origin: origin,
project: project,
type: .post, // #95: our keys win — external `type: outline` still imports as post
@@ -193,48 +192,6 @@ nonisolated enum PostStore {
)
}
/// #95/#107: external frontmatter keys ride along verbatim; `type`,
/// `pass_state` and `origin` are set/overwritten in place — our three
/// keys win, everything else untouched. Absent keys are inserted before
/// the closing `---` (in that order). Returns the block INCLUDING its
/// trailing newline; "" for a bare file (the caller then writes the #59
/// stamp shape via a fresh block).
private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
guard !block.isEmpty else {
return "---\ntype: post\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
}
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
// #107: three our-keys win — type/pass_state/origin set-overwrite in
// place, absent ones insert before the closing --- in stamp order.
// Ordered pairs (a Dictionary's iteration order is unspecified).
let ours: [(key: String, value: String)] = [
("type", "post"),
("pass_state", Post.PassState.firstDraft.rawValue),
("origin", origin.rawValue),
]
let oursByKey = Dictionary(ours.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = ours.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return lines.joined(separator: "\n") + "\n"
}
/// #62/#95: lazily materialize `projects/<project>/<slug>/post.md` with
/// the given (already stamped/merged) text. Shared by `writeNew` and
/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
@@ -275,7 +232,7 @@ nonisolated enum PostStore {
/// file's present `pass_state`/`origin`/`type` are preserved (origin
/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59).
/// **#31 audit fix: blocked files update the three owned keys IN PLACE
/// (stampingFrontmatter) and swap in the caller's body — the old
/// (PostFrontmatter.updating) and swap in the caller's body — the old
/// stamped() round-trip rebuilt the block from three parsed fields,
/// erasing the first-draft stats captured at the pass invocation and
/// any foreign frontmatter on every editor save.** A vanished post
@@ -284,13 +241,14 @@ nonisolated enum PostStore {
static func overwrite(id: String, body: String, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostStore.splitFrontmatter(LearningDecay.stampingFrontmatter(of: raw, with: [
("type", piece.type.rawValue),
("pass_state", piece.passState.rawValue),
("origin", piece.origin.rawValue),
])).block + body
// #180: the codec's postures — bare files take the fresh stamp,
// blocked files update the owned keys in place (the update walk)
// and swap in the caller's body.
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostFrontmatter.split(PostFrontmatter.updating(text: raw, with: PostFrontmatter.ownedKeys(
type: piece.type, passState: piece.passState, origin: piece.origin,
))).block + body
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -307,13 +265,14 @@ nonisolated enum PostStore {
else {
throw CocoaError(.fileReadNoSuchFile)
}
let matter = Post.frontmatter(of: existing)
let matter = PostFrontmatter.parse(existing)
let stamp = PostFrontmatter.decoded(matter)
return (
dir,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
splitFrontmatter(existing).body,
stamp.passState,
stamp.origin,
stamp.type,
PostFrontmatter.split(existing).body,
)
}
@@ -323,7 +282,7 @@ nonisolated enum PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return nil }
return splitFrontmatter(text).body
return PostFrontmatter.split(text).body
}
/// #114 (S4): Convert to Post — the one-time in-place transform. The
@@ -334,7 +293,7 @@ nonisolated enum PostStore {
static func convert(id: String, headingsLadder: Bool, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let transformed = headingsLadder ? OutlineTree.headingsLadderBody(piece.body) : piece.body
try stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
try PostFrontmatter.stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -349,7 +308,7 @@ nonisolated enum PostStore {
}
let fileURL = dir.appendingPathComponent("post.md")
let text = try String(contentsOf: fileURL, encoding: .utf8)
let (block, body) = splitFrontmatter(text)
let (block, body) = PostFrontmatter.split(text)
try (block + replacingTitleLine(of: body, with: "# \(title)"))
.write(to: fileURL, atomically: true, encoding: .utf8)
@@ -517,24 +476,6 @@ nonisolated enum PostStore {
return trimmed
}
/// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the
/// #17 reader parses.
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String {
"---\ntype: \(type.rawValue)\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func splitFrontmatter(_ text: String) -> (block: String, body: String) {
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
all[open].trimmed() == "---",
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
else { return ("", text) }
let block = all[open ... close].joined(separator: "\n") + "\n"
return (block, all[(close + 1)...].joined(separator: "\n"))
}
/// Replace the body's Title heading with `line`; a body whose first
/// non-empty line is NOT a heading keeps that line (it's content) and
/// gets the heading inserted above it. An empty body becomes just `line`.
@@ -605,7 +546,7 @@ nonisolated extension PostStore {
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
/// on a Pass-2 Done piece never regresses it. **#31 (S5.1): the state
/// update is an IN-PLACE key stamp (stampingFrontmatter), not the
/// update is an IN-PLACE key stamp (PostFrontmatter.updating), not the
/// existingStamp→stamped block rewrite — the rewrite carried only
/// type/pass_state/origin and silently erased the first-draft stats
/// captured at the invocation (and any foreign frontmatter).** Bare
@@ -615,9 +556,9 @@ nonisolated extension PostStore {
let piece = try existingStamp(id: id, home: home)
let advanced = higherState(piece.passState, kind.doneState)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: LearningDecay.stampingFrontmatter(of: raw, with: [("pass_state", advanced.rawValue)])
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: PostFrontmatter.updating(text: raw, with: [("pass_state", advanced.rawValue)])
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
// The decay clock counts completed passes per content type (#27).
// try?: a failed clock bump must never fail a completed pass, and
@@ -708,7 +649,7 @@ nonisolated extension PostStore {
/// own frontmatter alone (same lenient defaults as Post.scan — a bare
/// legacy post qualifies): origin writer, Pass State First Draft, type
/// post. Not eligible → false, file untouched. The stamp is in place
/// (stampingFrontmatter): every non-stats line byte-identical, so a
/// (PostFrontmatter.updating): every non-stats line byte-identical, so a
/// re-invocation while still First Draft overwrites — latest draft
/// state wins. Any read/write failure → false: a failed capture must
/// never fail the pass (the decay-clock posture).
@@ -717,16 +658,11 @@ nonisolated extension PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let matter = Post.frontmatter(of: text)
// ponytail: third copy of the lenient `?? default` stamp decode
// (Post.scan, existingStamp) — extract one shared decode when a
// fourth caller needs it.
guard Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer == .writer,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft == .firstDraft,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post == .post
else { return false }
// #180: the named capture predicate — pair ∧ First Draft, leniently
// decoded (a bare legacy post qualifies).
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body)
let stamped = LearningDecay.stampingFrontmatter(of: text, with: [
let stamped = PostFrontmatter.updating(text: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
@@ -752,7 +688,7 @@ nonisolated extension PostStore {
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try LearningDecay.stampingFrontmatter(of: raw, with: [("micropub_url", url)])
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
.write(to: file, atomically: true, encoding: .utf8)
}
}
+100 -94
View File
@@ -12,6 +12,11 @@
// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching
// + rescan sit in the file-scope watcher extension below (type-body
// ceiling).
// #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.
//
import CoreServices
@@ -171,8 +176,11 @@ 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?
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
/// #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()
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
/// post.md files, not the library (see PostScanCache).
@@ -196,6 +204,33 @@ final class PostsModel {
// 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
}
}
/// #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.
@@ -260,11 +295,10 @@ final class PostsModel {
/// 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. Rescans immediately (the watcher
/// would too, after its window).
func saveDraft(home: URL) {
/// writer keeps typing where they were. #179: the write rides the rail.
func saveDraft() {
guard let draft else { return }
do {
performWrite { home in
let post = try PostStore.writeNew(body: draft.text, project: draft.project, type: draft.type, home: home)
lastDraftWasOutline = draft.type == .outline // #109: covers the lagging rescan
self.draft = nil
@@ -272,10 +306,6 @@ final class PostsModel {
selectedPostID = post.id
session = EditorSession(postID: post.id, home: home)
wireSession()
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -283,18 +313,16 @@ final class PostsModel {
/// draft stamped `origin: ai` (never stats-eligible) and open it in
/// Posts (select's open path; the WorkspaceView selection onChange
/// hops the pane). Nil + lastError on failure; Cancel never gets here.
/// #179: the write rides the rail.
@discardableResult
func newPostFromSession(body: String, home: URL) -> Post? {
do {
func newPostFromSession(body: String) -> Post? {
var written: Post?
performWrite { home in
let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
select(post.id, home: home)
lastError = nil
Task { await rescan() }
return post
} catch {
lastError = error.localizedDescription
return nil
written = post
select(post.id)
}
return written
}
/// Select a Post; selecting anything abandons an unsaved draft (the
@@ -306,7 +334,8 @@ final class PostsModel {
/// fires the mixed-content guard — the open is held (routing stays
/// prose) until the writer picks. The old session still ends here:
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String, home: URL) {
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
dismissExternal()
// 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
@@ -318,7 +347,7 @@ final class PostsModel {
if let session {
session.teardown(flushFirst: true)
}
if isGuardedOutline(id, home: home) {
if isGuardedOutline(id) {
outlineGuardPieceID = id
proseOverridePostID = nil
session = nil
@@ -326,13 +355,13 @@ final class PostsModel {
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards(home: home) // #23: nil session — the held ask shows no cards
refreshCards() // #23: nil session — the held ask shows no cards
return
}
// The prior session was torn down above; openUnguarded's guards
// are dead code on this path (session is nil or a different id) —
// kept: one open body answers select and the ask alike.
openUnguarded(id, home: home)
openUnguarded(id)
proseOverridePostID = nil // #111: the override died with the open it covered
}
@@ -379,14 +408,14 @@ final class PostsModel {
/// 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. Sets lastError
/// on failure.
func rename(_ post: Post, to title: String, home: URL) {
/// 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 }
do {
performWrite { home in
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
@@ -395,18 +424,15 @@ final class PostsModel {
wireSession()
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// 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).
func trash(_ post: Post, home: URL) {
do {
/// #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
@@ -415,10 +441,6 @@ final class PostsModel {
session = nil
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -431,16 +453,12 @@ final class PostsModel {
newPost()
}
/// #108: raw create — the sheet composes on it. The failure reason on
/// false (shown inline in the sheet; never routed into lastError — the
/// strip behind the sheet must not double-message one error).
func createProject(named name: String, home: URL) -> String? {
do {
try PostStore.createProject(named: name, home: home)
return nil // success
} catch {
return error.localizedDescription
}
/// #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).
@@ -457,7 +475,8 @@ final class PostsModel {
/// 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(home: URL) -> [String] {
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(".") })
@@ -493,27 +512,25 @@ final class PostsModel {
/// #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.
func moveToProject(_ post: Post, project: String, home: URL) {
/// #179: the write rides the rail.
func moveToProject(_ post: Post, project: String) {
guard flushOrAbort(post.id) else { return }
do {
performWrite { home in
try PostStore.move(post, to: project, home: home)
if session?.postID == post.id {
session = EditorSession(postID: post.id, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #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).
func archivePost(_ post: Post, home: URL) {
/// the Archive pane, where they're listed). #179: the write rides the
/// rail.
func archivePost(_ post: Post) {
guard flushOrAbort(post.id) else { return }
do {
performWrite { home in
try PostStore.archive(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
@@ -522,10 +539,6 @@ final class PostsModel {
open.teardown(flushFirst: false) // already flushed above
session = nil
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -533,20 +546,17 @@ final class PostsModel {
/// 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.
func restorePost(_ post: Post, home: URL) {
/// #179: the write rides the rail.
func restorePost(_ post: Post) {
guard flushOrAbort(post.id) else { return }
do {
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, home: home)
select(post.id)
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -554,14 +564,16 @@ final class PostsModel {
/// 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).
func unarchiveProject(_ name: String, home: URL) {
/// #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.
/// #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: home)?.deletingLastPathComponent(),
let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(),
projectDir.lastPathComponent == name,
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
else { return nil }
@@ -572,16 +584,12 @@ final class PostsModel {
// #108 audit 2: the only #108 folder move that skipped the gate.
guard flushOrAbort(openID) else { return }
}
do {
performWrite { home in
try PostStore.unarchiveProject(name, home: home)
if let openID {
session = EditorSession(postID: openID, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -644,28 +652,26 @@ final class PostsModel {
/// 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).
func importFiles(origin: Post.Origin, home: URL) {
/// 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?
var failures = 0
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
} catch {
failures += 1
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
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, home: home)
select(last.id)
}
if failures == 0 {
lastError = nil
}
Task { await rescan() }
}
/// #146: internal — the split-out domain extensions wire sessions too.
@@ -739,6 +745,6 @@ extension PostsModel {
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards(home: home)
refreshCards()
}
}
+15 -13
View File
@@ -20,8 +20,11 @@ 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.
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
func refreshCards() {
guard let id = session?.postID,
let home = watchedHome,
let folder = PostStore.folder(of: id, home: home)
else {
openPieceCards = []
openPieceHasSnapshot = false
return
@@ -68,7 +71,7 @@ extension PostsModel {
/// flags the card and touches no text. A failed close after a landed
/// edit is reported via lastError, never silent.
@discardableResult
func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome {
func applyCard(_ card: FixCardStore.StoredFixCard) -> FixCardApplyOutcome {
guard card.status == .open else { return .refused("card already closed") }
guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") }
guard let session, let postID = session.postID else {
@@ -86,30 +89,29 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
refreshCards()
return .stale
}
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
closeCard(card, status: .applied, home: home)
closeCard(card, status: .applied)
return .applied
}
/// #25 (S3.3): Skip — not this instance. Closes the card recording
/// NOTHING beyond the status flip (CONTEXT.md).
func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .skipped, home: home)
func skipCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .skipped)
}
/// #25 (S3.3): Done — the writer rewrote the span themselves. Same
/// flip, different terminal.
func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .done, home: home)
func doneCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .done)
}
private func closeCard(
_ card: FixCardStore.StoredFixCard,
status: FixCardStore.StoredFixCard.Status,
home: URL,
) {
guard let session else {
lastError = "open the piece to work its cards"
@@ -120,7 +122,7 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards(home: home)
refreshCards()
}
}
@@ -140,7 +142,7 @@ extension PostsModel {
/// counter; the store guarantees the one-stamp rule). Touches no text
/// and flushes nothing: this writes a Learning, not an edit.
@discardableResult
func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome {
func promoteCard(_ card: FixCardStore.StoredFixCard) -> FixCardPromoteOutcome {
guard card.promotedAt == nil else { return .refused("card already promoted") }
guard let session else { return .refused("open the piece to work its cards") }
do {
@@ -149,7 +151,7 @@ extension PostsModel {
lastError = "learning write failed: \(error.localizedDescription)"
return .refused("learning write failed: \(error.localizedDescription)")
}
refreshCards(home: home)
refreshCards()
return .promoted
}
}
+35 -27
View File
@@ -21,33 +21,34 @@ extension PostsModel {
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
/// both. No watched home yet (pre-bind) = post: nothing to guard.
/// #146: internal — `select` (PostsModel.swift) asks the guard.
func isGuardedOutline(_ id: String, home: URL) -> Bool {
guard let dir = PostStore.folder(of: id, home: home),
func isGuardedOutline(_ id: String) -> Bool {
guard let home = watchedHome,
let dir = PostStore.folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
known
} else {
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
PostFrontmatter.decoded(PostFrontmatter.parse(text)).type
}
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
return type == .outline && OutlineTree.parsesWithLoss(PostFrontmatter.split(text).body)
}
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
/// outliner never mounts, nothing drops); Outline = explicit consent,
/// opens the outliner (saves normalize/drop as today). Cancel = back
/// out (no session); the piece stays guarded on the next open.
func openGuardedOutlineInProse(home: URL) {
func openGuardedOutlineInProse() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id, home: home)
openUnguarded(id)
}
func openGuardedOutlineAsOutline(home: URL) {
func openGuardedOutlineAsOutline() {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id, home: home)
openUnguarded(id)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
@@ -64,7 +65,8 @@ extension PostsModel {
/// explicit choice the ruling requires.
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String, home: URL) {
func openUnguarded(_ id: String) {
guard let home = watchedHome else { return }
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
@@ -76,7 +78,7 @@ extension PostsModel {
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards(home: home) // #23: the newly opened piece's cards, now
refreshCards() // #23: the newly opened piece's cards, now
}
}
@@ -95,12 +97,14 @@ extension PostsModel {
/// The open session's text is the truth when the piece is open — disk
/// lags the debounce, and a stale-clean read would drop the warning
/// for prose typed since the last flush (#114 audit).
func stageConversion(_ post: Post, home: URL) {
func stageConversion(_ post: Post) {
guard post.type == .outline else { return }
let body: String = if let session, session.postID == post.id {
session.text
} else {
} else if let home = watchedHome {
PostStore.readBody(id: post.id, home: home) ?? ""
} else {
""
}
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
}
@@ -110,40 +114,44 @@ extension PostsModel {
pendingConversion = nil
}
/// #114 audit: consent recheck — the sheet's warning covered the STAGED
/// body; if the answer-time body went lossy behind the ask (foreign
/// write, late edit) and the writer was never warned, Headings would
/// drop unconsented prose.
private func conversionWentLossyBehindAsk(_ pending: PendingConversion, headingsLadder: Bool) -> Bool {
guard headingsLadder, !pending.lossy, let home = watchedHome,
let body = PostStore.readBody(id: pending.id, home: home)
else { return false }
return OutlineTree.parsesWithLoss(body)
}
/// #114 (S4): the answer. Flush-first when the piece is open (the
/// transform reads disk), flip `type` + transform the body once, then
/// reopen the session routed to prose — proseOverridePostID covers the
/// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that
/// isn't open just converts; nothing else moves. One-way in v1.
func convertToPost(headingsLadder: Bool, home: URL) {
/// #179: the write rides the rail.
func convertToPost(headingsLadder: Bool) {
guard let pending = pendingConversion else { return }
pendingConversion = nil
guard flushOrAbort(pending.id) else { return }
do {
// The sheet's warning covered the STAGED body. If the
// answer-time body went lossy behind the ask (foreign write,
// late edit) and the writer was never warned, Headings would
// drop unconsented prose — abort, nothing converted (#114 audit).
if headingsLadder, !pending.lossy, let body = PostStore.readBody(id: pending.id, home: home), OutlineTree.parsesWithLoss(body) {
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
if conversionWentLossyBehindAsk(pending, headingsLadder: headingsLadder) {
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
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
proseOverridePostID = pending.id
openUnguarded(pending.id, home: home)
openUnguarded(pending.id)
}
if outlineGuardPieceID == pending.id {
// Multi-window: the held #111 ask targets an outline that no
// longer is — dismiss it as a cancel (the ask's own teardown).
cancelOutlineGuard()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
}
+67 -63
View File
@@ -11,6 +11,50 @@ import Foundation
// MARK: Pass orchestration (#24, S3.1)
// MARK: #181: the ONE guard rail behind runPass and blindRead
extension PostsModel {
/// #181: the shared guard grammar every engine run passes before it
/// touches anything — nothing already running (a pass or a Blind
/// 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)? {
guard runningPass == nil else {
lastError = "A pass is already running."
return nil
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return nil
}
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session)
}
}
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
@@ -19,40 +63,18 @@ extension PostsModel {
/// engine's turn ends normally — never on cancel, refusal, or crash,
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
func runPass(_ kind: PassKind, mentor: MentorSessionModel) async {
guard let (id, session) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings, BEFORE the open-piece guard so nothing writes
// to disk (not even the pre-pass snapshot).
// point at Settings. Nothing has touched disk yet (the snapshot
// comes after this guard).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
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 }
do {
try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home)
} catch {
@@ -82,13 +104,18 @@ extension PostsModel {
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
do {
_ = try PostStore.advancePassState(id: id, kind: kind, home: home)
lastError = nil
Task { await rescan() } // the library regroups by Pass State
} catch {
lastError = error.localizedDescription
// #179 audit: the engine ran for minutes — a Settings repoint since
// the snapshot re-bound watchedHome to another library. Advancing
// through the rail would stamp pass-state frontmatter onto THAT
// library (an unrelated same-slug piece on collision — silently).
// Refuse honestly; the snapshot stays in the pass's own library.
guard watchedHome == home else {
lastError = "The library changed while the pass ran — its Pass State was not advanced."
return
}
// #179: the pass-advance write rides the rail — one rescan, and the
// strip ownership is the rail's (the library regroups by Pass State).
performWrite { try PostStore.advancePassState(id: id, kind: kind, home: $0) }
}
/// #24 (S3.1): the pass bar's Cancel — the existing session/cancel
@@ -109,36 +136,13 @@ extension PostsModel {
/// advance, no cards, no Learnings — the verdict and the reveal live in
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a Blind Read."
return
}
func blindRead(mentor: MentorSessionModel) async {
guard let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
guard flushOrAbort(id) else { return }
guard let base = PostStore.latestPassSnapshot(id: id, home: home) else {
// #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 {
lastError = "No Pass snapshot yet — run a Pass first."
return
}
+9 -9
View File
@@ -92,7 +92,7 @@ struct PostsPaneView: View {
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
MicropubPublishSheet(posts: model, home: home)
MicropubPublishSheet(posts: model)
}
}
@@ -112,7 +112,7 @@ struct PostsPaneView: View {
draftText: draft.text,
draftEdited: { model.updateDraft($0) },
draftSave: {
model.saveDraft(home: home)
model.saveDraft()
},
outline: draft.type == .outline,
)
@@ -317,7 +317,7 @@ struct PostsLibraryColumn: View {
.background(LaunchFocusReset())
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
model.rename(post, to: title)
}
}
.sheet(item: $movingPost) { post in
@@ -325,8 +325,8 @@ struct PostsLibraryColumn: View {
// 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(home: home)) { project in
model.moveToProject(post, project: project, home: home)
MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in
model.moveToProject(post, project: project)
}
}
// #144: keystroke-debounced (250 ms), structured body scan —
@@ -355,7 +355,7 @@ struct PostsLibraryColumn: View {
/// 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, home: home)
model.select(post.id)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
@@ -363,15 +363,15 @@ struct PostsLibraryColumn: View {
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
model.stageConversion(post)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post, home: home)
model.archivePost(post)
}
Button("Move to Trash", role: .destructive) {
model.trash(post, home: home)
model.trash(post)
}
}
}
+5 -5
View File
@@ -54,19 +54,19 @@ nonisolated enum ProfileBackup {
/// hasn't landed yet) is simply absent from the stamp; only NO profile
/// at all skips.
/// - Parameters:
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - backupsRoot: snapshots base dir (tests inject; default Museion's
/// Application Support / Backups).
/// - now: clock injection for the age check (tests pass fixed dates).
static func perform(
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
profileRoot: String = ProfileLayout.defaultRoot,
backupsRoot: String = defaultBackupsRoot(),
now: Date = Date(),
psScan: () -> Bool = psContainsMuseion,
) -> Outcome {
let fileManager = FileManager.default
let sources = ProfileSurface.allCases
.map { (profileRoot as NSString).appendingPathComponent($0.profileName) }
.map { ProfileLayout.profileDir($0.profileName, root: profileRoot) }
.filter { fileManager.fileExists(atPath: $0) }
guard !sources.isEmpty else {
logInfo("skipped — no profile found")
@@ -174,7 +174,7 @@ nonisolated enum ProfileBackup {
/// the ps scan is global (one scan answers for every surface profile),
/// so the caller evaluates it once.
private static func idleProfileDir(_ profileDir: String) -> Bool {
let pidPath = (profileDir as NSString).appendingPathComponent("gateway.pid")
let pidPath = ProfileLayout.gatewayPID(in: profileDir)
if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 {
return false
}
@@ -311,7 +311,7 @@ final class BackupModel {
guard !running else { return }
running = true
defer { running = false }
let profileRoot = profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath
let profileRoot = profileRoot ?? ProfileLayout.defaultRoot
let backupsRoot = backupsRoot ?? ProfileBackup.defaultBackupsRoot()
lastOutcome = await Task.detached(priority: .utility) {
ProfileBackup.perform(profileRoot: profileRoot, backupsRoot: backupsRoot)
+48
View File
@@ -0,0 +1,48 @@
//
// ProfileLayout.swift
// Museion
//
// #182: the ONE owner of the Hermes profile layout — the root default and
// every per-profile path derivation. The provisioner, the settings writer,
// and backup/restore build paths only through here; no literal
// profile-root string lives outside this module (pinned in
// ProfileLayoutTests — a layout change is this module + that one suite).
//
// Deliberately NOT layout-owned: the RESTORE.md copy names
// `~/.hermes/profiles` as prose (static text that must outlive the app),
// and the backup ps scan greps argv text, not filesystem paths.
//
import Foundation
nonisolated enum ProfileLayout {
/// The profiles base dir (`~/.hermes/profiles`; tests inject their own root).
static let defaultRoot = ("~/.hermes/profiles" as NSString).expandingTildeInPath
/// `<root>/<profileName>` — the profile's home dir.
static func profileDir(_ profile: String, root: String) -> String {
(root as NSString).appendingPathComponent(profile)
}
/// The profile's `.env` — provider keys (the writer's fan-out surface).
static func envFile(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent(".env")
}
/// The configured marker — written by the provisioner after the config
/// rail completes; marker-gating keeps a re-pass from stomping a user's
/// later Settings change.
static func configuredMarker(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent(".museion-provisioned")
}
/// The engine gateway's pid file (the backup liveness gate reads it).
static func gatewayPID(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent("gateway.pid")
}
/// The profile's skills dir — the symlink farm into the ONE master copy.
static func skillsDir(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent("skills")
}
}
+35 -47
View File
@@ -107,7 +107,7 @@ nonisolated enum ProfileProvisioner {
/// museion-tools (#23). First failure wins; the next pass heals.
/// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle).
/// - masterRoot: the ONE master skills copy (#133; tests inject; default
/// Application Support — never a symlink into the bundle, which moves
@@ -116,7 +116,7 @@ nonisolated enum ProfileProvisioner {
/// `--serve-mcp` (tests inject; nil skips registration).
static func perform(
hermesBinary: String?,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
profileRoot: String = ProfileLayout.defaultRoot,
payloadRoot: String = defaultPayloadRoot(),
masterRoot: String = defaultMasterRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
@@ -178,7 +178,7 @@ nonisolated enum ProfileProvisioner {
timeout: TimeInterval,
) -> Outcome {
let fileManager = FileManager.default
let profileDir = (profileRoot as NSString).appendingPathComponent(surface.profileName)
let profileDir = ProfileLayout.profileDir(surface.profileName, root: profileRoot)
// Phase 1 — profile create. Dir-check first; spawn only when
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
@@ -197,7 +197,7 @@ nonisolated enum ProfileProvisioner {
// concurrent create — not ours, so not fresh); all errors print on stdout.
let alreadyExists = run.exitCode == 1 && run.stdout.contains("already exists")
guard run.exitCode == 0 || alreadyExists, fileManager.fileExists(atPath: profileDir) else {
return .failed(profile: surface.profileName, phase: .create, excerpt: excerpt(run))
return .failed(profile: surface.profileName, phase: .create, excerpt: HermesConfigRail.excerpt(run))
}
createdFresh = run.exitCode == 0
}
@@ -263,20 +263,19 @@ nonisolated enum ProfileProvisioner {
private static let subsystem = "com.babylondreams.Museion"
/// Configured-marker filename inside a profile dir — written only by us,
/// after the `config set` rail completes. This is what makes a re-pass a
/// no-op without stomping a later Settings-written model block.
private static let configuredMarker = ".museion-provisioned"
/// Configured marker: written only by us, after the config rail
/// completes. This is what makes a re-pass a no-op without stomping a
/// later Settings-written model block. The path derivation lives in the
/// layout (#182); the marker-gating policy stays here.
private static func markerExists(at profileDir: String) -> Bool {
FileManager.default.fileExists(atPath: (profileDir as NSString).appendingPathComponent(configuredMarker))
FileManager.default.fileExists(atPath: ProfileLayout.configuredMarker(in: profileDir))
}
/// Records the configured marker; nil on success, a configure-phase
/// failure when the write fails — an unrecorded configure must not count
/// as done (the next pass would re-stomp the defaults).
private static func markConfigured(_ profileDir: String, profile: String) -> Outcome? {
let marker = (profileDir as NSString).appendingPathComponent(configuredMarker)
let marker = ProfileLayout.configuredMarker(in: profileDir)
do {
try Data().write(to: URL(fileURLWithPath: marker))
return nil
@@ -285,39 +284,34 @@ nonisolated enum ProfileProvisioner {
}
}
/// One `config set` write: key, value, and whether it needs `--force`
/// (the budget key is unrecognized by some engine versions).
private struct ConfigWrite {
let key: String
let value: String
let force: Bool
}
/// #128/#132: write the per-surface defaults through the engine's own
/// CLI. Provider first (switching providers clears a stale inherited
/// base_url — live-probed), then the model, then the output budget.
/// Verified wire: exit 0, `✓ Set <key> = <value> in …config.yaml`.
/// CLI rail (#182) — provider first (switching providers clears a stale
/// inherited base_url — live-probed), then the model, then the output
/// budget (`--force`: the budget key is unrecognized by some engine
/// versions).
private static func configureDefaults(
profile: String,
hermesBinary: String,
timeout: TimeInterval,
) -> Outcome? {
let writes: [ConfigWrite] = [
ConfigWrite(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
ConfigWrite(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
ConfigWrite(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
]
for write in writes {
var arguments = [hermesBinary, "-p", profile, "config", "set", write.key, write.value]
if write.force {
arguments.append("--force")
}
let run = EngineProbe.execute(arguments, timeout: timeout)
// Wire-verified success, not exit code alone (finish-audit): a CLI
// that exits 0 while writing nothing must not count as configured.
guard run.exitCode == 0, run.stdout.contains("✓ Set \(write.key)") else {
return .failed(profile: profile, phase: .configure, excerpt: excerpt(run))
}
do {
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
.set(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
.set(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
],
profile: profile,
binary: hermesBinary,
timeout: timeout,
)
} catch {
let failure = error as? HermesConfigRail.Failure
return .failed(
profile: profile,
phase: .configure,
excerpt: failure?.excerpt ?? error.localizedDescription,
)
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -391,7 +385,7 @@ nonisolated enum ProfileProvisioner {
manifest: [String],
) -> Outcome {
let fileManager = FileManager.default
let skillsDir = (profileDir as NSString).appendingPathComponent("skills")
let skillsDir = ProfileLayout.skillsDir(in: profileDir)
sweepOrphanedTemps(skillsDir)
var linked = 0
var present = 0
@@ -470,7 +464,7 @@ nonisolated enum ProfileProvisioner {
)
// Verified wire contract: exit 0 + "Saved 'museion-tools'" on stdout.
guard add.exitCode == 0, add.stdout.contains("Saved 'museion-tools'") else {
return .failed(profile: profile, phase: .register, excerpt: excerpt(add))
return .failed(profile: profile, phase: .register, excerpt: HermesConfigRail.excerpt(add))
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -492,12 +486,6 @@ nonisolated enum ProfileProvisioner {
}
return outcome
}
/// Create-phase errors print on stdout (#43); copy-phase on stderr — take both.
private static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
}
}
/// Pure payload/tree filesystem helpers — same-file extension so the
@@ -645,7 +633,7 @@ final class ProvisioningModel {
let outcome = await Task.detached(priority: .utility) {
ProfileProvisioner.perform(
hermesBinary: hermesBinary,
profileRoot: profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath,
profileRoot: profileRoot ?? ProfileLayout.defaultRoot,
payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(),
masterRoot: masterRoot ?? ProfileProvisioner.defaultMasterRoot(),
)
+1 -2
View File
@@ -17,7 +17,6 @@ import SwiftUI
struct PromoteAskSheet: View {
let card: FixCardStore.StoredFixCard
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
@State private var refusal: String?
@@ -108,7 +107,7 @@ struct PromoteAskSheet: View {
}
private func promote() {
switch posts.promoteCard(card, home: home) {
switch posts.promoteCard(card) {
case .promoted:
dismiss()
case let .refused(reason):
+18 -22
View File
@@ -142,24 +142,19 @@ nonisolated enum ProviderProbe {
/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
/// chat-completions is the retired path). Nous (#175, live-probed
/// 2026-11-05) is plain OpenAI chat-completions on a versioned base.
/// A trailing slash on a hand-edited endpoint never doubles up. A
/// non-URL endpoint is nil (URL(string:) happily percent-encodes "not a
/// url" — the scheme check is what actually rejects garbage; probe
/// reports unreachable, never traps).
/// #181: the paths live on the descriptor's dialect — a trailing slash
/// on a hand-edited endpoint never doubles up. A non-URL endpoint is
/// nil (URL(string:) happily percent-encodes "not a url" — the scheme
/// check is what actually rejects garbage; probe reports unreachable,
/// never traps).
static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = switch provider {
case .anthropic: "/v1/messages"
case .openaiAPI: "/responses"
case .zai, .nous: "/chat/completions"
}
return httpURL(base + path)
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.chatPath)
}
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = provider == .anthropic ? "/v1/models" : "/models"
return httpURL(base + path)
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.modelsPath)
}
private static func httpURL(_ string: String) -> URL? {
@@ -172,14 +167,15 @@ nonisolated enum ProviderProbe {
/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
/// `anthropic-version` (factsheet §2.1 — never send none). Nous rides
/// Bearer too — the portal accepts the session agent_key and an API
/// key interchangeably (#175).
/// key interchangeably (#175). #181: the shape keys off the
/// descriptor's auth mode.
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
switch provider {
case .zai, .openaiAPI, .nous:
switch provider.authMode {
case .bearer:
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
case .anthropic:
case let .headerKey(version):
request.setValue(key, forHTTPHeaderField: "x-api-key")
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
request.setValue(version, forHTTPHeaderField: "anthropic-version")
}
}
@@ -255,10 +251,10 @@ nonisolated enum ProviderProbe {
return failure
}
let (text, finish): (String, String?)
switch provider {
switch provider.dialect {
case .anthropic: (text, finish) = anthropicStream(events)
case .openaiAPI: (text, finish) = responsesStream(events)
case .zai, .nous: (text, finish) = chatCompletionsStream(events)
case .responses: (text, finish) = responsesStream(events)
case .chatCompletions: (text, finish) = chatCompletionsStream(events)
}
if !text.isEmpty {
return .works(latencyMS: latencyMS, modelCount: modelCount)
+2 -2
View File
@@ -340,8 +340,8 @@ struct SessionsPaneView: View {
/// opened); a failed write keeps the sheet up with the draft intact
/// (ApplyAskSheet posture — the edited draft is never destroyed).
private func newPostFromSession() -> String? {
guard let posts, let home else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil {
guard let posts else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "") == nil {
return posts.lastError ?? "The piece couldn't be written."
}
sessionDraft = nil
+130 -36
View File
@@ -89,6 +89,78 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
case .nous: "NOUS_API_KEY"
}
}
/// #181: the wire family the probe speaks. The SELECTOR is data —
/// endpoint paths, auth shape, and the SSE decoder pick ride the
/// dialect; the per-family code (request bodies, stream decoders)
/// stays separate functions, not switch clothing.
nonisolated enum Dialect: Sendable {
/// Anthropic `/v1/messages`, header-key auth, Anthropic SSE.
case anthropic
/// OpenAI Responses `/responses`, Bearer, Responses SSE.
case responses
/// OpenAI chat-completions (`/chat/completions` — z.ai and the
/// Nous Portal), Bearer, chat-completions SSE.
case chatCompletions
/// The chat-call path appended to the endpoint base (callers trim
/// a trailing slash off the base first).
var chatPath: String {
switch self {
case .anthropic: "/v1/messages"
case .responses: "/responses"
case .chatCompletions: "/chat/completions"
}
}
var modelsPath: String {
switch self {
case .anthropic: "/v1/models"
case .responses, .chatCompletions: "/models"
}
}
}
/// #181: the provider's wire family (the probe's dialect selector).
var dialect: Dialect {
switch self {
case .zai, .nous: .chatCompletions
case .anthropic: .anthropic
case .openaiAPI: .responses
}
}
/// #181: the auth-header shape (factsheet §2.1) — Bearer everywhere
/// except Anthropic's `x-api-key` + a pinned `anthropic-version`
/// (never send none).
nonisolated enum AuthMode: Sendable {
/// `Authorization: Bearer <key>`.
case bearer
/// `x-api-key: <key>` plus the pinned version header.
case headerKey(version: String)
}
var authMode: AuthMode {
switch self {
case .zai, .openaiAPI, .nous: .bearer
case .anthropic: .headerKey(version: "2023-06-01")
}
}
/// #175: keyless providers run on the shared Hermes Portal login —
/// the engine's own credential stands in when no API key is pasted
/// (API key and subscription bill the same account credits).
var keyless: Bool {
self == .nous
}
/// The endpoint with any trailing slash trimmed — the ONE
/// normalization every endpoint consumer (the probe's URL builders,
/// the credential rail's official-endpoint gate) compares against;
/// divergent trims would gate or route differently in silence.
nonisolated static func trimmedEndpoint(_ endpoint: String) -> String {
endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
}
}
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
@@ -169,6 +241,44 @@ nonisolated enum PortalAuth {
}
}
/// #181: THE credential resolution — the provider's own API key, else the
/// shared Portal session key for keyless providers. Settings' Test
/// Connection and pass readiness both call this ONE function, so the
/// fallback can no longer drift between them. The implicit session
/// credential only ever rides the OFFICIAL endpoint (#175 finish-audit:
/// cleartext http / foreign host = silent exfiltration with no on-screen
/// cue) — a keyless provider on any other endpoint refuses with the
/// paste-a-key path. Nonisolated async, so the auth-store read never runs
/// on the main actor.
nonisolated enum ProviderCredential {
enum Resolved: Equatable {
case key(String)
case refused(String)
}
static func resolve(
provider: ModelProvider,
envKey: String,
endpoint: String,
portalAuthPath: String,
) async -> Resolved {
if !envKey.isEmpty {
return .key(envKey)
}
guard provider.keyless else {
return .refused("no API key set — paste the key first")
}
let trimmed = ModelProvider.trimmedEndpoint(endpoint)
guard trimmed == provider.defaultEndpoint else {
return .refused("custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)")
}
guard let sessionKey = PortalAuth.sessionKey(authJSONPath: portalAuthPath) else {
return .refused("no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`")
}
return .key(sessionKey)
}
}
/// The Settings page's state (#135): per-surface model configs, per-provider
/// keys, the registry the model combobox reads, and the write path every
/// committed change flows through. #136: hydrated from the profiles at pane
@@ -367,46 +477,30 @@ final class SettingsModel {
/// One probe per provider over the CURRENT key/endpoint state. Guarded
/// against stacking; the empty-key precondition makes an unkeyed probe
/// fail fast without touching the network. #175: an unkeyed NOUS probe
/// falls back to the shared Portal session key — the engine's own
/// credential — and names the login path when neither exists.
/// fail fast without touching the network. #181: the credential —
/// provider key, else the shared Portal session key for keyless
/// providers — resolves through the ONE rail pass readiness also calls.
func testConnection(for provider: ModelProvider) async {
guard testStates[provider] != .running else { return }
testStates[provider] = .running
var key = keyConfig(for: provider).apiKey
if provider == .nous, key.isEmpty {
// Finish-audit #175: the session agent_key is an IMPLICIT
// credential (never pasted, field reads empty) — it only ever
// rides the official https endpoint, never a hand-edited one
// (cleartext http / foreign host = silent exfiltration with no
// on-screen cue). Custom endpoints get the paste-a-key refusal.
let endpoint = keyConfig(for: .nous).endpoint
let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
guard trimmed == ModelProvider.nous.defaultEndpoint else {
testStates[provider] = .done(.authFailed(
"custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)",
))
return
}
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
if key.isEmpty {
testStates[provider] = .done(.authFailed(
"no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`",
))
return
}
}
let config = ProviderProbe.Config(
let keyConfig = keyConfig(for: provider)
switch await ProviderCredential.resolve(
provider: provider,
endpoint: keyConfig(for: provider).endpoint,
apiKey: key,
model: probeModel(for: provider),
)
let transport = probeTransport
testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport))
envKey: keyConfig.apiKey,
endpoint: keyConfig.endpoint,
portalAuthPath: portalAuthPath,
) {
case let .key(key):
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig.endpoint,
apiKey: key,
model: probeModel(for: provider),
)
testStates[provider] = await .done(ProviderProbe.probe(config, transport: probeTransport))
case let .refused(message):
testStates[provider] = .done(.authFailed(message))
}
}
/// The model the probe proves generation on: the first surface on this
+2 -1
View File
@@ -251,10 +251,11 @@ private struct ProviderKeyBlock: View {
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
if provider == .nous {
if provider.keyless {
// #175: the engine auths nous through hermes' own Portal
// login (device-code, shared across profiles) — the key
// field is optional and bills the same account credits.
// #181: keyed off the descriptor, like every provider fact.
Text(
"Chats ride your Hermes Portal login — no key needed once hermes is signed in (hermes auth add nous). "
+ "A pasted key bills the same account credits (API or subscription).",
+11 -12
View File
@@ -117,14 +117,14 @@ struct WorkspaceView: View {
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin, home: gate.museionHome)
gate.posts.importFiles(origin: origin)
}
}
// #108: File ▸ New Project… ask — commands can't present sheets, so
// the model stages and this window presents (OriginAsk pattern).
.sheet(isPresented: newProjectAskBinding) {
NewProjectSheet { name in
if let reason = gate.posts.createProject(named: name, home: gate.museionHome) {
if let reason = gate.posts.createProject(named: name) {
return reason
}
gate.posts.newProjectPending(named: name)
@@ -137,9 +137,9 @@ struct WorkspaceView: View {
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse(home: gate.museionHome)
gate.posts.openGuardedOutlineInProse()
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
gate.posts.openGuardedOutlineAsOutline()
}
}
// #114 (S4): the Convert to Post ask — which body the outline
@@ -147,7 +147,7 @@ struct WorkspaceView: View {
// is the default: lossless. Esc/Cancel converts nothing.
.sheet(isPresented: convertAskBinding) {
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome)
gate.posts.convertToPost(headingsLadder: headingsLadder)
}
}
}
@@ -286,7 +286,7 @@ struct WorkspaceView: View {
case .archive:
// #108: list-only pane — clicking a row selects the piece and
// hops to Posts where its editor lives.
ArchivePaneView(home: gate.museionHome, model: gate.posts) {
ArchivePaneView(model: gate.posts) {
selection = .posts
}
case .settings:
@@ -352,7 +352,6 @@ struct WorkspaceView: View {
/// 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 {
let home: URL
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
@@ -437,7 +436,7 @@ private struct ArchivePaneView: View {
// 'Unarchive Group' — it moves the whole
// project, not one piece.
Button("Unarchive Group") {
model.unarchiveProject(project, home: home)
model.unarchiveProject(project)
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
.help("Move the whole project back to projects/")
@@ -453,7 +452,7 @@ private struct ArchivePaneView: View {
// 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, home: home)
model.select(post.id)
onOpenPiece()
}
.overlay(alignment: .bottom) {
@@ -464,14 +463,14 @@ private struct ArchivePaneView: View {
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post, home: home)
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, home: home)
model.stageConversion(post)
}
}
}
@@ -496,7 +495,7 @@ private struct ArchivePaneView: View {
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
model.rename(post, to: title)
}
}
}
+4 -3
View File
@@ -32,19 +32,20 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `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).
- `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` — scan, write side, pass substrate, stats capture, research notes.
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates).
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `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.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
- `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline.
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests` — settings model, real CLI write path, probe decode + request builders.
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests`, `ProviderCredentialTests` — settings model, real CLI write path, probe decode + request builders, the #181 ONE credential resolution (pasted key wins, keyless fallback on the official endpoint, custom-endpoint and no-login refusals).
- `WordBoundaryTruncationTests`, `PolishSeamTests`, `ResearchCandidateTests`, `PersonaLoadOrderTests` — UI pure seams, research candidates, persona payload contract (the four-shared-sections + load-order pins).
## Verification
+7 -7
View File
@@ -117,7 +117,7 @@ struct BlindReadTests {
private func openJudgedPiece(on model: PostsModel, home: URL, snapshot: String, current: String) async throws -> String {
let post = try PostStore.writeNew(body: current, home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: snapshot, home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -199,14 +199,14 @@ struct BlindReadTests {
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let run = Task { await rig.model.blindRead(home: rig.home, mentor: rig.mentor) }
let run = Task { await rig.model.blindRead(mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningBlindRead)
// Mutual exclusion — a pass refuses while the read owns the rail.
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
await rig.model.runPass(.pass1, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("already running") == true)
// The pass bar's Cancel rail ends the held read — no reveal,
@@ -237,7 +237,7 @@ struct BlindReadTests {
snapshot: "MARKER-the-older-text", current: "# Judged\n\nMARKER-the-newer-text",
)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
await rig.model.blindRead(mentor: rig.mentor)
// The prompt carried BOTH bodies inline — and no path: the judge
// cannot learn which file is which (the engines' prompt log).
@@ -262,20 +262,20 @@ struct BlindReadTests {
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", home: rig.home)
rig.model.select(post.id, home: rig.home)
rig.model.select(post.id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// No pass ever ran — refuse, spawn nothing beyond the resident engine.
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
await rig.model.blindRead(mentor: rig.mentor)
#expect(rig.model.lastError?.contains("run a Pass") == true)
#expect(museionSpawns(rig) == 1)
// Snapshot exists but the document is unchanged since — a vacuous
// read refuses honestly.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Fresh\n\nNo pass yet.", home: rig.home)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
await rig.model.blindRead(mentor: rig.mentor)
#expect(rig.model.lastError?.contains("No edits") == true)
}
+1 -1
View File
@@ -23,7 +23,7 @@ private func makeSessionHome() -> URL {
private func seedPost(_ home: URL, id: String, body: String) {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer)
try? PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: .writer)
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
+8 -8
View File
@@ -51,7 +51,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
let chatBefore = rig.mentor.host.chat
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home)
rig.model.select(post.id, home: rig.home)
rig.model.select(post.id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -59,7 +59,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// In a Task — a full-mode scripted pass can complete inside one poll
// sleep (no child-process latency anymore), so the pass ENGINE is
// captured after the run from the spawn records, not polled mid-flight.
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
_ = await run.value
let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" }
let passEngineClosed = try #require(passEngine, "pass engine never spawned")
@@ -104,9 +104,9 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Held Pass\n\nCancel me.", home: rig.home)
rig.model.select(post.id, home: rig.home)
rig.model.select(post.id)
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
let heldEngine = try #require(await pollOneShot(of: rig.mentor), "pass engine never spawned")
#expect(rig.mentor.isPassEngineRunning)
@@ -291,7 +291,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
rig.mentor.passReadinessWriter = writer
await rig.mentor.refreshPassReadiness()
let post = try PostStore.writeNew(body: "# No Key\n\nPass me.", home: rig.home)
rig.model.select(post.id, home: rig.home)
rig.model.select(post.id)
for _ in 0 ..< 250 where rig.model.session?.postID != post.id {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -299,7 +299,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// this pin vacuously.
try #require(rig.model.session?.postID == post.id)
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
await rig.model.runPass(.pass1, mentor: rig.mentor)
#expect(rig.model.lastError == "Pass 1 needs a z.ai API key — add it in Settings → Provider Keys.")
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
@@ -320,7 +320,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
_ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active
let target = try #require(rig.mentor.roster.last) // sess-1, NOT active
let post = try PostStore.writeNew(body: "# Held Load\n\nResume races a pass.", home: rig.home)
rig.model.select(post.id, home: rig.home)
rig.model.select(post.id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -338,7 +338,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// pass prompt then HOLDS, so isStreaming is guaranteed when the parked
// load completes, and the #124 Cancel rail frees it afterwards.
rig.engines.mode = "hangOnPrompt"
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
try await Task.sleep(nanoseconds: 20_000_000)
}
+2 -2
View File
@@ -174,7 +174,7 @@ struct EngineSmokeTests {
await mentor.openSession() // the resident chat engine
let chatPid = try #require(mentor.childProcessIdentifier)
let post = try PostStore.writeNew(body: "# Smoke Pass\n\nVerdict me.", home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -182,7 +182,7 @@ struct EngineSmokeTests {
// In a Task — the pass child's pid is only observable while it runs
// (the old EngineLifecycleTests poll; the zsh wire latency holds the
// turn open long enough to catch it).
let run = Task { await model.runPass(kind, home: home, mentor: mentor) }
let run = Task { await model.runPass(kind, mentor: mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
+20 -20
View File
@@ -23,7 +23,7 @@ import Testing
/// hop-back instead of asserting synchronously (PostsModelTests convention).
/// The post-loop expect makes a silent timeout a failure, not a pass.
@MainActor
private func pollUntil(_ condition: @MainActor () -> Bool) async throws {
func pollUntil(_ condition: @MainActor () -> Bool) async throws {
for _ in 0 ..< 250 where !condition() {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -51,7 +51,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
model.select(post.id)
let session = try #require(model.session)
let generation = session.loadGeneration
@@ -59,7 +59,7 @@ struct FixCardApplyTests {
// buffer first (flush-first, like every op that reads the piece).
session.edit("# Carded\n\nThe anchor sentence.\nPlus a typed line.\n")
#expect(model.applyCard(written[0].card, home: home) == .applied)
#expect(model.applyCard(written[0].card) == .applied)
// Disk carries the replacement over the flushed buffer...
#expect(PostStore.readBody(id: post.id, home: home) == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n")
@@ -80,14 +80,14 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
model.select(post.id)
// The Post changed after the card was issued — the quote is gone.
model.session?.edit("# Carded\n\nThe sentence changed.\n")
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
#expect(model.applyCard(written[0].card, home: home) == .stale)
#expect(model.applyCard(written[0].card) == .stale)
#expect(try Data(contentsOf: postURL) == before) // nothing selected, nothing changed
let diskCard = try #require(FixCardStore.scan(pieceURL: folder).first)
@@ -104,11 +104,11 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(pattern: "Demo", fix: "The replaced sentence.", quote: "The anchor sentence.", lane: .demonstration)],
)
model.select(post.id, home: home)
model.select(post.id)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card, home: home)
let outcome = model.applyCard(written[0].card)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -127,7 +127,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
model.select(post.id)
// A foreign write lands on disk underneath the writer (#67) — the
// reload question is up and unanswered.
let postURL = folder.appendingPathComponent("post.md")
@@ -135,7 +135,7 @@ struct FixCardApplyTests {
model.session?.diskDidChange(diskText: "foreign text on disk")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card, home: home)
let outcome = model.applyCard(written[0].card)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -157,15 +157,15 @@ struct FixCardApplyTests {
card(pattern: "Telling", quote: "The anchor sentence."),
],
)
model.select(post.id, home: home)
model.select(post.id)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
model.skipCard(written[0].card, home: home)
model.skipCard(written[0].card)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.status == .skipped }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[0].card.id })?.status == .skipped)
model.doneCard(written[1].card, home: home)
model.doneCard(written[1].card)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[1].card.id })?.status == .done }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[1].card.id })?.status == .done)
@@ -241,7 +241,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Carded\n\nThe sentence changed.\n") // stale the anchor
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
@@ -252,7 +252,7 @@ struct FixCardApplyTests {
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: cardsDir.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cardsDir.path) }
#expect(model.applyCard(written[0].card, home: home) == .stale) // the primary contract holds…
#expect(model.applyCard(written[0].card) == .stale) // the primary contract holds…
#expect(model.lastError?.contains("card close failed") == true) // …and the flag failure is loud
#expect(try Data(contentsOf: postURL) == before) // still nothing selected or changed
}
@@ -270,12 +270,12 @@ struct FixCardApplyTests {
)
try FileManager.default.removeItem(at: folder.appendingPathComponent("post.md")) // the read will fail
model.select(post.id, home: home)
model.select(post.id)
#expect(model.session?.loadFailed == true)
// The writer typed the anchor into the empty failed-session buffer.
model.session?.edit("The anchor sentence. typed nowhere durable.")
let outcome = model.applyCard(written[0].card, home: home)
let outcome = model.applyCard(written[0].card)
guard case .refused = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -295,9 +295,9 @@ struct FixCardApplyTests {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
model.select(post.id, home: home)
model.select(post.id)
#expect(model.promoteCard(written[0].card, home: home) == .promoted)
#expect(model.promoteCard(written[0].card) == .promoted)
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
@@ -306,7 +306,7 @@ struct FixCardApplyTests {
// Already promoted → refused, no second file (one confirm = one entry).
let scanned = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(model.promoteCard(scanned, home: home) == .refused("card already promoted"))
#expect(model.promoteCard(scanned) == .refused("card already promoted"))
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
}
@@ -316,7 +316,7 @@ struct FixCardApplyTests {
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
#expect(model.promoteCard(written[0].card, home: home) == .refused("open the piece to work its cards"))
#expect(model.promoteCard(written[0].card) == .refused("open the piece to work its cards"))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path))
#expect(model.lastError == nil)
}
+139
View File
@@ -0,0 +1,139 @@
//
// HermesConfigRailTests.swift
// MuseionTests
//
// #182 — the config-set CLI contract's ONE pinning suite, over the shared
// fake-hermes double (makeFakeHermes, ProfileProvisionerTests.swift). The
// callers' suites pin only their own key lists.
//
// Scenario: The config-set wire is owned once — From user story #182
// Given the provisioner and the settings writer both write config keys
// through `hermes -p <profile> config set`
// When either hands the rail its key list
// Then every write rides the exact argv (with --force where asked), is
// verified against the `✓ Set` line (not exit code alone), executes
// provider-first (switching providers clears stale inherited values),
// and a failed write surfaces key + profile + CLI excerpt.
//
import Foundation
@testable import Museion
import Testing
@Suite("HermesConfigRailTests")
struct HermesConfigRailTests {
@Test func `set argv rides the exact wire with force`() throws {
let binDir = provTempDir("rail")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: "anthropic", force: false),
.set(key: "model.extra_body.max_tokens", value: "24000", force: true),
],
profile: "museion-pass1",
binary: binary,
timeout: 5,
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider anthropic",
"-p museion-pass1 config set model.extra_body.max_tokens 24000 --force",
])
}
@Test func `provider goes first whatever the caller s list order`() throws {
// model.provider clears a stale inherited base_url — the rail owns
// the rule; a caller can't order it wrong. Relative order holds.
let binDir = provTempDir("rail-order")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply(
[
.set(key: "model.base_url", value: "https://x", force: false),
.unset(key: "model.reasoning_effort"),
.set(key: "model.default", value: "m", force: false),
.set(key: "model.provider", value: "zai", force: false),
],
profile: "museion",
binary: binary,
timeout: 5,
)
#expect(fakeHermesLog(binDir, "config-set-museion") == [
"-p museion config set model.provider zai",
"-p museion config set model.base_url https://x",
"-p museion config set model.default m",
])
#expect(fakeHermesLog(binDir, "config-unset-museion") == [
"-p museion config unset model.reasoning_effort",
])
}
@Test func `unset of an absent key is idempotent success`() throws {
let binDir = provTempDir("rail-unset")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5)
}
@Test func `a failed set throws naming key and profile with the cli excerpt`() {
let binDir = provTempDir("rail-fail")
try? "".write(toFile: binDir + "/config-set-fails", atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply(
[.set(key: "model.default", value: "m", force: false)],
profile: "museion-pass2",
binary: binary,
timeout: 5,
)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.key == "model.default")
#expect(failure?.profile == "museion-pass2")
#expect(failure?.excerpt == "Error: config set exploded")
#expect(failure?.errorDescription == "couldn't set model.default on museion-pass2: Error: config set exploded")
}
}
@Test func `a failed unset throws the structured failure`() {
// The fourth branch: neither ✓ Unset nor the not-set line.
let binDir = provTempDir("rail-unset-fail")
try? "".write(toFile: binDir + "/config-unset-fails", atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.verb == "unset")
#expect(failure?.key == "model.reasoning_effort")
#expect(failure?.excerpt == "Error: config unset exploded")
}
}
@Test func `a value that looks like an option is refused before any spawn`() {
// Free-text fields (model IDs, endpoints) feed the rail; a leading
// `-` is an option to the child CLI, never a value.
let binDir = provTempDir("rail-dash")
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply(
[.set(key: "model.default", value: "--force", force: false)],
profile: "museion",
binary: binary,
timeout: 5,
)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.key == "model.default")
#expect(failure?.excerpt == "value starts with '-' — not written")
}
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty) // nothing reached the CLI
}
@Test func `excerpt caps at 500 chars`() {
// The #180 deliberate divergence (writer's old 300 is gone): pinned,
// not just commented.
let output = EngineProbe.ProcessOutput(exitCode: 1, stdout: String(repeating: "x", count: 900))
#expect(HermesConfigRail.excerpt(output).count == 500)
}
}
@@ -173,6 +173,30 @@ struct HermesSettingsWriterTests {
}
}
@Test func `whitespace-only endpoint is treated as empty at both gates`() async throws {
// Learning #6's class: raw isEmpty passes whitespace through; the
// gates mirror the trimmed emptiness the model side validates.
let (binDir, writer) = makeRig()
// Surface gate: a blank endpoint never rides base_url.
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil),
zaiEndpoint: " ",
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider zai",
"-p museion-pass1 config set model.default glm-5.3",
])
// Key gate: a blank zai endpoint skips the write-through (the key
// still fans out to .env).
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: " ", apiKey: "sk-z"),
profiles: [.chat],
)
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty)
}
@Test func `non-zai key write only touches env`() async throws {
let (binDir, writer) = makeRig()
let root = binDir + "/profiles"
+13 -13
View File
@@ -74,7 +74,7 @@ struct LearningDecayTests {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file, now: now)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
let frontmatter = PostFrontmatter.parse(stampedText)
#expect(frontmatter["dismissed"] == FixCardStore.formatted(now, "yyyy-MM-dd"))
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "1")
@@ -85,7 +85,7 @@ struct LearningDecayTests {
#expect(frontmatter["promoted"] == "2026-10-21")
#expect(frontmatter["from_card"] == "6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0")
// The body is byte-identical.
#expect(PostStore.splitFrontmatter(stampedText).body == PostStore.splitFrontmatter(learning).body)
#expect(PostFrontmatter.split(stampedText).body == PostFrontmatter.split(learning).body)
// Hidden from the pass rail.
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
}
@@ -125,7 +125,7 @@ struct LearningDecayTests {
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // resurfaced
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let frontmatter = try Post.frontmatter(of: readLearning(home, file))
let frontmatter = try PostFrontmatter.parse(readLearning(home, file))
#expect(frontmatter["dismiss_count"] == "2")
#expect(frontmatter["dismissed_at_pass"] == "10") // re-anchored at the current clock
@@ -221,7 +221,7 @@ struct LearningDecayTests {
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: hugeHome, typeDir: "posts", file: "20261021-huge.md")
}
#expect(try Post.frontmatter(of: readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
#expect(try PostFrontmatter.parse(readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
}
/// Scenario: dismiss is a write-path trust boundary — traversal-shaped
@@ -251,7 +251,7 @@ struct LearningDecayTests {
// Nothing escaped the learnings tree; the real learning is untouched.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("x.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings/x.md").path))
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == nil)
#expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == nil)
}
/// Scenario: a pre-planted symlinked learnings component must not
@@ -326,7 +326,7 @@ struct LearningDecayTests {
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
}
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == "1")
#expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == "1")
// A negative hand-edited count clamps to 0 at parse → stamp writes 1.
let negHome = try toolsHome()
@@ -338,7 +338,7 @@ struct LearningDecayTests {
---
""")
try LearningDecay.dismiss(home: negHome, typeDir: "posts", file: file)
#expect(try Post.frontmatter(of: readLearning(negHome, file))["dismiss_count"] == "1")
#expect(try PostFrontmatter.parse(readLearning(negHome, file))["dismiss_count"] == "1")
}
/// Scenario: decay is defined per pass-clocked content type — a foreign
@@ -360,11 +360,11 @@ struct LearningDecayTests {
contentsOf: home.appendingPathComponent("learnings/essays/\(file)"),
encoding: .utf8,
)
#expect(Post.frontmatter(of: text)["dismiss_count"] == nil)
#expect(PostFrontmatter.parse(text)["dismiss_count"] == nil)
}
/// Scenario: a Learning with NO frontmatter (a hand-made file) still
/// dismisses — stampingFrontmatter prepends a fresh block and the body
/// dismisses — the update walk prepends a fresh block and the body
/// rides verbatim below it (#27 audit: the prepend branch pinned).
@Test func `dismiss prepends a fresh block on a frontmatter-less file`() throws {
let home = try toolsHome()
@@ -375,14 +375,14 @@ struct LearningDecayTests {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
let frontmatter = PostFrontmatter.parse(stampedText)
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "0")
#expect(PostStore.splitFrontmatter(stampedText).body == body)
#expect(PostFrontmatter.split(stampedText).body == body)
}
/// Scenario: lines ABOVE the opening `---` (a hand-edit blank —
/// Post.frontmatter tolerates one) belong to neither block nor body;
/// PostFrontmatter.parse tolerates any count) belong to neither block nor body;
/// the stamp keeps them — the "every other line verbatim" contract
/// (#27 review pin).
@Test func `dismiss preserves lines above the frontmatter block`() throws {
@@ -394,7 +394,7 @@ struct LearningDecayTests {
let stampedText = try readLearning(home, file)
#expect(stampedText.hasPrefix("\n---\n")) // the leading blank survived
#expect(Post.frontmatter(of: stampedText)["dismiss_count"] == "1")
#expect(PostFrontmatter.parse(stampedText)["dismiss_count"] == "1")
#expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched
}
}
+23 -23
View File
@@ -19,12 +19,12 @@ struct MicropubModelTests {
@Test @MainActor func `sendDraft flushes the open piece and sends the disk body with the title`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Flush Me\n\nOriginal.", home: home)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
)
@@ -40,10 +40,10 @@ struct MicropubModelTests {
}
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
let (model, home) = try makeModelHome()
let (model, _) = try makeModelHome()
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -54,11 +54,11 @@ struct MicropubModelTests {
}
@Test @MainActor func `sendDraft refuses an unsaved draft`() async throws {
let (model, home) = try makeModelHome()
let (model, _) = try makeModelHome()
model.newPost() // staged draft — no folder, no session
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -73,11 +73,11 @@ struct MicropubModelTests {
// All-whitespace body — no Title, no content (a heading-only
// piece DOES send: the Title line is content on Micro.blog).
let post = try PostStore.writeNew(body: " \n", home: home)
model.select(post.id, home: home)
model.select(post.id)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -91,7 +91,7 @@ struct MicropubModelTests {
@Test @MainActor func `frontmatter category never travels`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
model.select(post.id, home: home)
model.select(post.id)
// The writer's own category frontmatter — permitted, inert.
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
let raw = try String(contentsOf: fileURL, encoding: .utf8)
@@ -100,7 +100,7 @@ struct MicropubModelTests {
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
)
@@ -113,11 +113,11 @@ struct MicropubModelTests {
@Test @MainActor func `a failed draft stamps nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Fails\n\nBody.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(500, body: "{}", log: log),
)
@@ -127,15 +127,15 @@ struct MicropubModelTests {
@Test @MainActor func `re-drafting overwrites the remembered url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
)
_ = await model.micropubSendDraft(
home: home, token: "tok",
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
)
@@ -147,7 +147,7 @@ struct MicropubModelTests {
/// Plants a PNG beside the piece; returns the piece's post.md URL.
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id, home: home)
model.select(post.id)
let dir = try #require(PostStore.folder(of: post.id, home: home))
try FileManager.default.createDirectory(at: dir.appendingPathComponent("assets", isDirectory: true), withIntermediateDirectories: true)
try micropubPNG().write(to: dir.appendingPathComponent("assets/path.png"))
@@ -162,7 +162,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// The three hops, in order: q=config → upload → create.
@@ -197,7 +197,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -228,7 +228,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -246,7 +246,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// config + ONE upload + create — the FILE uploads once, not once per ref.
@@ -266,7 +266,7 @@ struct MicropubModelTests {
) // path.png planted, ghost.png never
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -278,10 +278,10 @@ struct MicropubModelTests {
@Test @MainActor func `a piece without illustrations sends exactly one request`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Plain\n\nBody.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
// The #33 path unchanged: no config round-trip, straight to the create.
#expect(log.requests.count == 1)
+33 -33
View File
@@ -42,14 +42,14 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id, home: home)
model.select(post.id)
// Wait for the bind rescan to surface the piece — the pass label reads
// the library's title for it (the PostsModelTests poll pattern).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
@@ -73,9 +73,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home)
model.select(post.id, home: home)
model.select(post.id)
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
// Pre-pass is unconditional — the snapshot landed anyway.
@@ -91,9 +91,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home)
model.select(post.id, home: home)
model.select(post.id)
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -108,9 +108,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
await mentor.openSession()
model.newPost() // draft staged — no folder exists
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("post") == true)
#expect(model.lastError == "Open a saved post to run a pass.")
// Nothing landed on disk — the draft never even materialized a folder.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts").path))
}
@@ -120,15 +120,15 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nMid-pass.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let first = Task { await model.runPass(.pass1, home: home, mentor: mentor) }
let first = Task { await model.runPass(.pass1, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.runningPass == .pass1)
await model.runPass(.pass1, home: home, mentor: mentor) // one pass at a time
await model.runPass(.pass1, mentor: mentor) // one pass at a time
#expect(model.lastError?.contains("already running") == true)
model.cancelPass(mentor: mentor) // the pass bar's Cancel rail
@@ -147,9 +147,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nCancel me.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let run = Task { await model.runPass(.pass1, home: home, mentor: mentor) }
let run = Task { await model.runPass(.pass1, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -177,7 +177,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Busy\n\nMentor chatting.", home: home)
model.select(post.id, home: home)
model.select(post.id)
let chat = Task { await mentor.sendPrompt("just chatting") }
for _ in 0 ..< 250 where !mentor.isStreaming {
@@ -185,7 +185,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
}
#expect(mentor.isStreaming)
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("mid-reply") == true)
// The guard fired before the snapshot — nothing on disk.
#expect(!FileManager.default.fileExists(
@@ -199,9 +199,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
let (model, home, mentor) = try makePassRig() // never opened — engine idle
defer { mentor.shutdown() }
let post = try PostStore.writeNew(body: "# Cold\n\nNo engine yet.", home: home)
model.select(post.id, home: home)
model.select(post.id)
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("isn't ready") == true)
#expect(!FileManager.default.fileExists(
@@ -214,10 +214,10 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
@@ -231,9 +231,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home)
model.select(post.id, home: home)
model.select(post.id)
await model.runPass(.pass2, home: home, mentor: mentor)
await model.runPass(.pass2, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -248,18 +248,18 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Stats Piece\n\nOne two three. Four five! Six?", home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Capture fired at the invocation — the five keys ride post.md…
let matter = Post.frontmatter(of: onDisk)
let matter = PostFrontmatter.parse(onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
#expect(matter["stats_type_token_ratio"] != nil)
@@ -275,15 +275,15 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancelled Stats\n\nOne two three. Four five!", home: home)
model.select(post.id, home: home)
model.select(post.id)
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Stats fire at INVOCATION, not completion — a cancelled pass has them anyway…
let matter = Post.frontmatter(of: onDisk)
let matter = PostFrontmatter.parse(onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
// …while the Pass State never advanced.
@@ -295,12 +295,12 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# AI Piece\n\nMachine-born prose.", origin: .ai, home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -308,7 +308,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
// The pass ran (origin alone decides, never the outcome)…
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// …but nothing was stamped — ai-origin is never stats-eligible.
let matter = Post.frontmatter(of: onDisk)
let matter = PostFrontmatter.parse(onDisk)
#expect(matter["stats_captured"] == nil)
#expect(matter["stats_burstiness"] == nil)
}
@@ -326,12 +326,12 @@ struct DeslopLintWiringTests {
let body = "# Lint Piece\n\nUtilize the index — and delve twice — notably once, and again — "
+ "and again — and once more — to clear the dash budget. Utilize it twice."
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let cards = FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md"))
@@ -339,7 +339,7 @@ struct DeslopLintWiringTests {
#expect(cards.contains { $0.pattern == "utilize" && $0.lane == .mechanical })
// Stats capture fired at the same invocation — both hooks, one seam.
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
let matter = Post.frontmatter(of: onDisk)
let matter = PostFrontmatter.parse(onDisk)
#expect(matter["stats_captured"] != nil)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
}
+117
View File
@@ -0,0 +1,117 @@
//
// PostFrontmatterTests.swift
// MuseionTests
//
// #180: the Post frontmatter codec — one lenient read, three write
// postures (fresh / merge-import / update-keys), one known-key table.
// Pins: the foreign-keys-verbatim round trip through every posture
// (the class of bug that lost captured stats once, un-reintroducible),
// the lenient unknown-type decode, and the two named eligibility
// predicates the capture gate and the scan read-back gate share.
//
import Foundation
@testable import Museion
import Testing
// Scenario: One frontmatter codec behind every post read and write —
// from #180. Given a library whose post.md blocks were written by the
// old per-site writers, when any posture (import, save, advance,
// capture, publish-stamp) runs over a piece carrying foreign frontmatter
// keys, then the one PostFrontmatter engine keeps those keys verbatim,
// inserts owned keys in the one known order, reads unknown types
// leniently as post, and both eligibility gates agree on the same named
// predicates.
struct PostFrontmatterTests {
/// A block with foreign keys above and below our owned keys — every
/// posture must keep `foreign_key: keep-me` byte-identical.
private let withForeign = "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Body"
@Test func `fresh stamp is the 59 shape in known-key order`() {
#expect(PostFrontmatter.stamped(body: "# T", passState: .firstDraft, origin: .writer)
== "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# T")
#expect(PostFrontmatter.stamped(body: "- Root", passState: .pass2Done, origin: .ai, type: .outline)
== "---\ntype: outline\npass_state: Pass-2 Done\norigin: ai\n---\n- Root")
}
@Test func `merge-import keeps foreign keys verbatim and ours win in place`() {
// External block with foreign keys around ours; `origin` present
// (overwritten in place), `type`/`pass_state` absent (inserted
// before the closing --- in table order).
let external = "---\ntitle: Outside\norigin: ai\ndate: 2026-10-11\n---\n# Body"
#expect(PostFrontmatter.mergingImport(text: external, origin: .writer)
== "---\ntitle: Outside\norigin: writer\ndate: 2026-10-11\ntype: post\npass_state: First Draft\n---\n# Body")
// #95: an external `type: outline` still imports as post.
#expect(PostFrontmatter.mergingImport(text: "---\ntype: outline\n---\nB", origin: .writer)
== "---\ntype: post\npass_state: First Draft\norigin: writer\n---\nB")
// Bare file → the fresh block, body verbatim below.
#expect(PostFrontmatter.mergingImport(text: "# Bare", origin: .ai)
== "---\ntype: post\npass_state: First Draft\norigin: ai\n---\n# Bare")
// #180: a hand-edit blank above the `---` survives import (the old
// writer dropped it — lossless through every posture is the contract).
#expect(PostFrontmatter.mergingImport(text: "\n---\ntitle: Outside\n---\n# B", origin: .writer)
== "\n---\ntitle: Outside\ntype: post\npass_state: First Draft\norigin: writer\n---\n# B")
}
@Test func `update-keys stamps in place and keeps every other line byte-identical`() {
// An existing key overwrites in place; foreign keys and the body
// never move.
#expect(PostFrontmatter.updating(text: withForeign, with: [("pass_state", "Pass-1 Done")])
== "---\nforeign_key: keep-me\ntype: post\npass_state: Pass-1 Done\norigin: writer\n---\n# Body")
// An absent key inserts before the closing --- (pair order).
#expect(PostFrontmatter.updating(text: withForeign, with: [("micropub_url", "https://micro.blog/x")])
== "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\nmicropub_url: https://micro.blog/x\n---\n# Body")
// Bare text → a fresh block prepends, body rides verbatim.
#expect(PostFrontmatter.updating(text: "# Bare", with: [("pass_state", "Pass-1 Done")])
== "---\npass_state: Pass-1 Done\n---\n# Bare")
}
@Test func `update-keys preserves hand-edit lines above the block`() {
// The #27 review contract, codec-level: lines above the opening
// --- belong to neither block nor body; the stamp keeps them. The
// inserted key lands before the closing --- (after existing keys).
#expect(PostFrontmatter.updating(text: "\n---\ntype: post\n---\n# B", with: [("dismiss_count", "1")])
.hasPrefix("\n---\ntype: post\ndismiss_count: 1\n---\n"))
}
@Test func `foreign keys ride verbatim through every posture chained`() {
// The #180 round-trip pin: import → editor save (owned keys) →
// pass advance → micropub stamp, foreign keys intact at every hop.
var text = PostFrontmatter.mergingImport(text: "---\nforeign: keep\norigin: ai\n---\n# Chain", origin: .writer)
for pairs in [
[("type", "post"), ("pass_state", "First Draft"), ("origin", "writer")],
[("pass_state", "Pass-1 Done")],
[("micropub_url", "https://micro.blog/x")],
] {
text = PostFrontmatter.updating(text: text, with: pairs)
#expect(text.contains("\nforeign: keep\n")) // the line never moved
}
#expect(PostFrontmatter.parse(text)["foreign"] == "keep")
#expect(text.hasSuffix("---\n# Chain")) // body untouched throughout
}
@Test func `unknown type reads leniently as post`() {
#expect(PostFrontmatter.decoded(PostFrontmatter.parse("---\ntype: alien\norigin: writer\npass_state: First Draft\n---\nB")).type == .post)
// The lenient defaults: a bare legacy corpus post is a normal piece.
#expect(PostFrontmatter.decoded([:])
== PostFrontmatter.Stamp(type: .post, passState: .firstDraft, origin: .writer))
}
@Test func `eligibility predicates name the pair and the capture gate`() {
func matter(type: String? = nil, passState: String? = nil, origin: String? = nil) -> [String: String] {
["type": type, "pass_state": passState, "origin": origin].compactMapValues { $0 }
}
// The immutable pair: writer ∧ post, independent of pass_state —
// a writer piece that legitimately advanced still carries its arc.
#expect(PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", passState: "Pass-1 Done", origin: "writer")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "Pass-1 Done", origin: "writer")))
// Capture: the pair ∧ First Draft.
#expect(PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "First Draft", origin: "writer")))
#expect(PostFrontmatter.isCaptureEligible([:])) // bare legacy post qualifies
// Neither gate opens for ai or outline pieces.
#expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", origin: "ai")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", origin: "ai")))
#expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "outline", origin: "writer")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "outline", origin: "writer")))
}
}
+1 -1
View File
@@ -182,7 +182,7 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws {
@Test func `unterminated frontmatter is untitled, never leaked`() {
// No closing ---: frontmatter lines must never leak as the Title.
#expect(Post.title(of: "---\npass_state: First Draft\norigin: writer\n") == "untitled")
#expect(Post.frontmatter(of: "---\npass_state: First Draft\n")["pass_state"] == "First Draft")
#expect(PostFrontmatter.parse("---\npass_state: First Draft\n")["pass_state"] == "First Draft")
}
@Test func `leading blank line still opens frontmatter`() throws {
+11 -11
View File
@@ -309,7 +309,7 @@ private func threeDecimals(_ value: String) -> Bool {
let withForeign = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try withForeign.write(to: url, atomically: true, encoding: .utf8)
let bodyBefore = PostStore.splitFrontmatter(withForeign).body
let bodyBefore = PostFrontmatter.split(withForeign).body
let captured = PostStore.captureFirstDraftStats(
id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home,
@@ -317,7 +317,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(captured)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after) // the trend-view readiness read
let matter = PostFrontmatter.parse(after) // the trend-view readiness read
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable
#expect(matter["stats_burstiness"].map(threeDecimals) == true)
@@ -328,7 +328,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
// Body byte-identical — the stamp never touches content (#31 in-place proof).
#expect(PostStore.splitFrontmatter(after).body == bodyBefore)
#expect(PostFrontmatter.split(after).body == bodyBefore)
}
@Test func `capture refuses an ai origin piece untouched`() throws {
@@ -369,7 +369,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home))
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home))
let matter = try Post.frontmatter(of: String(
let matter = try PostFrontmatter.parse(String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
))
#expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won
@@ -394,7 +394,7 @@ private func threeDecimals(_ value: String) -> Bool {
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
let matter = PostFrontmatter.parse(after)
#expect(matter["stats_captured"] != nil)
#expect(after.contains("# Bare")) // the body survived the fresh-block prepend
}
@@ -416,14 +416,14 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(advanced == .pass1Done)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
let matter = PostFrontmatter.parse(after)
#expect(matter["pass_state"] == "Pass-1 Done")
#expect(matter["stats_captured"] != nil) // survived the advance
#expect(matter["stats_trigram_repetition"] != nil)
#expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.")
#expect(PostFrontmatter.split(after).body == "# Kept\n\nBody stays.")
}
@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws {
@@ -442,13 +442,13 @@ private func threeDecimals(_ value: String) -> Bool {
try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = Post.frontmatter(of: after)
let matter = PostFrontmatter.parse(after)
#expect(matter["stats_captured"] != nil) // survived the editor save
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
#expect(PostFrontmatter.split(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
}
@Test func `overwrite normalizes a bare post with the full stamp`() throws {
@@ -465,9 +465,9 @@ private func threeDecimals(_ value: String) -> Bool {
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8,
)
let matter = Post.frontmatter(of: after)
let matter = PostFrontmatter.parse(after)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.")
#expect(PostFrontmatter.split(after).body == "Bare body, edited.")
}
+2 -2
View File
@@ -575,7 +575,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
#expect(verbatim.hasPrefix("---\ntype: post\n"))
#expect(verbatim.contains("pass_state: First Draft"))
#expect(verbatim.contains("origin: writer"))
#expect(PostStore.splitFrontmatter(verbatim).body == "# Chapter\n- one\n - nested")
#expect(PostFrontmatter.split(verbatim).body == "# Chapter\n- one\n - nested")
// folder never moved; scan reads the new type on rescan
#expect(Post.scan(home: home).first?.id == post.id)
#expect(Post.scan(home: home).first?.type == .post)
@@ -584,7 +584,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
try PostStore.convert(id: post.id, headingsLadder: true, home: home)
let ladder = try readPost(home, post.id)
#expect(ladder.hasPrefix("---\ntype: post\n"))
#expect(PostStore.splitFrontmatter(ladder).body == "# Chapter\n## one\n### nested")
#expect(PostFrontmatter.split(ladder).body == "# Chapter\n## one\n### nested")
// a vanished piece throws, never resurrects
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
+176 -62
View File
@@ -5,6 +5,9 @@
// #108 audit: the model-layer lifecycle the store tests can't see —
// archive clearing the open session, move reopening it at the new parent,
// restore keeping the writer in the piece, New Project's draft targeting.
// #179: the write-rail pins — one seam pairs every library store write
// with exactly one rescan and owns the error strip; the model owns the
// Home (no method takes one).
//
import Foundation
@@ -27,10 +30,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
@Test @MainActor func `archiving the open piece clears selection and session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home)
model.select(post.id, home: home)
model.select(post.id)
#expect(model.session?.postID == post.id)
model.archivePost(post, home: home)
model.archivePost(post)
#expect(model.selectedPostID == nil)
#expect(model.session == nil)
@@ -41,10 +44,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
@Test @MainActor func `moving the open piece reopens its session at the new parent`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Traveler\n", project: "essays", home: home)
model.select(post.id, home: home)
model.select(post.id)
#expect(model.session?.folderURL.path.contains("projects/essays") == true)
model.moveToProject(post, project: "posts", home: home)
model.moveToProject(post, project: "posts")
#expect(model.session?.postID == post.id) // same piece, fresh session
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
@@ -55,10 +58,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Revived\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id, home: home) // opened from the Archive pane
model.select(post.id) // opened from the Archive pane
#expect(model.session?.folderURL.path.contains("archive/") == true)
model.restorePost(post, home: home)
model.restorePost(post)
#expect(model.selectedPostID == post.id) // the writer stays in it
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
@@ -73,7 +76,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
#expect(model.draft?.project == "essays")
model.updateDraft("# Fresh\n")
model.saveDraft(home: home)
model.saveDraft()
let scanned = Post.scan(home: home)
#expect(scanned.first?.project == "essays")
@@ -100,10 +103,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Keeper\n\nDirty.") // inside the debounce window
model.unarchiveProject("posts", home: home)
model.unarchiveProject("posts")
// The edits landed on disk (readBody resolves by id — through the move).
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nDirty.")
@@ -121,7 +124,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
model.select(post.id, home: home)
model.select(post.id)
model.newOutline()
@@ -142,7 +145,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
model.newOutline()
model.saveDraft(home: home)
model.saveDraft()
#expect(model.draft == nil)
#expect(model.lastError == nil)
@@ -157,7 +160,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home) // empty — no pieces
#expect(model.moveTargets(home: home) == ["essays", "posts"])
#expect(model.moveTargets() == ["essays", "posts"])
// "posts" exists too (bind created it); a dot-project never shows.
}
@@ -177,7 +180,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.select(post.id)
#expect(model.outlineGuardPieceID == post.id) // the ask is up
#expect(model.session == nil) // nothing editable while it's up
@@ -191,8 +194,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineInProse(home: home)
model.select(post.id)
model.openGuardedOutlineInProse()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
@@ -209,8 +212,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home)
model.select(post.id)
model.openGuardedOutlineAsOutline()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
@@ -226,13 +229,13 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.select(post.id)
model.cancelOutlineGuard()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session == nil)
// Still guarded: the next open re-fires the ask, file untouched.
model.select(post.id, home: home)
model.select(post.id)
#expect(model.outlineGuardPieceID == post.id)
}
@@ -242,12 +245,12 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home) // consent; disk still mixed
model.select(post.id)
model.openGuardedOutlineAsOutline() // consent; disk still mixed
let session = try #require(model.session)
session.edit("- one\n- two\nedited") // dirty; debounce armed
model.select(post.id, home: home) // muscle-memory re-click on the open row
model.select(post.id) // muscle-memory re-click on the open row
#expect(model.outlineGuardPieceID == nil) // no re-ask over a prior answer
#expect(model.session === session) // the open session survives, dirty state intact
@@ -257,15 +260,15 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home) // ask up
model.select(post.id) // ask up
model.newPost() // ⌘N fires while the sheet is up
#expect(model.outlineGuardPieceID == nil) // the ask died with the displacement
#expect(model.draft != nil)
model.updateDraft("# Keep me\n")
// Answering the (now-gone) ask is inert — the draft survives.
model.openGuardedOutlineInProse(home: home)
model.openGuardedOutlineAsOutline(home: home)
model.openGuardedOutlineInProse()
model.openGuardedOutlineAsOutline()
#expect(model.draft != nil)
#expect(model.selectedPostID == nil) // the draft still owns the editor
}
@@ -279,7 +282,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
}
#expect(model.posts.contains(where: { $0.id == post.id }))
model.select(post.id, home: home)
model.select(post.id)
#expect(model.outlineGuardPieceID == post.id) // the scan path guards too
}
@@ -288,11 +291,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
let clean = try PostStore.writeNew(body: "# Clean\n\n- one\n- two\n", type: .outline, home: home)
let prose = try PostStore.writeNew(body: "# Plain\n\nA paragraph.\n", home: home)
model.select(clean.id, home: home)
model.select(clean.id)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == clean.id)
model.select(prose.id, home: home)
model.select(prose.id)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == prose.id)
}
@@ -302,12 +305,12 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `convert reopens the open piece routed to prose`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home)
model.select(post.id, home: home)
model.select(post.id)
model.stageConversion(post, home: home)
model.stageConversion(post)
#expect(model.pendingConversion?.id == post.id)
#expect(model.pendingConversion?.lossy == false) // clean outline
model.convertToPost(headingsLadder: true, home: home)
model.convertToPost(headingsLadder: true)
#expect(model.pendingConversion == nil)
#expect(model.session?.postID == post.id) // reopened on the converted body
@@ -321,10 +324,10 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let open = try PostStore.writeNew(body: "# Stay\n", home: home)
let outline = try PostStore.writeNew(body: "- a\n - b", type: .outline, home: home)
model.select(open.id, home: home)
model.select(open.id)
model.stageConversion(outline, home: home)
model.convertToPost(headingsLadder: false, home: home)
model.stageConversion(outline)
model.convertToPost(headingsLadder: false)
#expect(model.session?.postID == open.id) // untouched
#expect(model.selectedPostID == open.id)
@@ -344,9 +347,9 @@ private func writeMixedOutline(home: URL) throws -> Post {
}
#expect(model.posts.first(where: { $0.id == post.id })?.type == .outline)
model.select(post.id, home: home)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home) // VERBATIM
model.select(post.id)
model.stageConversion(post)
model.convertToPost(headingsLadder: false) // VERBATIM
#expect(model.proseOverridePostID == post.id)
#expect(model.session?.postID == post.id)
@@ -362,11 +365,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `dirty open piece flushes before the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Chapter\n- one\n - typed child") // unflushed edit
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(onDisk.contains("type: post"))
@@ -376,11 +379,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `staging warns from the session text when the piece is dirty`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
model.select(post.id, home: home)
model.select(post.id)
// prose typed since the last flush — disk still clean, session is not
model.session?.edit("# Clean\n- one\nA paragraph between bullets.\n- two")
model.stageConversion(post, home: home)
model.stageConversion(post)
#expect(model.pendingConversion?.lossy == true) // from session.text, not stale disk
}
@@ -389,7 +392,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home) // closed piece — disk is the truth
model.stageConversion(post, home: home)
model.stageConversion(post)
#expect(model.pendingConversion?.lossy == true)
}
@@ -398,13 +401,15 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
model.stageConversion(post, home: home) // staged clean, no warning shown
model.stageConversion(post) // staged clean, no warning shown
// a foreign write makes the body mixed while the sheet was up
let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
try PostStore.stamped(body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline)
.write(to: file, atomically: true, encoding: .utf8)
try PostFrontmatter.stamped(
body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline,
)
.write(to: file, atomically: true, encoding: .utf8)
model.convertToPost(headingsLadder: true, home: home)
model.convertToPost(headingsLadder: true)
#expect(model.lastError?.contains("nothing was converted") == true)
#expect(model.session?.postID == nil || model.session?.postID != post.id)
@@ -413,8 +418,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
#expect(onDisk.contains("A paragraph between bullets."))
// the consented path still converts: a WARNED mixed piece + Headings proceeds
model.stageConversion(post, home: home) // now stages lossy from disk
model.convertToPost(headingsLadder: true, home: home)
model.stageConversion(post) // now stages lossy from disk
model.convertToPost(headingsLadder: true)
let converted = try String(contentsOf: file, encoding: .utf8)
#expect(converted.contains("type: post"))
#expect(!converted.contains("A paragraph between bullets.")) // dropped, as consented
@@ -423,14 +428,14 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `unanswered conflict aborts the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one", type: .outline, home: home)
model.select(post.id, home: home)
model.select(post.id)
// #67 conflict up: disk holds foreign text, the editor's version unwritten
model.session?.diskDidChange(diskText: "# Foreign rewrite\nbody")
#expect(model.session?.conflictAlert == true)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
#expect(model.lastError?.contains("reload question") == true)
#expect(model.session?.conflictAlert == true) // still answerable, not trampled
@@ -441,13 +446,13 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `failed flush aborts the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
model.select(post.id, home: home)
model.select(post.id)
model.session?.edit("# Chapter\n- one\n - child") // dirty
// vanish the piece: the flush throws (never resurrects), convert must abort
try FileManager.default.removeItem(at: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true))
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: true, home: home)
model.stageConversion(post)
model.convertToPost(headingsLadder: true)
#expect(model.lastError?.contains("nothing was changed") == true)
#expect(model.session?.postID == post.id) // session stays up, dirty and honest
@@ -457,11 +462,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id, home: home) // guard fires, open held
model.select(post.id) // guard fires, open held
#expect(model.outlineGuardPieceID == post.id)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
#expect(model.outlineGuardPieceID == nil) // the stale ask died with the outline
#expect(model.selectedPostID == nil) // cancel teardown: nothing was open
@@ -483,13 +488,122 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
}
}
// #179: the rail's rescan lands via Task — bounded poll (FixCardApplyTests'
// pollUntil, made internal; the post-loop expect makes a silent timeout a
// failure, not a pass).
/// Scenario: one write rail for every library verb (from #179).
/// Given a model bound to a Home, when a verb's store write runs, then it
/// lands through the ONE seam — the library reflects it via exactly one
/// rescan and a stale error strip is cleared on success.
/// Suite member (not free function): suite-name filters must reach the
/// rail pins (MuseionTests/AGENTS.md rule).
@Suite("write rail #179")
struct PostsModelWriteRailTests {
@Test @MainActor func `pairs the write with the library refresh and clears the strip`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Rail Pin\n", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
model.lastError = "stale strip" // the rail owns the strip from here
model.rename(post, to: "Rail Pin Two")
#expect(model.lastError == nil)
try await pollUntil { model.posts.contains { $0.id == "rail-pin-two" } }
#expect(model.posts.contains { $0.id == post.id } == false)
}
/// Scenario: the rail owns the error strip on a failed write (from #179).
/// Given a bound model and a store write that throws, the verb's failure
/// reason lands in the strip AND rides the return for the sheet.
@Test @MainActor func `owns the strip when the write throws`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "dup", home: home) // the store already has it
let reason = model.createProject(named: "dup")
#expect(reason != nil)
#expect(model.lastError == reason)
}
/// Scenario: the rail refuses cleanly with no Home bound (from #179).
/// Given a model that was never bound, a write verb refuses with a reason
/// and nothing reaches any disk.
@Test @MainActor func `refuses cleanly before a home is bound`() {
let model = PostsModel()
let reason = model.createProject(named: "nowhere")
#expect(reason != nil)
#expect(model.lastError == reason)
#expect(model.posts.isEmpty)
}
/// Scenario: a mid-batch import failure keeps its strip message while
/// the good files land (from #179 — the rail clears the strip BEFORE
/// the write exactly so the per-file failures set inside the closure
/// survive the success tail).
@Test @MainActor func `import batch keeps per-file failure messages on the strip`() async throws {
let (model, _) = try makeModelHome()
let scratch = FileManager.default.temporaryDirectory
.appendingPathComponent("import-batch-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)
let good = scratch.appendingPathComponent("good.md")
try "# Good Piece\n".write(to: good, atomically: true, encoding: .utf8)
let missing = scratch.appendingPathComponent("missing.md") // never written — the read throws
model.stageImport([good, missing])
model.importFiles(origin: .writer)
#expect(model.lastError?.contains("Import failed — missing.md") == true)
// the library refresh rides the rail's rescan Task — poll for it
try await pollUntil { model.posts.contains { $0.id == "good-piece" } }
#expect(model.selectedPostID == "good-piece") // …and opened (synchronous select)
}
/// Scenario: a Home repoint while a pass runs refuses the pass advance
/// (from #179 audit — the rail resolves watchedHome at call time, and
/// the engine's turn spans minutes). Given a pass that ends normally
/// after its library was repointed, the advance is refused with the
/// honest strip message, both libraries keep their pass states, and
/// nothing was written into the new library.
@Test @MainActor func `home repoint mid-pass refuses the advance`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Repoint\n", home: rig.home)
rig.model.select(post.id)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
try await pollUntil { rig.model.runningPass == .pass1 } // the engine holds the turn
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
// 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
// under load (the #30/#147 flake family). #require afterwards:
// nothing held after the poll means the parked prompt hit its
// deadline — fail loudly, not on a confusing nil strip.
let engine = try #require(rig.mentor.host.oneShot as? ScriptedEngine)
try await pollUntil { engine.hasHeldPrompt }
try #require(engine.endHeldPrompt())
await run.value
#expect(rig.model.lastError == "The library changed while the pass ran — its Pass State was not advanced.")
#expect(Post.scan(home: rig.home).first?.passState == .firstDraft) // the pass's own library: not advanced
#expect(Post.scan(home: homeB).isEmpty) // the new library: nothing stamped
}
}
@Test @MainActor func `opening a piece surfaces its stored fix cards`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
model.select(post.id)
try await waitForCards(model, 1)
#expect(model.openPieceCards.map(\.pattern) == ["Hedging"])
@@ -501,7 +615,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
model.select(post.id)
try await waitForCards(model, 1)
// An MCP client submits another card while the piece stays open —
@@ -520,7 +634,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
model.select(post.id)
try await waitForCards(model, 1)
model.newPost()
@@ -536,7 +650,7 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
#expect(folder.path.contains("/archive/"))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home) // opened from the Archive pane
model.select(post.id) // opened from the Archive pane
try await waitForCards(model, 1)
#expect(model.openPieceCards.count == 1)
+35
View File
@@ -0,0 +1,35 @@
//
// ProfileLayoutTests.swift
// MuseionTests
//
// #182 — the profile layout's one pinning suite.
//
// Scenario: A layout change is one module + one suite — From user story #182
// Given the Hermes profile layout (root, per-profile dir, .env, marker,
// gateway pid, skills dir) is owned by ProfileLayout alone
// When any layout fact moves (root renamed, a file renamed)
// Then ProfileLayout.swift plus exactly this suite change — the provisioner,
// the settings writer, and backup/restore derive every path through it and
// no literal profile-root string exists outside the layout module.
//
import Foundation
@testable import Museion
import Testing
@Suite("ProfileLayoutTests")
struct ProfileLayoutTests {
/// Pinned against LITERALS (not the layout's own inputs) so a fact change
/// fails here — this suite is the layout contract of record.
@Test func `root default is the hermes profiles dir`() {
#expect(ProfileLayout.defaultRoot == NSHomeDirectory() + "/.hermes/profiles")
}
@Test func `per-profile path builders pin every layout fact`() {
#expect(ProfileLayout.profileDir("museion-pass1", root: "/r") == "/r/museion-pass1")
#expect(ProfileLayout.envFile(in: "/r/museion") == "/r/museion/.env")
#expect(ProfileLayout.configuredMarker(in: "/r/museion") == "/r/museion/.museion-provisioned")
#expect(ProfileLayout.gatewayPID(in: "/r/museion") == "/r/museion/gateway.pid")
#expect(ProfileLayout.skillsDir(in: "/r/museion") == "/r/museion/skills")
}
}
+6 -2
View File
@@ -35,8 +35,8 @@ struct SeedSkill {
/// 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` force the matching
/// failure. Every `profile create` name appends to
/// 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
@@ -77,6 +77,10 @@ private func fakeHermesConfigCLI() -> String {
fi
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "unset" ]]; then
PROFILE="$2"; KEY="$5"
if [[ -f "${0:h}/config-unset-fails" ]]; then
print "Error: config unset exploded"
exit 1
fi
print -r -- "$*" >> "${0:h}/config-unset-$PROFILE"
STORE="${0:h}/config-store-$PROFILE"
if [[ -f "$STORE" && -n "$(grep -m1 "^${KEY}=" "$STORE")" ]]; then
+117
View File
@@ -0,0 +1,117 @@
//
// ProviderCredentialTests.swift
// MuseionTests
//
// ## Scenario: one credential resolution behind probe and readiness
// From #181
//
// Given a provider, its `.env` key (possibly empty), and the endpoint the
// key would ride
// When the ONE credential resolution runs — Settings' Test Connection and
// pass readiness both call it
// Then a pasted key always wins, a keyless provider on its official
// endpoint borrows the shared Portal session key, and every other empty
// case refuses honestly — the implicit session credential never rides a
// user-set URL.
import Foundation
@testable import Museion
import Testing
@Suite("Provider credential resolution")
struct ProviderCredentialTests {
/// Writes a portal auth store carrying `agent_key` and answers its path.
private func makeAuthFile(key: String) throws -> String {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("cred-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let path = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"\#(key)"}}}"#.write(toFile: path, atomically: true, encoding: .utf8)
return path
}
/// A pasted key always wins — no provider's resolution touches the
/// Portal auth store when its own key is set.
@Test func `pasted key wins for every provider`() async {
let missingAuth = FileManager.default.temporaryDirectory
.appendingPathComponent("cred-missing-\(UUID().uuidString)").path
for provider in ModelProvider.allCases {
let resolved = await ProviderCredential.resolve(
provider: provider,
envKey: "sk-pasted",
endpoint: provider.defaultEndpoint,
portalAuthPath: missingAuth,
)
#expect(resolved == .key("sk-pasted"))
}
}
/// A keyed provider with no key refuses the paste path — the probe's
/// old empty-key precondition, now the shared rail's.
@Test func `keyed provider without a key refuses the paste path`() async {
let resolved = await ProviderCredential.resolve(
provider: .anthropic,
envKey: "",
endpoint: ModelProvider.anthropic.defaultEndpoint,
portalAuthPath: "/nonexistent/auth.json",
)
guard case let .refused(message) = resolved else {
Issue.record("expected a refusal, got \(resolved)")
return
}
#expect(message == "no API key set — paste the key first")
}
/// The keyless fallback: nous on the official endpoint (trailing slash
/// tolerated) borrows the session's agent_key.
@Test func `keyless provider borrows the portal session key on the official endpoint`() async throws {
let authPath = try makeAuthFile(key: "ak-shared-123")
for endpoint in [
ModelProvider.nous.defaultEndpoint,
ModelProvider.nous.defaultEndpoint + "/",
] {
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: endpoint,
portalAuthPath: authPath,
)
#expect(resolved == .key("ak-shared-123"))
}
}
/// Finish-audit #175, on the shared rail: the implicit session
/// credential never rides a user-set URL — a custom endpoint with an
/// empty key refuses even though the login exists.
@Test func `the session key never rides a custom endpoint`() async throws {
let authPath = try makeAuthFile(key: "ak-shared-123")
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: "http://proxy.example/v1",
portalAuthPath: authPath,
)
guard case let .refused(message) = resolved else {
Issue.record("expected the custom-endpoint refusal, got \(resolved)")
return
}
#expect(message.contains("paste an API key"))
}
/// Keyless with neither key nor login names the portal login path,
/// not a bare "no key".
@Test func `keyless without key or login names the portal path`() async {
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: ModelProvider.nous.defaultEndpoint,
portalAuthPath: "/nonexistent/auth.json",
)
guard case let .refused(message) = resolved else {
Issue.record("expected a refusal, got \(resolved)")
return
}
#expect(message.contains("hermes auth add nous"))
}
}
+25
View File
@@ -157,6 +157,14 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable {
queue.sync { heldLoad != nil }
}
/// True while a hangOnPrompt prompt is parked — the #179 repoint pin
/// polls for the PARK (runningPass flips before the one-shot engine
/// even spawns; ending the hold in that window false-fails under load,
/// the #30/#147 flake family).
var hasHeldPrompt: Bool {
queue.sync { heldPromptID != nil }
}
// MARK: EngineTransport
/// The fake always spawns cleanly — there is no process.
@@ -234,6 +242,23 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable {
}
}
/// Test hook (#179 audit): release a held prompt as a NORMALLY ended
/// turn — session/cancel answers "cancelled"; the mid-pass repoint pin
/// needs the turn to end .ended after the hold. Returns false (and
/// no-ops) when nothing is held — e.g. the parked request already hit
/// its deadline under machine load — so the caller can fail loudly
/// instead of reading a confusing nil strip.
@discardableResult
func endHeldPrompt() -> Bool {
queue.sync {
guard let id = self.heldPromptID,
let continuation = self.parked.removeValue(forKey: id) else { return false }
self.heldPromptID = nil
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return true
}
}
/// Test hook: the kill(pid, SIGKILL) rail's in-process twin (#178 B2) —
/// the engine dies unexpectedly: onCrash fires, every pending request
/// fails. The crash-restart pins drive real crashes through this.
+5 -5
View File
@@ -31,12 +31,12 @@ struct SessionLifecycleTests {
let defaultSession = try #require(mentor.activeEntry)
let rosterBefore = mentor.roster.count
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
await model.runPass(.pass1, mentor: mentor)
// The roster never grew — the pass entry is transient.
#expect(mentor.roster.count == rosterBefore)
@@ -69,7 +69,7 @@ struct SessionLifecycleTests {
/// newest-first, active; a non-nil pieceTitle rides the entry —
/// association by convention only.
@Test @MainActor func `freeform new session is rostered newest-first and active`() async throws {
let (model, home, mentor) = try makePassRig()
let (_, _, mentor) = try makePassRig()
defer { mentor.shutdown() }
#expect(!mentor.canStartSession) // never opened — nothing may start
await mentor.openSession()
@@ -200,7 +200,7 @@ struct SessionLifecycleTests {
/// renders, the raw slash command never does, the summary streams into
/// the transcript — and is refused while a turn streams.
@Test @MainActor func `compact sends the labeled command and is refused while streaming`() async throws {
let (model, home, mentor) = try makePassRig()
let (_, _, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
@@ -330,7 +330,7 @@ struct SessionLifecycleTests {
#expect(SessionsPaneView.openPiece(in: nil) == nil) // no Posts at all
let post = try PostStore.writeNew(body: "# Open Piece\n", home: home)
model.select(post.id, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
+2 -2
View File
@@ -78,8 +78,8 @@ struct TrendViewTests {
#expect(abs(captured.stats.trigramRepetition - expected.trigramRepetition) < 0.0005)
// The parsed date round-trips through the exact stamp format — the
// symmetric-read proof, locale-independent by construction.
let onDisk = try Post.frontmatter(
of: String(
let onDisk = try PostFrontmatter.parse(
String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"),
encoding: .utf8,
),
+3 -3
View File
@@ -172,13 +172,13 @@ struct WritingLockTests {
// the outline routing reads the real type, not the lagging list).
let post = try PostStore.writeNew(body: "# Prose piece\n\nBody words.\n", home: home)
try await Self.waitForScan(model, id: post.id)
model.select(post.id, home: home)
model.select(post.id)
#expect(model.canArmWritingLock)
#expect(model.editorBodyText == "# Prose piece\n\nBody words.\n")
let outline = try PostStore.writeNew(body: "- an outline\n", project: "posts", type: .outline, home: home)
try await Self.waitForScan(model, id: outline.id)
model.select(outline.id, home: home)
model.select(outline.id)
#expect(!model.canArmWritingLock)
// A MIXED outline fires the #111 guard ask instead — the held
@@ -186,7 +186,7 @@ struct WritingLockTests {
// branch's fourth path, pinned so the mirror can't drift.
let mixed = try PostStore.writeNew(body: "- bullet\nprose between bullets\n", project: "posts", type: .outline, home: home)
try await Self.waitForScan(model, id: mixed.id)
model.select(mixed.id, home: home)
model.select(mixed.id)
#expect(model.outlineGuardPieceID == mixed.id)
#expect(!model.canArmWritingLock)
}
@@ -0,0 +1,79 @@
# #179 PostsModel write rail — one seam pairs every store write with the rescan
> **Date:** 2026-11-09
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/179
## Goal
From the 2026-11-09 architecture review (content line, step 1 of 2): route every library verb through ONE internal seam that pairs the store write with the library rescan and owns the error strip — fourteen hand-copied write-then-rescan-then-error choreographies meant a new verb could silently forget the pairing. The model owns the Home: the parameter disappears from its public methods, construction and the Settings repoint remain the only two places it is set. The editor's flush keeps its own posture outside the rail.
## What Was Done
- `performWrite` write rail in `Museion/PostsModel.swift` (~:209) — one seam: closure takes the bound Home, a clean run fires exactly one `Task { await rescan() }` and returns nil, a throw lands `localizedDescription` in the strip and returns the reason; nil-Home refuses with nothing written.
- 10 verbs + the pass advance converted: `saveDraft`, `newPostFromSession`, `rename`, `trash`, `createProject`, `moveToProject`, `archivePost`, `restorePost`, `unarchiveProject`, `importFiles`, `runPass`'s `advancePassState`. Post-write state surgery rides inside each verb's closure (runs only on write success). Grep-proof: `Task { await rescan() }` now exists only in `bind` (initial scan), the rail, and the watcher.
- Model owns the Home: `watchedHome` is `private(set)` (set only by `bind`/`startWatching`); every public method dropped its `home:` parameter — `select`, `saveDraft`, `rename`, `trash`, `createProject`, `moveTargets`, `moveToProject`, `archivePost`, `restorePost`, `unarchiveProject`, `importFiles`, `stageConversion`, `convertToPost`, the guard answers, `runPass`, `blindRead`, `applyCard`/`skipCard`/`doneCard`/`promoteCard`, `micropubSendDraft`, `refreshCards`.
- Call-site sweep: 14 view sites (WorkspaceView, PostsPaneView, SessionsPaneView, MentorPaneView, FixCardsWindow, PromoteAskSheet, MicropubPublishSheet) and ~115 test sites across 9 test files; dead `home` plumbing cut (ArchivePaneView property, PassBarView property, ApplyAskSheet/PromoteAskSheet/MicropubPublishSheet properties, two test bindings).
- 5 rail pins in `@Suite("write rail #179") struct PostsModelWriteRailTests` (suite members — name filters reach them, verified `-only-testing` 5/5): write→refresh+strip-cleared, failed write owns the strip, nil-Home refusal, import batch keeps per-file strip messages, mid-pass Home repoint refuses the advance.
- Audit fixes (finish-audit fanout, 3 reviewers): repoint guard before the advance (`PostsModelPasses.swift:88`), dead-code cuts, `waitForPosts`→`pollUntil` consolidation (made internal in FixCardApplyTests).
- Rig: `ScriptedEngine.endHeldPrompt()` — releases a held prompt as a NORMALLY ended turn (session/cancel only ever answers "cancelled"; the repoint pin needs `.ended` after the hold).
- DOX: `Museion/AGENTS.md` PostsModel bullet (#179 write rail contract + runPass repoint refusal), `MuseionTests/AGENTS.md` suite map (rail pins + rig hook).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Strip clears BEFORE the write, not after | `importFiles` sets per-file failure messages mid-closure and must keep them while the batch still rescans; clear-before preserves that with zero special-casing. Flip-verified by its pin. |
| `createProject` failure now shows in sheet AND strip | Issue: "the seam owns the error strip" — supersedes the #108 sheet-only rule. Flagged to the maintainer; default kept. |
| `saveDraft` rides the rail | Read "the editor's flush/save-draft keeps its own posture" as EditorSession's debounced flush (⌘S on a saved piece); the verb list explicitly names "create post / outline" (= saveDraft). Flagged to the maintainer. |
| Card closes, pass substrate (`snapshotPass`/stats/lint), micropub publish stay OFF the rail | None regroup the library (no rescan owed); micropub's stamp failure must never un-send the draft. Documented in code + AGENTS. |
| Repoint guard (`watchedHome == home`) over passing the frozen home into the rail closure | Security reviewer's one-liner would write library A while the rail rescans library B — the exact desync the rail exists to kill. The guard keeps write+rescan consistent and refuses honestly. Converged finding (security + general, independent). |
| `conversionWentLossyBehindAsk` helper | #142: swiftformat pushes a wrapped condition list's brace to its own line, swiftlint flags it, and nested ifs get collapsed into a 154-char line — the hoisted helper is the sanctioned escape. |
| Nil-Home: rail speaks, pre-bind paths silently no-op | Pre-bind verb calls are unreachable in practice (every path needs posts/session ⇒ bound); the rail's refusal is the only reachable one and it says so. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| swiftformat collapsed the nested-if guard into one 154-char line (new lint warning) | #142 formatter/linter brace fight; swiftformat reflows wraps AND merges nested ifs | Hoisted `conversionWentLossyBehindAsk` helper — short condition, guard-shaped, stable under both tools |
| Test sweep left ~28 straggler call sites | First sed pass only handled trailing/first-arg `home:` shapes; mid-list `, home: home, ` and multiline continuation forms missed | Second scoped pass on those two shapes; compiler caught the rest |
| `import batch` pin failed on first run | Library refresh rides the rail's rescan Task (async by design); the pin asserted `model.posts` synchronously | Poll via `pollUntil` (the suite's own convention); strip + select assertions stay synchronous |
| Two xcresult summary reads died on a half-written bundle | `ls -td … \| head -1` chained to xcodebuild's exit races bundle finalization | Read the bundle in a LATER command (known #33 learning — re-bitten twice, worth re-pinning) |
| Full suite exceeds the 420 s foreground terminal cap | Suite grew to ~8 min under load | `build-for-testing` + `test-without-building` split, suite run as a tracked background job with notify |
| Repoint pin failed once in a full run (`lastError → nil`) | The parked scripted prompt hit its deadline while the UI-test runner starved the machine enabling automation mode; `endHeldPrompt` no-opped silently | Pin green isolated (5/5) and in the prior full run; `endHeldPrompt` now returns whether it released (queue.sync) and the pin `#require`s it — the next occurrence fails loudly (#30 flake family) |
| Next-morning verify run: BOTH test runners "hung before establishing connection", zero tests executed | #134 machine wedge — testmanagerd/automation daemon degraded through the evening, reboot pending; an untouched control suite (WritingGoalTests) hangs identically | Machine-state, not the diff: 657/657 green the prior evening on this code, rail pins 5/5 isolated after the last (test-only) edit; committed with the wedge named |
## Verification
- `build-for-testing`: **SUCCEEDED** at the final tree (re-verified after every edit, incl. the test-rig hardening).
- Full suite (`test-without-building`): **657/657 passed, 0 failed, 0 skipped** — verified by xcresult counts, never the banner (655 pre-existing + 2 new pins; the 3 original rail pins were already in the 655 count). One later full run flaked the repoint pin under UI-runner load (see Gotchas — passed isolated, rig hardened); the next-morning re-run could not start at all: BOTH runners hung before establishing connection (#134 machine wedge, control suite hangs identically) — the 657/657 evening run on this code plus a 5/5 isolated rail-suite run after the last test-only edit are the verification of record.
- Flip cycle: repoint guard `|| true` + rail clear-ordering flipped in one edit → both target pins FAILED, other three passed; restored → green. Each pin discriminates its own guard.
- swiftformat clean; swiftlint **279 = 279** pre-change baseline parity (no new violations).
- GitNexus: impact read before editing (verbs LOW; `refreshCards` CRITICAL / `openUnguarded` HIGH = hub fan-out on signature-only changes); `detect-changes` scope = intended symbols only; index re-analyzed.
- Reviews: implement-close two-axis review (Standards+Spec) AND finish-audit three-reviewer fanout (ponytail/security/general) — 2+5 findings triaged, 7 fixed, rest accepted-as-designed with rationale above.
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostsModel.swift` | `performWrite` rail; verbs converted; `watchedHome` private(set); header |
| `Museion/PostsModelOutline.swift` | Home-less guard/convert verbs; `conversionWentLossyBehindAsk` helper |
| `Museion/PostsModelPasses.swift` | `runPass`/`blindRead` Home-less; advance on the rail; mid-pass repoint guard |
| `Museion/PostsModelCards.swift` | Card verbs + `refreshCards` Home-less |
| `Museion/Micropub.swift` | `micropubSendDraft` Home-less (off-rail, documented) |
| `Museion/WorkspaceView.swift`, `PostsPaneView.swift`, `SessionsPaneView.swift`, `MentorPaneView.swift`, `FixCardsWindow.swift`, `PromoteAskSheet.swift`, `MicropubPublishSheet.swift` | Call-site sweep + dead `home` plumbing cut |
| `MuseionTests/PostsModelTests.swift` | `PostsModelWriteRailTests` suite: 5 pins + scenario headers |
| `MuseionTests/ScriptedEngine.swift` | `endHeldPrompt()` test hook |
| `MuseionTests/FixCardApplyTests.swift` | `pollUntil` made internal (shared poll) |
| 8 further test files | Mechanical `home:` sweep |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX: write-rail contract, repoint refusal, suite map |
## Open Items & Next Steps
- [ ] Maintainer ruling: `createProject` failure double-message (sheet + strip) — default kept per the issue's rail-owns-the-strip posture.
- [ ] Maintainer ruling: `saveDraft` on the rail (reading of "the editor's flush/save-draft").
- [ ] None otherwise — all five acceptance criteria of #179 met and pinned.
---
*Log written by write-log skill*
@@ -0,0 +1,69 @@
# #180 PostFrontmatter codec — one read/write engine, named eligibility predicates
> **Date:** 2026-11-10
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/180
## Goal
Consolidate the three near-twin post frontmatter writers (fresh stamp, import merge, in-place key update) into ONE codec module behind one known-key table and one insertion-order rule; name the Unaided First Draft eligibility pair once and consume it from both gates; keep every existing piece byte-identical on disk. Step 2 of 2 of the 2026-11-09 architecture review's content line.
## What Was Done
- New `Museion/PostFrontmatter.swift` — the codec: the lenient read (`parse` moved from `Post.frontmatter(of:)`, `split` from `PostStore.splitFrontmatter`, plus `decoded` — the ONE lenient `?? default` stamp decode, extracting the third copy the #31 ponytail note deferred) and the three named write postures: `stamped` (fresh), `mergingImport` (external keys verbatim, ours win), `updating` (the in-place line-walk moved verbatim from `LearningDecay.stampingFrontmatter`). One known-key table: `ownedKeys(type:passState:origin:)`.
- Two named eligibility predicates, consumed by both gates: `isUnaidedFirstDraftPair` (writer ∧ post — `Post.scan`'s read-back gate in `PostLibrary.parse`) and `isCaptureEligible` (pair ∧ First Draft — `PostStore.captureFirstDraftStats`).
- Deleted the twins: `PostStore.stamped`, `PostStore.splitFrontmatter`, `PostStore.mergedFrontmatter`, `LearningDecay.stampingFrontmatter`, `Post.frontmatter(of:)` — 21 call sites swept across 7 production files (PostStore, PostLibrary, LearningDecay, FixCardStore ×2, LearningsPaneView, PostsModelOutline, Micropub) and 8 test files.
- New `MuseionTests/PostFrontmatterTests.swift` — 7 pins: fresh-stamp byte shape, merge-import (foreign keys verbatim, ours win in place, bare file, #180 prefix-preservation divergence), update-keys (in-place overwrite, insert-before-close, bare prepend, hand-edit lines above the block), the chained posture round-trip (import → save → advance → micropub, foreign key verbatim at every hop), lenient unknown-type decode, and the two predicates' truth table (pair true at Pass-1 Done, capture false — the AC's exact distinction).
- DOX pass: root AGENTS.md trust-boundaries learning re-pointed to the new symbols; `Museion/AGENTS.md` map entry + PostStore/PostLibrary bullets; `MuseionTests/AGENTS.md` suite map.
- Reviews: implement-close Standards+Spec fanout (2 findings, both fixed), finish-audit fanout (ponytail/security/general — 0 critical, 1 shrink applied, 2 comment fixes applied, 1 security INFO deferred with a ceiling comment).
Net **−133 lines**, 18 files modified + 2 new.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `mergingImport` = one line over `updating` with `ownedKeys` | The import twin's line-walk was byte-for-byte the same walk; unifying killed the twin. Only reachable delta: hand-edit lines above `---` now SURVIVE import where the old split-first shape dropped them — deliberate, lossless-direction divergence, doc-commented on `mergingImport` and pinned in the suite (both reviewers converged on flagging it unpinned; the pin + comment landed). |
| `overwrite`'s blocked path keeps the `split(updating(...)).block + body` dance | Preserves the exact old composition (update walk → re-split → take block → swap body), so save output stays byte-identical including the prefix-drop the re-split incidentally performs. No fourth posture invented for one caller. |
| `decoded` returns a `Stamp` struct, not a 3-tuple | swiftlint `large_tuple` (default rules) warns on >2-element tuples; the struct reads better at call sites and carries `Equatable` for the bare-defaults pin. |
| `isCaptureEligible` re-derives the pair instead of calling `isUnaidedFirstDraftPair` | One decode instead of two; identical semantics (lenient triple + three equals). |
| Learnings dismiss rides `PostFrontmatter.updating` | Ticket keeps Learning/Fix Card DOCUMENTS out of scope, but deleting `stampingFrontmatter` (an AC) forces its one learning caller onto the codec's generic walk — mechanical reuse, document shape unchanged. |
| `Post.title(of:)` NOT unified with `split` | Title's unterminated-block branch returns `untitled`; split's returns the whole text as body. Different contracts; unifying would change bytes. Out of scope. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| My first prefix pin expected the inserted key ABOVE existing keys | The walk inserts before the CLOSING `---` (after existing keys) — the code was right, the pin was wrong | Corrected the expectation to the real shape; test green |
| `home repoint mid-pass refuses the advance` failed in both full-suite runs | Pre-existing #179 timing flake: the held prompt times out under full-suite machine load before `endHeldPrompt` — the test's own comment predicts it | PROVEN pre-existing: full suite on stashed clean main failed the same test; the suite in isolation (5/5) and the final verify run (664/664) pass. Not this diff's seam. |
| One new line_length violation after the rename sweep | `PostStore.stamped(` → `PostFrontmatter.stamped(` grew PostsModelTests:407 to 146 chars | Wrapped the call; swiftlint back to exactly the clean-main count (279) |
| Mixed `//` + `///` comment block on `mergingImport` | The #143 orphaned-doc-comment trap | Folded into one `///` block with a blank `///` separator |
| Terminal cwd drifted into a reviewer child's scratch probe dir | Child probe dirs share the session shell | Re-ran with explicit workdir; no repo files touched |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostFrontmatter.swift` | NEW — the codec: parse/split/decoded, three postures, ownedKeys, two predicates |
| `MuseionTests/PostFrontmatterTests.swift` | NEW — 7 pins incl. the posture round-trip and prefix divergence |
| `Museion/PostStore.swift` | Swept to the codec; mergedFrontmatter/stamped/splitFrontmatter deleted; capture gate → isCaptureEligible |
| `Museion/PostLibrary.swift` | parse → codec read; read-back gate → isUnaidedFirstDraftPair; Post.frontmatter deleted |
| `Museion/LearningDecay.swift` | dismiss → codec updating; stampingFrontmatter deleted |
| `Museion/FixCardStore.swift` ×2 sites, `Museion/LearningsPaneView.swift`, `Museion/PostsModelOutline.swift`, `Museion/Micropub.swift` | Mechanical read-site sweep |
| `MuseionTests/` (8 files) | Mechanical rename sweep + comment fixes |
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass |
## Open Items & Next Steps
- [ ] Flat-key ceiling: an indented `key: value` inside a nested YAML block scalar is rewritten unindented by the walk (inherited verbatim from the deleted writers; security-review INFO-1, local-only, user's own import). Recorded as a `ponytail:` comment at the walk; indentation-aware walk only if nested frontmatter ever matters.
- [ ] The `home repoint mid-pass` flake remains open from #179 (fails under full-suite load ~2/3 runs this session, green in isolation and in the final run) — its timing assumptions, not this ticket.
## Verification
- `build-for-testing` exit 0; `test-without-building` exit 0 — **664 executed / 664 passed / 0 failed** (xcresult count, not the banner).
- swiftformat clean; swiftlint 279 violations = exact clean-main parity.
- GitNexus detect-changes (index-relative): affected flows all route through `overwrite`/`learnings` — the diff's own seams.
---
*Log written by write-log skill*
@@ -0,0 +1,66 @@
# Provider descriptor + Pass Readiness — provider facts as data, one credential resolution
> **Date:** 2026-11-10
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/181
## Goal
Issue #181 (from the 2026-11-09 architecture review, settings cluster): per-provider facts become **data on the provider enum** instead of five switches across Settings, the probe, and the pane; **one credential-resolution function** (provider key, else the shared Portal session key for keyless providers) serves Test Connection and pass readiness; **pass readiness leaves the session model** into its own module; the probe's **dialect selector keys off the descriptor** (SSE decoders stay separate functions); rider: **runPass and blindRead share one guard helper**. Red line (ADR-0014): provider metadata only — no app-side model-settings store. Blocked by #178 (closed — verified before work started).
## What Was Done
- `ModelProvider` is now the provider-descriptor table: existing facts (label, effort ladder, flagship, default endpoint, env var) joined by `dialect` (`Dialect` enum: chat/models paths + the SSE decoder selector), `authMode` (`AuthMode`: Bearer vs Anthropic's `x-api-key` + pinned version), `keyless` (nous rides the Portal login), and `trimmedEndpoint(_:)` — the ONE trailing-slash normalization shared by the probe's URL builders and the credential gate.
- `ProviderCredential.resolve` (SettingsModel.swift) — the ONE credential rail: pasted key wins; keyless providers fall back to the Portal session key **only on the official default endpoint**; refusals name the paste-a-key path or `hermes auth add nous`. Settings' `testConnection` and pass readiness both call it (the twice-implemented #175 fallback is now one function).
- `Museion/PassReadiness.swift` (new) — the readiness module: reads each pass surface's provider + `.env` key through the `SettingsWriting` seam, resolves credentials through `ProviderCredential`, answers `[PassKind: PassReadiness]`. `MentorSessionModel.refreshPassReadiness` is a thin delegate; the model reads no keys and no auth files.
- `ProviderProbe` — `chatURL`/`modelsURL`/`applyAuth`/`decodeChat` select by `provider.dialect` / `provider.authMode`; the per-dialect request bodies and stream decoders stay separate functions.
- `PostsModelPasses.guardOpenPieceRun` — the ONE guard rail behind `runPass` and `blindRead` (nothing running, mentor not mid-turn, engine ready, open saved piece); returns `(id, session)`; refusal strings byte-identical to the old per-runner messages except the busy message now names the actual blocker.
- `ProviderCredentialTests` (new, 5 pins) — the shared credential suite; `ScriptedEngine.hasHeldPrompt` + a poll in the #179 repoint pin de-flake the spawn-window race; PassRunTests' open-piece pin tightened to the exact interpolated message.
- DOX pass: `Museion/AGENTS.md` (Settings bullet rewritten as the descriptor table + credential rail + PassReadiness file; PostsModel runPass chain + MentorSessionModel readiness bullets updated), `MuseionTests/AGENTS.md` (suite map + the hasHeldPrompt note).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Readiness gained the official-endpoint gate (behavior delta) | The unified rail carries the #175 exfiltration posture: a nous pass profile on a user-set `base_url` with no pasted key now reads `.missingKey` (was `.ready` — the old session-model fallback had NO endpoint gate). Both finish-audit reviewers rate this the correct tightening; the remedy (paste a key) is consistent. |
| missingKey guard moved AFTER the shared open-piece rail | The rail owns the common grammar; the kind-specific readiness check stays caller-side. "No piece open + no key" now shows "Open a saved post" (was the key message). The load-bearing invariant — key guard before anything touches disk — holds; no test pinned the old order. Flagged to the maintainer. |
| z.ai branches stay provider-keyed | Key-type UI toggle, endpoint families, thinking knobs, and the 1113 error decode are zai-specific config, not provider metadata; the ticket blesses "genuinely different code, not switch clothing". |
| `refreshPassReadiness` stays as a thin delegate | Museion/AGENTS.md pins the model as the pane's observable; the module computes, the model stores. |
| `PassKind`-keyed refresh return, surfaces baked in | One caller, constant `[.pass1, .pass2]` — the parameter was a dead degree of freedom (finish-audit ponytail trim). |
| De-flaked the #179 repoint pin instead of re-running | `runningPass` flips before the one-shot engine parks its prompt; `endHeldPrompt()` fired into that window false-fails under parallel-suite load — the #30/#147 green-by-luck family. Fix the test's timing assumption, not the schedule. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Full-suite run 1: `home repoint mid-pass refuses the advance` failed (`endHeldPrompt()` → false) | The pin polled `runningPass`, which flips BEFORE the one-shot engine spawns and parks its prompt — the poll passed, the park hadn't happened; parallel-suite load widened the window | Added `ScriptedEngine.hasHeldPrompt`; the pin now polls for the PARK, then requires the release (`#require` still fails loudly on a genuine timeout) |
| `-only-testing:MuseionTests/<Suite>` filters silently matched subsets (12 of 71 expected tests) | Several suites are free functions / differently-named structs — the known #31 trap; verified against per-file `@Test` counts | Ran the whole MuseionTests suite and verified by the xcresult EXECUTED count (668), never the SUCCEEDED banner |
| A patch intended as `provider.keyless` mangled a newline in SettingsPagesView instead | old_string/new_string differed only by trailing newline | Re-read the region, restored the newline, applied the real change |
| detect-changes listed serif-writing files this session never touched | Index-staleness relative to a pre-#180 index state; `git status` showed them unmodified | Trusted `git status` as the commit's file list; analyze rebuilt the index |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/SettingsModel.swift` | Descriptor additions (dialect, authMode, keyless, trimmedEndpoint), `ProviderCredential`, `testConnection` through the rail |
| `Museion/PassReadiness.swift` | NEW — the readiness module over the descriptor + credential rail |
| `Museion/MentorSessionModel.swift` | Nested `PassReadiness` + refresh body removed; thin delegate remains (−~65 lines) |
| `Museion/ProviderProbe.swift` | URL/auth/SSE selectors key off the descriptor |
| `Museion/PostsModelPasses.swift` | `guardOpenPieceRun` shared rail; both runners rewritten onto it |
| `Museion/SettingsPagesView.swift` | Keyless branch keys off `provider.keyless` |
| `MuseionTests/ProviderCredentialTests.swift` | NEW — the shared credential suite (5 pins) |
| `MuseionTests/ScriptedEngine.swift` | `hasHeldPrompt` park observable |
| `MuseionTests/PostsModelTests.swift` | Repoint pin polls the park first |
| `MuseionTests/PassRunTests.swift` | Open-piece pin tightened to the exact message |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass (+ gitnexus stats bump) |
## Open Items & Next Steps
- [x] All six acceptance criteria met; full suite green
- [ ] Deferred (audit): cross-repo coupling — `defaultEndpoint` assumes hermes' unset-`base_url` default matches the app's constant (comment names it; revisit only if the portal URL moves)
- [ ] Deferred (audit): `auth.json` read once per surface (twice when both passes ride nous) — local JSON, off-main, pane-entry only; cache when it ever shows
- [ ] #182 ProfileLayout + config-set rail is the next ticket in the architecture batch
---
*Log written by write-log skill*
@@ -0,0 +1,61 @@
# ProfileLayout + one config-set rail — the Hermes profile's paths and CLI contract get owners
> **Date:** 2026-11-10
> **Type:** issue
> **Reference:** Closes #182 (settings cluster, 2026-11-09 architecture review)
## Goal
The profile-root string repeated five times across provisioner/settings-writer/backup and the `config set` CLI contract (argv shape, provider-first ordering, ✓-line verification) was hand-rolled twice. Give both a single owner so a layout or contract change is one module + one pinning suite.
## What Was Done
- `Museion/ProfileLayout.swift` (new) — `defaultRoot` + five per-profile path builders (`profileDir`, `envFile(in:)`, `configuredMarker(in:)`, `gatewayPID(in:)`, `skillsDir(in:)`).
- `Museion/HermesConfigRail.swift` (new) — the ONE `config set/unset` owner: argv (+`--force`), provider-first hoisting (`isProviderSet`, stable relative order), ✓-line verification, unset-idempotence, leading-dash value refusal, structured `Failure` (verb/key/profile/excerpt) consumed by both callers' error surfaces.
- Adopted: provisioner (`perform` default, `provisionSurface`, marker reads/writes, skills dir, `ProvisioningModel.runPass` fallback, `configureDefaults` now hands the rail provider/default/max_tokens), settings writer (`profileRoot` default, env fan-out + read paths, `writeSurface` hands the rail provider/default/effort-set-or-unset/base_url, `writeProviderKey` base_url write-through), backup (`perform` default, source dirs, `gateway.pid`, `BackupModel.runPass` fallback).
- Deleted: `ConfigWrite`, the writer's `setKey`/`unsetKey`/`excerpt` trio, the provisioner's private `excerpt` (rail exports one, #180-audited 500 cap).
- Pinning suites (new): `ProfileLayoutTests` (every builder against literals), `HermesConfigRailTests` (argv+force, provider-first hoisting, ✓-verification, unset-idempotence, failed-unset, dash-refusal, excerpt cap). Fake-hermes gained a `config-unset-fails` knob. Writer suite gained the whitespace-endpoint pin (both gates).
- Audit fixes (finish-audit fanout): cut `providerKey` constant, `Equatable` conformances, and the tautological layout pin (ponytail); trimmed-emptiness at both endpoint gates (learning #6's class); leading-dash value guard (security LOW-1 — free-text values can't reach the child CLI as options).
- DOX: `Museion/AGENTS.md` (ProfileLayout + HermesConfigRail map entries, configure/backup/settings bullets updated), `MuseionTests/AGENTS.md` suite map.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Rail hoists `model.provider` first, callers' lists stay literal | The ordering RULE is the rail's (a caller can't order it wrong); each caller's ordered key list is its own pin — the spec's "each caller keeps its own key list" |
| `Failure` throws structured fields, writer rethrows directly | `SettingsModel` renders `error.localizedDescription`; message shape byte-matches the old `WriteError`; provisioner maps to `Outcome.failed` with the excerpt |
| Excerpt cap 500 (not the writer's old 300) | The more-lossless twin wins when absorbing near-twins (#180); marked deliberate AND pinned (`excerpt(900).count == 500`) |
| `RESTORE.md` prose + ps-scan grep keep their literal path text | Prose that must outlive the app, and argv-text matching — not path derivations; documented in the layout header |
| `Op` renamed `Write` | SwiftLint 3-char identifier floor |
| Declined: precondition on layout builders | Every production call site passes the fixed `ProfileSurface` table (verified twice by reviewers) — YAGNI |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| First background full-suite ran on pre-rename products | `test-without-building` tests the BUILT products; the `Op`→`Write` rename landed after `build-for-testing` | Rebuilt + reran the definitive gate on the final tree (680/0 → 684/0 after audit pins) |
| One patch gutted `non-zai key write only touches env` | Inverted old/new strings in the patch — signature kept, body deleted | Re-read region, restored body + inserted the new whitespace pin |
| `detect-changes` listed untouched `ref/writing skills` files | Index-relative noise (mid-session analyze snapshot vs pre-audit index) | `git status` is the file-list truth; re-ran `analyze` after the audit edits |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProfileLayout.swift` | new — the profile layout owner (root default + 5 path builders) |
| `Museion/HermesConfigRail.swift` | new — the config set/unset CLI rail (argv, hoist, ✓-verify, dash guard, Failure) |
| `Museion/ProfileProvisioner.swift` | paths via layout; configureDefaults → rail; private excerpt deleted |
| `Museion/ProfileBackup.swift` | paths via layout (perform default, sources, gateway.pid, model fallback) |
| `Museion/HermesSettingsWriter.swift` | profileRoot default, env/base_url paths via layout; set/unset → rail; trimmed endpoint gates |
| `MuseionTests/ProfileLayoutTests.swift` | new — the layout pinning suite |
| `MuseionTests/HermesConfigRailTests.swift` | new — the rail contract suite (7 pins) |
| `MuseionTests/ProfileProvisionerTests.swift` | fake-hermes config-unset-fails knob |
| `MuseionTests/HermesSettingsWriterTests.swift` | whitespace-endpoint pin (both gates) |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass + gitnexus stats bump |
## Open Items & Next Steps
- None — all five acceptance criteria met and verified (full suite **684 passed / 0 failed** on the final tree; swiftformat/swiftlint clean; flip-cycle verified the dash + whitespace pins discriminate).
---
*Log written by write-log skill*
+4
View File
@@ -6,6 +6,10 @@ Complete history of session logs in this directory, newest first. One-line summa
| Date | Type | File | Summary |
|------|------|------|---------|
| 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) |
| 2026-11-10 | issue | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | One PostFrontmatter codec: lenient read + three byte-identical write postures, named eligibility predicates both gates consume |
| 2026-11-09 | issue | [20261109-issue179-postsmodel-write-rail_log.md](20261109-issue179-postsmodel-write-rail_log.md) | One `performWrite` rail pairs every library write with one rescan and owns the strip; model owns the Home (#179) |
| 2026-11-09 | issue | [20261109-issue178-extract-engine-host-transport-seam_log.md](20261109-issue178-extract-engine-host-transport-seam_log.md) | Engine lifecycle → EngineHost behind the EngineTransport seam; scripted in-process tests, one real smoke per surface |
| 2026-11-09 | issue | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | SessionRow text rows typed (speaker+notice), kick-off sniffed at append seam, one ToolPayloads decoder both rails read |
| 2026-11-09 | issue | [20261109-issue183-shrink-agentsmd_log.md](20261109-issue183-shrink-agentsmd_log.md) | AGENTS.md rails shrunk 206 KB → 36 KB — contracts and rulings kept, per-issue diaries cut; serif payload untouched (#183) |