feat(mentor): blind read A/B judgment (#122)
CI / ci (push) Canceled after 0s

A purposeful writer action on the open post — the "Blind Read" button
beside Run Pass — triggers a whole-document advisory judgment: the
current document against the Pass-start snapshot (the newest
passes/pass-N.md on disk), decided by a FRESH session of the same
museion profile over the existing one-shot ACP rail. Both versions
travel inline in one prompt under neutral A/B position labels with
randomized order — the judge never learns which is the rewrite — and
the A/B-to-origin reveal appends only after the verdict, so the mapping
cannot leak; cancelled, refused, and spawn-failed turns reveal nothing.

Advisory-only per decision #120: no Pass State advance, no cards, no
Learnings, the roster never grows — the verdict is display-only and
dies with the transient transcript. The writer stays judge of record;
demonstrator picks and Fix Card status are untouched. Honest refusals
for the degenerate states: no snapshot yet, an unchanged document, or
a busy rail (passes and reads refuse each other; the pass bar's one
Cancel ends either).

The pass engine's spawn/session/teardown block became one shared
runOneShot rail (failure rows speak the run's own name), the pass-bar
button gates on a derived openPieceHasSnapshot flag, the fake ACP
gained a prompt-log observable, and the GLOSSARY "Blind Read" term
landed with the issue.

Finish-audit (three reviewers): a refusal still ends .ended, so the
reveal now gates on the stopReason (flip-verified pin), plus the
Cancel-rail and pass/blind-read exclusivity pins. Suite 500; swiftformat
clean; swiftlint adds no violations over the HEAD baseline.

Closes #122
This commit is contained in:
AlexKucera committed 2026-10-30 17:31:00 +01:00
1 parent 4724e00b73
commit 97e86cf62d
15 files changed
+627 -32

No files matched your search

+4 -5
View File
@@ -111,7 +111,7 @@ When the user requests a durable behavior change, record it here or in the relev
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
| `docs/AGENTS.md` | Durable documentation — ADRs and their conventions |
| `ref/writing skills/AGENTS.md` | Bundled writing-skill set — the G3a payload seeded into the museion profile |
| `CONTEXT.md` | Binding project glossary — shared vocabulary for app, mentor, and docs |
| `GLOSSARY.md` | Binding project glossary — shared vocabulary for app, mentor, and docs |
## Agent skills
@@ -125,12 +125,12 @@ Default five canonical roles, label string = role name. See `docs/agents/triage-
### Domain docs
Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/domain.md`.
Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/domain.md`.
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (5285 symbols, 20153 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (5336 symbols, 20660 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -190,6 +190,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) |
| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) |
| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) |
| 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) |
@@ -199,6 +200,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) |
| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) |
| 2026-10-22 | [20261022-issue29-research-library-light_log.md](20261022-issue29-research-library-light_log.md) |
| 2026-10-22 | [20261022-issue28-session-lifecycle-ui_log.md](20261022-issue28-session-lifecycle-ui_log.md) |
| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](20261021-issue27-dismiss-decay-learnings_log.md) |
<!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added
- **mentor:** Blind Read — writer-triggered advisory A/B judgment (#122, decision #120) — a purposeful "Blind Read" button beside Run Pass in the pass bar judges the current document against the Pass-start snapshot (the newest `passes/pass-N.md` on disk): both versions travel INLINE in one prompt under neutral A/B position labels with randomized order (origin words never appear — the judge can't know which is the rewrite), a fresh one-shot engine on the same `museion` chat profile renders its pick + one-line reason into the transient transcript, and the A/B↔origin reveal lands only AFTER the verdict so it can never leak; cancelled, refused, and spawn-failed turns reveal nothing. Advisory-only per #120: nothing advances, no cards, no Learnings, the roster never grows — the verdict dies with the transcript and the writer stays judge of record. Honest refusals: no snapshot yet ("run a Pass first"), an unchanged document ("No edits since…"), or a busy rail (passes and reads refuse each other; one Cancel ends either). The pass engine's spawn/session/teardown block became one shared `runOneShot` rail (failure rows speak the run's own name), the fake ACP gained a prompt-log observable, and the GLOSSARY "Blind Read" term landed. Finish-audit (3 reviewers) fixed the refusal-reveal gate (a refusal still ends `.ended` — gate on the stopReason; flip-verified), the hardcoded "Pass failed" copy, and pinned the Cancel/exclusivity rail. Suite 500 (issue #122)
- **mentor:** Native deslop lint at pass invocation (PRD S3.4) — running a pass now computes the deslop skill's deterministic findings (banned-vocab tiers + em-dash density) natively in Swift at the invocation — after first-draft stats capture, before the engine turn, no engine round-trip — and each finding lands as a real fix card (emitter `lint`) under `<piece>/cards/`, rendered by the existing Fix Cards palette with ask-before Apply on mechanical mapping cards (mapped phrases like `utilize`→`use` carry the replacement; unmapped ones land demonstration for judgment). One card per phrase over its tier allowance, case-insensitive whole-word matching (`delved` never fires `delve`), anchor = the first match with case preserved, em-dash density card first when over budget, tiers ranked by first match. The tier data ships as `Resources/deslop-lint.json` mirroring the deslop doctrine verbatim (`key`/`landscape`/`highlight`/bare `underscore` deliberately omitted as POS-ambiguous — add via `<home>/deslop-lint.json`, which wins whenever it exists and decodes); emit dedups against OPEN cards before submit so re-runs make progress (closed cards never block) and the engine never re-cards a live lint finding. A failed lint never blocks the pass (the stats-capture posture). Suite 487 (issue #6)
- **mentor:** Prompt-end constraint ordering verified + pinned (#1) — the PRD's cross-cutting rule audited on the app's REAL wire: an ACP probe (initialize → session/new → session/prompt against the provisioned museion-pass1) plus the engine's own state.db read-back show constraint bodies never ride the system prompt — they enter as `skill_view` results, so "assembly order" is the mentor's tool-call order, and the baseline already loaded deslop AFTER the piece but by model choice. Both personas (pass 1.5 / session 1.2) gain the verbatim-shared "Draft first, rules last" pin converting observed-once into instructed-always; `PersonaLoadOrderTests` guards presence + parity over the bundled payload; the verified layout, the `hermes -z` trap (one-shot swaps the skills directive — a `-z` probe loads ZERO skills and assembles a different prompt), and the additive-only propagation cost (content edits need a hand-copy to master/profile copies; byte-match then migrates) live in `docs/research/prompt-layout-factsheet.md` with the probe script in-repo. Suite 479 + 1 load-flake cleared in isolation (issue #1)
+4
View File
@@ -91,6 +91,10 @@ _Avoid_: review, run, check
The maturity of a Piece, recorded in its frontmatter: First Draft, Pass-1 Done, Pass-2 Done. Explicit, never inferred. Advances when the Pass completes — the engine's turn ends — not when its Fix Cards are resolved; passes run in any order.
_Avoid_: status, draft state
**Blind Read**:
A writer-triggered, whole-document judgment: the current Piece against its Pass-start snapshot, compared by a fresh session of the Museion profile that never saw the editing history. The two versions go in unlabeled and in randomized order; the verdict — a pick and one line why — is display-only. Records nothing; the writer stays judge of record.
_Avoid_: A/B test, vote, score
**Fix Card**:
One finding from a pass: pattern, problem, diagnostic question, fix, anchor, lane, emitter, provenance, status. Anchored to a text span by quote; travels as a typed tool call, never prose to parse. The lane is declared, never inferred — mechanical (the whole fix is a pure function of the anchor plus fixed tables: cut, move, mapping, case) or demonstration (any generation).
_Avoid_: suggestion, comment, annotation
+4 -3
View File
@@ -28,7 +28,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`).
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "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." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
@@ -75,8 +76,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (#137: `init(binaryPath:profile:)` — default `museion` for chat, pass engines pass their own profile; ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`ensureDefaultSession`), the bridge is session-agnostic.** `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
**#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; **#30 dogfood: the REAL 0.21.5 load response carries NO top-level `sessionId` — the id rides `_meta.hermes.sessionProvenance.acpSessionId`, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"**), `forkActiveSession()` (wire session/fork → "<name> (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginBrainstormSession(pieceTitle:)` (#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn is `brainstormPrompt`, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript), `draftCandidateText()` / `draftCandidateText(in:)` (#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. **#29 (S8.1–S8.3) research candidates:** `ResearchCandidate` (nonisolated: piecePath/title/url/quote/note + `Disposition` pending|kept(fileName)|rejected) rides `SessionRow.Content.researchNote` — `appendToolCall` routes on PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses via `ResearchCandidate.batch` (one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted). `setResearchDisposition(rowID:_:)` flips the ACTIVE session's row in place (unknown id = no-op). `isWritingRow` keeps `.researchNote` visible in the writing voice.
**#137 (S4, ADR-0014) per-surface engine lifecycle:** passes run on their OWN one-shot engines — `runPass(kind:stub:pieceTitle:)` spawns `ACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))` (museion-passN), streams the verdict into a TRANSIENT unrostered transcript under `passTranscriptKey` ("pass", the active entry lives only for the run — #129: passes are never rostered; `handleNotification` maps the pass wire sid onto the key), and tears the engine down at the verdict (`teardownPassEngine`; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). The turn pipeline is ONE `turnCore(client:wireSid:key:prompt:label:)` shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush); `sendPrompt` refuses the pass surface with a visible row (read-only transcript). Restart posture: `restart()` (crash button) and `requestRestart()` (model-change, Settings fires it) share `respawn()` — teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest); `requestRestart` defers to turn end while `isStreaming` (`pendingRestart`, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config). `stopStreaming` routes `session/cancel` to the PASS engine while a pass runs. Internal test observables: `passEngineChildPid`, `isPassEngineRunning`. **Run Pass readiness (#137 acceptance 3, slice B):** `PassReadiness` (ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (`passReadiness`; `passReadinessWriter` = injectable read seam, nil → ad-hoc `HermesSettingsWriter` over the gate's binary, no binaryPath → stays empty); `refreshPassReadiness()` reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps `.unknown` (never block on our own read failure). `PostsModel.runPass` guards `.missingKey` BEFORE the open-piece guard: `lastError` names the provider and nothing touches disk, not even the pre-pass snapshot.
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the state row carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task` runs `refreshPassReadiness()` before the hosted-test guard — pane re-entry re-fires it, so a key added in Settings re-enables Run Pass. `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carrLine truncated
**#137 (S4, ADR-0014) per-surface engine lifecycle:** passes run on their OWN one-shot engines — `runPass(kind:stub:pieceTitle:)` spawns `ACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))` (museion-passN), streams the verdict into a TRANSIENT unrostered transcript under `passTranscriptKey` ("pass", the active entry lives only for the run — #129: passes are never rostered; `handleNotification` maps the pass wire sid onto the key), and tears the engine down at the verdict (`teardownPassEngine`; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). **#122: the spawn/session/new/teardown block is ONE private rail — `runOneShot(profile:name:prompt:pieceTitle:)` — shared by `runPass` and `runBlindRead(prompt:pieceTitle:reveal:)` (the Blind Read rides the CHAT profile `museion`: context-free = a fresh session, not a different judge — decision #120; the reveal row appends only on `.ended` with stopReason ≠ "refusal" — a refusal still ends .ended, and a 2×-document prompt makes length refusals realistic — after the turn-end flush, so the mapping can never leak to the judge). `name` ("Pass 1"/"Blind Read") composes the label; the rail's failure rows speak `\(label) failed` so a Blind Read spawn failure never reads "Pass failed".** The turn pipeline is ONE `turnCore(client:wireSid:key:prompt:label:)` shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush); `sendPrompt` refuses the pass surface with a visible row (read-only transcript). Restart posture: `restart()` (crash button) and `requestRestart()` (model-change, Settings fires it) share `respawn()` — teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest); `requestRestart` defers to turn end while `isStreaming` (`pendingRestart`, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config). `stopStreaming` routes `session/cancel` to the PASS engine while a pass runs. Internal test observables: `passEngineChildPid`, `isPassEngineRunning`. **Run Pass readiness (#137 acceptance 3, slice B):** `PassReadiness` (ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (`passReadiness`; `passReadinessWriter` = injectable read seam, nil → ad-hoc `HermesSettingsWriter` over the gate's binary, no binaryPath → stays empty); `refreshPassReadiness()` reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps `.unknown` (never block on our own read failure). `PostsModel.runPass` guards `.missingKey` BEFORE the open-piece guard: `lastError` names the provider and nothing touches disk, not even the pre-pass snapshot.
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams or (#122) `posts.runningBlindRead` — one Cancel rail ends either run) ↔ **#122: Blind Read** (bordered, beside Run — disabled with the reason in help: no open post, `!posts.openPieceHasSnapshot` ("run a Pass first"), or the engine can't take the turn; one click fires `posts.blindRead`; help otherwise names it advisory-only, records nothing) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11 `Missing <provider> key —` line under the state row carries a borderless accent **Open Settings** button (`onOpenSettings`, threaded MentorPaneView→PostsPaneView→WorkspaceView's `selection = .settings`, ArchivePaneView closure precedent), the disabled Run's help names the reason, and `.unknown` never disables (the spawn's honest failure owns that path). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). The header's session chip hides while the transient pass transcript (`passTranscriptKey`) owns the active surface, and the pane's `.task` runs `refreshPassReadiness()` before the hosted-test guard — pane re-entry re-fires it, so a key added in Settings re-enables Run Pass. `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSessioLine truncated
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
+37
View File
@@ -0,0 +1,37 @@
//
// BlindRead.swift
// Museion
//
// #122: the Blind Read — a writer-triggered, whole-document A/B judgment
// (advisory, decision #120). The comparison pair is the current document
// vs the Pass-start snapshot; the judge is a fresh session of the same
// museion profile. Verdict = pick + one line why, display-only; nothing
// is recorded (Skip's records-nothing doctrine).
//
import Foundation
/// #122: the Blind Read's prompt vocabulary — both versions inline and
/// origin-free (neutral position labels, randomized order kills position
/// bias; the judge must not know which is the rewrite), plus the app-side
/// reveal that lands only AFTER the verdict.
nonisolated enum BlindRead {
/// The judge prompt. `snapshotFirst` decides which body takes position
/// A — the caller rolls `Bool.random()` at trigger time.
static func prompt(snapshot: String, current: String, snapshotFirst: Bool) -> String {
let versionA = snapshotFirst ? snapshot : current
let versionB = snapshotFirst ? current : snapshot
return "Blind Read — two versions of one piece. Judge only the text below.\n\n"
+ "Version A:\n\(versionA)\n\nVersion B:\n\(versionB)\n\n"
+ "Pick the stronger version. Answer with exactly \"A\" or \"B\" and one line why — "
+ "no rewrites, no fixes."
}
/// The mapping the WRITER reads after the verdict — never sent to the
/// judge, so it cannot leak into the pick.
static func reveal(kind: PassKind, snapshotFirst: Bool) -> String {
snapshotFirst
? "A = \(kind.rawValue) start snapshot · B = current document"
: "A = current document · B = \(kind.rawValue) start snapshot"
}
}
+38 -10
View File
@@ -288,26 +288,54 @@ private struct PassBarView: View {
return posts.posts.first(where: { $0.id == posts.selectedPostID })?.passState.rawValue ?? "—"
}
/// Cancel while a pass runs; Run otherwise — disabled with no open
/// piece, while the engine can't take the turn, or (#137) while the
/// pass profile's provider has no key (the help names it).
/// Cancel while a pass or Blind Read runs; Run otherwise — disabled
/// with no open piece, while the engine can't take the turn, or (#137)
/// while the pass profile's provider has no key (the help names it).
/// #122: the Blind Read trigger sits beside Run — advisory-only.
@ViewBuilder
private var actions: some View {
if posts?.runningPass != nil {
if posts?.runningPass != nil || posts?.runningBlindRead == true {
Button("Cancel") {
posts?.cancelPass(mentor: model)
}
.buttonStyle(.bordered)
} else if let label = missingKeyLabel {
runPassButton
.disabled(true)
.help("\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys.")
} else {
runPassButton
.disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming)
blindReadButton
if let label = missingKeyLabel {
runPassButton
.disabled(true)
.help("\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys.")
} else {
runPassButton
.disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming)
}
}
}
/// #122: the Blind Read — one purposeful click judges the current
/// document against the Pass-start snapshot, blind. Disabled with the
/// blocking reason in help (no snapshot yet is the fresh-piece norm).
private var blindReadButton: some View {
Button("Blind Read") {
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
}
.buttonStyle(.bordered)
.disabled(blindReadBlocked != nil)
.help(
blindReadBlocked
?? "Judge the current document against the Pass-start snapshot — advisory only, nothing is recorded.",
)
}
/// #122: why the Blind Read can't fire right now (nil = it can).
private var blindReadBlocked: String? {
guard let posts, posts.session?.postID != nil else { return "Open a post to run a Blind Read." }
guard posts.openPieceHasSnapshot else { return "No Pass snapshot yet — run a Pass first." }
guard model.phase.isReady, !model.isStreaming else { return "The mentor engine can't take the turn right now." }
return nil
}
/// The Run button core — shared by the ready and missing-key branches.
private var runPassButton: some View {
Button("Run \(kind.rawValue)") {
+52 -10
View File
@@ -845,11 +845,56 @@ extension MentorSessionModel {
/// running untouched.
@discardableResult
func runPass(kind: PassKind, stub: String, pieceTitle: String) async -> TurnOutcome {
// #137 audit: no force-unwrap — the map is total over today's two
// kinds, but a future PassKind case must refuse, not trap.
guard let surface = ProfileSurface(passKind: kind) else { return .failed }
return await runOneShot(
profile: surface.profileName,
name: kind.rawValue,
prompt: stub,
pieceTitle: pieceTitle,
)
}
/// #122: run one Blind Read — a whole-document A/B judgment by a FRESH
/// session of the SAME museion profile (the chat surface: context-free
/// means no editing history, not a different judge — decision #120; the
/// Knife floor + no-flattery personas ride the profile). The verdict and
/// the app-side reveal stream into the shared transient transcript;
/// the reveal lands only on a completed turn. Never rostered, never
/// saved — advisory-only, records nothing.
@discardableResult
func runBlindRead(prompt: String, pieceTitle: String, reveal: String) async -> TurnOutcome {
let outcome = await runOneShot(
profile: ProfileSurface.chat.profileName,
name: "Blind Read",
prompt: prompt,
pieceTitle: pieceTitle,
)
// The mapping the writer reads — appended AFTER the turn so it can
// never leak to the judge. Cancelled/refused turns reveal nothing
// (a refusal still ends .ended — gate on the stopReason, runPass's
// advance posture; a 2×-document prompt makes context-length
// refusals a realistic path).
if case let .ended(stopReason) = outcome, stopReason != "refusal" {
appendRow(.text(reveal), to: Self.passTranscriptKey)
}
return outcome
}
/// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read): a
/// fresh engine on `profile`, a transient unrostered transcript, one
/// turn, teardown at its end. Same lifecycles for both riders — the
/// cancel rail (stopStreaming) and the read-only composer guard key on
/// the transient entry and need no per-rider branches. `name` ("Pass 1"
/// / "Blind Read") composes the entry label — callers can't pass a
/// title-inconsistent one.
private func runOneShot(profile: String, name: String, prompt: String, pieceTitle: String) async -> TurnOutcome {
guard phase.isReady, !isStreaming, passClient == nil, let binaryPath else { return .failed }
let label = "\(kind.rawValue) · \(pieceTitle)"
let label = "\(name) · \(pieceTitle)"
// The transient surface: a fresh transcript under the pass key and a
// pass entry that lives only for this run — never rostered, never
// saved (#129: passes are one-shot, the chat engine owns sessions).
// saved (#129: one-shot runs, the chat engine owns sessions).
transcripts[Self.passTranscriptKey] = SessionTranscript()
activeEntry = SessionEntry(
sessionId: Self.passTranscriptKey, name: label, pieceTitle: pieceTitle, createdAt: Date(),
@@ -860,10 +905,7 @@ extension MentorSessionModel {
teardownPassEngine()
firePendingRestartIfRequested()
}
// #137 audit: no force-unwrap — the map is total over today's two
// kinds, but a future PassKind case must refuse, not trap.
guard let surface = ProfileSurface(passKind: kind) else { return .failed }
let pass = ACPEngineClient(binaryPath: binaryPath, profile: surface.profileName)
let pass = ACPEngineClient(binaryPath: binaryPath, profile: profile)
passClient = pass
passClientRef = pass
// KNOWN EDGE (#137, accepted v1): a CHAT-engine crash mid-pass flips
@@ -895,21 +937,21 @@ extension MentorSessionModel {
"mcpServers": .array([]),
]))
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
appendRow(.text("Pass failed — the engine refused a session."), to: Self.passTranscriptKey)
appendRow(.text("\(label) failed — the engine refused a session."), to: Self.passTranscriptKey)
return .failed
}
passWireId = sid
} catch {
appendRow(.text("Pass failed — \(error.localizedDescription)"), to: Self.passTranscriptKey)
appendRow(.text("\(label) failed — \(error.localizedDescription)"), to: Self.passTranscriptKey)
return .failed
}
// Cancel clicked while the engine was spawning: stop before the
// prompt — the run ends cancelled, nothing streams.
if passCancelRequested {
appendRow(.text("\(kind.rawValue) cancelled."), to: Self.passTranscriptKey)
appendRow(.text("\(label) cancelled."), to: Self.passTranscriptKey)
return .cancelled
}
return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: stub, label: label)
return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: prompt, label: label)
}
/// Kill the pass engine and clear its rail — at the verdict (the defer
+26
View File
@@ -607,6 +607,32 @@ nonisolated extension PostStore {
try body.write(to: passes.appendingPathComponent(kind.snapshotFileName), atomically: true, encoding: .utf8)
}
/// #122: the Blind Read's comparison base — the newest pre-pass
/// snapshot on disk, either pass kind (a re-run overwrites in place,
/// so the newest file IS the latest Pass-start). Nil when no pass ever
/// ran over the piece. Read-only; the Blind Read records nothing.
static func latestPassSnapshot(id: String, home: URL) -> (kind: PassKind, body: String)? {
guard let dir = folder(of: id, home: home) else { return nil }
let passesDir = dir.appendingPathComponent("passes")
var newest: (kind: PassKind, date: Date)?
for kind in PassKind.allCases {
let url = passesDir.appendingPathComponent(kind.snapshotFileName)
guard let date = try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]
as? Date else { continue }
if newest == nil || date > newest!.date {
newest = (kind, date)
}
}
guard let newest else { return nil }
// ponytail: read-after-stat race is a stale base at worst — the
// snapshot only changes at a pass invocation, never mid-read.
guard let body = try? String(
contentsOf: passesDir.appendingPathComponent(newest.kind.snapshotFileName),
encoding: .utf8,
) else { return nil }
return (kind: newest.kind, body: body)
}
/// #24 (S3.1): advance `pass_state` when a pass completes. Monotonic:
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
+81 -2
View File
@@ -140,6 +140,14 @@ final class PostsModel {
/// #24 (S3.1): the pass currently streaming over the open piece —
/// one at a time; nil = idle. Drives the pass bar's Run ↔ Cancel swap.
private(set) var runningPass: PassKind?
/// #122: the Blind Read currently judging over the open piece —
/// one at a time beside runningPass; false = idle. Shares the pass
/// bar's Run ↔ Cancel swap.
private(set) var runningBlindRead = false
/// #122: does the OPEN piece have a Pass-start snapshot on disk (the
/// Blind Read's comparison base)? Refreshed with the cards at the
/// rescan tail and open transitions.
private(set) var openPieceHasSnapshot = false
/// #23 (M2, slice 3): the OPEN piece's stored fix cards
/// (`<piece>/cards/*.json`, newest-first) — what any MCP client
/// submitted; nil session (draft/guest/nothing) shows none.
@@ -818,7 +826,7 @@ extension PostsModel {
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
}
@@ -891,12 +899,78 @@ extension PostsModel {
/// #24 (S3.1): the pass bar's Cancel — the existing session/cancel
/// rail stops the agent; nothing advances (runPass reads .cancelled).
/// #122: the Blind Read shares the rail — Cancel ends either run.
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil else { return }
guard runningPass != nil || runningBlindRead else { return }
mentor.stopStreaming()
}
}
// MARK: Blind Read (#122)
extension PostsModel {
/// #122: run one Blind Read over the OPEN piece — the current document
/// vs the newest Pass-start snapshot, judged blind by a fresh session
/// of the museion profile. Advisory-only (decision #120): no Pass State
/// advance, no cards, no Learnings — the verdict and the reveal live in
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a Blind Read."
return
}
guard flushOrAbort(id) else { return }
guard let base = PostStore.latestPassSnapshot(id: id, home: home) else {
lastError = "No Pass snapshot yet — run a Pass first."
return
}
let current = session.text
guard current != base.body else {
lastError = "No edits since the Pass started — the Blind Read judges the current document against the Pass-start snapshot."
return
}
// House posture (runPass's success path): the run is firing — a
// stale guard refusal no longer owns the error strip.
lastError = nil
runningBlindRead = true
defer { runningBlindRead = false }
// Randomized order kills position bias (#120's flagged default);
// the reveal names the mapping only after the verdict.
let snapshotFirst = Bool.random()
_ = await mentor.runBlindRead(
prompt: BlindRead.prompt(snapshot: base.body, current: current, snapshotFirst: snapshotFirst),
pieceTitle: title(of: id),
reveal: BlindRead.reveal(kind: base.kind, snapshotFirst: snapshotFirst),
)
// Advisory-only: nothing to advance or record — the outcome row in
// the transient transcript IS the deliverable.
}
}
// MARK: Stored fix cards (#23, M2 slice 3)
extension PostsModel {
@@ -906,9 +980,12 @@ extension PostsModel {
/// nil-session rule clears: draft, external guest, held guard ask,
/// nothing open → []. Called at the rescan tail and the open
/// transitions — the piece-roots watcher already fires on cards/ writes.
/// #122: the same pass also derives `openPieceHasSnapshot` (the Blind
/// Read's base) — one detached read of the open piece's disk facts.
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
openPieceCards = []
openPieceHasSnapshot = false
return
}
// Plain disk reads re-run on every watcher burst (typing retriggers
@@ -917,9 +994,11 @@ extension PostsModel {
// piece switch.
Task.detached { [weak self] in
let cards = FixCardStore.scan(pieceURL: folder)
let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil
await MainActor.run { [weak self] in
guard let self, session?.postID == id else { return }
openPieceCards = cards
openPieceHasSnapshot = hasSnapshot
}
}
}
+1
View File
@@ -89,6 +89,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
elif [[ "$method" == "session/prompt" ]]; then
print -r -- "$line" >> "${0:h}/\(name)-prompt-log" # every prompt's wire line — tests pin what the engine was asked (#122)
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
if [[ "$mode" == "refuseOnPrompt" ]]; then
+2 -1
View File
@@ -18,7 +18,7 @@ Owned by the root AGENTS.md contract.
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
@@ -27,6 +27,7 @@ Owned by the root AGENTS.md contract.
- `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. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). **#6 (S3.4) wiring pin** (`DeslopLintWiringTests`, suite member at file tail — the #31/#134 vacuous-filter lesson): a pass invocation on a sloppy piece seeds emitter `lint` cards under `<piece>/cards/` AND the `stats_*` keys — stats capture and lint both fired at the one invocation seam.
- `BlindReadTests.swift` (#122 — scenario headers at file top, `@Suite` so suite-filters run it) — the Blind Read pins: `BlindRead.prompt` (both bodies inline under "Version A/B" in the given order, flip swaps, NO origin words — snapshot/current/original/revised never appear, the pick+one-line ask) and `reveal` (exact mapping per kind+flip); `PostStore.latestPassSnapshot` (newest mtime wins across pass-1/pass-2 — decisive +60 s attribute set, the write-order race is real; none → nil); the advisory run over `makeBlindRig` (makeModelHome + `makeFakeACP` + the fake's DIR — makePassRig doesn't expose it): the mentor rail (fresh `acp -p museion` spawn counted in the spawn log — the resident engine is the only other `museion` spawn, pass profiles never; label row "Blind Read · <title>"; reveal lands ONLY on `.ended`, `cancelOnPrompt` leaves none; roster never grows) and the model orchestration (`blindRead`: prompt-log carries both bodies and no path; `pass_state` stays First Draft — records nothing; `runningBlindRead` clears; no-snapshot → `lastError` "run a Pass first" with nothing spawned beyond the resident engine; snapshot == current → "No edits since" refusal). **Finish-audit pins:** a REFUSED read (`refuseOnPrompt`) ends `.ended(stopReason: "refusal")` and reveals nothing (the gate is the stopReason, never the outcome — a refusal still ends .ended; flip-verified), and a held read (`hangOnPrompt`) owns the rail — a concurrent pass refuses "already running", `cancelPass` ends the turn with no reveal and `pass_state` untouched.
- `DeslopLintTests.swift` (#6, S3.4 — scenario header at file top, all tests `@Suite` members) — the native deslop lint pins: the exact finding set AND rank order over a known sloppy draft (em-dash first, Tier 1 by first-match position, Tier 2 after; exact owner-facing problem/diagnostic copy, mixed-case anchor preservation `Utilize` with its exact-substring occurrence, mechanical lane for the mapped `utilize`→`use`, demonstration for `delve`, counts inside the problem strings, NO finding for within-allowance `furthermore`), whole-word boundaries (`delved`/`harnessed`/`showcased` never fire their stems), em-dash at budget 4 → silent (0 too), the empty AND whitespace-phrase trust-boundary pin (#6 audit: the `— —` body is space-phrase bait — a plain body passes vacuously; submit's validation trims, so a whitespace phrase would kill the whole submit), the config story (Home override wins when it exists AND decodes, malformed override falls back to the bundled default, `home: nil` → bundled, `bundledConfig()` decodes the two tiers + budget 4 + the mapped replacements), and the store-level emit loop over `PostStore.writeNew` (cards land emitter `lint`/open/pass 1/valid anchors, re-emit dedups against OPEN cards, a `.skipped` close re-emits its still-present finding).
- `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
- `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home).
+306
View File
@@ -0,0 +1,306 @@
//
// BlindReadTests.swift
// MuseionTests
//
// #122: the Blind Read — a writer-triggered, whole-document A/B judgment
// (advisory). From user story #122 / decision #120.
//
// ## Scenario: the blind judge prompt
// Given a Pass-start snapshot and the current document
// When the writer triggers a Blind Read
// Then both versions travel inline in one prompt — origin-free labels,
// randomized order — so the judge cannot tell which is which.
//
// ## Scenario: snapshot selection
// Given a piece whose Passes left snapshots in `<piece>/passes/`
// When a Blind Read triggers
// Then the newest snapshot (either pass kind) is the comparison base;
// with none, the read refuses honestly.
//
// ## Scenario: the advisory run
// Given an open piece with a snapshot and edits since
// When the writer clicks Blind Read
// Then a fresh one-shot engine on the museion profile judges, the verdict
// and a reveal row land in the transient transcript, the roster stays
// untouched, and nothing on disk changes.
//
import Foundation
@testable import Museion
import Testing
@MainActor
struct BlindReadTests {
// MARK: Scenario 1 — the blind judge prompt
@Test func `prompt carries both bodies inline in the given order`() {
let prompt = BlindRead.prompt(
snapshot: "The snapshot prose.",
current: "The current prose.",
snapshotFirst: true,
)
#expect(prompt.contains("Version A:\nThe snapshot prose."))
#expect(prompt.contains("Version B:\nThe current prose."))
}
@Test func `prompt flip swaps which version leads`() {
let prompt = BlindRead.prompt(
snapshot: "The snapshot prose.",
current: "The current prose.",
snapshotFirst: false,
)
#expect(prompt.contains("Version A:\nThe current prose."))
#expect(prompt.contains("Version B:\nThe snapshot prose."))
}
@Test func `prompt never names an origin or a path`() {
let prompt = BlindRead.prompt(
snapshot: "One body.",
current: "Another body.",
snapshotFirst: true,
)
// Blindness: the judge must not learn which version is the
// rewrite — no origin words, no file paths.
#expect(!prompt.lowercased().contains("snapshot"))
#expect(!prompt.lowercased().contains("current"))
#expect(!prompt.lowercased().contains("original"))
#expect(!prompt.lowercased().contains("revised"))
}
@Test func `prompt asks for a pick and one line why`() {
let prompt = BlindRead.prompt(snapshot: "One body.", current: "Another body.", snapshotFirst: true)
#expect(prompt.contains(#""A" or "B""#))
#expect(prompt.lowercased().contains("one line"))
}
@Test func `reveal names the mapping per kind and flip`() {
#expect(
BlindRead.reveal(kind: .pass1, snapshotFirst: true)
== "A = Pass 1 start snapshot · B = current document",
)
#expect(
BlindRead.reveal(kind: .pass2, snapshotFirst: false)
== "A = current document · B = Pass 2 start snapshot",
)
}
// MARK: Scenario 2 — snapshot selection
@Test func `latest snapshot is the newest on disk either kind`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Judged\n\nThe base text.", home: home)
// Only pass-1's snapshot exists for the first read.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "The pass-one start.", home: home)
#expect(PostStore.latestPassSnapshot(id: post.id, home: home)?.body == "The pass-one start.")
// pass-2's snapshot goes decisively newer on disk — it becomes the base.
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "The pass-two start.", home: home)
let piece = try #require(PostStore.folder(of: post.id, home: home))
let pass2 = piece.appendingPathComponent("passes/pass-2.md")
try FileManager.default.setAttributes(
[.modificationDate: Date().addingTimeInterval(60)],
ofItemAtPath: pass2.path,
)
let latest = PostStore.latestPassSnapshot(id: post.id, home: home)
#expect(latest?.kind == .pass2)
#expect(latest?.body == "The pass-two start.")
}
// MARK: Scenario 3 — the advisory run (mentor rail)
/// makePassRig + the fake's directory (the spawn/prompt logs live
/// beside the fake — makePassRig doesn't expose it).
// swiftlint:disable:next large_tuple
private func makeBlindRig(mode: String = "full") throws -> (model: PostsModel, home: URL, mentor: MentorSessionModel, fakeDir: String) {
let (model, home) = try makeModelHome()
let dir = acpTempDir("blindread")
let fake = makeFakeACP(at: dir, mode: mode)
let mentor = MentorSessionModel(binaryPath: fake)
return (model, home, mentor, dir)
}
/// Open a piece with a planted snapshot and a differing buffer — the
/// blind read's given state. Returns the piece id.
@discardableResult
private func openJudgedPiece(on model: PostsModel, home: URL, snapshot: String, current: String) async throws -> String {
let post = try PostStore.writeNew(body: current, home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: snapshot, home: home)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
return post.id
}
// swiftlint:disable:next large_tuple
private func spawnLog(_ rig: (model: PostsModel, home: URL, mentor: MentorSessionModel, fakeDir: String)) throws -> String {
try String(contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"), encoding: .utf8)
}
@Test func `blind read judges on a fresh chat-profile engine never rostered`() async throws {
let rig = try makeBlindRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "# Judged\n\nNewer prose.")
let outcome = await rig.mentor.runBlindRead(
prompt: BlindRead.prompt(snapshot: "Older prose.", current: "# Judged\n\nNewer prose.", snapshotFirst: true),
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .ended(stopReason: "end_turn"))
// The verdict + reveal render in the transient transcript.
#expect(textRows(of: rig.mentor).contains("Blind Read · Judged"))
#expect(textRows(of: rig.mentor).contains("A = Pass 1 start snapshot · B = current document"))
// The roster never grew — records nothing (#129 posture).
#expect(rig.mentor.roster.count == rosterBefore)
// A fresh CHAT-profile engine judged (the resident engine is the
// only other `museion` spawn; pass profiles never ran).
let spawns = try spawnLog(rig)
#expect(spawns.components(separatedBy: "\n").filter { $0.contains("acp -p museion") }.count == 2)
#expect(!containsPassProfile(spawns))
}
/// Non-`museion` (pass-profile) spawns — negation helper.
private func containsPassProfile(_ spawns: String) -> Bool {
spawns.components(separatedBy: "\n").contains { $0.contains("museion-pass") }
}
@Test func `cancelled blind read leaves no reveal`() async throws {
let rig = try makeBlindRig(mode: "cancelOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let outcome = await rig.mentor.runBlindRead(
prompt: "prompt",
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .cancelled)
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
}
// MARK: Audit pins (finish-audit: the refusal gate + the Cancel rail)
@Test func `refused blind read reveals nothing`() async throws {
let rig = try makeBlindRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
// A refusal still ENDS .ended — the reveal must gate on the
// stopReason (runPass's advance posture), never on the outcome
// alone. Realistic path: a 2×-document prompt can refuse on length.
let outcome = await rig.mentor.runBlindRead(
prompt: "prompt",
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .ended(stopReason: "refusal"))
#expect(textRows(of: rig.mentor).contains { $0.contains("(refused the prompt)") })
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
}
@Test func `cancel ends a held blind read and the rail is exclusive`() async throws {
let rig = try makeBlindRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let run = Task { await rig.model.blindRead(home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningBlindRead)
// Mutual exclusion — a pass refuses while the read owns the rail.
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("already running") == true)
// The pass bar's Cancel rail ends the held read — no reveal,
// nothing on disk.
rig.model.cancelPass(mentor: rig.mentor)
for _ in 0 ..< 250 where rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(!rig.model.runningBlindRead)
rig.mentor.shutdown() // frees the held turn if the rail regressed — bounds the await
_ = await run.value
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
}
// MARK: Scenario 3 (model half) — the advisory orchestration
@Test func `blind read sends both bodies blind and records nothing`() async throws {
let rig = try makeBlindRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(
on: rig.model, home: rig.home,
snapshot: "MARKER-the-older-text", current: "# Judged\n\nMARKER-the-newer-text",
)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
// The prompt carried BOTH bodies inline — and no path: the judge
// cannot learn which file is which.
let promptLog = try String(
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-prompt-log"),
encoding: .utf8,
)
#expect(promptLog.contains("MARKER-the-older-text"))
#expect(promptLog.contains("MARKER-the-newer-text"))
#expect(!promptLog.contains(".md"))
// The reveal landed below the verdict.
#expect(textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
// Records nothing: Pass State untouched, rail idle, no error.
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(rig.model.runningBlindRead == false)
#expect(rig.model.lastError == nil)
}
@Test func `blind read refuses without a snapshot or without edits`() async throws {
let rig = try makeBlindRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", home: rig.home)
rig.model.select(post.id, home: rig.home)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// No pass ever ran — refuse, spawn nothing beyond the resident engine.
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("run a Pass") == true)
#expect(try spawnLog(rig).components(separatedBy: "\n").filter { $0.contains("acp -p museion") }.count == 1)
// Snapshot exists but the document is unchanged since — a vacuous
// read refuses honestly.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Fresh\n\nNo pass yet.", home: rig.home)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("No edits") == true)
}
/// A throwaway Home (PostLibraryTests' temp-dir pattern).
private func storeHome() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("blindread-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ Owned by the root AGENTS.md contract.
- ADRs live in `docs/adr/`, sequentially numbered `NNNNN-slug.md` (currently `0001`–`0014`: stack, license, forge/CI, content layout, learnings home, fix-card transport, state ownership, tools host, sandbox posture, prose editor substrate, apex HTML reading pipeline, projects/archive layout + type-as-frontmatter, outliner block surface, one Hermes profile per LLM surface).
- ADR format follows the domain-modeling skill's `ADR-FORMAT.md`: short title + 1–3 sentences; optional Considered Options / Consequences only when they earn their place.
- `docs/agents/` holds the engineering-skills config (issue tracker, triage labels, domain-docs consumer rules) written by `setup-matt-pocock-skills` — edit directly, no child doc needed.
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7, #11, and #123 verification artifacts); card shape follows CONTEXT.md (lane and emitter fields included), anchors follow ADR-0006.
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7, #11, and #123 verification artifacts); card shape follows GLOSSARY.md (lane and emitter fields included), anchors follow ADR-0006.
## Work Guidance
@@ -0,0 +1,68 @@
# Blind Read: writer-triggered whole-document A/B judgment (advisory) (#122)
> **Date:** 2026-10-30
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/122 (decision #120, rides #24's pass machinery)
## Goal
Implement Gitea #122: the writer purposefully triggers a whole-document A/B judgment — current document vs the Pass-start snapshot — performed by a fresh session of the same museion profile. Advisory-only: pick + one-line reason, display-only, records nothing (Skip's doctrine); the writer stays judge of record. Glossary term lands with the issue.
## What Was Done
- `Museion/BlindRead.swift` (new) — the judge prompt (both bodies INLINE under neutral "Version A/B" position labels, order randomized per trigger, origin words never appear) + the writer-side reveal line
- `PostStore.latestPassSnapshot(id:home:)` — newest `passes/pass-N.md` by mtime, either pass kind; read-only
- `MentorSessionModel` — `runPass`'s spawn/session/new/teardown block extracted to one private `runOneShot(profile:name:prompt:pieceTitle:)` rail; `runBlindRead` rides it on the CHAT profile (`museion`) — fresh session, verdict streams into the transient unrostered transcript, reveal appends only on `.ended` with stopReason ≠ "refusal"
- `PostsModel.blindRead(home:mentor:)` — guard matrix mirrors runPass (one rail, mutual exclusion with `runningPass`); `runningBlindRead` + `openPieceHasSnapshot` state, the latter derived in `refreshCards`
- `MentorPaneView` — "Blind Read" button beside Run Pass in the pass bar; one Cancel rail ends either run
- `GLOSSARY.md` — "Blind Read" term (avoid: A/B test, vote, score)
- `BlindReadTests.swift` — 12 pins: prompt blindness + flip, reveal mapping, snapshot selection, chat-profile spawn (prompt/spawn logs), roster untouched, pass_state unchanged, no-snapshot/no-edits refusals, refusal-no-reveal (flip-verified), held-run cancel + rail exclusivity
- Fake ACP gains a `prompt-log` knob (every session/prompt wire line) — the what-the-engine-was-asked observable
- DOX: both AGENTS.md files updated; stale `CONTEXT.md` references corrected to `GLOSSARY.md` (root index + docs)
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| "Unlabeled" = neutral A/B position labels + `Bool.random()` order + post-verdict reveal | #120's flagged default; a pick must reference something — position labels kill origin bias, randomization kills position bias; the reveal lands after the turn so the judge never sees it |
| Newest-mtime snapshot wins when both kinds exist | "The Pass-start snapshot" in the singular = the latest pass run's start; a re-run overwrites in place, so newest file IS the latest Pass-start |
| One-shot engine on the chat profile (`museion`) | #120: context-free = fresh session, NOT a different judge; no new profile. One-shot avoids roster pollution and reuses the #137 rail — Cancel, read-only composer, and teardown all come free |
| "No edits since" refusal (beyond spec) | Judging an identical pair is vacuous; honest refusal beats a coin-flip verdict. Flagged to the user |
| No chat-provider-key pre-check | The resident chat engine proves the profile works; a fresh spawn's honest failure row owns the error path (#137's .unknown posture) |
| View-side disabled-with-help duplicating model guards | The existing Run Pass precedent — view prevents, model refuses honestly |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Reveal row landed on REFUSED turns | `turnCore` maps refusals to `.ended(stopReason: "refusal")`, so `if case .ended` wasn't enough — and a 2×-document prompt makes length refusals realistic | Gate on `stopReason != "refusal"` (runPass's advance posture); pinned + flip-verified (finish-audit, 2 reviewers converged) |
| "Pass failed" copy on Blind Read spawn failures | The shared rail's failure rows hardcoded "Pass" | `runOneShot` takes `name`, composes the label, failure rows speak `\(label) failed` — callers can't pass a title-inconsistent label |
| Snapshot-order test flaked on write order | Both snapshots written ms apart — pass-2 was already newest at the first assert (APFS ns mtimes) | Write pass-1, assert, THEN write pass-2 with a decisive +60 s mtime |
| `@Suite` attribute vanished mid-session | Lost in a patch cycle; suite-filters still ran (implicit naming) but the DOX claimed it | Restored; learning #134 says suite-name matching is exactly where vacuous passes bite |
| Stale `CONTEXT.md` in root AGENTS.md index | The a1d1cd3 rename to GLOSSARY.md never updated the index/docs | Corrected in root AGENTS.md (2 sites) + docs/AGENTS.md |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/BlindRead.swift` (new) | Judge prompt + reveal vocabulary |
| `Museion/PostStore.swift` | `latestPassSnapshot` reader |
| `Museion/MentorSessionModel.swift` | `runOneShot` extraction, `runBlindRead`, parameterized failure copy, refusal gate |
| `Museion/PostsModel.swift` | `blindRead`, `runningBlindRead`, `openPieceHasSnapshot`, refresh seam, guard mutual exclusion |
| `Museion/MentorPaneView.swift` | Blind Read button + shared Cancel rail |
| `MuseionTests/BlindReadTests.swift` (new) | 12 pins incl. two audit pins |
| `MuseionTests/ACPClientTests.swift` | Fake gains the prompt-log knob |
| `GLOSSARY.md` | "Blind Read" term |
| `AGENTS.md`, `docs/AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass + CONTEXT.md→GLOSSARY.md corrections |
## Open Items & Next Steps
- [ ] Parked (security LOW-1): no size ceiling on the 2× inline prompt — the editor is unusable long before the prompt build matters; if the app ever grows a doc-size cap it belongs at the editor/save boundary, not this rail
- [ ] Deferred read of #124 Cancel-visibility: blind read reuses the pass posture (`runningBlindRead` set before the await, sync guards) — revisit only if a spawn-window cancel escape is ever reported
- [ ] The parked stern-coach prompt stance (security reviewer's note): personas ride the profile per #120 — no action unless verdicts read too soft in dogfooding
---
**Verification (finish-up):** full xcodebuild suite **500 passed / 0 failed** (unit + UI, counted from the log per learning #134); swiftformat clean; swiftlint zero new violations vs the HEAD baseline; GitNexus re-indexed (5,338 nodes); detect-changes scoped RunPass + RunBlindRead flows only.
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-10-30 | issue | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | #122 Blind Read: advisory whole-document A/B on a fresh museion session, randomized unlabeled pair, reveal after verdict; 500 tests |
| 2026-10-30 | issue | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | #6 native deslop lint: banned-vocab tiers + em-dash budget as data, emitter-lint cards at pass invocation; audit fixes — 489 tests |
| 2026-10-30 | issue | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) | #1 prompt-end constraints: ACP audit, draft-first-rules-last persona pin, layout factsheet, real-run verify |
| 2026-10-28 | issue | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | Pass engines on-demand per profile, transient transcripts, chat restart deferred mid-turn, missing-key Run Pass — 2 race fixes |