feat(mentor): per-surface engine lifecycle (#137)
CI / ci (push) Canceled after 0s

Profiles S4: passes run on their OWN one-shot engines —
`hermes acp -p museion-passN` spawns per pass run and tears down at
the verdict, so a model switch costs nothing (the next spawn reads
fresh config). The verdict streams into a TRANSIENT unrostered
transcript (#129's ruling: one Sessions surface over the chat
engine; a rostered pass session would be unresumable by the chat
engine). `beginPassSession` died with it — passes never mint
sessions; the #28 roster pins flipped to the transient posture.

The chat engine stays resident (adopted museion profile): a Chat
model change in Settings fires onChatSurfaceWrite after a
successful chat-surface write only, wired to requestRestart —
re-spawn in place when idle (resuming the pre-restart active
session), deferred to turn end while any turn streams (#129).

Missing-key posture (#132): refreshPassReadiness reads both pass
profiles' providers and their .env keys at pane entry; Run Pass
disables naming the provider with an Open Settings link, .unknown
never blocks, and the guard refuses before anything touches disk.

Finish-audit (ponytail/security/general fanout) applied: the
general reviewer's Medium — a session/new/load/fork completing
mid-pass stole the active surface and lost the Cancel to the wrong
engine — fixed with ONE claimActive gate across the post-await
activation writers, pinned deterministically via the fake's
loadReplayHold park + a mode-file flip (flip-verified: guard off
fails on the steal observables and the misrouted-cancel hang).
Also fixed: a spawn-window cancel loss in stopStreaming (keyed on
the transient entry, not the late-arriving wire id), and a
PRE-EXISTING rescan bug where a stale scan snapshot "vanished" a
just-opened piece and killed its session, cancelling the edit
debounce — the vanish-kill now re-checks disk and the watched
home. Ponytail cut ~59 lines of test duplication; the app target's
only force-unwrap is gone.

Suite 477 (was 472): EngineLifecycleTests new (own-engine
end-to-end, held-pass cancel, idle + deferred restart ordering,
readiness, steal pin), +3 Settings hook pins, one duplicate pin
deduplicated. swiftformat clean, swiftlint at HEAD baseline.

Closes #137
This commit is contained in:
AlexKucera committed 2026-10-28 17:26:40 +01:00
1 parent a4ea914690
commit 1c697440d8
19 files changed
+1034 -162

No files matched your search

+3
View File
@@ -47,6 +47,8 @@ import Testing
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
/// Every spawn appends its argv line to `<name>-spawn-log` beside the fake
/// (#137) — the "which engine (profile) ran" observable.
/// Internal (not private) so later test files can reuse the fake (#24).
/// One contiguous zsh program — splitting the script string would break the
/// wire-line inspectability the script's own comment pins.
@@ -61,6 +63,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
#!/bin/zsh
mode="full"
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran
card=$(print -- '\(fixCardB64)' | base64 -d)
research=$(print -- '\(researchB64)' | base64 -d)
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
+5 -4
View File
@@ -18,7 +18,7 @@ Owned by the root AGENTS.md contract.
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
@@ -26,8 +26,9 @@ Owned by the root AGENTS.md contract.
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#28:** one roster pin — a completed pass grows the roster with "Pass 1 · \<title\>" active (the auto-created session). **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome).
- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass auto-creates its session (rostered "Pass 1 · \<title\>" newest-first, active, pass streams into ITS transcript), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome).
- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
- `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home).
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
@@ -39,7 +40,7 @@ Owned by the root AGENTS.md contract.
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
## Verification
+367
View File
@@ -0,0 +1,367 @@
//
// EngineLifecycleTests.swift
// MuseionTests
//
// #137 (Profiles S4): per-surface engine lifecycle — passes run on their
// own ONE-SHOT engines (spawned per run on the pass profile, torn down at
// the verdict, never rostered per #129) and the Chat model-change restart
// posture (restart in place when idle, defer to turn end while streaming).
// Real client + fake ACP path; the fake's spawn log pins WHICH engine ran.
//
import Foundation
@testable import Museion
import Testing
/// makePassRig's shape plus the fake's directory — the spawn log beside
/// the fake is the "which engine (profile) spawned" observable (#137).
@MainActor
private struct EngineRig {
let model: PostsModel
let home: URL
let mentor: MentorSessionModel
let fakeDir: String
}
@MainActor
private func makeEngineRig(mode: String = "full") throws -> EngineRig {
let (model, home) = try makeModelHome()
let dir = acpTempDir("engine-lifecycle")
let fake = makeFakeACP(at: dir, mode: mode)
return EngineRig(model: model, home: home, mentor: MentorSessionModel(binaryPath: fake), fakeDir: dir)
}
/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house
/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously.
@MainActor
private func pollReaped(_ pid: pid_t) async throws -> Bool {
for _ in 0 ..< 100 where kill(pid, 0) == 0 {
try await Task.sleep(nanoseconds: 20_000_000)
}
return kill(pid, 0) != 0
}
// Scenario: A pass run lives on its own engine
// From user story #137 acceptance 1
// Given a saved piece is open and the chat engine is resident
// When the writer runs Pass 1
// Then Museion spawns `hermes acp -p museion-pass1`, streams the verdict
// into the pane's transcript, tears that engine down at the verdict
// (nothing pass-shaped stays resident), rosters nothing, and the chat
// engine keeps running untouched.
@Test @MainActor func `a pass run lives on its own engine and rosters nothing`() async throws {
let rig = try makeEngineRig()
defer { rig.mentor.shutdown() } // #124: at rig creation — the children die with the test
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
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)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// In a Task — the pass child's pid is only observable while it runs.
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
_ = await run.value
// The run completed as today: snapshot landed, Pass-1 Done stamped.
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Verdict me."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// The pass engine spawned under its own profile; the chat engine under museion.
let lines = try String(
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
encoding: .utf8,
).split(separator: "\n").map(String.init)
#expect(lines.contains("acp -p museion-pass1"))
#expect(lines.contains("acp -p museion"))
// Nothing pass-shaped stays resident…
#expect(rig.mentor.roster.count == rosterBefore)
#expect(!rig.mentor.isPassEngineRunning)
if let passPid {
#expect(try await pollReaped(passPid))
} else {
Issue.record("pass engine pid never observed while the run was in flight")
}
// …and the chat engine is untouched.
#expect(kill(chatPid, 0) == 0)
#expect(rig.mentor.phase.isReady)
// The label row and the streamed critique rendered on the active surface.
#expect(textRows(of: rig.mentor).contains("Pass 1 · \(post.title)"))
#expect(!textRows(of: rig.mentor).contains { $0.contains("Critique the piece") })
var streamed = false
for _ in 0 ..< 250 {
streamed = textRows(of: rig.mentor).contains { $0.contains("Hello mentor.") }
if streamed {
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(streamed)
}
/// A1 cancel: the pass bar's Cancel reaches the PASS engine — the held turn
/// ends cancelled, the pass child is reaped, the roster never grew, and the
/// pre-pass snapshot still landed (pre-pass is unconditional).
@Test @MainActor func `cancelling a live pass cancels the turn and reaps the pass engine`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
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)
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let heldPid = try #require(passPid, "pass engine never spawned")
#expect(rig.mentor.isPassEngineRunning)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
for _ in 0 ..< 250 where rig.model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == nil)
_ = await run.value
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Cancel me."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(!rig.mentor.isPassEngineRunning)
#expect(try await pollReaped(heldPid))
#expect(rig.mentor.roster.count == rosterBefore)
}
// Scenario: A Chat model change restarts the resident engine, but never mid-reply
// From user story #137 acceptance 2
// Given the resident chat engine is mid-turn (streaming)
// When a chat model change is requested (Settings fires it; this slice
// exposes the engine-side API)
// Then the restart waits for the turn to end, then re-spawns the engine in
// place and replays the active rostered session — while idle, it restarts
// immediately.
/// A2 idle: requestRestart re-spawns in place — old child reaped, new child
/// alive, phase back to .ready, and the PRE-restart active rostered session
/// is resumed with its transcript replayed from the engine.
@Test @MainActor func `idle requestRestart respawns in place and replays the active rostered session`() async throws {
let rig = try makeEngineRig(mode: "loadReplay")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let active = try #require(rig.mentor.activeEntry)
_ = await rig.mentor.sendPrompt("hello mentor") // history in the active session
let oldPid = try #require(rig.mentor.childProcessIdentifier)
rig.mentor.requestRestart()
var newPid: pid_t?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != oldPid {
newPid = pid
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let respawned = try #require(newPid, "chat engine never re-spawned")
#expect(try await pollReaped(oldPid))
#expect(kill(respawned, 0) == 0)
// The writer stays where they were: same rostered session, replayed.
#expect(rig.mentor.activeEntry == active)
var replayed = false
for _ in 0 ..< 250 {
replayed = !rig.mentor.transcriptRows(of: active).isEmpty
if replayed {
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(replayed)
}
/// A2 deferred ordering pin: requested mid-turn, the restart holds (same
/// child, still streaming) until the turn ends — the pid swap happens only
/// AFTER the turn.
@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
let turn = Task { await rig.mentor.sendPrompt("hold this") }
for _ in 0 ..< 250 where !rig.mentor.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.mentor.isStreaming)
rig.mentor.requestRestart() // Settings fires — mid-turn
try await Task.sleep(for: .milliseconds(300))
// Still streaming, same child: the restart deferred, never mid-reply.
#expect(rig.mentor.isStreaming)
#expect(rig.mentor.childProcessIdentifier == chatPid)
#expect(kill(chatPid, 0) == 0)
rig.mentor.stopStreaming() // ends the held turn — the restart fires now
_ = await turn.value
#expect(!rig.mentor.isStreaming)
var newPid: pid_t?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != chatPid {
newPid = pid
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(newPid != nil, "the deferred pid swap never happened after turn end")
#expect(try await pollReaped(chatPid))
}
// Scenario: Run Pass names the missing key instead of failing silently
// From user story #137 acceptance 3
// Given Pass 1's provider has no key in the profiles' .env
// When the writer opens the mentor pane
// Then Run Pass is disabled with the reason named (provider) and a Settings
// link; once the key is provided via Settings, Run Pass re-enables (pane
// re-entry refreshes).
/// B1 readiness pins: refreshPassReadiness over the injected RecordingWriter
/// — keyed provider reads .ready, an unkeyed one reads .missingKey with its
/// label, a key landing re-enables on the next refresh (the pane's .task),
/// and a surface we can't read reads .unknown (never blocks on our own
/// failure — the spawn's honest failure row owns that path).
@Test @MainActor func `pass readiness names the missing provider key and re-enables on rekey`() async {
let mentor = MentorSessionModel()
let writer = RecordingWriter()
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5", effort: nil), nil)
writer.cannedKeys[.anthropic] = "sk-live"
writer.cannedReads[.pass2] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil)
mentor.passReadinessWriter = writer
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .ready)
#expect(mentor.readiness(for: .pass2) == .missingKey(providerLabel: "z.ai"))
// The Settings path: the key lands, pane re-entry re-fires the
// refresh — Run Pass re-enables.
writer.cannedKeys[.zai] = "sk-z"
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass2) == .ready)
// Unreadable surfaces read .unknown — a read failure of OURS never
// blocks the run.
mentor.passReadinessWriter = RecordingWriter()
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .unknown)
#expect(mentor.readiness(for: .pass2) == .unknown)
}
/// B1 guard pin: with readiness .missingKey the runPass guard names the
/// provider in lastError — and fires BEFORE the open-piece guard's
/// snapshot, so nothing lands on disk.
@Test @MainActor func `run pass names the missing provider key and writes nothing`() async throws {
let rig = try makeEngineRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let writer = RecordingWriter()
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil)
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)
for _ in 0 ..< 250 where rig.model.session?.postID != post.id {
try await Task.sleep(nanoseconds: 20_000_000)
}
// The piece must be OPEN — otherwise the open-piece guard would pass
// this pin vacuously.
try #require(rig.model.session?.postID == post.id)
await rig.model.runPass(.pass1, home: rig.home, 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)")
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("passes/pass-1.md").path))
#expect(rig.model.runningPass == nil)
}
/// #137 audit (finish): a session/load that STARTED before a pass and
/// COMPLETES mid-pass must not steal the pass surface — the post-await
/// claimActive guard refuses, Cancel keeps routing to the pass engine.
/// loadReplayHold parks the load until `load-go` lands beside the fake
/// (SessionLifecycleTests' in-flight seam), which makes the interleaving
/// deterministic instead of lucky.
@Test @MainActor func `a resume completing mid-pass does not steal the pass surface`() async throws {
let rig = try makeEngineRig(mode: "loadReplayHold")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession() // default Mentor session (sess-1)
_ = 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)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// Park a resume of sess-1. The fake announces the park with a
// `hold-load` stderr line (the chat engine's stderrTail surfaces it).
let resume = Task { await rig.mentor.resumeSession(target) }
for _ in 0 ..< 250 where !rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
try #require(rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }))
// Deterministic window: flip the mode file to hangOnPrompt BEFORE the
// pass engine spawns (each child reads the mode at startup) — the pass
// prompt then HOLDS, so isStreaming is guaranteed when the parked load
// completes, and the #124 Cancel rail frees it afterwards.
try "hangOnPrompt".write(
toFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-mode"),
atomically: true,
encoding: .utf8,
)
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
try await Task.sleep(nanoseconds: 20_000_000)
}
try #require(rig.mentor.isPassEngineRunning)
// Free the parked load — its completion lands while the pass holds
// (nothing blocks the load; the held pass makes the direct await safe).
try Data().write(to: URL(fileURLWithPath: (rig.fakeDir as NSString).appendingPathComponent("load-go")))
// The resume refused post-await while the pass still held the surface…
#expect(await resume.value == false)
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)
// …and Cancel still routes to the pass engine (#124 rail) — the held
// turn ends cancelled, the pass never advances.
rig.model.cancelPass(mentor: rig.mentor)
for _ in 0 ..< 250 where rig.model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
_ = await run.value
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)
#expect(textRows(of: rig.mentor).contains("Resume refused — the mentor is mid-turn."))
#expect(rig.mentor.roster.contains(target))
}
+3 -22
View File
@@ -24,8 +24,10 @@ func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessio
return (model, home, mentor)
}
/// Internal (shared-helper convention): EngineLifecycleTests reads the same
/// transcript projection over its rigs.
@MainActor
private func textRows(of model: MentorSessionModel) -> [String] {
func textRows(of model: MentorSessionModel) -> [String] {
model.rows.compactMap {
if case let .text(text) = $0.content {
text
@@ -239,27 +241,6 @@ private func textRows(of model: MentorSessionModel) -> [String] {
#expect(onDisk.contains("pass_state: Pass-2 Done"))
}
/// #28 (S2.3): every pass auto-creates its session — the roster grows by
/// 'Pass N · <title>' and that entry is the active transcript's owner.
@Test @MainActor func `running a pass grows the roster with its pass session active`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let before = mentor.roster.count
let post = try PostStore.writeNew(body: "# Rostered Pass\n\nOne session per pass.", home: home)
model.select(post.id, home: home)
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)
#expect(mentor.roster.count == before + 1)
#expect(mentor.roster.first?.name == "Pass 1 · \(post.title)")
#expect(mentor.activeEntry == mentor.roster.first)
#expect(model.lastError == nil)
}
// MARK: First-draft stats capture (#31, S5.1)
@Test @MainActor func `pass on a writer first draft piece captures stats and still completes`() async throws {
+23 -19
View File
@@ -16,14 +16,15 @@ import Testing
@Suite("SessionLifecycleTests")
struct SessionLifecycleTests {
/// #28 AC2: the pass's session is rostered newest-first, active, and the
/// pass prompt streams into ITS transcript — the default freeform
/// session stays untouched while Pass State advances exactly as before.
@Test @MainActor func `pass auto-creates its rostered session`() async throws {
/// #137 (per #129): a pass streams into a TRANSIENT, unrostered
/// transcript — visible through the active surface while it runs, the
/// entry named by convention, never rostered, never persisted.
@Test @MainActor func `a pass streams into a transient unrostered transcript`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
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)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
@@ -32,25 +33,24 @@ struct SessionLifecycleTests {
await model.runPass(.pass1, home: home, mentor: mentor)
// Rostered newest-first, named by convention, and active.
#expect(mentor.roster.first?.name == "Pass 1 · \(post.title)")
#expect(mentor.activeEntry == mentor.roster.first)
// The prompt streamed into ITS transcript; the wire stub never lands.
// The roster never grew — the pass entry is transient.
#expect(mentor.roster.count == rosterBefore)
// The transient pass entry owns the active surface while it lives.
let entry = try #require(mentor.activeEntry)
#expect(texts(in: mentor.transcriptRows(of: entry)).contains("Pass 1 · \(post.title)"))
// The streamed verdict lands via a client notification Task that can
// settle just after runPass returns under load — bounded settle.
#expect(entry.name == "Pass 1 · \(post.title)")
#expect(entry.sessionId == MentorSessionModel.passTranscriptKey)
// The prompt streamed through the ACTIVE surface; the wire stub never lands.
#expect(texts(in: mentor.rows).contains("Pass 1 · \(post.title)"))
#expect(!texts(in: mentor.rows).contains { $0.contains("Critique the piece") })
var streamed = false
for _ in 0 ..< 250 {
streamed = texts(in: mentor.transcriptRows(of: entry)).contains(where: { $0.contains("Hello mentor.") })
streamed = texts(in: mentor.rows).contains { $0.contains("Hello mentor.") }
if streamed {
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
let rows = mentor.transcriptRows(of: entry)
#expect(streamed)
#expect(!texts(in: rows).contains { $0.contains("Critique the piece") })
// The pre-existing freeform session's transcript is untouched.
#expect(mentor.transcriptRows(of: defaultSession).isEmpty)
// Pass State advanced on the completed turn, exactly as before.
@@ -455,11 +455,15 @@ struct SessionLifecycleTests {
return false
})
}
}
// Scenario: draft candidate — from #30 (S2.7). Given a session
// transcript, when the sheet prefills, then the last mentor text row is
// the draft candidate; thought/card/research/raw rows never prefill.
@Test @MainActor func `draft candidate is the last mentor text row`() {
// Scenario: draft candidate — from #30 (S2.7). Given a session
// transcript, when the sheet prefills, then the last mentor text row is
// the draft candidate; thought/card/research/raw rows never prefill.
// File-scope extension — type_body_length posture; same suite, same file.
@MainActor
extension SessionLifecycleTests {
@Test func `draft candidate is the last mentor text row`() {
let rows: [SessionRow] = [
SessionRow(content: .text("You: help me draft this")),
SessionRow(content: .thought("thinking hard about angles")),
@@ -477,7 +481,7 @@ struct SessionLifecycleTests {
#expect(MentorSessionModel.draftCandidateText(in: rows) == "second and latest reply")
}
@Test @MainActor func `no mentor text yields no draft candidate`() {
@Test func `no mentor text yields no draft candidate`() {
// Empty transcript, user-only, and non-text lanes never prefill.
#expect(MentorSessionModel.draftCandidateText(in: []) == nil)
#expect(MentorSessionModel.draftCandidateText(in: [
@@ -148,4 +148,42 @@ struct SettingsModelWritePathTests {
#expect(model.probeModel(for: .anthropic) == ProfileSurface.defaultModelID)
#expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel)
}
// Scenario: Saving a Chat model change reaches the resident engine
// From user story #137 acceptance 2
// Given the Settings pane is open
// When a Chat surface model write succeeds (provider/model/effort/reset)
// Then onChatSurfaceWrite fires after the write lands — pass-surface
// writes and key writes never fire it, and failed writes don't either.
@Test @MainActor func `a successful chat surface write fires onChatSurfaceWrite`() async {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
var fired = 0
model.onChatSurfaceWrite = { fired += 1 }
model.setModel("claude-sonnet-5", for: .chat)
await model.awaitPendingWrites()
#expect(fired == 1)
}
@Test @MainActor func `pass surface writes and key writes never fire onChatSurfaceWrite`() async {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
var fired = 0
model.onChatSurfaceWrite = { fired += 1 }
model.setEffort(.max, for: .pass1)
model.setAPIKey("sk-a", for: .anthropic)
await model.awaitPendingWrites()
#expect(fired == 0)
}
@Test @MainActor func `a failed chat write never fires onChatSurfaceWrite`() async {
let writer = RecordingWriter()
writer.failSurfaceWrites = true
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
var fired = 0
model.onChatSurfaceWrite = { fired += 1 }
model.setModel("claude-sonnet-5", for: .chat)
await model.awaitPendingWrites()
#expect(fired == 0)
#expect(model.lastWriteError != nil)
}
}