feat(sessions): session lifecycle UI (S2.3) (#28)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Each Session is a conversation Museion UIs, never owns. The mentor bridge hosts multiple engine-owned sessions: per-session transcripts keyed by wire sessionId behind same-named proxies (every existing caller compiles unchanged), a names-only roster at Application Support/sessions.json (0600; id/name/pieceTitle/date — the words stay engine-owned per ADR-0007), and the standard affordances over the wire: session/new, session/load, session/fork, compact as the /compress slash prompt, session/cancel as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece- associated by name when Posts has an open piece), row-click resume with the engine's full-history replay (user turns included), Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session and streams into it; the transcript renderer is shared with the mentor pane. Notification hops ride the main queue (FIFO with the continuation resume) so the adapter's replay-before- response contract is guaranteed, not probabilistic. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history); concurrent replays refuse instead of interleaving; restart replays from the engine rather than trusting a diverging local copy. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (12 lifecycle pins; 359 tests green). Closes #28
This commit is contained in:
1 parent
78c8844184
commit
9895614b7e
15 files changed
+1523
-245
No files matched your search
@@ -31,7 +31,17 @@ import Testing
|
||||
/// session/cancel is answered — any other request waits until teardown;
|
||||
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled"
|
||||
/// with no cancel needed; `refuseOnPrompt` answers stopReason "refusal" (no
|
||||
/// chunks).
|
||||
/// chunks); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork
|
||||
/// all require `mcpServers` (-32602 without, the #44 invariant), session ids
|
||||
/// are minted uniquely (sess-1, sess-2, …), session/load replays
|
||||
/// user+thought+message chunks for ANY minted sess-* id then answers its id
|
||||
/// (a relaunch default-open resumes the newest rostered entry, #28 review
|
||||
/// fix; any other id answers with NO sessionId = unknown), and session/fork
|
||||
/// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork
|
||||
/// log "load <id>" / "fork <id>" to stderr so tests can pin the wire call.
|
||||
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
|
||||
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
|
||||
/// the finish-audit interleaving pin's in-flight observable.
|
||||
/// 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.
|
||||
@@ -50,8 +60,10 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
|
||||
card=$(print -- '\(fixCardB64)' | base64 -d)
|
||||
framing='{"jsonrpc":"2.0","id":'
|
||||
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
|
||||
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \n escapes of multi-line prompts
|
||||
sessn=0
|
||||
forkn=0
|
||||
mcpcheck='import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")'
|
||||
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \\n escapes of multi-line prompts
|
||||
[[ -z "$line" ]] && continue
|
||||
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
|
||||
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
|
||||
@@ -59,8 +71,18 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
|
||||
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
|
||||
elif [[ "$method" == "session/new" ]]; then
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
|
||||
if [[ "$mode" == "loadReplay" ]]; then # #44 invariant: mcpServers required
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
|
||||
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
|
||||
elif [[ "$method" == "session/prompt" ]]; then
|
||||
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
|
||||
if [[ "$mode" == "refuseOnPrompt" ]]; then
|
||||
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
|
||||
continue
|
||||
@@ -93,6 +115,51 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
done
|
||||
fi
|
||||
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
||||
elif [[ "$method" == "session/load" ]]; then
|
||||
if [[ "$mode" != loadReplay* ]]; then continue; fi
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
lsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
print -u2 -- "load $lsid" # the wire call, visible in model.stderrTail
|
||||
if [[ "$mode" == "loadReplayHold" ]]; then
|
||||
# Finish-audit pin support: park the replay until `load-go` lands
|
||||
# beside the fake; the pre-hold stderr line above is the observable
|
||||
# that the load (and the model's replay slot) is in flight.
|
||||
print -u2 -- "hold-load"
|
||||
while [[ ! -f "${0:h}/load-go" ]]; do sleep 0.05; done
|
||||
fi
|
||||
# Any MINTED id replays: a relaunch default-open resumes the newest
|
||||
# rostered session (review fix), so load answers every id session/new
|
||||
# ever issued, not one planted id.
|
||||
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
|
||||
if [[ "$lsid" == sess-* ]]; then
|
||||
# Full history replay, wire order, BEFORE the load response — the
|
||||
# real adapter's contract (#28).
|
||||
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
|
||||
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
|
||||
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
|
||||
echo $framing"$rid",'"result":{"sessionId":"'"$lsid"'"}}'
|
||||
else
|
||||
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
|
||||
fi
|
||||
elif [[ "$method" == "session/fork" ]]; then
|
||||
if [[ "$mode" != "loadReplay" ]]; then continue; fi
|
||||
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
|
||||
if [[ "$ok" == "0" ]]; then
|
||||
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
|
||||
continue
|
||||
fi
|
||||
fsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
|
||||
print -u2 -- "fork $fsid"
|
||||
if [[ "$fsid" == "sess-1" ]]; then
|
||||
forkn=$((forkn+1))
|
||||
echo $framing"$rid",'"result":{"sessionId":"F-'"$forkn"'"}}'
|
||||
else
|
||||
echo $framing"$rid",'"result":{"sessionId":""}}' # empty = fork refused
|
||||
fi
|
||||
elif [[ "$method" == "session/cancel" ]]; then
|
||||
print -u2 -- "cancel received"
|
||||
fi
|
||||
@@ -308,12 +375,12 @@ struct ACPClientTests {
|
||||
/// #23 dogfood: the writing-session filter — prose + card events stay,
|
||||
/// raw session/tool rows and thinking are debug-only.
|
||||
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
|
||||
#expect(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
||||
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
|
||||
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
|
||||
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
|
||||
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
|
||||
))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
||||
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
||||
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .thought("thinking…"))))
|
||||
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -389,24 +456,32 @@ struct ACPClientTests {
|
||||
|
||||
// MARK: - Model tests
|
||||
|
||||
@MainActor
|
||||
@Test func `model handshake renders version and streams fix card`() async {
|
||||
@Test @MainActor func `model handshake renders version and streams fix card`() async throws {
|
||||
let fake = makeFakeACP(at: acpTempDir("model"))
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
defer { model.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready, got \(model.phase)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
#expect(model.activeEntry?.sessionId == "sess-1")
|
||||
#expect(model.engineVersion == "9.9.9")
|
||||
await model.sendPrompt("hello mentor")
|
||||
let hasCard = model.rows.contains { row in
|
||||
if case let .fixCard(card) = row.content {
|
||||
return card.pattern == "Blame tense"
|
||||
// The card row lands via a client notification Task that can settle just
|
||||
// after the response resumes this test under full-suite load — bounded
|
||||
// settle (house poll pattern); the pin itself is unchanged.
|
||||
var hasCard = false
|
||||
for _ in 0 ..< 250 where !hasCard {
|
||||
hasCard = model.rows.contains { row in
|
||||
if case let .fixCard(card) = row.content {
|
||||
return card.pattern == "Blame tense"
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !hasCard {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
#expect(hasCard)
|
||||
let hasText = model.rows.contains { row in
|
||||
@@ -464,11 +539,11 @@ struct ACPClientTests {
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
defer { model.shutdown() }
|
||||
await model.openSession()
|
||||
guard case let .ready(sessionId) = model.phase else {
|
||||
guard case .ready = model.phase else {
|
||||
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
|
||||
return
|
||||
}
|
||||
#expect(sessionId == "sess-1")
|
||||
#expect(model.activeEntry?.sessionId == "sess-1")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -18,14 +18,15 @@ 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.
|
||||
- `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; an unknown id answers WITHOUT a sessionId), `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 the profile 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. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #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), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) 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). **#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 stamp round-trip; 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) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
|
||||
- `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. **#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.
|
||||
- `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).
|
||||
- `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).
|
||||
- `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.
|
||||
|
||||
@@ -238,3 +238,24 @@ 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)
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
//
|
||||
// SessionLifecycleTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #28 (S2.3): the session lifecycle model layer — pass auto-create,
|
||||
// freeform new + piece association, resume of engine-owned history
|
||||
// (user turns included) with an honest refusal for unknown sessions,
|
||||
// fork, compact over the prompt rail, and roster persistence across
|
||||
// model instances. Runs over the real client + fake ACP server
|
||||
// (ACPClientTests' fake in its `loadReplay` lifecycle mode).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
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 {
|
||||
let (model, home, mentor) = try makePassRig()
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
let defaultSession = try #require(mentor.activeEntry)
|
||||
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 }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
|
||||
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.
|
||||
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.
|
||||
var streamed = false
|
||||
for _ in 0 ..< 250 {
|
||||
streamed = texts(in: mentor.transcriptRows(of: entry)).contains(where: { $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.
|
||||
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.passState != .pass1Done {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(model.posts.first(where: { $0.id == post.id })?.passState == .pass1Done)
|
||||
}
|
||||
|
||||
/// #28 AC2: freeform sessions are wired session/new, rostered
|
||||
/// 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()
|
||||
defer { mentor.shutdown() }
|
||||
#expect(!mentor.canStartSession) // never opened — nothing may start
|
||||
await mentor.openSession()
|
||||
#expect(mentor.canStartSession)
|
||||
|
||||
let free = await mentor.newSession(name: "Doctor", pieceTitle: nil)
|
||||
#expect(free != nil)
|
||||
#expect(mentor.roster.first == free)
|
||||
#expect(mentor.activeEntry == free)
|
||||
#expect(free?.pieceTitle == nil)
|
||||
|
||||
let titled = await mentor.newSession(name: "Notes", pieceTitle: "Essay X")
|
||||
#expect(titled?.pieceTitle == "Essay X")
|
||||
#expect(mentor.roster.first == titled)
|
||||
// Distinct wire ids — every rostered session is its own session.
|
||||
#expect(Set(mentor.roster.map(\.sessionId)).count == 3)
|
||||
}
|
||||
|
||||
/// #28 AC1+AC4: resume replays the ENGINE's history in wire order (user
|
||||
/// turns included) into the entry's transcript; a session the engine
|
||||
/// does not know returns false honestly — entry stays, explanatory row,
|
||||
/// nothing fabricated.
|
||||
@Test @MainActor func `resume replays engine history and refuses unknown honestly`() async throws {
|
||||
let rosterDir = acpTempDir("resume-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("resume"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
// The rostered entry is back and active — and the default open
|
||||
// already RESUMED it (#28 review fix): the engine does not know the
|
||||
// ghost, so the honest refusal row landed during openSession itself.
|
||||
#expect(mentor.activeEntry == ghost)
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
|
||||
// The engine does not know it: false, entry stays, explanatory row.
|
||||
let unknown = await mentor.resumeSession(ghost)
|
||||
#expect(!unknown)
|
||||
#expect(mentor.roster.contains(ghost))
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost).filter { row in
|
||||
if case .text = row.content {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}).contains { $0.contains("does not know") })
|
||||
|
||||
// A session the engine still knows: session/load, then the replayed
|
||||
// history renders in wire order — user turn first, thought lane kept.
|
||||
let known = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(known != nil)
|
||||
let resumed = try await mentor.resumeSession(#require(known))
|
||||
#expect(resumed)
|
||||
#expect(mentor.activeEntry == known)
|
||||
// The replayed rows ride notification Tasks — bounded settle, then
|
||||
// the wire-order pins (user turn first, thought lane kept).
|
||||
let resumedEntry = try #require(known)
|
||||
var settled = false
|
||||
for _ in 0 ..< 250 {
|
||||
settled = mentor.transcriptRows(of: resumedEntry).count >= 3
|
||||
if settled {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let replayed = mentor.transcriptRows(of: resumedEntry)
|
||||
#expect(settled)
|
||||
#expect(texts(in: replayed).first == "You: earlier ask")
|
||||
#expect(replayed.contains { row in
|
||||
if case let .thought(text) = row.content {
|
||||
return text == "old thinking"
|
||||
}
|
||||
return false
|
||||
})
|
||||
#expect(texts(in: replayed).contains("Mentor: earlier verdict"))
|
||||
// The wire calls went out over session/load.
|
||||
#expect(mentor.stderrTail.contains { $0.contains("load ghost") })
|
||||
#expect(mentor.stderrTail.contains { $0.contains("load sess-1") })
|
||||
}
|
||||
|
||||
/// #28 AC1: fork wires session/fork, rosters '<name> (fork)' with the
|
||||
/// same pieceTitle, activates it with a FRESH transcript, and leaves the
|
||||
/// original untouched; an empty-string sessionId from the wire is a
|
||||
/// refusal — honest row, nil return.
|
||||
@Test @MainActor func `fork activates a fresh transcript and refuses unknown honestly`() async throws {
|
||||
let rosterDir = acpTempDir("fork-roster")
|
||||
let source = SessionEntry(sessionId: "sess-1", name: "Essay", pieceTitle: "Pt", createdAt: Date())
|
||||
SessionRoster.save([source], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("fork"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello mentor") // history in the original's transcript
|
||||
|
||||
let fork = await mentor.forkActiveSession()
|
||||
#expect(fork?.sessionId == "F-1")
|
||||
#expect(fork?.name == "Essay (fork)")
|
||||
#expect(fork?.pieceTitle == "Pt") // the association travels
|
||||
#expect(mentor.roster.first == fork)
|
||||
#expect(mentor.activeEntry == fork)
|
||||
#expect(try mentor.transcriptRows(of: #require(fork)).isEmpty) // FRESH transcript
|
||||
#expect(!mentor.transcriptRows(of: source).isEmpty) // original untouched
|
||||
#expect(mentor.stderrTail.contains { $0.contains("fork sess-1") })
|
||||
|
||||
// Refusal rig: a session the engine does not know forks into "".
|
||||
let refusalDir = acpTempDir("fork-refusal")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: refusalDir)
|
||||
let refuser = MentorSessionModel(
|
||||
binaryPath: makeFakeACP(at: acpTempDir("fork-refuser"), mode: "loadReplay"),
|
||||
rosterDirectory: refusalDir,
|
||||
)
|
||||
defer { refuser.shutdown() }
|
||||
await refuser.openSession()
|
||||
let refused = await refuser.forkActiveSession()
|
||||
#expect(refused == nil)
|
||||
#expect(refuser.activeEntry == ghost) // the refusal did not switch sessions
|
||||
#expect(texts(in: refuser.transcriptRows(of: ghost)).contains { $0.contains("Fork refused") })
|
||||
}
|
||||
|
||||
/// #28 AC1: compact rides the existing sendPrompt rail — the label
|
||||
/// 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()
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
|
||||
await mentor.compactActiveSession()
|
||||
|
||||
#expect(texts(in: mentor.rows).contains("Compact…"))
|
||||
#expect(!texts(in: mentor.rows).contains { $0.contains("/compress") })
|
||||
#expect(texts(in: mentor.rows).contains { $0.contains("Hello mentor.") }) // summary streamed
|
||||
|
||||
// Refusal rig: compact while a turn streams does nothing.
|
||||
let (busy, busyHome, busyMentor) = try makePassRig(mode: "hangOnPrompt")
|
||||
defer { busyMentor.shutdown() }
|
||||
_ = busy
|
||||
_ = busyHome
|
||||
await busyMentor.openSession()
|
||||
let chat = Task { await busyMentor.sendPrompt("just chatting") }
|
||||
for _ in 0 ..< 250 where !busyMentor.isStreaming {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let before = busyMentor.rows.count
|
||||
await busyMentor.compactActiveSession()
|
||||
#expect(busyMentor.rows.count == before)
|
||||
#expect(!texts(in: busyMentor.rows).contains("Compact…"))
|
||||
busyMentor.shutdown() // frees the held turn — bounds the await below
|
||||
_ = await chat.value
|
||||
}
|
||||
|
||||
/// #28 AC4 (ownership) + review fix (the default open RESUMES): a new
|
||||
/// model over the same roster directory restores every entry — the
|
||||
/// roster FILE carries no transcript payload (pinned against the raw
|
||||
/// JSON) — and openSession session/load's the newest entry so its
|
||||
/// history replays from the engine (nothing fabricated locally).
|
||||
@Test @MainActor func `roster survives relaunch transcripts do not`() async throws {
|
||||
let rosterDir = acpTempDir("relaunch-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("relaunch"), mode: "loadReplay")
|
||||
let first = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { first.shutdown() }
|
||||
await first.openSession() // creates + persists the default 'Mentor'
|
||||
let notes = await first.newSession(name: "Notes", pieceTitle: "Essay X")
|
||||
#expect(notes != nil)
|
||||
|
||||
// The ownership pin: the roster FILE holds names only — exactly the
|
||||
// four entry keys, no transcript payload of any kind (ADR-0007).
|
||||
let rosterURL = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
|
||||
let raw = try JSONSerialization.jsonObject(with: Data(contentsOf: rosterURL))
|
||||
let firstEntry = (raw as? [[String: Any]])?.first ?? [:]
|
||||
#expect(Set(firstEntry.keys) == ["sessionId", "name", "pieceTitle", "createdAt"])
|
||||
|
||||
let second = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { second.shutdown() }
|
||||
#expect(second.roster.count == 2)
|
||||
#expect(second.roster.first == notes) // newest-first, all four fields equal
|
||||
#expect(second.roster.last?.name == "Mentor")
|
||||
#expect(second.activeEntry == nil) // nothing active before open
|
||||
|
||||
await second.openSession()
|
||||
#expect(second.activeEntry == second.roster.first)
|
||||
// The default open RESUMED (#28 review fix): the engine's replay
|
||||
// filled the newest entry's transcript — user turns included — so
|
||||
// prompt/fork/compact never run against unloaded state.
|
||||
let rows = try second.transcriptRows(of: #require(second.activeEntry))
|
||||
#expect(rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("earlier ask")
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
/// #28 AC2, the pane's New-Session choice rail: the open piece in Posts
|
||||
/// is the association target; nothing open (or no Posts) = free-floating
|
||||
/// only. Pure SwiftUI layout needs no test (house rule) — this is the
|
||||
/// posts-coupled helper behind the control.
|
||||
@Test @MainActor func `new-session choice reads Posts' open piece`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
#expect(SessionsPaneView.openPiece(in: model) == nil) // nothing open
|
||||
#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)
|
||||
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(SessionsPaneView.openPiece(in: model)?.id == post.id)
|
||||
}
|
||||
|
||||
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
|
||||
/// resume while a session/load is in flight refuses instead of diverting
|
||||
/// the first's replayed chunks into live streaming buffers.
|
||||
/// `loadReplayHold` parks the load until `load-go` lands beside the
|
||||
/// fake; the pre-hold "hold-load" stderr line is the in-flight
|
||||
/// observable.
|
||||
@Test @MainActor func `concurrent resume refuses while a replay is in flight`() async throws {
|
||||
let dir = acpTempDir("hold-load")
|
||||
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
|
||||
let rosterDir = acpTempDir("hold-roster")
|
||||
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([known], directory: rosterDir)
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
|
||||
var inFlight = false
|
||||
for _ in 0 ..< 250 {
|
||||
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
|
||||
inFlight = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(inFlight)
|
||||
|
||||
// The slot is taken: the second resume refuses honestly.
|
||||
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
|
||||
let ok = await mentor.resumeSession(other)
|
||||
#expect(!ok)
|
||||
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
|
||||
|
||||
// Release the hold: the parked resume completes and replays.
|
||||
try "go".write(toFile: (dir as NSString).appendingPathComponent("load-go"), atomically: true, encoding: .utf8)
|
||||
var replayed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
|
||||
replayed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(replayed)
|
||||
}
|
||||
|
||||
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
|
||||
/// refusal lands in its own store, never in the active session's
|
||||
/// transcript.
|
||||
@Test @MainActor func `resume refusal is attributed to the entry not the active session`() async throws {
|
||||
let rosterDir = acpTempDir("attrib-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("attrib"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession() // activates ghost; its load refuses (unknown id)
|
||||
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(second != nil)
|
||||
|
||||
_ = await mentor.resumeSession(ghost) // refuses again
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
let secondEntry = try #require(second)
|
||||
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
|
||||
}
|
||||
|
||||
/// Finish-audit: the creation rail refuses while a turn streams — a
|
||||
/// programmatic caller must not switch the active session out from
|
||||
/// under a live turn (Stop would cancel the wrong session).
|
||||
@Test @MainActor func `new session refuses while a turn streams`() async throws {
|
||||
let (_, _, mentor) = try makePassRig(mode: "hangOnPrompt")
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
let chat = Task { await mentor.sendPrompt("just chatting") }
|
||||
for _ in 0 ..< 250 where !mentor.isStreaming {
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(mentor.isStreaming)
|
||||
|
||||
let created = await mentor.newSession(name: "Sneaky", pieceTitle: nil)
|
||||
#expect(created == nil)
|
||||
#expect(texts(in: mentor.rows).contains { $0.contains("Session refused — the mentor is mid-turn.") })
|
||||
mentor.shutdown() // frees the held turn — bounds the await below
|
||||
_ = await chat.value
|
||||
}
|
||||
|
||||
/// Finish-audit: the roster file is writer-only (0600) — names carry
|
||||
/// piece titles, and the default umask is group/world-readable.
|
||||
@Test @MainActor func `roster file is writer only`() throws {
|
||||
let rosterDir = acpTempDir("perm-roster")
|
||||
SessionRoster.save([SessionEntry(sessionId: "s", name: "N", pieceTitle: "T", createdAt: Date())], directory: rosterDir)
|
||||
let url = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
|
||||
let perms = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int
|
||||
#expect(perms == 0o600)
|
||||
}
|
||||
|
||||
/// Finish-audit: restart() REPLAYS the active transcript from the
|
||||
/// engine (ADR-0007 — the engine owns the words; the pre-crash local
|
||||
/// rows are replaced by the replay, not preserved).
|
||||
@Test @MainActor func `restart replays the active transcript from the engine`() async throws {
|
||||
let rosterDir = acpTempDir("restart-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("restart"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello") // a turn lands in the active session
|
||||
#expect(!mentor.transcriptRows(of: try #require(mentor.activeEntry)).isEmpty)
|
||||
|
||||
if let pid = mentor.childProcessIdentifier {
|
||||
kill(pid, SIGKILL) // crash the child
|
||||
}
|
||||
var crashed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if case .crashed = mentor.phase {
|
||||
crashed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(crashed)
|
||||
|
||||
await mentor.restart()
|
||||
// The post-restart transcript is the ENGINE's replay — the replay
|
||||
// marker proves the words came from the engine, not the local copy.
|
||||
let rows = mentor.transcriptRows(of: try #require(mentor.activeEntry))
|
||||
#expect(rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("earlier ask")
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func texts(in rows: [SessionRow]) -> [String] {
|
||||
rows.compactMap {
|
||||
if case let .text(text) = $0.content {
|
||||
text
|
||||
} else {
|
||||
nil
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user