feat(microblog): post summary for Micro.blog

A piece's `summary:` frontmatter line now travels to Micro.blog
beside `category:`. A first send carries the summary when it is not
empty; a re-send replaces the post's summary only when the piece has
the line (opt-in by key; an empty value clears it; no line leaves the
blog's). The same rule as categories, so a piece that never gained
the line cannot blank a summary set on Micro.blog itself.

The publish sheet gains a Summary field and an AI summary button. The
button drafts a first-person teaser from the open piece on a fresh
one-shot engine on the chat profile (the Blind Read's rail — the
resident session is never touched); the reply fills the field for the
writer to edit, and nothing is written until the send stamps the
line. The sheet is modal, so while its own turn runs the button is
the Stop; a Pass or Blind Read that owns the rail disables the button
with the reason on hover and refuses from behind it.

The summary is read off the RAW frontmatter line, never through the
lenient decode — which trims every edge quote — and the read walks
the block the way the lenient reader does. A `split`-based read finds
no block in a mixed-ending file while the lenient reader still sees
the key, and the empty value it answers would have been sent over a
live post's summary.

Reviewed twice (two-axis during the build, three-reviewer
finish-audit after): the mixed-ending read, an unfenced body line
claiming the key, the uncancellable modal turn, and the wrapper rule
eating a teaser's edge quotes were found and fixed before this
commit. Every guard was watched fail on its own pin. Rail 814/814;
SwiftFormat and SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, and the devlog.

Closes #208
This commit is contained in:
AlexKucera committed 2026-12-05 12:32:38 +01:00
1 parent 6db4cf8cf1
commit 36393a9e8e
22 files changed
+1096 -36

No files matched your search

+3 -3
View File
@@ -31,7 +31,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on. Mode strings (mirroring the retired zsh fake): full/crashAfterHandshake/hangOnPrompt/hangOnPromptLoad/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/summaryOnPrompt (#208 — a summary-shaped two-chunk reply, a normal end, NO fix-card tool call; placed AHEAD of the `full` mode's `Hello mentor.` chunks, which concatenate into the one agent row)/loadReplay*/strictMcp.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
@@ -39,10 +39,10 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses); #207 `MicropubCategoryTests` — categories travel (a create carries the list when non-empty; a re-send opt-in by key, `[]` clears), the codec list incl. the unbracketed primitives, apply-at-send with the failed-write refusal, the blog's `q=category` list, publish-applies-first (a failed update never publishes — the request count is pinned; the flip targets the post the send touched, never a stale caller URL), the sanitized name on disk and wire, the model's `openPieceCategories()` read, the import keeps a category line, + the sheet field's pure rules (pending edit, picks-add completion, the menu). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared; `plantedPiece` (a saved `# Titled` piece with planted frontmatter) lives in `MicropubTests.swift` beside the other shared helpers. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests`, `MicropubSummaryTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses); #207 `MicropubCategoryTests` — categories travel (a create carries the list when non-empty; a re-send opt-in by key, `[]` clears), the codec list incl. the unbracketed primitives, apply-at-send with the failed-write refusal, the blog's `q=category` list, publish-applies-first (a failed update never publishes — the request count is pinned; the flip targets the post the send touched, never a stale caller URL), the sanitized name on disk and wire, the model's `openPieceCategories()` read, the import keeps a category line, + the sheet field's pure rules (pending edit, picks-add completion, the menu); #208 `MicropubSummaryTests` — the summary travels (create when non-empty; re-send opt-in by key, `""` clears), the one-line codec (`summaryValue`/`summary(inText:)` — the raw-line read; newlines collapse, controls drop, quote-bearing values render quoted and round-trip), apply-at-send with the failed-write refusal, the model's `openPieceSummary()` read, an edge-quote summary reaching the wire exactly as typed, + the sheet field's trimmed-string pending-edit rule. `plantIllustratedPiece` lives in `MicropubModelTests` and is shared; `plantedPiece` (a saved `# Titled` piece with planted frontmatter) lives in `MicropubTests.swift` beside the other shared helpers. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `SummaryGenerationTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, #208 the AI post summary (`SummaryGenerationTests` — the pure prompt + `cleaned`, and `summarize` over the `summaryOnPrompt` rig: a fresh chat-profile one-shot drafts and the cleaned reply comes back with NOTHING written and the roster untouched; refusals — no open piece, the one-shot rail busy, a refused/empty turn), per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import, image ingest + the 27.2 drag-routing seam (`DragInfoStub`, the suite's NSDraggingInfo mock: a Finder-shaped drag routes through the text view and never pastes the path; text-only drags keep the stock drop; outline rows bounce; the probe follows `changeCount`; web URLs and vanished files refuse with the right notice) + the one router's pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal).
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
+377
View File
@@ -0,0 +1,377 @@
// MicropubSummaryTests.swift
// MuseionTests
//
// #208: a post summary for Micro.blog — the wire + codec half. The
// sheet's Summary field is sheet state (the Categories discipline);
// the edit lands on the piece AT THE SEND as a one-line `summary:`
// key, and the wire reads from disk: a CREATE carries
// `properties.summary` when non-empty; a RE-SEND carries `summary`
// in `replace` ONLY when the piece has the line (opt-in by key —
// an empty string is sent and clears the post's summary; no line →
// `replace` names exactly name + content, the blog keeps whatever it
// has). The AI half (the one-shot engine drafting the summary) rides
// its own file; the sheet itself is not pinned here.
//
// Pins: S1 the codec reads the line · S2 create carries it · S3 the
// re-send opt-in by key · S4 the edit lands at the send (sanitized,
// one line, readable through the model; a failed write refuses).
//
// ## Scenario: the summary travels on the wire
// From #208
//
// Given a saved Post whose frontmatter carries a one-line `summary:`
// When the writer sends it to Micro.blog or re-sends over the
// remembered post
// Then a CREATE carries `properties.summary` (only when non-empty);
// a RE-SEND carries `summary` in `replace` ONLY when the piece has
// the line (`""` is sent and clears; no line leaves the blog's).
//
// ## Scenario: the edit lands at the send
// From #208
//
// Given a sheet Summary edit (the model's `summary:` argument)
// When the writer sends
// Then the line is written to the piece AFTER the flush and BEFORE
// the one disk read that feeds the wire — disk and blog never
// disagree; a write that cannot land REFUSES the send with nothing
// on the wire.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubSummaryTests")
struct MicropubSummaryTests {
/// A saved piece opened in the model, with `frontmatter` planted
/// after the owned keys; returns its id.
@MainActor private func openPiece(_ model: PostsModel, _ home: URL, frontmatter: String = "") throws -> String {
let id = try plantedPiece(home, frontmatter: frontmatter)
model.select(id)
return id
}
/// A recorded create's `properties` — through `request(_:)`, never a
/// subscript (#206).
private nonisolated func createProperties(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
let request = try #require(log.request(index))
return try #require(micropubJSON(request)["properties"] as? [String: Any])
}
/// A recorded update's `replace`.
private nonisolated func updateReplace(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
let request = try #require(log.request(index))
return try #require(micropubJSON(request)["replace"] as? [String: Any])
}
// MARK: S1 — the codec reads the one-line summary (pure)
@Test func `summary read is the raw line's scalar and empty when absent`() {
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left the city.\n---\n") == "Why I left the city.")
#expect(PostFrontmatter.summary(inText: "---\nsummary: Padded. \n---\n") == "Padded.")
// A hand-quoted scalar reads back as the bare text.
#expect(PostFrontmatter.summary(inText: "---\nsummary: \"Quoted, with comma\"\n---\n") == "Quoted, with comma")
// Empty, blank, or absent → "" (a piece without a line never gains one).
#expect(PostFrontmatter.summary(inText: "---\nsummary:\n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\nsummary: \n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n") == "")
// A body line named summary: never claims the key.
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n\nsummary: not frontmatter\n") == "")
// No block at all → nothing.
#expect(PostFrontmatter.summary(inText: "# Title\n\nBody.\n") == "")
// A body line named summary: never claims the key — fenced or not.
#expect(PostFrontmatter.summary(inText: "# Title\n\nsummary: body prose\n") == "")
// ponytail: a CRLF post.md is one grapheme-cluster "line" to every
// `\n` split in the corpus (PostStore: LF-only by design, CRLF is
// normalized at the boundaries) — no reader sees its block, this
// one included. The MIXED shape (an LF block with a stray trailing
// \r on one line) is where parse and a `.whitespaces` trim would
// diverge — pinned at the wire in `a mixed-line-ending piece…`.
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left.\r\n---\n") == "Why I left.")
}
@Test func `summary value strips newlines so the line-bounded sink is safe`() {
// The frontmatter sink is line-bounded — a summary can never ride
// a newline into the block; the value is one line or nothing.
let value = PostFrontmatter.summaryValue("Line one.\nLine two.")
#expect(!value.contains("\n"))
#expect(PostFrontmatter.summary(inText: "---\nsummary: \(value)\n---\n") == "Line one. Line two.")
// Leading/trailing whitespace trims; a blank becomes "".
#expect(PostFrontmatter.summaryValue(" ") == "")
}
@Test func `summary value round-trips through the raw line read without losing edge quotes or controls`() {
// The lenient parse trims EVERY leading/trailing quote char, so
// the wire and the sheet read the raw line (`summary(inText:)`);
// the render QUOTES anything holding a quote or backslash, so
// `asked "why"` ships exactly as typed.
let read = { text in PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n") }
#expect(read(#"I finally asked "why""#) == #"I finally asked "why""#)
#expect(read(#""Why did you leave?" haunted me."#) == #""Why did you leave?" haunted me."#)
// An inner quote and a newline together: flattened AND round-tripped.
#expect(read("Line \"one\".\nLine two.") == "Line \"one\". Line two.")
// A backslash survives too (the category codec's escape).
#expect(read(#"C:\path "x""#) == #"C:\path "x""#)
// Control characters (NUL, ESC) never reach the sink — the
// category codec's rule; whitespace still collapses to one space.
#expect(PostFrontmatter.summaryValue("a\u{0}b\u{1B} c") == "ab c")
// A plain value renders bare.
#expect(PostFrontmatter.summaryValue("Why I left.") == "Why I left.")
}
// MARK: S2 — a create carries the summary when non-empty (builder + model)
@Test func `draft request carries summary only when non-empty`() throws {
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", summary: "Why I left.")
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["summary"] as? [String] == ["Why I left."])
#expect(props["name"] as? [String] == ["T"])
#expect(props["content"] as? [String] == ["B"])
// No summary → no key at all (a create never carries an empty one).
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
#expect(bare["summary"] == nil)
}
@Test @MainActor func `create carries the piece's summary and no key when there is none`() async throws {
let (model, home) = try makeModelHome()
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/summarized"], log: log)
_ = try openPiece(model, home, frontmatter: "summary: Why I left the city.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .drafted(url: "https://example.micro.blog/summarized", preview: nil))
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["Why I left the city."])
// No line at all → no key; an empty line → no key either.
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 1)["summary"] == nil)
_ = try openPiece(model, home, frontmatter: "summary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 2)["summary"] == nil)
}
// MARK: S3 — a re-send replaces, opt-in by key (the model)
@Test @MainActor func `a re-send carries the line's summary in replace and clears on an empty one`() async throws {
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let transport = micropubCanned(200, log: log)
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .updated(url: url))
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
#expect(replace["name"] as? [String] == ["Titled"])
// An empty summary IS sent — it clears the post's.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] as? [String] == [""])
// No line → replace names exactly name + content: the blog keeps whatever it has.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let kept = try updateReplace(log, 2)
#expect(Set(kept.keys) == ["name", "content"])
}
// MARK: S4 — the edit lands at the send
@Test @MainActor func `a summary edit lands on the piece before the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home) // no summary line yet
let before = try PostFrontmatter.split(readPost(home, id)).body
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/edited"], log: log)
let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport)
#expect(outcome == .drafted(url: "https://example.micro.blog/edited", preview: nil))
let after = try readPost(home, id)
// The line is a line of the block; the body is byte-identical.
#expect(PostFrontmatter.split(after).block.contains("\nsummary: A teaser.\n"))
#expect(PostFrontmatter.split(after).body == before)
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["A teaser."])
}
@Test @MainActor func `a refused send with a summary edit writes nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never opened
let before = try readPost(home, post.id)
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: micropubCanned(201, log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
#expect(try readPost(home, post.id) == before) // the edit never reached the disk
}
@Test @MainActor func `a summary write that cannot land refuses the send with nothing on the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home)
// The piece folder goes read-only: the summary line cannot land.
let dir = try #require(PostStore.folder(of: id, home: home))
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
let log = MicropubRequestLog()
let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: micropubCanned(201, log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.hasPrefix("Couldn't save this piece's summary — nothing was sent."))
#expect(log.requests.isEmpty)
#expect(try PostFrontmatter.summary(inText: readPost(home, id)) == "")
}
@Test @MainActor func `an edge-quote summary reaches the wire exactly as typed`() async throws {
// The review's finding: the lenient parse trims every edge quote,
// so a teaser closing in `"why"` must still ship whole — on a
// create AND on a re-send, and reopen whole in the sheet's read.
let (model, home) = try makeModelHome()
let teaser = #"I finally asked "why""#
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/quoted"], log: log)
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", summary: teaser, transport: transport)
#expect(try createProperties(log, 0)["summary"] as? [String] == [teaser])
#expect(model.openPieceSummary() == teaser)
// A re-send reads the stamped line back — still whole. The piece
// remembers its post from the first send, so this is the update.
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 1)["summary"] as? [String] == [teaser])
}
@Test @MainActor func `the sheet's disk read is the open piece's summary line`() async throws {
let (model, home) = try makeModelHome()
#expect(model.openPieceSummary() == "") // nothing open
_ = try openPiece(model, home)
#expect(model.openPieceSummary() == "") // no line yet
_ = await model.micropubSend(
token: "tok",
summary: "A teaser.",
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: MicropubRequestLog()),
)
#expect(model.openPieceSummary() == "A teaser.") // read from disk, never a snapshot
}
@Test @MainActor func `a mixed-line-ending piece re-sends its real summary never an empty clear`() async throws {
// The trimmed() rule. A pure CRLF file is ONE grapheme "line" to
// every `\n` split in the corpus (LF-only by design, normalized at
// the boundaries) — no reader sees its block, so nothing can
// disagree. The shape that CAN: an LF block carrying a stray
// trailing \r on the summary line (a half-converted edit) — parse's
// trimmed() sees the key, a `.whitespaces` trim would leave `\r`
// on the fence and read "" → replace summary [""] over the live post.
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n")
let id = try #require(model.selectedPostID)
let file = try #require(PostStore.folder(of: id, home: home)?.appendingPathComponent("post.md"))
try String(contentsOf: file, encoding: .utf8)
.replacingOccurrences(of: "summary: Why I left.\n", with: "summary: Why I left.\r\n")
.write(to: file, atomically: true, encoding: .utf8)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 1)
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
}
@Test @MainActor func `publish with only a summary edit updates first then flips the status`() async throws {
// The applies-first condition is `categories != nil || summary != nil` —
// a summary-only edit must still send before the flip, or Publish
// would publish the stale post and silently drop the edit.
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/drafted"
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
let log = MicropubRequestLog()
let outcome = await model.micropubPublish(url: url, token: "tok", summary: "A teaser.", transport: micropubCanned(200, log: log))
#expect(outcome == .published)
// TWO requests, in order: the update carrying the edit, THEN the flip.
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 0)["summary"] as? [String] == ["A teaser."])
let flip = try #require(log.request(1))
let flipReplace = try #require(micropubJSON(flip)["replace"] as? [String: Any])
#expect(flipReplace["post-status"] as? [String] == ["published"])
#expect(flipReplace["summary"] == nil)
#expect(model.openPieceSummary() == "A teaser.")
#expect(try PostFrontmatter.split(readPost(home, id)).block.contains("micropub_published: "))
}
@Test @MainActor func `clearing a sent summary writes the empty line and clears the post's`() async throws {
// End to end through the model's own written form (not a hand-planted
// line): send, then clear → the update carries summary [""].
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let transport = micropubCanned(200, headers: ["Location": url], log: log)
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
_ = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport)
#expect(model.openPieceSummary() == "A teaser.")
let outcome = await model.micropubSend(token: "tok", summary: "", transport: transport)
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 2)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] as? [String] == [""])
let id = try #require(model.selectedPostID)
let disk = try readPost(home, id)
#expect(PostFrontmatter.split(disk).block.contains("\nsummary: \n"))
#expect(model.openPieceSummary() == "")
}
@Test func `an imported summary line rides through import`() throws {
let home = try storeHome()
// The summary is the writer's content, like `category:` — it stays;
// only Museion's bookkeeping drops at the boundary (#206).
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("summarized-\(UUID().uuidString).md")
try "---\nsummary: Why I left.\nmicropub_url: https://example.micro.blog/x\n---\n\n# Outside\n\nBody.\n"
.write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
let disk = try readPost(home, post.id)
let matter = try PostFrontmatter.parse(disk)
#expect(PostFrontmatter.summary(inText: disk) == "Why I left.")
#expect(matter["micropub_url"] == nil)
}
// MARK: S5 — the sheet field's pending-edit rule (pure)
@Test func `a summary edit is pending only when the trimmed field differs from the settled one`() {
#expect(MicropubSummaryField.pendingSummary(field: "Why I left.", settled: "Why I left.") == nil)
// Trailing whitespace is not an edit.
#expect(MicropubSummaryField.pendingSummary(field: "Why I left. ", settled: "Why I left.") == nil)
// Clearing a piece that had a line sends an empty summary.
#expect(MicropubSummaryField.pendingSummary(field: "", settled: "Why I left.") == "")
#expect(MicropubSummaryField.pendingSummary(field: "New", settled: "") == "New")
// A piece without a line never gains an empty key.
#expect(MicropubSummaryField.pendingSummary(field: " ", settled: "") == nil)
}
}
+10
View File
@@ -334,6 +334,16 @@ extension ScriptedEngine {
continuation.resume(returning: .object(["stopReason": .string("refusal")]))
return
}
if mode == "summaryOnPrompt" {
// #208: a summary-shaped reply — two chunks of one sentence,
// a normal end, NO fix-card tool call (the draft IS the reply
// text). Ahead of the "Hello mentor." chunks so the summary
// pins read the reply exactly.
chunk(sid, "agent_message_chunk", "I left the city because ")
chunk(sid, "agent_message_chunk", "the noise never stopped.")
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return
}
chunk(sid, "user_message_chunk", "echo")
chunk(sid, "agent_thought_chunk", "weighing the structure")
chunk(sid, "agent_message_chunk", "Hello ")
+176
View File
@@ -0,0 +1,176 @@
//
// SummaryGenerationTests.swift
// MuseionTests
//
// ## Scenario: the AI drafts a first-person summary
// From #208
//
// Given an open saved piece and an idle one-shot rail
// When the writer asks for an AI summary
// Then a fresh one-shot engine on the museion profile receives the
// piece's Title and body (flushed to disk first) with a prompt that
// asks for a first-person teaser, and the reply text comes back to
// the caller — nothing is written to disk, the roster is untouched,
// and the transcript it ran in is transient.
//
import Foundation
@testable import Museion
import Testing
@Suite("SummaryGenerationTests")
struct SummaryGenerationTests {
// MARK: The pure prompt (SummaryPrompt)
@Test func `prompt carries the title and body and asks for first person`() {
let prompt = SummaryPrompt.prompt(title: "T", body: "B")
#expect(prompt.contains("T"))
#expect(prompt.contains("B"))
#expect(prompt.lowercased().contains("first person"))
#expect(prompt.lowercased().contains("entice"))
}
@Test func `cleaned trims drops a leading label and surrounding quotes`() {
#expect(SummaryPrompt.cleaned(" Summary: Why I left. ") == "Why I left.")
#expect(SummaryPrompt.cleaned("\"Why I left.\"") == "Why I left.")
#expect(SummaryPrompt.cleaned("Line one.\nLine two.") == "Line one. Line two.")
#expect(SummaryPrompt.cleaned(" ") == "")
// A reply that merely opens with the word keeps it.
#expect(SummaryPrompt.cleaned("Summary opens the piece.") == "Summary opens the piece.")
// Prose bracketed by quoted words is a teaser, not a wrapper — the
// edge quotes are the writer's and stay.
let bracketed = "\"Why did you leave?\" I asked. She said \"never.\""
#expect(SummaryPrompt.cleaned(bracketed) == bracketed)
// Label and wrapper together.
#expect(SummaryPrompt.cleaned("Summary: \"Why I left.\"") == "Why I left.")
}
// MARK: The model half (PostsModel.summarize over the scripted rig)
/// A saved `# Titled` piece opened in the model, waited into the
/// library scan (the label and the prompt read the library's title).
@MainActor private func openPiece(_ rig: ScriptedRig) async throws -> String {
let id = try plantedPiece(rig.home)
rig.model.select(id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
return id
}
/// How many `museion` (chat-profile) engines spawned — the resident
/// plus every one-shot (BlindReadTests' countable).
@MainActor private func museionSpawns(_ rig: ScriptedRig) -> Int {
rig.engines.spawnedProfiles.filter { $0 == "museion" }.count
}
@Test @MainActor func `summarize runs a fresh chat-profile engine and returns the cleaned reply`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == "I left the city because the noise never stopped.")
// A fresh CHAT-profile engine drafted (the resident is the only
// other `museion` spawn; pass profiles never ran).
#expect(museionSpawns(rig) == 2)
#expect(!rig.engines.spawnedProfiles.contains { $0.contains("museion-pass") })
// The prompt carried the piece's body inline (the engines' prompt log).
let asked = rig.engines.engines.flatMap(\.promptLog).map(\.text).joined()
#expect(asked.contains("Body."))
// The transient label renders; the roster never grew; nothing was
// written — the piece on disk carries no summary line.
#expect(textRows(of: rig.mentor).contains("Summary · Titled"))
#expect(rig.mentor.roster.count == rosterBefore)
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(!onDisk.contains("summary:"))
#expect(rig.model.lastError == nil)
}
@Test @MainActor func `summarize refuses when no piece is open`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("Open a saved post") == true)
// Nothing ran beyond the resident engine.
#expect(museionSpawns(rig) == 1)
}
@Test @MainActor func `summarize refuses while the one-shot rail is busy`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
for _ in 0 ..< 250 where rig.model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == .pass1)
// Exclusivity — the summary refuses while the pass owns the rail.
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("already running") == true)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
for _ in 0 ..< 250 where rig.model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == nil)
rig.mentor.shutdown() // frees the held turn if the rail regressed — bounds the await
_ = await run.value
}
@Test @MainActor func `a cancelled summary turn returns nil and frees the rail`() async throws {
// A hung engine must not hold the sheet's spinner forever: the pass
// bar's Cancel (cancelPass) ends the summary turn like a Blind Read's.
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.summarize(mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.summarizing) // the flag the pass bar's Cancel keys on
// Reverse exclusivity: a Pass refuses while the summary owns the
// rail — and the refusal NAMES the summary (the guard, not the
// host's engine lock downstream).
await rig.model.runPass(.pass1, mentor: rig.mentor)
#expect(rig.model.lastError == "A summary is already running.")
#expect(rig.model.runningPass == nil)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
let summary = await run.value
#expect(summary == nil)
for _ in 0 ..< 250 where rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(!rig.model.summarizing)
#expect(!rig.mentor.isStreaming) // the rail is free again
}
@Test @MainActor func `a refused or empty turn returns nil`() async throws {
let rig = try makeScriptedRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("didn't return a summary") == true)
}
}