feat(mentor): research & library-light (S8) (#29)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
The mentor researches mid-pass and its findings arrive as candidate
source-notes with provenance inside their Session. A third museion-
tools tool, submit_research_notes, is the typed rail (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.
Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).
The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).
Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).
Closes #29
This commit is contained in:
1 parent
9895614b7e
commit
b02d36bb5d
22 files changed
+977
-33
No files matched your search
@@ -34,7 +34,9 @@ import Testing
|
||||
/// 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
|
||||
/// user+thought+message chunks PLUS one submit_research_notes tool call
|
||||
/// (#29 — candidates re-materialize on resume) 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
|
||||
@@ -52,6 +54,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
let path = (dir as NSString).appendingPathComponent(name)
|
||||
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
|
||||
let fixCardB64 = fixCardPayloadB64()
|
||||
let researchB64 = researchPayloadB64()
|
||||
// ponytail: one echo per wire message — long payloads ride shell vars so
|
||||
// each line stays under the lint cap and inspectable against the schema.
|
||||
let script = """
|
||||
@@ -59,6 +62,8 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
mode="full"
|
||||
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
|
||||
card=$(print -- '\(fixCardB64)' | base64 -d)
|
||||
research=$(print -- '\(researchB64)' | base64 -d)
|
||||
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
|
||||
framing='{"jsonrpc":"2.0","id":'
|
||||
sessn=0
|
||||
forkn=0
|
||||
@@ -99,6 +104,14 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
continue
|
||||
fi
|
||||
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
|
||||
if [[ "$mode" == "strayResearchOnPrompt" ]]; then
|
||||
# #29 audit pin: a research payload carrying stray fix-card keys at
|
||||
# the top level must route by shape (notes array), not vanish into
|
||||
# a card row.
|
||||
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_research_notes","rawInput":'"$researchstray"'}}}'
|
||||
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
|
||||
continue
|
||||
fi
|
||||
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
|
||||
if [[ "$mode" == "hangOnPrompt" ]]; then
|
||||
# #124: the cancel-acknowledging hold — the real engine answers its
|
||||
@@ -141,6 +154,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
|
||||
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 $rnot'{"sessionUpdate":"tool_call","toolCallId":"tc2","title":"submit_research_notes","rawInput":'"$research"'}}}'
|
||||
echo $framing"$rid",'"result":{"sessionId":"'"$lsid"'"}}'
|
||||
else
|
||||
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
|
||||
@@ -188,6 +202,25 @@ private func fixCardPayloadB64() -> String {
|
||||
return Data(json.utf8).base64EncodedString()
|
||||
}
|
||||
|
||||
/// The research-notes payload for the fake's replayed tool call (#29) —
|
||||
/// base64 like the fix card so shell quoting can never break the wire JSON.
|
||||
/// Two notes: one complete, one with quote/note absent (the "" defaults).
|
||||
private func researchPayloadB64() -> String {
|
||||
let json = #"{"piece_path":"/tmp/piece","notes":["# +
|
||||
#"{"title":"Hinge Study","url":"https://example.org/hinge","quote":"We should stop listening.","note":"Counts the pivot tense."},"# +
|
||||
#"{"title":"Second Source","url":"https://example.org/second"}]}"#
|
||||
return Data(json.utf8).base64EncodedString()
|
||||
}
|
||||
|
||||
/// The #29 routing pin's payload: a research batch that ALSO carries stray
|
||||
/// fix-card keys at the top level (LLM tool calls pick up stray keys). The
|
||||
/// notes-array shape must win over the pattern/problem match.
|
||||
private func strayResearchPayloadB64() -> String {
|
||||
let json = #"{"pattern":"stray","problem":"stray","piece_path":"/tmp/piece","notes":["# +
|
||||
#"{"title":"Hinge Study","url":"https://example.org/hinge"}]}"#
|
||||
return Data(json.utf8).base64EncodedString()
|
||||
}
|
||||
|
||||
func acpTempDir(_ label: String) -> String {
|
||||
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
@@ -400,6 +433,43 @@ struct ACPClientTests {
|
||||
#expect(refused)
|
||||
}
|
||||
|
||||
/// #29 audit pin: a research payload with stray fix-card keys routes by
|
||||
/// SHAPE (the notes array) — it renders candidates, never a card row.
|
||||
/// Title-based routing would also work on the fake but titles are
|
||||
/// display text; the payload is the contract.
|
||||
@MainActor
|
||||
@Test func `research payload with stray card keys renders candidates not a card`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("stray-research"), mode: "strayResearchOnPrompt")
|
||||
let model = MentorSessionModel(binaryPath: fake)
|
||||
defer { model.shutdown() }
|
||||
await model.openSession()
|
||||
let outcome = await model.sendPrompt("research this")
|
||||
guard case .ended = outcome else {
|
||||
Issue.record("turn did not end: \(outcome)")
|
||||
return
|
||||
}
|
||||
var hasCandidates = false
|
||||
var hasCard = false
|
||||
for _ in 0 ..< 250 {
|
||||
hasCandidates = model.rows.contains {
|
||||
if case .researchNote = $0.content {
|
||||
return true
|
||||
}; return false
|
||||
}
|
||||
hasCard = model.rows.contains {
|
||||
if case .fixCard = $0.content {
|
||||
return true
|
||||
}; return false
|
||||
}
|
||||
if hasCandidates {
|
||||
break
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(hasCandidates, "the stray-key research batch never rendered as candidates")
|
||||
#expect(!hasCard, "the research payload was swallowed by the fix-card parser")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
|
||||
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
|
||||
|
||||
@@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract.
|
||||
- `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.
|
||||
- `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 — **#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.
|
||||
- `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).
|
||||
- `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).
|
||||
- `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). `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).
|
||||
- `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.
|
||||
|
||||
@@ -48,12 +48,16 @@ struct EditorSessionTests {
|
||||
#expect(session.saveState == .saved) // Changed → flush → Saved lands here
|
||||
#expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.")
|
||||
|
||||
// Sidecar: written on flush, reads back.
|
||||
// Sidecar: written on flush, reads back. Await the sidecar rather
|
||||
// than sleeping a fixed window — same starvation rule as above.
|
||||
let cursor = PostStore.CursorState(selectionLocation: 3, selectionLength: 2, scrollOffset: 128)
|
||||
session.cursorUpdate(cursor)
|
||||
session.edit("# Alpha\n\nOne. Two. Three.")
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
let restored = PostStore.readCursor(id: "alpha", home: home)
|
||||
var restored: PostStore.CursorState?
|
||||
while restored != cursor, ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(20))
|
||||
restored = PostStore.readCursor(id: "alpha", home: home)
|
||||
}
|
||||
#expect(restored == cursor)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,16 @@
|
||||
// -32601 unknown method, -32700 garbage. Wire facts verified live
|
||||
// against the real hermes MCP client.
|
||||
//
|
||||
// ## Scenario: candidate rail and the keep write
|
||||
// From #29 (S8.1/S8.2)
|
||||
// Given a piece in the library and the mentor researching mid-pass
|
||||
// When the engine delivers findings as submit_research_notes tool calls
|
||||
// Then well-formed candidates are accepted with a received count and
|
||||
// nothing is written anywhere; malformed ones answer a tool error
|
||||
// And the pass prompt names that rail
|
||||
// And when the writer keeps one, one plain markdown note with provenance
|
||||
// lands in the piece's research/ — nothing else auto-saves.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
@@ -70,11 +80,14 @@ struct MCPServerWireTests {
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
@Test func `tools list exposes both tools with schemas`() throws {
|
||||
@Test func `tools list exposes all three tools with schemas`() throws {
|
||||
let replies = try runWire([toolsListLine])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
let tools = try #require(result["tools"] as? [[String: Any]])
|
||||
#expect(Set(tools.compactMap { $0["name"] as? String }) == ["query_learnings", "submit_fix_cards"])
|
||||
#expect(
|
||||
Set(tools.compactMap { $0["name"] as? String })
|
||||
== ["query_learnings", "submit_fix_cards", "submit_research_notes"],
|
||||
)
|
||||
|
||||
let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" })
|
||||
let schema = try #require(submit["inputSchema"] as? [String: Any])
|
||||
@@ -100,6 +113,20 @@ struct MCPServerWireTests {
|
||||
let query = try #require(tools.first { $0["name"] as? String == "query_learnings" })
|
||||
let querySchema = try #require(query["inputSchema"] as? [String: Any])
|
||||
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
|
||||
|
||||
// #29 (S8.1): the research rail requires piece_path + notes, and a
|
||||
// note item requires title + url.
|
||||
let research = try #require(tools.first { $0["name"] as? String == "submit_research_notes" })
|
||||
let researchSchema = try #require(research["inputSchema"] as? [String: Any])
|
||||
let researchRequired = try #require(researchSchema["required"] as? [String])
|
||||
#expect(researchRequired.contains("piece_path"))
|
||||
#expect(researchRequired.contains("notes"))
|
||||
let researchProps = try #require(researchSchema["properties"] as? [String: Any])
|
||||
let notesProp = try #require(researchProps["notes"] as? [String: Any])
|
||||
let noteItems = try #require(notesProp["items"] as? [String: Any])
|
||||
let noteRequired = try #require(noteItems["required"] as? [String])
|
||||
#expect(noteRequired.contains("title"))
|
||||
#expect(noteRequired.contains("url"))
|
||||
}
|
||||
|
||||
/// One throwaway wire piece: home + `projects/posts/<name>/post.md`
|
||||
@@ -224,4 +251,69 @@ struct MCPServerWireTests {
|
||||
)) ?? []).filter { $0.hasSuffix(".json") }
|
||||
#expect(onDisk.count == 10)
|
||||
}
|
||||
|
||||
/// #29 (S8.1): one submit_research_notes wire line over the given
|
||||
/// arguments (JSONSerialization-built — no line_length fights).
|
||||
private func researchCall(id: Int, arguments: [String: Any]) throws -> String {
|
||||
let request: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": ["name": "submit_research_notes", "arguments": arguments] as [String: Any],
|
||||
]
|
||||
return try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8))
|
||||
}
|
||||
|
||||
/// #29 (S8.1): well-formed candidates answer a received count — and
|
||||
/// create NOTHING on disk (candidates live in their session; keeping
|
||||
/// is the writer's separate act).
|
||||
@Test func `research notes reply received and write nothing`() throws {
|
||||
let (_, piece) = try seedWirePiece("research-piece")
|
||||
let note = [
|
||||
"title": "The Long Now",
|
||||
"url": "https://example.org/long-now",
|
||||
"quote": "pace layers",
|
||||
"note": "Supports the slowness claim.",
|
||||
] as [String: Any]
|
||||
let line = try researchCall(id: 21, arguments: ["piece_path": piece.path, "notes": [note]])
|
||||
|
||||
let replies = try runWire([initializeLine, initializedLine, line])
|
||||
#expect(replies.count == 2)
|
||||
let result = try #require(replies[1]["result"] as? [String: Any])
|
||||
#expect(result["isError"] == nil)
|
||||
let payload = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any],
|
||||
)
|
||||
#expect(payload["received"] as? Int == 1)
|
||||
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path))
|
||||
}
|
||||
|
||||
/// #29 (S8.1): malformed candidates answer a tool error — the trust
|
||||
/// boundary. Missing fields fail decode; a whitespace-only title is
|
||||
/// refused; none of them writes anything.
|
||||
@Test func `malformed research notes answer a tool error`() throws {
|
||||
let (_, piece) = try seedWirePiece("research-error-piece")
|
||||
let lines = try [
|
||||
// notes item missing url → decode fails.
|
||||
researchCall(id: 31, arguments: ["notes": [["title": "T"]]]),
|
||||
// notes item missing title → decode fails.
|
||||
researchCall(id: 32, arguments: ["notes": [["url": "https://example.org"]]]),
|
||||
// whitespace-only title → CardError.
|
||||
researchCall(id: 33, arguments: [
|
||||
"piece_path": piece.path,
|
||||
"notes": [["title": " ", "url": "https://example.org"]],
|
||||
]),
|
||||
// piece_path missing → decode fails.
|
||||
researchCall(id: 34, arguments: [
|
||||
"notes": [["title": "T", "url": "https://example.org"]],
|
||||
]),
|
||||
]
|
||||
for line in lines {
|
||||
let replies = try runWire([line])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
|
||||
#expect(replies[0]["error"] == nil)
|
||||
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,16 @@
|
||||
// project (#60), Trash delete, save-time normalization.
|
||||
// #108: project moves, archive/restore, project unarchive + creation.
|
||||
//
|
||||
// ## Scenario: candidate rail and the keep write
|
||||
// From #29 (S8.1/S8.2)
|
||||
// Given a piece in the library and the mentor researching mid-pass
|
||||
// When the engine delivers findings as submit_research_notes tool calls
|
||||
// Then well-formed candidates are accepted with a received count and
|
||||
// nothing is written anywhere; malformed ones answer a tool error
|
||||
// And the pass prompt names that rail
|
||||
// And when the writer keeps one, one plain markdown note with provenance
|
||||
// lands in the piece's research/ — nothing else auto-saves.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
@@ -669,15 +679,19 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `stub carries pass name piece path and fix-card reminder`() {
|
||||
@Test func `stub carries pass name piece path research rail and fix-card reminder`() {
|
||||
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
|
||||
let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false)
|
||||
|
||||
#expect(stub.contains("Pass 1 — paragraph level and up."))
|
||||
#expect(stub.contains("Piece: /vault/projects/essays/essay/post.md"))
|
||||
#expect(!stub.contains("Research notes:"))
|
||||
let closing = "Critique the piece for this pass. Deliver the verdict in your reply — "
|
||||
+ "findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder."
|
||||
// #29: the typed research rail is named in the closing block — the
|
||||
// engine delivers findings, it never writes candidates itself.
|
||||
let closing = "Critique the piece for this pass. Fact-check claims where needed — research findings "
|
||||
+ "travel as candidate source-note tool calls (submit_research_notes), never written to disk. "
|
||||
+ "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). "
|
||||
+ "Do not write to the piece folder."
|
||||
#expect(stub.contains(closing))
|
||||
#expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false)
|
||||
.contains("Pass 2 — sentence level and below."))
|
||||
@@ -703,3 +717,122 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Research notes (#29)
|
||||
|
||||
/// The keep writes "today" — computed at test time like promote's day
|
||||
/// stamp (a midnight rollover mid-suite is tolerated).
|
||||
private func researchDay() -> String {
|
||||
FixCardStore.formatted(Date(), "yyyyMMdd")
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote lands the pinned markdown shape in research`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Kept\n", home: home)
|
||||
|
||||
let name = try PostStore.writeResearchNote(
|
||||
piecePath: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true).path,
|
||||
title: "The Long Now",
|
||||
url: "https://example.org/long-now",
|
||||
quote: "pace layers",
|
||||
note: "Supports the slowness claim.",
|
||||
home: home,
|
||||
)
|
||||
|
||||
let day = researchDay()
|
||||
#expect(name == "\(day)-the-long-now.md")
|
||||
let markdown = try String(
|
||||
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)"),
|
||||
encoding: .utf8,
|
||||
)
|
||||
let expected = "---\nsource: https://example.org/long-now\nkept: \(day)\n---\n\n"
|
||||
+ "# The Long Now\n\nSupports the slowness claim.\n\n> pace layers\n"
|
||||
#expect(markdown == expected)
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote omits absent note and quote sections`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Bare\n", home: home)
|
||||
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
|
||||
|
||||
// Both absent: frontmatter + heading, nothing else.
|
||||
let name = try PostStore.writeResearchNote(
|
||||
piecePath: pieceDir.path, title: "Only A Link", url: "https://example.org/one",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
let bare = try String(contentsOf: pieceDir.appendingPathComponent("research/\(name)"), encoding: .utf8)
|
||||
#expect(bare == "---\nsource: https://example.org/one\nkept: \(researchDay())\n---\n\n# Only A Link\n")
|
||||
|
||||
// Quote without note: the note section goes, the quote stays.
|
||||
let quoted = try PostStore.writeResearchNote(
|
||||
piecePath: pieceDir.path, title: "Quoted", url: "https://example.org/two",
|
||||
quote: "citation needed", note: "", home: home,
|
||||
)
|
||||
let text = try String(contentsOf: pieceDir.appendingPathComponent("research/\(quoted)"), encoding: .utf8)
|
||||
#expect(text.hasSuffix("\n\n# Quoted\n\n> citation needed\n"))
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote collision takes -2`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Twice\n", home: home)
|
||||
let piecePath = home.appendingPathComponent("projects/posts/\(post.id)").path
|
||||
|
||||
let first = try PostStore.writeResearchNote(
|
||||
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
let second = try PostStore.writeResearchNote(
|
||||
piecePath: piecePath, title: "Same Source", url: "https://example.org/same",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
|
||||
let day = researchDay()
|
||||
#expect(first == "\(day)-same-source.md")
|
||||
#expect(second == "\(day)-same-source-2.md")
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote accepts the post.md file form`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# File Form\n", home: home)
|
||||
|
||||
let name = try PostStore.writeResearchNote(
|
||||
piecePath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path,
|
||||
title: "Via File", url: "https://example.org/file",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
|
||||
#expect(FileManager.default.fileExists(
|
||||
atPath: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)").path,
|
||||
))
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote on vanished piece throws`() throws {
|
||||
let home = try storeHome()
|
||||
#expect(throws: FixCardStore.CardError(message: "piece not found: /nowhere/post.md")) {
|
||||
try PostStore.writeResearchNote(
|
||||
piecePath: "/nowhere/post.md", title: "Ghost", url: "https://example.org",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `writeResearchNote refuses a symlinked research dir`() throws {
|
||||
let home = try storeHome()
|
||||
let post = try PostStore.writeNew(body: "# Guarded\n", home: home)
|
||||
let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true)
|
||||
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
|
||||
try FileManager.default.createSymbolicLink(
|
||||
at: pieceDir.appendingPathComponent("research"),
|
||||
withDestinationURL: target,
|
||||
)
|
||||
|
||||
let planted = pieceDir.appendingPathComponent("research").path
|
||||
#expect(throws: FixCardStore.CardError(message: "research path is a symlink: \(planted)")) {
|
||||
try PostStore.writeResearchNote(
|
||||
piecePath: pieceDir.path, title: "Planted", url: "https://example.org",
|
||||
quote: "", note: "", home: home,
|
||||
)
|
||||
}
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//
|
||||
// ResearchCandidateTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #29 (S8.1–S8.3): the research-candidate pins, own file —
|
||||
// SessionLifecycleTests crossed its type-body ceiling (MCPToolsPromoteTests
|
||||
// precedent). Reuses the shared fake ACP harness.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
// #29 suite: candidate parsing, curation, and replay survival.
|
||||
|
||||
struct ResearchCandidateTests {
|
||||
/// #29 (S8.2): the batch parser — two notes → two candidates with ""
|
||||
/// defaults; a missing piece_path, an empty/absent notes array, or a
|
||||
/// note missing title/url yields NO candidates (the raw row owns it).
|
||||
@Test func `research batch parses notes and refuses garbage`() {
|
||||
let good: JSONValue = .object([
|
||||
"piece_path": .string("/tmp/piece"),
|
||||
"notes": .array([
|
||||
.object(["title": .string("A"), "url": .string("https://a"), "quote": .string("q"), "note": .string("n")]),
|
||||
.object(["title": .string("B"), "url": .string("https://b")]),
|
||||
]),
|
||||
])
|
||||
let batch = ResearchCandidate.batch(good)
|
||||
#expect(batch.count == 2)
|
||||
#expect(batch[0] == ResearchCandidate(piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "q", note: "n"))
|
||||
#expect(batch[1].quote == "")
|
||||
#expect(batch[1].note == "")
|
||||
#expect(batch[1].disposition == .pending)
|
||||
|
||||
// Garbage: no piece_path / empty notes / absent notes / note missing url / not an object.
|
||||
#expect(ResearchCandidate.batch(.object([
|
||||
"notes": .array([.object(["title": .string("A"), "url": .string("https://a")])]),
|
||||
])).isEmpty)
|
||||
#expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece"), "notes": .array([])])).isEmpty)
|
||||
#expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece")])).isEmpty)
|
||||
#expect(ResearchCandidate.batch(.object([
|
||||
"piece_path": .string("/tmp/piece"),
|
||||
"notes": .array([.object(["title": .string("A")])]),
|
||||
])).isEmpty)
|
||||
// Audit pin: whitespace-only title/url are the wire's refusal too —
|
||||
// both boundaries must agree (an invisible-titled card used to be
|
||||
// keepable as `-untitled.md`).
|
||||
#expect(ResearchCandidate.batch(.object([
|
||||
"piece_path": .string("/tmp/piece"),
|
||||
"notes": .array([.object(["title": .string(" "), "url": .string("https://a")])]),
|
||||
])).isEmpty)
|
||||
#expect(ResearchCandidate.batch(.object([
|
||||
"piece_path": .string("/tmp/piece"),
|
||||
"notes": .array([.object(["title": .string("A"), "url": .string(" ")])]),
|
||||
])).isEmpty)
|
||||
#expect(ResearchCandidate.batch(nil).isEmpty)
|
||||
}
|
||||
|
||||
/// #29 AC (S8.2): candidates live in their session — resume
|
||||
/// re-materializes them from the replayed transcript (engine-owned
|
||||
/// cargo). The planted session's history carries one research tool call
|
||||
/// with two notes; the default open RESUMES it, so the candidates are
|
||||
/// there without any extra turn.
|
||||
@Test @MainActor func `resume re-materializes research candidates from the replay`() async throws {
|
||||
let rosterDir = acpTempDir("research-roster")
|
||||
let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([entry], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("research"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
|
||||
var candidates: [ResearchCandidate] = []
|
||||
for _ in 0 ..< 500 {
|
||||
candidates = mentor.transcriptRows(of: entry).compactMap {
|
||||
if case let .researchNote(candidate) = $0.content {
|
||||
candidate
|
||||
} else {
|
||||
nil
|
||||
}
|
||||
}
|
||||
if candidates.count == 2 {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
// #require (not bare #expect + subscript): a missed settle must fail
|
||||
// the test, never trap the runner on an out-of-bounds index.
|
||||
try #require(candidates.count == 2, "expected two candidates from the replay, got \(candidates.count)")
|
||||
#expect(candidates.allSatisfy { $0.piecePath == "/tmp/piece" })
|
||||
#expect(candidates[0].title == "Hinge Study")
|
||||
#expect(candidates[0].url == "https://example.org/hinge")
|
||||
#expect(candidates[0].quote == "We should stop listening.")
|
||||
#expect(candidates[0].note == "Counts the pivot tense.")
|
||||
// The second note's absent quote/note default to "".
|
||||
#expect(candidates[1].title == "Second Source")
|
||||
#expect(candidates[1].quote == "")
|
||||
#expect(candidates[1].note == "")
|
||||
#expect(candidates.allSatisfy { $0.disposition == .pending })
|
||||
}
|
||||
|
||||
/// #29 (S8.3): the curation mutation — kept/rejected replace the row's
|
||||
/// content in the ACTIVE session's transcript; an unknown row id no-ops.
|
||||
@Test @MainActor func `research disposition flips the row and no-ops unknown ids`() async throws {
|
||||
let rosterDir = acpTempDir("disposition-roster")
|
||||
let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([entry], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("disposition"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
|
||||
var rows: [SessionRow] = []
|
||||
for _ in 0 ..< 500 {
|
||||
rows = mentor.transcriptRows(of: entry).filter {
|
||||
if case .researchNote = $0.content {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if rows.count == 2 {
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
try #require(rows.count == 2, "expected two candidate rows, got \(rows.count)")
|
||||
|
||||
mentor.setResearchDisposition(rowID: rows[0].id, .kept(fileName: "20261022-hinge-study.md"))
|
||||
mentor.setResearchDisposition(rowID: rows[1].id, .rejected)
|
||||
mentor.setResearchDisposition(rowID: UUID(), .rejected) // unknown id — no-op
|
||||
|
||||
let after = mentor.transcriptRows(of: entry)
|
||||
#expect(after.contains { row in
|
||||
if case let .researchNote(candidate) = row.content {
|
||||
return candidate.disposition == .kept(fileName: "20261022-hinge-study.md")
|
||||
}
|
||||
return false
|
||||
})
|
||||
#expect(after.contains { row in
|
||||
if case let .researchNote(candidate) = row.content {
|
||||
return candidate.disposition == .rejected
|
||||
}
|
||||
return false
|
||||
})
|
||||
// Exactly two research rows still — the unknown id added nothing.
|
||||
#expect(after.filter {
|
||||
if case .researchNote = $0.content {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}.count == 2)
|
||||
}
|
||||
|
||||
/// #29 (S8.3): the writing filter keeps candidate cards visible.
|
||||
@Test func `writing filter keeps research candidate rows`() {
|
||||
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .researchNote(ResearchCandidate(
|
||||
piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "", note: "",
|
||||
)))))
|
||||
}
|
||||
}
|
||||
@@ -380,7 +380,7 @@ struct SessionLifecycleTests {
|
||||
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)
|
||||
#expect(try !mentor.transcriptRows(of: #require(mentor.activeEntry)).isEmpty)
|
||||
|
||||
if let pid = mentor.childProcessIdentifier {
|
||||
kill(pid, SIGKILL) // crash the child
|
||||
@@ -398,7 +398,7 @@ struct SessionLifecycleTests {
|
||||
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))
|
||||
let rows = try mentor.transcriptRows(of: #require(mentor.activeEntry))
|
||||
#expect(rows.contains { row in
|
||||
if case let .text(text) = row.content {
|
||||
return text.contains("earlier ask")
|
||||
|
||||
Reference in new issue
Block a user