feat(mentor): research & library-light (S8) (#29)
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:
AlexKucera committed 2026-10-22 14:06:16 +02:00
1 parent 9895614b7e
commit b02d36bb5d
22 files changed
+977 -33

No files matched your search

+160
View File
@@ -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: "",
)))))
}
}