diff --git a/AGENTS.md b/AGENTS.md index 8c9e2d0..9302c4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6169 symbols, 26678 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** (6294 symbols, 27487 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). @@ -176,6 +176,7 @@ This project is indexed by GitNexus as **museion** (6169 symbols, 26678 relation ### Testing +- A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162) - Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) - Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) - Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33) @@ -200,14 +201,14 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| -| 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) | -| 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_log.md) | -| 2026-11-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](docs/devlog/20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) | -| 2026-11-04 | [20261104-issue155-shared-conversation-surface-editorial-voice_log.md](docs/devlog/20261104-issue155-shared-conversation-surface-editorial-voice_log.md) | -| 2026-11-03 | [20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md](docs/devlog/20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md) | -| 2026-11-03 | [20261103-issue58-voice-payload-landed_log.md](docs/devlog/20261103-issue58-voice-payload-landed_log.md) | -| 2026-11-03 | [20261103-issue147-app-target-lint-clean-five-error-spots_log.md](docs/devlog/20261103-issue147-app-target-lint-clean-five-error-spots_log.md) | -| 2026-11-03 | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](docs/devlog/20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | -| 2026-11-03 | [20261103-issue144-library-search-across-titles-and-bodies_log.md](docs/devlog/20261103-issue144-library-search-across-titles-and-bodies_log.md) | -| 2026-11-03 | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](docs/devlog/20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | +| 2026-11-04 | [20261104-issue162-cold-turkey-writing-lock-integration_log.md](20261104-issue162-cold-turkey-writing-lock-integration_log.md) | +| 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](20261104-issue161-cold-turkey-goal-engine_log.md) | +| 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](20261104-issue160-cold-turkey-contract-render_log.md) | +| 2026-11-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) | +| 2026-11-04 | [20261104-issue155-shared-conversation-surface-editorial-voice_log.md](20261104-issue155-shared-conversation-surface-editorial-voice_log.md) | +| 2026-11-03 | [20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md](20261103-issue151-gateless-launch-async-engine-check-rail-pill-auto-fire_log.md) | +| 2026-11-03 | [20261103-issue58-voice-payload-landed_log.md](20261103-issue58-voice-payload-landed_log.md) | +| 2026-11-03 | [20261103-issue147-app-target-lint-clean-five-error-spots_log.md](20261103-issue147-app-target-lint-clean-five-error-spots_log.md) | +| 2026-11-03 | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | +| 2026-11-03 | [20261103-issue144-library-search-across-titles-and-bodies_log.md](20261103-issue144-library-search-across-titles-and-bodies_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index b5c8d90..4d0f332 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Changed +- **cold-turkey:** The writing lock (#162, wayfinder map #158 — Build S2; wires #161's goal engine + #160's contract into the app) — Cold Turkey is live: armed from a quiet dot in focus mode's bottom-right corner (hover-labeled) or View ▸ Start Cold Turkey…, the arm-bar carries a chip that blends into the focus ground (ground color, faintest hairline, no shadow — the bare seat let document text show through) with minutes|words selector, ± steppers AND a directly typeable value (parsed and clamped at every read; what you type is what arms — 1…1000 words / 1…60 min, defaults 250/5); Start enters the macOS app-kiosk per the #159 factsheet (7-option presentation combo + fullscreen, the window restored on completion) and the readout follows — numerals + 2px hairline, terracotta inside the last 20%, on the same blending chip. While the block holds: ⌥⌘F/reading/new-buffer paths refused (the open Piece stays the counted one), library + mentor hover zones suppressed (editor-only), ⌘W/⌃⌘F/⌘N swallowed by a key-code-matched monitor (charactersIgnoringModifiers is layout- and Caps-Lock-blind while AppKit menus match the physical key — the audit-caught hole; no .closeItem placement exists and SwiftUI owns the window delegate), and ⌘Q asks once (#163's ruling): "Walk away from the block?" — Walk Away quits cleanly, Keep Writing holds. Typing is never interrupted by the unlock: lock ⇒ focus freezes the view branch under the editor, chrome mounts as overlays only, and the fullscreen round trip preserves the first responder. Completion returns quietly to focus with a fading mono note ("● 250 words · 14:02"). Nothing persists — the block dies with the session. Glossary term landed; +19 tests incl. flip-verified refusal-key, parse-fallback, and canArm-mirror pins; finish-audit fanout (3 reviewers) landed the key-match fix, a ticker-race test seam, chip dedup, and window-capture-on-exit. Suite 620 (issue #162) + - **cold-turkey:** Pure goal engine (#161, wayfinder map #158 — Build S1 of the Cold Turkey writing lock) — `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun`, the armed block: `update(text:)` takes whole-document text and `netNewWords` falls out of the delta (deleting costs — net, not gross; a 2000-word paste counts), and `now` is injected into every call, so the countdown cannot pause by construction. The minutes deadline is arm+minutes (inclusive boundary), `isMet` is live truth, unlatched (deleting below target un-mets; the lock completes on the first true tick), `progress(now:)` is the clamped 0…1 fraction the readout hairline rides, and word counting goes through the new internal `DraftStats.words(in:)` — net-words and first-draft stats share one tokenizer and can never drift ("writer's" is two words, headings are body text, frontmatter never reaches the editor body). Finish-audit fanout (3 reviewers): the `Int()` conversion trap in `secondsRemaining` fixed at the seam (isFinite guard + `Double(Int.max).nextDown` cap — the naive `Double(Int.max)` cap is itself off-by-one at 2^63 and still traps; flip-verified pin), two unpinnable `> 0` guards in `progress` deleted (degenerate zero targets already fall out to 1 through the Double math), `baselineWords` narrowed to `let`; the S2 throttle note landed on #162 (never feed the word count per keystroke). Suite 602 (issue #161) - **mentor:** Editorial pane chrome (#156, wayfinder map #153 — the #154 contract's build slice 2; the map closes here) — MentorPaneView's chrome now speaks the same two-color editorial voice the transcript gained in #155. The header drops the icon and "Mentor Session" headline for a serif-15/600 "Mentor", and the ready state becomes the semantic green dot (`DesignTokens.readyGreen` — the palette's single sanctioned exception) + lowercase mono `ready`; the base engine version moves to the tooltip (the rare gate/handshake drift note stays visible in orange). The segmented Pass 1 | Pass 2 | Chat picker is gone — the pass bar always carries and owns a compact text-tab selector (mono-10 uppercase tracked, 2pt accent underline on the active tab) above a `PASS N · STATE` status line, the cost line, and the actions as the contract's `MonoButton` (accent solid Run/Restart, surface+border Blind Read, accent-outline Cancel — danger is terracotta, no second hue). The fix-cards row is the ruled plain mono link (no card, no hairline of its own), and the crash / missing-engine / starting states render as quiet state-cards (terracotta tri, serif head, sans-muted body, mini-spinner mono interim). Finish-audit pass: security clean; the orphaned pass-surface MARK, the stale `hermes ` doc comment, and a phantom-border comment are fixed; two advisories parked in the devlog (pass-selector state resets on a phase dip — filed as swift-wiki gotcha #28; solid-button contrast ≈ 3.85:1, inherited from #155, to fix pane-wide if flagged). Suite 592 (issue #156) diff --git a/GLOSSARY.md b/GLOSSARY.md index 658ebb5..1c982d4 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -61,6 +61,10 @@ _Avoid_: trash, cold storage The rendered presentation of a Piece's text: view-and-select, never editing. Toggled explicitly; clicking the text drops into editing at that spot. Distinct from a Pass, which critiques rather than presents. _Avoid_: preview, read mode +**Cold Turkey**: +A self-imposed writing lock nested inside Focus: armed from a quiet corner dot (or View ▸ Start Cold Turkey…), enforced by the macOS app-kiosk (fullscreen, no ⌘Tab/⌘Q/⌘W), editor-only, one goal — net new words or minutes. Completion returns quietly to Focus; the block dies with the session, nothing persists. Internal Swift state: `writingLock`. +_Avoid_: blocker, sprint, pomodoro, focus timer + ### The Mentor Loop **Mentor**: diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index a07e128..9c47d8b 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Local Contracts -- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped state; #151 gateless — `ContentView.task` fires `startLaunchCheck`, the async engine check + auto-fire chain). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires). +- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped state; #151 gateless — `ContentView.task` fires `startLaunchCheck`, the async engine check + auto-fire chain). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#162 (Cold Turkey S2):** `WritingLockAppDelegate` rides `@NSApplicationDelegateAdaptor` (quit refused while a block holds); the View group gains Start Cold Turkey… (focus-gated, disabled on outline/no piece — the #160 second path behind the dot) and the lock refusals — Toggle Focus Mode, Toggle Reading Mode, and every File entry that would swap the editor surface (New Post/Outline/Project, Open…, Import…) disable while locked; ⌘W is swallowed by the kiosk's key monitor (WritingLockState.swift). **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires). - `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project). - Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`. - App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file. @@ -21,18 +21,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Workspace shell (M1, #17 + #18 / S1.1) - `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette, with the single semantic exception `readyGreen` (#153/#156: the mentor header's ready dot; a meaning, never a style color). -- `WorkspaceView.swift` — the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card). **#155 (map #153, contract `ref/prototypes/wf154-mentor-pane-prototype.html`):** the surface wears the editorial chat voice — `speaker(of:)` (static, test-pinned) maps the model's `"Mentor: "`/`"You: "` prefixes onto agent serif-15/1.6 prose (markdown at flush, verbatim while streaming — Vivarium #97; **interpreted markdown opens http(s) ONLY — `linkVerdict` gates the surface's `openURL` environment, every other scheme discards: engine prose echoes imported content, #34 gate-at-sink doctrine**) / right-aligned terracotta-wash-14% capsule (radius 12/12/2/12, 85% of live column width — `onGeometryChange`, both panes' columns) / mono-11 status box on the fg-wash-6% card (refusals, pass kick-off labels, reveals — the system voice); ThinkingBlock port (mono-11 toggle, serif-13 muted on the wash card, open while live, collapsed when flushed, per-instance expansion state); research-note cards inherit the wash family; the composer restyles per contract — surface-fill input, ONE accent Send flipping to terracotta-outlined Stop (default-action shortcut rides Send only), floating `.thinMaterial` liveness chip above the composer (streaming only, hit-through), plain Return sends / Shift+Return breaks the line (Vivarium owner-report fix; `send()` gained the empty-trim guard), and the debug toggle seats at the composer's trailing edge via `debugBinding: Binding?` (nil = no toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). -- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). +- `WorkspaceView.swift` — the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card). **#155 (map #153, contract `ref/prototypes/wf154-mentor-pane-prototype.html`):** the surface wears the editorial chat voice — `speaker(of:)` (static, test-pinned) maps the model's `"Mentor: "`/`"You: "` prefixes onto agent serif-15/1.6 prose (markdown at flush, verbatim while streaming — Vivarium #97; **interpreted markdown opens http(s) ONLY — `linkVerdict` gates the surface's `openURL` environment, every other scheme discards: engine prose echoes imported content, #34 gate-at-sink doctrine**) / right-aligned terracotta-wash-14% capsule (radius 12/12/2/12, 85% of live column width — `onGeometryChange`, both panes' columns) / mono-11 status box on the fg-wash-6% card (refusals, pass kick-off labels, reveals — the system voice); ThinkingBlock port (mono-11 toggle, serif-13 muted on the wash card, open while live, collapsed when flushed, per-instance expansion state); research-note cards inherit the wash family; the composer restyles per contract — surface-fill input, ONE accent Send flipping to terracotta-outlined Stop (default-action shortcut rides Send only), floating `.thinMaterial` liveness chip above the composer (streaming only, hit-through), plain Return sends / Shift+Return breaks the line (Vivarium owner-report fix; `send()` gained the empty-trim guard), and the debug toggle seats at the composer's trailing edge via `debugBinding: Binding?` (nil = no toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#162:** the window drop destination refuses while a Cold Turkey block holds (the open Piece stays the counted one), and the left-edge focus overlay is suppressed for the same window (hover reveal dies with the lock, PostsPaneView's mentor overlay alike). **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). +- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). **#162:** the focused branch mounts the Cold Turkey chrome as overlays (`ColdTurkeySeat` bottom-center, `ColdTurkeyDot` bottom-right) and suppresses the mentor hover reveal while a block holds; leaving focus drops a stale arm-bar (`onDisappear`). - `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling). - `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. **#33 (S6.1):** `stampMicropubURL(id:url:home:)` — in-place `micropub_url` stamp through `stampingFrontmatter` (frontmatter-only: body + foreign keys byte-identical, so the open session's readBody echo check never fires); vanished piece throws. **#141:** same-file extension — the illustration ingest write side: `ingestImage(from:pieceFolder:)` copies (never moves) a dropped image into the piece's `assets/` and returns the ref destination; type gate = #34's `Micropub.mimeType` set (PNG/JPEG/GIF/WebP/SVG — nothing enters assets/ that can't ship, `IngestError.notPublishable`), a Finder folder with an image extension refuses (`isFolder`), a symlinked/file-shaped `assets/` refuses (`hostileAssets` — never write through it, the rail would refuse the send anyway); base name through the shared `slug` (parser-clean: the #34 regex never matches space-bearing destinations, so ref and file agree at ingest), collisions suffix `-2`/`-3` within `assets/`; `illustrationRef(_:)` is the one `![alt](assets/…)` builder the drop surface and tests share. - `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`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). **#161:** internal `words(in:)` (`tokens(in:).count`) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift. - `WritingGoal.swift` — #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock): `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun` (the armed block: goal + `armedAt` + baseline/current word counts via `DraftStats.words`). `update(text:)` takes whole-document text — typing/deleting/pasting/undo all land the same way, `netNewWords` falls out of the delta (deleting costs; a big paste counts). `now` is INJECTED (`isMet(now:)`, `secondsRemaining(now:)`, `progress(now:)` 0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary; `isMet` is live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2's `WritingLockState` owns the ticker and calls this. +- `WritingLockState.swift` — #162 (Cold Turkey S2, map #158) the writing lock machine + kiosk: `WritingLockState` (@Observable, app-scoped as `gate.writingLock`; `static weak active` is the app-delegate's quit-refusal handle) — `start(goal:body:at:)` arms (refuses a second block while locked), a 1 s ticker + the per-keystroke `feed(text:)` (ProseTextView.onTextChange, both editor modes) drive `WritingGoalRun`, `tick(at:)` completes on the first met tick (internal seam — tests inject the decisive moments), `complete()` exits the kiosk and leaves `completionNote` fading ~6 s. `WritingLockKiosk` — the #159 recipe verbatim (6-option combo + `.disableScreenCornerInteractions`), enter = activate→options→toggle (returns whether WE toggled fullscreen — an already-fullscreen window is entered in place; exit replays only what entry toggled), exit = options-clear-FIRST then toggle (never churn mid-transition); ⌘W + ⌃⌘F + ⌘N refusals = a local keyDown monitor (matched by KEY CODE with the exact modifier set plus a lowercased character net — audit 2026-11-04: charactersIgnoringModifiers is layout- and Caps-Lock-dependent, a Cyrillic/caps ⌘W slipped past while the stock Close still fired; ⌘N covers the stock New Window item SwiftUI owns, which stays enabled mid-lock) swallowing all three while locked (⌃⌘F added 2026-11-04: the kiosk holds even windowed, so a user-initiated fullscreen exit mid-block left a windowed kiosk — menu bar gone, quit refused — the dogfood trap; fullscreen now leaves only via completion) (SwiftUI owns the stock window delegate and `.closeItem` has no CommandGroupPlacement — the OutlineDrag monitor pattern, installed/removed with the lock); hosted-test guard = full no-op (never kiosk the test machine). `WritingLockAppDelegate` (`@NSApplicationDelegateAdaptor` in MuseionApp) — `applicationShouldTerminate` while locked asks ONCE (#163 ruling 2026-11-04: "Walk away from the block?" — Walk Away clears the kiosk and quits, the block dying quietly with the process; Keep Writing cancels; unlocked quits pass straight through, all quit paths route here). Nothing persists — the block dies with the session. - `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft). - `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 `/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). - `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. - `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `![alt](assets/…)` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `![alt]()` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploads (Micro.blog keeps both copies; dedup via `q=source` is v2's call). **`MicropubPublishSheet.swift`** — the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain; `Send Again` re-drafts (the piece changed post-draft) and overwrites the remembered URL; `.onAppear` seeds from the piece's `micropubURL` so a draft from an earlier session still publishes. -- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** 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; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `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 `extension PostsModel` in PostsModelOutline.swift (#146). 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`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in the Convert extension (PostsModelOutline.swift, #146). rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in PostsModelPasses.swift (#146): guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (PostsModelPasses.swift, #146) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). **#34 (S6.2):** the send first routes through the private `uploadIllustrations` rail (same file) whenever the body carries asset illustration refs — floor + pre-flight + `q=config` + one upload per PNG — then hands `Micropub.sendDraft` the wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** 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; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `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 `extension PostsModel` in PostsModelOutline.swift (#146). 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`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in the Convert extension (PostsModelOutline.swift, #146). rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in PostsModelPasses.swift (#146): guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (PostsModelPasses.swift, #146) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). **#34 (S6.2):** the send first routes through the private `uploadIllustrations` rail (same file) whenever the body carries asset illustration refs — floor + pre-flight + `q=config` + one upload per PNG — then hands `Micropub.sendDraft` the wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). **#162 (Cold Turkey S2):** `canArmWritingLock` (can the lock arm on what's open — mirrors the editor branch's outline routing: prose drafts, the external guest, prose posts qualify; outline pieces never) and `editorBodyText` (the live whole-document text of the surface the editor is showing — the lock's arm-time baseline; the per-keystroke feed rides ProseTextView.onTextChange). - `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). @@ -40,7 +41,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **#142 paragraph-scoped fold maintenance:** a `shouldChangeText` override records the last accepted single-line edit (range + UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes it to the in-place re-key (`rekey` — pure, `RekeyOutcome`: survivors shifted by delta, marker-line edits kill the fold and return the scope for un-hiding, scope-interior edits grow/shrink it and flag the edited line for re-hide + caret park) — no parents rescan, no `setAttributedString` swap. The single-line gate is `\.isNewline`, never a literal `"\n"`/`"\r"` compare — `"\r\n"` is ONE grapheme equal to neither, and a CRLF-carrying edit must reach the full pass (finish-audit pin); `apply()` nulls `pendingPlainEdit` outright — structural edits reshape blocks even when the replacement is single-line (a childless unterminated block's outdent; finish-audit pin, `performOutdent` internal for it). A font probe at each survivor's scope head guards the path: hidden styling still present, else fall back to the full pass (wholesale restyles like the fence-flip self-heal this way); dead-scope un-hides are bounds-hardened at the sink. Full pass stays for structural edits, wholesale loads, and toggleFold. `Fold` carries the hidden `scope` (shift-maintained; the full pass re-derives it). **Chrome rendering (#115 field findings, #142 rework):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render as one TINY per-glyph CALayer (contents = a small flipped NSImage raster, `isGeometryFlipped` on the overlay layer so sublayer frames speak lineRect's top-left y) in the click-through `ProseChromeView` overlay (deferred one main-queue tick past textDidChange) — NEVER a document-sized bitmap (~35M pixels per keystroke on a tall doc, #142/F2); glyph rasters are cached by string (`chromeGlyphImages` — 50k parents share a handful of images; layers stay unculled because scroll fires no refresh, ponytail-noted); an edit at/after every parent line skips the rebuild outright (`parentsUnmoved`), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting. **#141 illustration ingest:** window-level SwiftUI `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'s #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (`allSatisfy` — a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the drop point. The source must be a PLAIN file — a dropped symlink refuses (`IngestError.isLink`: `copyItem` would land the LINK itself and the #34 rail would refuse the whole send; finish-audit 2026-11-02, empirically verified), a Finder folder with an image extension refuses (`isFolder`); collisions ride `FixCardStore.uniqueFile` (`-2`/`-3`, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure's `location` is UNUSABLE under this hosting; the pointer's screen position (`NSEvent.mouseLocation`) maps to an index via `firstRect(forCharacterRange:)` — its y is bottom-up screen coords like the mouse (no flip), non-contiguous layout makes OFF-SCREEN characters return garbage rects (whole-doc searches converge on the layout boundary), so `dropIndex(length:targetY:bandMinY:bandMaxY:rectY:)` — a `nonisolated static` PURE function (pinned by tests without a window) — SAMPLES the document (512 points), keeps only rects inside the viewport band (plain NSView geometry), brackets the drop between two in-band samples, binary-searches the bracket; a pointer above every in-band sample clamps to the first visible char, below all to the last in-band sample, no in-band evidence to 0 (never the old silent index-0-on-garbage), then slides the index to the next whitespace gap (never splices inside a word or an existing ref; dogfood-verified 2026-11-02, landing within one line). `alt` selected (offset +2, length 3) and scrolled to, with `CaretCentering.syncTypewriterInset` re-synced after the edit — without it the typewriter inset is stale and the editor freezes scrolling until the next keypress; one shouldChangeText step = one undo, didChangeText driving the coordinator (reattribute + session.edit + folds); refusals land in the transient `showIngestNotice` strip (mono-11 rust pill pinned to the scroll view's top-center, auto-hide ~4 s), multi-image ingest is non-atomic by design (ponytail comment). Outline surfaces have no ProseTextView → the bridge is nil → image drags bounce (AC4), markdown forwards. Reading mode swaps the surface away — no editor drop target while reading. - Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes), `testConnection(for:)` runs the probe per provider (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are ignored by hermes for other providers — and pre-lands for any later provider switch; var names from hermes' own registry, `ModelProvider.envVarName`: GLM_API_KEY/ANTHROPIC_API_KEY/OPENAI_API_KEY; foreign lines preserved byte-for-byte via pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes the read→upsert→write across concurrent cross-provider key writes (the same three files — a racing last writer would drop the other's var); 0600 — hermes' own .env posture; an EMPTY key leaves `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (pre-gate) refuses writes honestly. `ProviderProbe.swift` — Test Connection (factsheet §4, live-probed wire shapes 2026-10-27, corrected 2026-10-28 after dogfood): step 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-Type: application/json`** (the 2026-10-28 live incident: without it URLSession defaults to form-urlencoded — z.ai answers HTTP 200 with an error envelope, OpenAI can't parse the body at all; curl set it, the app didn't, Anthropic tolerated it); zai pins the stable GLM wire (`thinking:enabled`+`reasoning_effort:low`) at `{endpoint}/chat/completions`; **OpenAI speaks the RESPONSES API** (`{endpoint}/responses`, `input` + `max_output_tokens` — maintainer correction 2026-10-28, chat-completions is the retired path); Anthropic posts `{endpoint}/v1/messages` (`max_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; the token cap is **512** (`probeTokenCap` — the live tail proved 64 starves reasoning models: glm-5.3 burned 64/64 on thinking, finish=length, zero content); decode is honest per the factsheet envelopes — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_id`), transport errors → unreachable, `finish=length`/`max_tokens`/`incomplete` + empty content → starved, an empty 200 → requestFailed, and **errors riding a 2xx decode as the provider error** (z.ai's 200-carried content-type envelope live-probed; OpenAI nests it under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure is injectable (production buffers the streamed response over URLSession); URL builders are nil-safe (a garbage endpoint reads unreachable, never traps). The Provider Keys page carries a per-provider **Test Connection** button + one-line verdict (`TestConnectionResult`: accent "✓ works · N ms · N models" / orange decoded failures). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.mentor.requestRestart()`, so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). -- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. +- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. **#162 (Cold Turkey S2, map #158):** the chrome lineage grows the lock — `ColdTurkeySeat` (one bottom-center seat: the arm-bar before Start, the live readout while locked, the completion note fading ~6 s; the arm-bar carries a chip that BLENDS into the focus ground — 2026-11-04 dogfood amendment: the ground's own color + the faintest token hairline, no shadow, because the bare seat let the document text show through; readout + note stay bare mono; readout = numerals + 2px hairline, terracotta numerals inside the last 20 %, piece title absent; the arm value is directly typeable — parsed and clamped at every read — with ± steppers for coarse moves; defaults 250 words / 5 min, ranges 1…1000 words / 1…60 min — what's typed is what arms, the 2026-11-04 dogfood amendments; the readout and completion note carry the same blending chip) and `ColdTurkeyDot` (the persistent muted pip bottom-right, label on hover, click opens the arm-bar — hidden while the bar is up, a block runs, or nothing prose is open). The arm-bar's Esc = a hidden `.cancelAction` button (the PostEditorView ⌘S rail — `.onExitCommand` never fires behind the hosting view, the #109 probe). Both mount as overlays on PostsPaneView's focused ZStack only, so lock transitions never restructure the editor column (the #87 remount hazard / typing-continuity AC). `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
     - `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error). 
     - `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
    diff --git a/Museion/FocusChrome.swift b/Museion/FocusChrome.swift
    index 686ec1c..c24b52d 100644
    --- a/Museion/FocusChrome.swift
    +++ b/Museion/FocusChrome.swift
    @@ -7,6 +7,8 @@
     //  the soft caret centering. Panes NEVER push the measure: revealed panels
     //  float above the surface and slide off when hover ends. Animation feel is
     //  the fog's "slide curve" knob — calibrate here if not-calm.
    +//  #162 (map #158): the chrome lineage GROWS the Cold Turkey lock — the
    +//  corner dot, arm-bar, readout, and completion note live here too.
     //
     
     import AppKit
    @@ -135,6 +137,291 @@ struct FocusOverlayPanel: View {
     	}
     }
     
    +// MARK: - Cold Turkey chrome (#162, map #158)
    +
    +/// The Cold Turkey seat: one bottom-center position, one lineage — the
    +/// arm-bar before Start, the live readout while locked, the completion
    +/// note on quiet return (never two at once, per the contract render).
    +/// Seat = BARE mono on the focus ground — no chip box; Start's accent
    +/// fill is the only boxed element anywhere in the lineage.
    +struct ColdTurkeySeat: View {
    +	@Environment(AppGateState.self) private var gate
    +
    +	var body: some View {
    +		let lock = gate.writingLock
    +		ZStack {
    +			if lock.showsArmBar, !lock.isLocked {
    +				ColdTurkeyArmBar()
    +					.transition(.opacity)
    +			} else if lock.isLocked, let run = lock.run {
    +				ColdTurkeyReadout(run: run, now: lock.now)
    +					.transition(.opacity)
    +			} else if let note = lock.completionNote {
    +				ColdTurkeyNote(text: note)
    +					.transition(.opacity)
    +			}
    +		}
    +		.padding(.bottom, 46)
    +		.animation(.easeInOut(duration: 0.2), value: lock.isLocked)
    +		.animation(.easeInOut(duration: 0.2), value: lock.showsArmBar)
    +		.animation(.easeInOut(duration: 1.2), value: lock.completionNote)
    +	}
    +}
    +
    +/// The arm-bar (#160): minutes|words selector + value stepper/entry +
    +/// Start, quiet and non-modal on the focus ground. Esc dismisses — the
    +/// hidden cancel-action button is the PostEditorView ⌘S rail (key
    +/// equivalents ride the menu machinery, which DOES reach behind the
    +/// hosting view — unlike `.onExitCommand`, the #109 Esc probe).
    +/// Amendment (2026-11-04, live dogfood): the bar carries a chip that
    +/// BLENDS into the focus ground — the ground's own color, the faintest
    +/// token hairline, no shadow. The bare seat let the document text show
    +/// through and obscure the controls; blending, not transparency, is the
    +/// ruling now. The value is directly typeable (± steppers stay for the
    +/// coarse moves); defaults 250 words / 5 minutes.
    +private struct ColdTurkeyArmBar: View {
    +	@Environment(AppGateState.self) private var gate
    +	@State private var minutes = false
    +	/// The typeable value for the selected kind — parsed and clamped at
    +	/// every read (Start, steppers, submit), so unsubmitted or garbage
    +	/// text can never arm an out-of-range block. Switching kinds resets
    +	/// it to that kind's default.
    +	@State private var fieldText = String(WritingLockState.ArmScale.words.defaultValue)
    +
    +	private var scale: WritingLockState.ArmScale {
    +		minutes ? .minutes : .words
    +	}
    +
    +	private var value: Int {
    +		scale.parse(fieldText)
    +	}
    +
    +	private var goal: WritingGoal {
    +		minutes ? .minutes(value) : .words(value)
    +	}
    +
    +	/// Rewrite the field to the clamped value (submit, kind switch).
    +	private func commitField() {
    +		fieldText = String(value)
    +	}
    +
    +	var body: some View {
    +		VStack(spacing: 9) {
    +			HStack(spacing: 14) {
    +				selectorButton("Words", isOn: !minutes) {
    +					minutes = false
    +					fieldText = String(WritingLockState.ArmScale.words.defaultValue)
    +				}
    +				selectorButton("Minutes", isOn: minutes) {
    +					minutes = true
    +					fieldText = String(WritingLockState.ArmScale.minutes.defaultValue)
    +				}
    +			}
    +			HStack(spacing: 10) {
    +				stepButton("−") { fieldText = String(scale.clamp(value - scale.step)) }
    +				HStack(alignment: .firstTextBaseline, spacing: 7) {
    +					TextField("", text: $fieldText)
    +						.textFieldStyle(.plain)
    +						.font(.system(size: 13, design: DesignTokens.mono))
    +						.kerning(0.5)
    +						.multilineTextAlignment(.center)
    +						.foregroundStyle(DesignTokens.foreground)
    +						.frame(width: 56)
    +						.onSubmit(commitField)
    +					Text(minutes ? "MIN" : "WORDS")
    +						.font(.system(size: 10, design: DesignTokens.mono))
    +						.kerning(0.8)
    +						.textCase(.uppercase)
    +						.foregroundStyle(DesignTokens.muted)
    +				}
    +				stepButton("+") { fieldText = String(scale.clamp(value + scale.step)) }
    +				Button("Start") {
    +					gate.startWritingLock(goal: goal)
    +				}
    +				.buttonStyle(.plain)
    +				.font(.system(size: 11, design: DesignTokens.mono))
    +				.kerning(0.7)
    +				.textCase(.uppercase)
    +				.foregroundStyle(DesignTokens.surface)
    +				.padding(.horizontal, 16)
    +				.frame(height: 28)
    +				.background(DesignTokens.accent, in: RoundedRectangle(cornerRadius: 6))
    +			}
    +			Text("esc dismisses · nothing armed yet")
    +				.font(.system(size: 9, design: DesignTokens.mono))
    +				.kerning(0.8)
    +				.textCase(.uppercase)
    +				.foregroundStyle(DesignTokens.muted.opacity(0.7))
    +		}
    +		.padding(.horizontal, 16)
    +		.padding(.vertical, 12)
    +		.blendingChip()
    +		.background {
    +			Button("") { gate.writingLock.showsArmBar = false }
    +				.keyboardShortcut(.cancelAction)
    +				.opacity(0)
    +				.frame(width: 1, height: 1)
    +				.accessibilityHidden(true)
    +		}
    +	}
    +
    +	/// Selector tab: mono-10 uppercase, the selected kind carries a 2px
    +	/// accent underline (the render's `border-bottom` language).
    +	private func selectorButton(_ title: String, isOn: Bool, action: @escaping () -> Void) -> some View {
    +		Button(action: action) {
    +			Text(title)
    +				.font(.system(size: 10, design: DesignTokens.mono))
    +				.kerning(0.8)
    +				.textCase(.uppercase)
    +				.foregroundStyle(isOn ? DesignTokens.foreground : DesignTokens.muted)
    +				.padding(.bottom, 3)
    +				.overlay(alignment: .bottom) {
    +					if isOn {
    +						Rectangle()
    +							.fill(DesignTokens.accent)
    +							.frame(height: 2)
    +					}
    +				}
    +		}
    +		.buttonStyle(.plain)
    +	}
    +
    +	/// Bare stepper — no box (ruling 1: Start is the only boxed element).
    +	private func stepButton(_ glyph: String, action: @escaping () -> Void) -> some View {
    +		Button(action: action) {
    +			Text(glyph)
    +				.font(.system(size: 11, design: DesignTokens.mono))
    +				.foregroundStyle(DesignTokens.foreground)
    +				.frame(width: 26, height: 26)
    +		}
    +		.buttonStyle(.plain)
    +	}
    +}
    +
    +/// The live readout while locked: numerals + unit (numerals only — the
    +/// piece title is ruled absent) over the 2px progress hairline. Near
    +/// goal (inside the last 20 %) the numerals flip terracotta.
    +private struct ColdTurkeyReadout: View {
    +	let run: WritingGoalRun
    +	let now: Date
    +
    +	private var progress: Double {
    +		run.progress(now: now)
    +	}
    +
    +	var body: some View {
    +		let shape = WritingLockState.readout(run, now: now)
    +		VStack(spacing: 3) {
    +			HStack(alignment: .firstTextBaseline, spacing: 7) {
    +				Text(shape.numerals)
    +					.font(.system(size: 13, design: DesignTokens.mono))
    +					.kerning(0.65)
    +					.foregroundStyle(
    +						WritingLockState.isNearGoal(progress: progress)
    +							? DesignTokens.accent.opacity(0.8)
    +							: DesignTokens.foreground,
    +					)
    +				Text(shape.unit)
    +					.font(.system(size: 10, design: DesignTokens.mono))
    +					.kerning(0.8)
    +					.textCase(.uppercase)
    +					.foregroundStyle(DesignTokens.muted)
    +			}
    +			ZStack(alignment: .leading) {
    +				Rectangle()
    +					.fill(DesignTokens.foreground.opacity(0.06))
    +					.frame(width: 148, height: 2)
    +				Rectangle()
    +					.fill(DesignTokens.accent)
    +					.frame(width: max(0, 148 * progress), height: 2)
    +			}
    +			.clipShape(Capsule())
    +		}
    +		.padding(.horizontal, 16)
    +		.padding(.vertical, 8)
    +		.blendingChip()
    +		.allowsHitTesting(false)
    +	}
    +}
    +
    +/// The completion note: `● 500 words · 14:02`, bare mono, fading ~6 s
    +/// (the fade task lives in the state; the transition lives here).
    +private struct ColdTurkeyNote: View {
    +	let text: String
    +
    +	var body: some View {
    +		HStack(spacing: 8) {
    +			Text("●")
    +				.foregroundStyle(DesignTokens.accent)
    +			Text(text)
    +				.foregroundStyle(DesignTokens.muted)
    +		}
    +		.font(.system(size: 11, design: DesignTokens.mono))
    +		.kerning(0.88)
    +		.textCase(.uppercase)
    +		.padding(.horizontal, 14)
    +		.padding(.vertical, 8)
    +		.blendingChip()
    +		.allowsHitTesting(false)
    +	}
    +}
    +
    +/// The persistent dot (#160 ruling 6): the quiet always-there Cold
    +/// Turkey presence in plain focus — muted 6px pip tucked bottom-right,
    +/// terracotta + label on hover, click opens the arm-bar. Hidden while
    +/// the bar is up or a block runs, and wherever there is nothing prose
    +/// to lock (Posts + drafts + the guest, never Outline — #158 settle 11).
    +struct ColdTurkeyDot: View {
    +	@Environment(AppGateState.self) private var gate
    +	var model: PostsModel
    +	@State private var hover = false
    +
    +	var body: some View {
    +		let lock = gate.writingLock
    +		if !lock.isLocked, !lock.showsArmBar, model.canArmWritingLock {
    +			Button {
    +				lock.showsArmBar = true
    +			} label: {
    +				HStack(spacing: 8) {
    +					Circle()
    +						.fill(hover ? DesignTokens.accent : DesignTokens.muted)
    +						.frame(width: 6, height: 6)
    +					if hover {
    +						Text("Cold Turkey")
    +							.font(.system(size: 10, design: DesignTokens.mono))
    +							.kerning(0.8)
    +							.textCase(.uppercase)
    +							.foregroundStyle(DesignTokens.muted.opacity(0.85))
    +							.transition(.opacity)
    +					}
    +				}
    +				.padding(6)
    +			}
    +			.buttonStyle(.plain)
    +			.onHover { hover = $0 }
    +			.animation(.easeInOut(duration: 0.15), value: hover)
    +			.padding(.bottom, 12)
    +			.padding(.trailing, 14)
    +			.help("Start Cold Turkey")
    +			.accessibilityLabel("Start Cold Turkey")
    +		}
    +	}
    +}
    +
    +/// The 2026-11-04 dogfood amendment's chip, ONE definition for the
    +/// seat's three surfaces (arm-bar, readout, note): the focus ground's
    +/// own color + the token hairline (the faintest line the palette has),
    +/// no shadow — blending, not transparency. Padding stays per-site.
    +private extension View {
    +	func blendingChip() -> some View {
    +		background(DesignTokens.background, in: RoundedRectangle(cornerRadius: DesignTokens.radius))
    +			.overlay(
    +				RoundedRectangle(cornerRadius: DesignTokens.radius)
    +					.strokeBorder(DesignTokens.border),
    +			)
    +	}
    +}
    +
     // MARK: - Soft caret centering (#21)
     
     /// Soft caret centering (the Neo input, softened): keep the caret inside a
    diff --git a/Museion/MuseionApp.swift b/Museion/MuseionApp.swift
    index 562bb2c..fc1a893 100644
    --- a/Museion/MuseionApp.swift
    +++ b/Museion/MuseionApp.swift
    @@ -39,6 +39,11 @@ final class AppGateState {
     	/// rail/library/mentor and the editor toolbar; overlay panes return on
     	/// edge hover.
     	var isFocused = false
    +	/// #162 (Cold Turkey S2, map #158): the writing lock — armed from the
    +	/// focus-mode arm-bar, held while the goal runs. Lock ⇒ focus: while
    +	/// locked, `isFocused` cannot leave true (the ⌥⌘F refusal IS the
    +	/// lock), hover-reveal zones stay suppressed, and the kiosk holds.
    +	let writingLock = WritingLockState()
     	/// #17: the Museion Home — repoint-only (ADR-0004). Defaults to
     	/// `~/Documents/Museion`; UserDefaults is the persistence floor: a Home is
     	/// a plain folder, nothing app-owned to put in a database. Non-file URLs
    @@ -74,6 +79,15 @@ final class AppGateState {
     		await gateModel.beginAutomaticCheck()
     	}
     
    +	/// #162: Start Cold Turkey — the arm-bar's single commit. The lock ⇒
    +	/// focus invariant is settled here (arming is focus-gated anyway;
    +	/// this is the belt), and the baseline body is the live editor text.
    +	func startWritingLock(goal: WritingGoal) {
    +		guard !writingLock.isLocked else { return }
    +		isFocused = true
    +		writingLock.start(goal: goal, body: posts.editorBodyText ?? "")
    +	}
    +
     	/// The auto-fire chain — the exact onEnginePass body from the gate era,
     	/// moved verbatim: provisioning (#47, idempotent — re-fires per passing
     	/// Re-check are no-ops), then the daily backup (#50 — a failed
    @@ -92,6 +106,9 @@ final class AppGateState {
     /// between the app and the headless `--serve-mcp` tool server.
     struct MuseionApp: App {
     	@State private var gate = AppGateState()
    +	/// #162: the quit refusal while a Cold Turkey block holds (#159
    +	/// delegate-level coverage — every quit path routes through here).
    +	@NSApplicationDelegateAdaptor(WritingLockAppDelegate.self) private var appDelegate
     
     	var body: some Scene {
     		WindowGroup {
    @@ -149,12 +166,25 @@ struct MuseionApp: App {
     					NotificationCenter.default.post(name: .toggleReadingMode, object: nil)
     				}
     				.keyboardShortcut("r", modifiers: .command)
    +				// #162: the editor is the only surface while locked — the
    +				// reading swap would interrupt typing mid-block.
    +				.disabled(gate.writingLock.isLocked)
     				// #21: focus mode — beside reading, same posture (system View
     				// menu + shortcut). Transient like reading: no persistence, no
     				// Esc exit (rejected at charting) — the toggle is the only way.
     				// ⌥⌘F — ⇧⌘F is taken by a system-wide shortcut on this machine,
     				// ⌃F shadows the editor's Emacs caret-forward binding.
    +				// #162: disabled while a Cold Turkey block holds — the refusal
    +				// IS the lock (#158 settle 6: completion drops back to focus).
     				FocusModeToggle(gate: gate)
    +					.disabled(gate.writingLock.isLocked)
    +				// #162 (#160 ruling 6): the second arming path — dot-first,
    +				// menu second. Focus-mode-gated; nothing prose to lock or a
    +				// block already running disables it.
    +				Button("Start Cold Turkey…") {
    +					gate.writingLock.showsArmBar = true
    +				}
    +				.disabled(!gate.isFocused || gate.writingLock.isLocked || !gate.posts.canArmWritingLock)
     			}
     			// #50: reveal the snapshots folder in Finder (restore = manual
     			// copy-back, documented in the bundled help doc).
    @@ -215,6 +245,9 @@ private struct NewPostButton: View {
     	var body: some View {
     		Button("New Post") { gate.posts.newPost() }
     			.keyboardShortcut("n", modifiers: .command)
    +			// #162: the open Piece stays stable for counting while a
    +			// Cold Turkey block holds.
    +			.disabled(gate.writingLock.isLocked)
     	}
     }
     
    @@ -226,6 +259,8 @@ private struct NewOutlineButton: View {
     	var body: some View {
     		Button("New Outline") { gate.posts.newOutline() }
     			.keyboardShortcut("n", modifiers: [.command, .shift])
    +			// #162: piece stability while a block holds.
    +			.disabled(gate.writingLock.isLocked)
     	}
     }
     
    @@ -237,6 +272,8 @@ private struct NewProjectButton: View {
     	var body: some View {
     		Button("New Project…") { gate.posts.stageNewProject() }
     			.keyboardShortcut("n", modifiers: [.command, .option])
    +			// #162: piece stability while a block holds.
    +			.disabled(gate.writingLock.isLocked)
     	}
     }
     
    @@ -252,6 +289,8 @@ private struct OpenExternalButton: View {
     			}
     		}
     		.keyboardShortcut("o", modifiers: .command)
    +		// #162: piece stability while a block holds.
    +		.disabled(gate.writingLock.isLocked)
     	}
     }
     
    @@ -268,6 +307,8 @@ private struct ImportFilesButton: View {
     			}
     		}
     		.keyboardShortcut("o", modifiers: [.command, .shift])
    +		// #162: piece stability while a block holds.
    +		.disabled(gate.writingLock.isLocked)
     	}
     }
     
    diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift
    index 17b4cde..231ca8b 100644
    --- a/Museion/PostEditorView.swift
    +++ b/Museion/PostEditorView.swift
    @@ -182,6 +182,8 @@ struct PostEditorView: View {
     				focused: gate.isFocused,
     				caretHint: flipBackCaret,
     				dropBridge: gate.proseDrop,
    +				// #162: the Cold Turkey word feed.
    +				onTextChange: { gate.writingLock.feed(text: $0) },
     			)
     		} else {
     			ProseTextView(
    @@ -194,6 +196,8 @@ struct PostEditorView: View {
     				},
     				caretHint: flipBackCaret,
     				dropBridge: gate.proseDrop,
    +				// #162: the Cold Turkey word feed.
    +				onTextChange: { gate.writingLock.feed(text: $0) },
     			)
     		}
     	}
    @@ -338,6 +342,10 @@ struct ProseTextView: NSViewRepresentable {
     	var session: EditorSession?
     	var draft: String?
     	var onEdit: ((String) -> Void)?
    +	/// #162: the Cold Turkey feed — whole-document text on every edit,
    +	/// both modes (session + draft). No-op at rest; the lock's word
    +	/// count rides the same keystroke the editor already emits.
    +	var onTextChange: ((String) -> Void)?
     	var spellChecking = false
     	/// #21: focus mode — the text ground joins the workspace background.
     	var focused = false
    @@ -357,11 +365,13 @@ struct ProseTextView: NSViewRepresentable {
     		focused: Bool = false,
     		caretHint: (location: Int, token: Int)? = nil,
     		dropBridge: ProseDropBridge,
    +		onTextChange: ((String) -> Void)? = nil,
     	) {
     		self.session = session
     		self.spellChecking = spellChecking
     		self.focused = focused
     		self.caretHint = caretHint
    +		self.onTextChange = onTextChange
     		ingestFolder = session.postID != nil ? session.folderURL : nil
     		self.dropBridge = dropBridge
     	}
    @@ -373,12 +383,14 @@ struct ProseTextView: NSViewRepresentable {
     		onEdit: @escaping (String) -> Void,
     		caretHint: (location: Int, token: Int)? = nil,
     		dropBridge: ProseDropBridge,
    +		onTextChange: ((String) -> Void)? = nil,
     	) {
     		self.draft = draft
     		self.spellChecking = spellChecking
     		self.focused = focused
     		self.onEdit = onEdit
     		self.caretHint = caretHint
    +		self.onTextChange = onTextChange
     		self.dropBridge = dropBridge
     	}
     
    @@ -512,6 +524,8 @@ struct ProseTextView: NSViewRepresentable {
     
     	final class Coordinator: NSObject, NSTextViewDelegate {
     		let onEdit: ((String) -> Void)?
    +		/// #162: the Cold Turkey feed (see the representable's property).
    +		let onTextChange: ((String) -> Void)?
     		weak var textView: NSTextView?
     		var sessionRef: EditorSession?
     		var loadedGeneration = -1
    @@ -523,6 +537,7 @@ struct ProseTextView: NSViewRepresentable {
     
     		init(representable: ProseTextView) {
     			onEdit = representable.onEdit
    +			onTextChange = representable.onTextChange
     		}
     
     		func textDidChange(_ notification: Notification) {
    @@ -551,6 +566,8 @@ struct ProseTextView: NSViewRepresentable {
     			} else {
     				onEdit?(storage.string)
     			}
    +			// #162: the lock's word count rides the same keystroke.
    +			onTextChange?(storage.string)
     			// #115: fold maintenance LAST — hidden styling over the refreshed presentation.
     			(tv as? ProseListTextView)?.refreshFolds()
     		}
    diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift
    index d189f08..605b4a8 100644
    --- a/Museion/PostsModel.swift
    +++ b/Museion/PostsModel.swift
    @@ -341,6 +341,42 @@ final class PostsModel {
     		draft?.text = text
     	}
     
    +	// MARK: - Cold Turkey (#162, map #158)
    +
    +	/// #162: can the writing lock arm on what's open? Mirrors the editor
    +	/// column's branch precedence and outline routing (PostsPaneView) —
    +	/// prose drafts, the external guest, and prose posts qualify; an
    +	/// outline piece never does (#158 settle 11: Posts + drafts, not
    +	/// Outline). Keep the expression in step with the editor branch.
    +	var canArmWritingLock: Bool {
    +		if let draft {
    +			return draft.type != .outline
    +		}
    +		if externalSession != nil {
    +			return true
    +		}
    +		guard let session, session.postID == selectedPostID else { return false }
    +		let outline = session.postID != proseOverridePostID
    +			&& (lastDraftWasOutline || posts.first(where: { $0.id == session.postID })?.type == .outline)
    +		return !outline
    +	}
    +
    +	/// #162: the live whole-document text of the surface the editor is
    +	/// showing — the lock's baseline at Start. The per-keystroke feed
    +	/// rides ProseTextView.onTextChange; this is the arm-time snapshot.
    +	var editorBodyText: String? {
    +		if let draft {
    +			return draft.text
    +		}
    +		if let externalSession {
    +			return externalSession.text
    +		}
    +		if let session, session.postID == selectedPostID {
    +			return session.text
    +		}
    +		return nil
    +	}
    +
     	/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
     	/// first (rename reads the file from disk — unflushed edits must land
     	/// before the move), then reopens a session at the new id. Sets lastError
    diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift
    index a14d3e1..29d4dc3 100644
    --- a/Museion/PostsPaneView.swift
    +++ b/Museion/PostsPaneView.swift
    @@ -47,14 +47,29 @@ struct PostsPaneView: View {
     				// the workspace background is all that remains. The mentor
     				// returns by right-edge hover (overlay below) — only while the
     				// width budget grants it (#17's collapse verdict stands here too).
    +				// #162: hover reveal suppressed while a Cold Turkey block holds
    +				// (editor-only — passes and chat unreachable, #158 settle 5);
    +				// the Cold Turkey chrome mounts on this branch, so a lock
    +				// transition never restructures the editor column itself
    +				// (typing-continuity AC — the #87 remount hazard).
     				ZStack(alignment: .trailing) {
     					editorColumn
    -					if showsMentor {
    +					if showsMentor, !gate.writingLock.isLocked {
     						FocusOverlayPanel(edge: .trailing, panelWidth: DesignTokens.mentorWidth) {
     							mentorColumn
     						}
     					}
     				}
    +				// #162: the Cold Turkey seat (arm-bar | readout | note,
    +				// bottom-center) + the quiet corner dot — overlays only,
    +				// never wrappers around editorColumn.
    +				.overlay(alignment: .bottom) { ColdTurkeySeat() }
    +				.overlay(alignment: .bottomTrailing) { ColdTurkeyDot(model: model) }
    +				.onDisappear {
    +					// Leaving focus mid-arm drops the bar (no stale bar on
    +					// the next focus entry).
    +					gate.writingLock.showsArmBar = false
    +				}
     			} else {
     				HStack(spacing: 0) {
     					if showsLibrary {
    diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift
    index 3ce27db..5b73b98 100644
    --- a/Museion/WorkspaceView.swift
    +++ b/Museion/WorkspaceView.swift
    @@ -55,6 +55,9 @@ struct WorkspaceView: View {
     			// #91: drag a markdown file onto the window — same guest slot as
     			// File ▸ Open… Non-markdown drops are refused.
     			.dropDestination(for: URL.self) { urls, _ in
    +				// #162: no new buffers while a Cold Turkey block holds —
    +				// the open Piece is the one being counted.
    +				guard !gate.writingLock.isLocked else { return false }
     				// #141: the window destination is the only one that ever
     				// fires (field-verified 2026-11-02 — nested editor-level
     				// SwiftUI targets are never consulted, and AppKit views
    @@ -74,8 +77,10 @@ struct WorkspaceView: View {
     			// #21: left-edge hover slides rail+library back in as an overlay.
     			// Library only while the window width allows it (#17 verdict stands:
     			// a collapsed pane is not summoned by focus).
    +			// #162: suppressed while a Cold Turkey block holds — the library
    +			// stays hidden and the open Piece stable for counting (#158).
     			.overlay {
    -				if gate.isFocused {
    +				if gate.isFocused, !gate.writingLock.isLocked {
     					// #17 verdict: the library reveal honors the width collapse.
     					let showsLibrary = geo.size.width >= 1100
     					FocusOverlayPanel(edge: .leading, panelWidth: leftRevealWidth(showsLibrary)) {
    @@ -176,6 +181,13 @@ struct WorkspaceView: View {
     				selection = .posts
     			}
     		}
    +		// #162 audit: View ▸ Start Cold Turkey… can fire while another
    +		// pane is up (the rail is hover-reachable in focus) — the bar
    +		// would pop stale on the next Posts mount. Any pane change
    +		// drops a pending arm-bar.
    +		.onChange(of: selection) { _, _ in
    +			gate.writingLock.showsArmBar = false
    +		}
     	}
     
     	/// #94: the ask presents while a batch is staged.
    diff --git a/Museion/WritingLockState.swift b/Museion/WritingLockState.swift
    new file mode 100644
    index 0000000..8fecedf
    --- /dev/null
    +++ b/Museion/WritingLockState.swift
    @@ -0,0 +1,345 @@
    +//
    +//  WritingLockState.swift
    +//  Museion
    +//
    +//  #162 (Cold Turkey S2, map #158): the writing lock's state machine —
    +//  arms from the quiet arm-bar, holds while the goal engine runs, and
    +//  completes quietly back into focus. The kiosk recipe, the quit
    +//  refusal, and the readout formatting live here; the chrome views
    +//  grow FocusChrome.swift (one chrome lineage, #158 settle 6).
    +//
    +
    +import AppKit
    +import SwiftUI
    +
    +/// #162: the Cold Turkey lock machine. One block per launch moment:
    +/// `start` arms from the focus-mode arm-bar, the ticker asks the goal
    +/// engine (`WritingGoalRun`, #161) whether the block is met on every
    +/// 1 s tick plus every keystroke feed, and `complete` exits the kiosk
    +/// and leaves the completion note fading on the focus ground. Nothing
    +/// persists — the block dies quietly with the process (#158 settle 3).
    +@Observable
    +final class WritingLockState {
    +	/// The process's one lock (AppGateState owns it). The app delegate's
    +	/// quit refusal reads it — AppKit asks before SwiftUI state is handy.
    +	weak static var active: WritingLockState?
    +
    +	/// The armed block while locked; nil at rest.
    +	private(set) var run: WritingGoalRun?
    +
    +	/// True while the block holds: focus exit refused (the refusal IS the
    +	/// lock), hover-reveal zones suppressed, kiosk options set.
    +	private(set) var isLocked = false
    +
    +	/// The readout clock — bumped by the ticker each second so a minutes
    +	/// countdown renders without a UI-owned timer.
    +	private(set) var now = Date()
    +
    +	/// #160 contract: the completion note on quiet return to focus,
    +	/// bare mono in the readout's seat, fading after ~6 s.
    +	private(set) var completionNote: String?
    +
    +	/// The arm-bar's presentation flag — the corner dot and the View ▸
    +	/// Start Cold Turkey… item both set it; Esc dismisses; `start`
    +	/// consumes it (#160: dot-first, menu second).
    +	var showsArmBar = false
    +
    +	private var ticker: Task?
    +	private var noteFade: Task?
    +	/// Whether the lock itself toggled fullscreen at entry (an already-
    +	/// fullscreen window is left alone — exit only toggles back what
    +	/// entry toggled).
    +	private var enteredFullscreen = false
    +
    +	init() {
    +		Self.active = self
    +	}
    +
    +	/// Arm the block. Focus is forced by the caller (AppGateState —
    +	/// lock ⇒ focus is the invariant, #158 settle 6); `at` is injectable
    +	/// so tests drive deterministic deadlines. `spawnsTicker` lets the
    +	/// machine tests opt out of the real 1 s ticker (audit 2026-11-04:
    +	/// a >1 s main-actor stall let the live ticker complete a met words
    +	/// goal before the injected tick, flipping the note pin — the repo's
    +	/// own #30/#147 flake family).
    +	func start(goal: WritingGoal, body: String, at armedAt: Date = Date(), spawnsTicker: Bool = true) {
    +		guard !isLocked else { return }
    +		run = WritingGoalRun(goal: goal, armedAt: armedAt, body: body)
    +		now = armedAt
    +		isLocked = true
    +		showsArmBar = false
    +		enteredFullscreen = WritingLockKiosk.enter()
    +		guard spawnsTicker else { return }
    +		ticker = Task { [weak self] in
    +			while true {
    +				try? await Task.sleep(for: .seconds(1))
    +				guard let self, !Task.isCancelled, isLocked else { return }
    +				tick()
    +			}
    +		}
    +	}
    +
    +	/// The per-keystroke feed: whole-document text from the live editor
    +	/// surface (#161's `update(text:)` contract — typing, deleting,
    +	/// pasting, undo all land the same way). No-op at rest.
    +	func feed(text: String) {
    +		run?.update(text: text)
    +	}
    +
    +	/// One heartbeat: record `now`, ask the engine, complete on the
    +	/// first met tick. Internal seam — the ticker drives it with the
    +	/// real clock, tests inject the decisive moments.
    +	func tick(at date: Date = Date()) {
    +		guard isLocked, let armed = run else { return }
    +		now = date
    +		if armed.isMet(now: date) {
    +			complete()
    +		}
    +	}
    +
    +	/// Quiet return to focus: kiosk off, block cleared, note left in the
    +	/// readout's seat. Typing is never touched — the fullscreen round
    +	/// trip preserves the first responder (#159 probe), and the editor
    +	/// column's identity is unchanged by design.
    +	private func complete() {
    +		guard let armed = run else { return }
    +		ticker?.cancel()
    +		ticker = nil
    +		WritingLockKiosk.exit(toggledFullscreen: enteredFullscreen)
    +		enteredFullscreen = false
    +		isLocked = false
    +		run = nil
    +		completionNote = Self.completionNoteText(
    +			goal: armed.goal,
    +			elapsed: now.timeIntervalSince(armed.armedAt),
    +		)
    +		noteFade?.cancel()
    +		noteFade = Task { [weak self] in
    +			try? await Task.sleep(for: .seconds(6))
    +			guard let self, !Task.isCancelled else { return }
    +			// Plain assignment — the seat's value-scoped animation owns
    +			// both fade directions with one curve (audit: a withAnimation
    +			// here ran a SECOND, different curve over the same flip).
    +			completionNote = nil
    +		}
    +	}
    +
    +	// MARK: - Readout formatting (#160 contract: numerals + unit + hairline)
    +
    +	nonisolated struct ArmScale {
    +		/// Amended 2026-11-04 (live dogfood): defaults 250 words / 5 min;
    +		/// ranges widened DOWN and capped — what the writer types is what
    +		/// arms (a 10-word sprint is legal), the ceilings are 1000 words /
    +		/// 60 min. Floor 1: a zero/empty entry falls back to the default,
    +		/// never an already-met block.
    +		static let words = ArmScale(defaultValue: 250, step: 50, range: 1 ... 1000)
    +		static let minutes = ArmScale(defaultValue: 5, step: 5, range: 1 ... 60)
    +
    +		let defaultValue: Int
    +		let step: Int
    +		let range: ClosedRange
    +
    +		func clamp(_ value: Int) -> Int {
    +			min(max(value, range.lowerBound), range.upperBound)
    +		}
    +
    +		/// The arm-bar's read pipeline: typed text → Int, empty/garbage/
    +		/// overflow falling to the default (Swift's failable `Int(String)`
    +		/// returns nil on a 30-digit string — never traps), clamped to
    +		/// the range. Extracted pure so the fallback cases pin.
    +		func parse(_ text: String) -> Int {
    +			clamp(Int(text) ?? defaultValue)
    +		}
    +	}
    +
    +	/// The readout's numerals + trailing unit. Words: live net over
    +	/// target. Minutes: the countdown, never paused (#158 settle 4).
    +	nonisolated static func readout(_ run: WritingGoalRun, now: Date) -> (numerals: String, unit: String) {
    +		switch run.goal {
    +		case let .words(target):
    +			return ("\(run.netNewWords) / \(target)", "words")
    +		case .minutes:
    +			let seconds = run.secondsRemaining(now: now) ?? 0
    +			return (clockString(seconds: seconds), "left")
    +		}
    +	}
    +
    +	/// Near-goal: terracotta numerals inside the last 20 % (#160 ruling 4).
    +	nonisolated static func isNearGoal(progress: Double) -> Bool {
    +		progress >= 0.8
    +	}
    +
    +	/// The completion note's text: `● 500 words · 14:02` shape (the dot
    +	/// and the uppercase are the view's; the string stays lowercase).
    +	nonisolated static func completionNoteText(goal: WritingGoal, elapsed: TimeInterval) -> String {
    +		let clock = clockString(seconds: max(0, Int(elapsed.rounded())))
    +		switch goal {
    +		case let .words(target):
    +			return "\(target) words · \(clock)"
    +		case let .minutes(total):
    +			return "\(total) min · \(clock)"
    +		}
    +	}
    +
    +	/// mm:ss under an hour, h:mm:ss above (the 180-min ceiling needs it).
    +	nonisolated static func clockString(seconds: Int) -> String {
    +		let total = max(0, seconds)
    +		let hours = total / 3600
    +		let minutes = (total % 3600) / 60
    +		let secs = total % 60
    +		if hours > 0 {
    +			return String(format: "%d:%02d:%02d", hours, minutes, secs)
    +		}
    +		return String(format: "%02d:%02d", minutes, secs)
    +	}
    +}
    +
    +/// #159 factsheet recipe, verbatim: the six-option kiosk combo plus the
    +/// macOS 27 hot-corner kill switch (`.disableScreenCornerInteractions`,
    +/// deployment target 27 — no availability dance). Build the option set
    +/// ONLY from this validated recipe; an invalid combo is an ObjC
    +/// exception, i.e. a crash, not a degradation.
    +@MainActor
    +enum WritingLockKiosk {
    +	/// The recipe is data — nonisolated so any context can pin it.
    +	nonisolated static let lockOptions: NSApplication.PresentationOptions = [
    +		.hideDock, // rider bit — enables the rest
    +		.hideMenuBar, // requires .hideDock (never the autoHide pair for a lock)
    +		.disableProcessSwitching, // ⌘Tab / Mission Control / Spaces / App Exposé
    +		.disableForceQuit, // ⌥⌘⎋ panel
    +		.disableSessionTermination, // Restart / Shut Down / Log Out / power-key panel
    +		.disableHideApplication, // ⌘H fires even with the menu bar hidden
    +		.disableScreenCornerInteractions, // macOS 27: the official Hot Corners switch
    +	]
    +
    +	/// Hosted tests run in this app — never kiosk the test machine
    +	/// (the panes' XCTest guard pattern).
    +	@MainActor
    +	static var hostedTests: Bool {
    +		ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
    +	}
    +
    +	/// Options before the toggle (invalid combos throw; ordering per the
    +	/// probe: set-then-toggle is the clean order). Returns whether WE
    +	/// toggled fullscreen — an already-fullscreen window is entered in
    +	/// place, and exit only replays what entry toggled (#158 settle 9:
    +	/// completion restores the previous window size, which the native
    +	/// fullscreen round trip does by itself).
    +	static func enter() -> Bool {
    +		guard !hostedTests else { return false }
    +		installRefusalMonitor()
    +		NSApp.activate(ignoringOtherApps: true) // options take effect only while frontmost
    +		NSApp.presentationOptions = lockOptions
    +		let window = NSApp.keyWindow
    +		lockedWindow = window
    +		let alreadyFullscreen = window?.styleMask.contains(.fullScreen) ?? true
    +		if !alreadyFullscreen {
    +			window?.toggleFullScreen(nil)
    +		}
    +		return !alreadyFullscreen
    +	}
    +
    +	/// Clear options FIRST, then the fullscreen toggle back — never churn
    +	/// options mid-transition (the probe's D1/D3 anomaly). On macOS 27
    +	/// the exit auto-clears anyway; the explicit clear is the 26.x belt.
    +	/// The window ENTERED is the window EXITED (audit 2026-11-04: reading
    +	/// the key window at exit could un-fullscreen the wrong window if
    +	/// focus moved mid-block).
    +	static func exit(toggledFullscreen: Bool) {
    +		guard !hostedTests else { return }
    +		removeRefusalMonitor()
    +		NSApp.presentationOptions = []
    +		let window = lockedWindow ?? NSApp.keyWindow
    +		lockedWindow = nil
    +		if toggledFullscreen {
    +			window?.toggleFullScreen(nil)
    +		}
    +	}
    +
    +	/// The window the block entered (cleared at exit) — see `exit`.
    +	static var lockedWindow: NSWindow?
    +
    +	/// #159's `windowShouldClose` refusal, expressed where SwiftUI allows
    +	/// it: the stock Close item has no `CommandGroupPlacement` to replace
    +	/// and SwiftUI owns the window delegate, so while a block holds the
    +	/// local key monitor swallows ⌘W (close) and ⌃⌘F (the system
    +	/// fullscreen toggle) — the OutlineDrag monitor pattern, running
    +	/// before menu key equivalents resolve. ⌃⌘F matters because the
    +	/// kiosk options hold even windowed (the #159 probe's own finding):
    +	/// without this swallow the writer can toggle fullscreen off
    +	/// mid-block, "escape" the lock's looks while it still holds, and
    +	/// land in a windowed kiosk with no menu bar and quit refused — the
    +	/// 2026-11-04 dogfood trap. Fullscreen now leaves ONLY via
    +	/// completion. Quiet by design: nil, no beep, no dialog.
    +	static var refusalMonitor: Any?
    +
    +	/// The refusal key set, matched the way AppKit's menu machinery
    +	/// matches key equivalents: by KEY CODE (physical, layout- and
    +	/// case-independent) with the exact modifier set, plus the
    +	/// lowercased character as a second net. Audit 2026-11-04:
    +	/// `charactersIgnoringModifiers == "w"` is layout- and Caps-Lock
    +	/// dependent — a Cyrillic ⌘W or a caps-on "W" slipped past while the
    +	/// stock Close still fired, wedging a windowless kiosk. 13 =
    +	/// kVK_ANSI_W (⌘W close), 3 = kVK_ANSI_F (⌃⌘F fullscreen), 45 =
    +	/// kVK_ANSI_N (⌘N — the stock File ▸ New Window item SwiftUI owns
    +	/// stays enabled mid-lock; a second window would strand the count).
    +	nonisolated static func refusesKey(keyCode: UInt16, characters: String?, modifiers: NSEvent.ModifierFlags) -> Bool {
    +		let exact = modifiers.intersection([.command, .control, .option, .shift])
    +		let key = characters?.lowercased()
    +		if exact == [.command], keyCode == 13 || key == "w" {
    +			return true
    +		}
    +		if exact == [.command, .control], keyCode == 3 || key == "f" {
    +			return true
    +		}
    +		if exact == [.command], keyCode == 45 || key == "n" {
    +			return true
    +		}
    +		return false
    +	}
    +
    +	private static func installRefusalMonitor() {
    +		guard refusalMonitor == nil else { return }
    +		refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
    +			if WritingLockState.active?.isLocked == true,
    +			   Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags)
    +			{
    +				return nil // swallowed — the lock holds
    +			}
    +			return event
    +		}
    +	}
    +
    +	private static func removeRefusalMonitor() {
    +		if let refusalMonitor {
    +			NSEvent.removeMonitor(refusalMonitor)
    +		}
    +		refusalMonitor = nil
    +	}
    +}
    +
    +/// #162: quit mid-block asks once — #163's ruling (2026-11-04, live
    +/// dogfood): self-aware friction, not silence. Every quit path (⌘Q, the
    +/// Quit menu, AppleEvents) routes through `applicationShouldTerminate`;
    +/// unlocked quits proceed, a held block gets ONE modal ask — walk away
    +/// (the block dies quietly with the process, nothing kept — #158 settle
    +/// 3) or keep writing.
    +@MainActor
    +final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
    +	func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
    +		guard WritingLockState.active?.isLocked == true else { return .terminateNow }
    +		let alert = NSAlert()
    +		alert.messageText = "Walk away from the block?"
    +		alert.informativeText = "A Cold Turkey block is still running. Quitting ends it — nothing is kept, no record."
    +		alert.addButton(withTitle: "Walk Away")
    +		alert.addButton(withTitle: "Keep Writing")
    +		let walkAway = alert.runModal() == .alertFirstButtonReturn
    +		if walkAway {
    +			// Belt: the process is about to die; clear the kiosk + monitor
    +			// so nothing lingers through the termination dance.
    +			WritingLockKiosk.exit(toggledFullscreen: false)
    +			return .terminateNow
    +		}
    +		return .terminateCancel
    +	}
    +}
    diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift
    index 0703998..98b46cf 100644
    --- a/MuseionTests/ACPClientTests.swift
    +++ b/MuseionTests/ACPClientTests.swift
    @@ -16,8 +16,8 @@
     // files build rigs on it) + the client/model suites that pin its contract.
     
     import Foundation
    -import SwiftUI
     @testable import Museion
    +import SwiftUI
     import Testing
     
     // MARK: - Fake ACP server + helpers
    diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
    index 713bb09..43984a7 100644
    --- a/MuseionTests/AGENTS.md
    +++ b/MuseionTests/AGENTS.md
    @@ -25,6 +25,7 @@ Owned by the root AGENTS.md contract.
     - `PostStorePassTests.swift` (#147 split — PostStoreTests crossed its file-length ceiling; MicropubTests → MicropubModelTests precedent; shared helpers stay in PostStoreTests.swift) — the pass-adjacent write sides: **#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`.
     - `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
     - `WritingGoalTests.swift` (#161, Cold Turkey S1 — scenario header at file top, `@Suite("WritingGoalTests")`; BARE `@Suite` is stripped by this repo's swiftformat — always give the attribute its string argument) — the goal engine's 11 pins: arm baseline + zero net, exact-target completion (499 ≠ met), delete-below-baseline (net −2, progress clamps 0), 2000-word paste counts in full, undo-to-baseline nets zero, words-goal ignores the clock (`secondsRemaining` nil), minutes deadline boundary (−1 s not met, on-the-second met, remaining 60/0), minutes-goal ignores words + deadline immovable, an absurd `.minutes(.max)` never traps the countdown (the Int-seam clamp pin — flip-verified), tokenizer parity with DraftStats ("writer's" 2 / "writer's note" 3 / headings count / digits count / punctuation-only 0), and the `progress(now:)` fractions for both goal kinds.
    +- `WritingLockTests.swift` (#162, Cold Turkey S2 — scenario header at file top, `@Suite`; machine tests `@MainActor`) — the lock machine's pins: words block completes on the tick after the target lands (note "2 words · 14:02"), minutes block completes exactly on the deadline tick and not a second early, deleting below baseline keeps the hold, a second start while locked is refused (armedAt unchanged), feed/tick at rest are no-ops; the #160 contract shapes — readout (words net "212 / 500", countdown "13:27 left"), clock spans (mm:ss under an hour, h:mm:ss above), near-goal at the 0.8 boundary, completion note text, arm scales (250/50/1…1000, 5/5/1…60 + clamps — 2026-11-04 amendments: what's typed is what arms, ceilings 1000 words / 60 min); the #159 recipe — `WritingLockKiosk.lockOptions` equals the 7-bit set; the canArm mirror over `makeModelHome` (nothing open false, prose draft true, outline draft false, prose piece true + `editorBodyText` reads its disk body, outline piece false — scan-poll waited so the routing reads the real type) and the external-guest pins; and the lock ⇒ focus invariant (`AppGateState.startWritingLock` forces `isFocused` and runs the block over the open draft). the refusal key set (keyCode + exact modifiers + lowercased character net — layout/Caps-Lock cases), `ArmScale.parse` (garbage/empty/overflow → default), the #111 mixed-outline guard hold disarming canArm, and the quit delegate's unlocked pass-through. Kiosk calls no-op under hosted tests by construction — never pinned by driving them. Machine tests pass `spawnsTicker: false` (the real 1 s ticker could complete a met goal before an injected tick under a >1 s main-actor stall — the #30/#147 flake family).
     - `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `![alt]()` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
     - `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
     - `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
    diff --git a/MuseionTests/WritingLockTests.swift b/MuseionTests/WritingLockTests.swift
    new file mode 100644
    index 0000000..2f6ff55
    --- /dev/null
    +++ b/MuseionTests/WritingLockTests.swift
    @@ -0,0 +1,265 @@
    +//
    +//  WritingLockTests.swift
    +//  MuseionTests
    +//
    +//  #162 (Cold Turkey S2, map #158): the writing lock's machine + contract
    +//  facts. Scenario: arm the state machine over small bodies with injected
    +//  clocks and drive the decisive ticks by hand (the 1 s ticker's real-now
    +//  ticks can never fire first — deadlines are minutes out); the arm
    +//  scales, readout shapes, kiosk recipe, and the canArm mirror of the
    +//  editor branch are pinned against the #160 contract render and the
    +//  #159 factsheet. Kiosk calls no-op under hosted tests by construction.
    +//
    +
    +import AppKit
    +@testable import Museion
    +import Testing
    +
    +@Suite("WritingLockTests")
    +struct WritingLockTests {
    +	// MARK: - Machine
    +
    +	@Test @MainActor
    +	func `a words block completes on the tick after the target lands`() {
    +		let lock = WritingLockState()
    +		let arm = Date()
    +		lock.start(goal: .words(2), body: "one two", at: arm, spawnsTicker: false)
    +		#expect(lock.isLocked)
    +		#expect(lock.run?.baselineWords == 2)
    +		#expect(!lock.showsArmBar) // Start consumed the bar
    +
    +		lock.feed(text: "one two three four") // net +2 — met
    +		lock.tick(at: arm.addingTimeInterval(842))
    +		#expect(!lock.isLocked)
    +		#expect(lock.run == nil)
    +		#expect(lock.completionNote == "2 words · 14:02")
    +	}
    +
    +	@Test @MainActor
    +	func `a minutes block completes exactly on the deadline tick and not a second early`() {
    +		let lock = WritingLockState()
    +		let arm = Date()
    +		lock.start(goal: .minutes(30), body: "", at: arm, spawnsTicker: false)
    +		lock.tick(at: arm.addingTimeInterval(1799))
    +		#expect(lock.isLocked)
    +		lock.tick(at: arm.addingTimeInterval(1800)) // inclusive boundary
    +		#expect(!lock.isLocked)
    +		#expect(lock.completionNote == "30 min · 30:00")
    +	}
    +
    +	@Test @MainActor
    +	func `deleting below baseline keeps the hold — the count is net`() {
    +		let lock = WritingLockState()
    +		let arm = Date()
    +		lock.start(goal: .words(5), body: "one two", at: arm, spawnsTicker: false)
    +		lock.feed(text: "one") // net −1
    +		lock.tick(at: arm.addingTimeInterval(10))
    +		#expect(lock.isLocked) // deleting costs — no completion
    +		lock.feed(text: "one two three four five six seven eight")
    +		lock.tick(at: arm.addingTimeInterval(11))
    +		#expect(!lock.isLocked)
    +	}
    +
    +	@Test @MainActor
    +	func `a second start while locked is refused`() {
    +		let lock = WritingLockState()
    +		let arm = Date()
    +		lock.start(goal: .words(10), body: "seed", at: arm, spawnsTicker: false)
    +		lock.start(goal: .minutes(180), body: "seed", at: arm.addingTimeInterval(99), spawnsTicker: false)
    +		#expect(lock.isLocked)
    +		#expect(lock.run?.goal == .words(10))
    +		#expect(lock.run?.armedAt == arm) // one block per moment — unchanged
    +	}
    +
    +	@Test @MainActor
    +	func `feed and tick at rest are no-ops`() {
    +		let lock = WritingLockState()
    +		lock.feed(text: "anything")
    +		lock.tick(at: Date())
    +		#expect(!lock.isLocked)
    +		#expect(lock.run == nil)
    +		#expect(lock.completionNote == nil)
    +	}
    +
    +	// MARK: - Readout + note formatting (#160 contract)
    +
    +	@Test @MainActor
    +	func `readout shapes the words net and the minutes countdown`() {
    +		let arm = Date(timeIntervalSince1970: 1_000_000)
    +		var words = WritingGoalRun(goal: .words(500), armedAt: arm, body: "one two")
    +		#expect(WritingLockState.readout(words, now: arm).numerals == "0 / 500")
    +		#expect(WritingLockState.readout(words, now: arm).unit == "words")
    +		words.update(text: String(repeating: "word ", count: 212) + "one two")
    +		#expect(WritingLockState.readout(words, now: arm).numerals == "212 / 500")
    +
    +		let minutes = WritingGoalRun(goal: .minutes(30), armedAt: arm, body: "")
    +		let shape = WritingLockState.readout(minutes, now: arm.addingTimeInterval(30 * 60 - 807))
    +		#expect(shape.numerals == "13:27")
    +		#expect(shape.unit == "left")
    +	}
    +
    +	@Test
    +	func `clock spans minutes and hours`() {
    +		#expect(WritingLockState.clockString(seconds: 0) == "00:00")
    +		#expect(WritingLockState.clockString(seconds: 59) == "00:59")
    +		#expect(WritingLockState.clockString(seconds: 60) == "01:00")
    +		#expect(WritingLockState.clockString(seconds: 842) == "14:02")
    +		#expect(WritingLockState.clockString(seconds: 3600) == "1:00:00")
    +		#expect(WritingLockState.clockString(seconds: 3722) == "1:02:02")
    +	}
    +
    +	@Test
    +	func `near-goal fires inside the last twenty percent`() {
    +		#expect(!WritingLockState.isNearGoal(progress: 0.79))
    +		#expect(WritingLockState.isNearGoal(progress: 0.8))
    +		#expect(WritingLockState.isNearGoal(progress: 1))
    +		#expect(!WritingLockState.isNearGoal(progress: 0))
    +	}
    +
    +	@Test
    +	func `completion note names the goal and the elapsed`() {
    +		#expect(WritingLockState.completionNoteText(goal: .words(500), elapsed: 842) == "500 words · 14:02")
    +		#expect(WritingLockState.completionNoteText(goal: .minutes(30), elapsed: 1800) == "30 min · 30:00")
    +	}
    +
    +	// MARK: - Kiosk recipe + arm scales (#159 factsheet, #160 render)
    +
    +	@Test
    +	func `kiosk options are the factsheet recipe plus the corner switch`() {
    +		#expect(WritingLockKiosk.lockOptions == [
    +			.hideDock,
    +			.hideMenuBar,
    +			.disableProcessSwitching,
    +			.disableForceQuit,
    +			.disableSessionTermination,
    +			.disableHideApplication,
    +			.disableScreenCornerInteractions,
    +		])
    +	}
    +
    +	@Test
    +	func `arm scales carry the render's defaults ranges and clamps`() {
    +		let words = WritingLockState.ArmScale.words
    +		#expect(words.defaultValue == 250) // 2026-11-04 amendment: 250 words / 5 min
    +		#expect(words.step == 50)
    +		#expect(words.range == 1 ... 1000) // what's typed is what arms (2026-11-04 amendment)
    +		#expect(words.clamp(0) == 1)
    +		#expect(words.clamp(10) == 10) // the dogfood case — 10 words STAYS 10
    +		#expect(words.clamp(1001) == 1000)
    +
    +		let minutes = WritingLockState.ArmScale.minutes
    +		#expect(minutes.defaultValue == 5)
    +		#expect(minutes.step == 5)
    +		#expect(minutes.range == 1 ... 60)
    +		#expect(minutes.clamp(0) == 1)
    +		#expect(minutes.clamp(61) == 60)
    +	}
    +
    +	// MARK: - The canArm mirror (PostsModel)
    +
    +	@Test @MainActor
    +	func `canArmWritingLock gates on the open surface`() async throws {
    +		let (model, home) = try makeModelHome()
    +		#expect(!model.canArmWritingLock) // nothing open
    +
    +		model.newPost() // prose draft
    +		#expect(model.canArmWritingLock)
    +
    +		model.newOutline() // outline draft replaces it
    +		#expect(!model.canArmWritingLock)
    +
    +		// A prose piece on disk, opened as a session (wait for the scan so
    +		// the outline routing reads the real type, not the lagging list).
    +		let post = try PostStore.writeNew(body: "# Prose piece\n\nBody words.\n", home: home)
    +		try await Self.waitForScan(model, id: post.id)
    +		model.select(post.id, home: home)
    +		#expect(model.canArmWritingLock)
    +		#expect(model.editorBodyText == "# Prose piece\n\nBody words.\n")
    +
    +		let outline = try PostStore.writeNew(body: "- an outline\n", project: "posts", type: .outline, home: home)
    +		try await Self.waitForScan(model, id: outline.id)
    +		model.select(outline.id, home: home)
    +		#expect(!model.canArmWritingLock)
    +
    +		// A MIXED outline fires the #111 guard ask instead — the held
    +		// guard (no session, empty editor) must disarm too: the editor
    +		// branch's fourth path, pinned so the mirror can't drift.
    +		let mixed = try PostStore.writeNew(body: "- bullet\nprose between bullets\n", project: "posts", type: .outline, home: home)
    +		try await Self.waitForScan(model, id: mixed.id)
    +		model.select(mixed.id, home: home)
    +		#expect(model.outlineGuardPieceID == mixed.id)
    +		#expect(!model.canArmWritingLock)
    +	}
    +
    +	@Test @MainActor
    +	func `the external guest can arm and carries its live text`() throws {
    +		let (model, _) = try makeModelHome()
    +		let url = FileManager.default.temporaryDirectory
    +			.appendingPathComponent("guest-\(UUID().uuidString).md", isDirectory: false)
    +		try "# Guest words\n".write(to: url, atomically: true, encoding: .utf8)
    +		model.openExternal(url)
    +		#expect(model.canArmWritingLock)
    +		#expect(model.editorBodyText == "# Guest words\n")
    +	}
    +
    +	// MARK: - The lock ⇒ focus invariant (AppGateState)
    +
    +	@Test @MainActor
    +	func `startWritingLock forces focus and runs the block over the open draft`() {
    +		let gate = AppGateState()
    +		gate.posts.newPost()
    +		gate.posts.draft?.text = "seed words here"
    +		#expect(!gate.isFocused)
    +		gate.startWritingLock(goal: .words(2))
    +		#expect(gate.isFocused) // the invariant, settled at start
    +		#expect(gate.writingLock.isLocked)
    +		gate.writingLock.feed(text: "seed words here plus two more")
    +		gate.writingLock.tick()
    +		#expect(!gate.writingLock.isLocked)
    +	}
    +
    +	@Test
    +	func `the refusal key set matches key codes with the exact modifiers`() {
    +		// keyCode net: physical key, layout- and case-independent.
    +		#expect(WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command]))
    +		#expect(WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command, .control]))
    +		#expect(WritingLockKiosk.refusesKey(keyCode: 45, characters: nil, modifiers: [.command]))
    +		// character net: Caps-Lock case and plain text both match.
    +		#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "W", modifiers: [.command]))
    +		#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "f", modifiers: [.command, .control]))
    +		// near misses stay live: extra modifiers, wrong keys, bare letters.
    +		#expect(!WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command, .option]))
    +		#expect(!WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command]))
    +		#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "w", modifiers: []))
    +		#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "q", modifiers: [.command]))
    +	}
    +
    +	@Test
    +	func `arm parse falls to the default on garbage and overflow`() {
    +		let words = WritingLockState.ArmScale.words
    +		#expect(words.parse("10") == 10)
    +		#expect(words.parse("") == 250)
    +		#expect(words.parse("abc") == 250)
    +		#expect(words.parse("999999999999999999999999999999") == 250) // Int(String) nil on overflow, never traps
    +		#expect(words.parse("1001") == 1000)
    +		#expect(WritingLockState.ArmScale.minutes.parse("7") == 7)
    +	}
    +
    +	@Test @MainActor
    +	func `the quit delegate passes an unlocked app straight through`() {
    +		// The locked branch is a modal ask — unpinnable headless; the
    +		// unlocked path is the seam this pins.
    +		let delegate = WritingLockAppDelegate()
    +		#expect(delegate.applicationShouldTerminate(NSApplication.shared) == .terminateNow)
    +	}
    +
    +	/// Bounded poll for the watched scan to surface a piece (the
    +	/// PostsModelTests poll pattern — the FSEvents latency window).
    +	@MainActor
    +	private static func waitForScan(_ model: PostsModel, id: String) async throws {
    +		for _ in 0 ..< 200 where !model.posts.contains(where: { $0.id == id }) {
    +			try await Task.sleep(for: .milliseconds(10))
    +		}
    +		#expect(model.posts.contains(where: { $0.id == id }))
    +	}
    +}
    diff --git a/docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md b/docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md
    new file mode 100644
    index 0000000..871e8ea
    --- /dev/null
    +++ b/docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md
    @@ -0,0 +1,120 @@
    +# Build S2: Cold Turkey WritingLock — kiosk, chrome integration, unbroken typing
    +
    +> **Date:** 2026-11-04
    +> **Type:** issue
    +> **Reference:** [#162](https://git.babylondreams.de/AlexKucera/museion/issues/162) (map [#158](https://git.babylondreams.de/AlexKucera/museion/issues/158), work issue [#140](https://git.babylondreams.de/AlexKucera/museion/issues/140))
    +
    +## Goal
    +
    +The integration slice: wire the S1 goal engine (#161) and the #160 contract render into the app — `WritingLockState` (lock ⇒ focus invariant), the kiosk per the #159 factsheet, the arm-bar/readout/dot/note chrome, the refusals (⌥⌘F, focus exit, quit, ⌘W, new-buffer paths), and the hard AC: typing is never interrupted by the unlock transition.
    +
    +## What Was Done
    +
    +- **`Museion/WritingLockState.swift`** (new) — the machine (`WritingLockState`: start/feed/tick/complete, 1 s ticker, `completionNote` fading ~6 s, `static weak active` for the delegate), the kiosk (`WritingLockKiosk`: 6-option recipe + `.disableScreenCornerInteractions`, already-fullscreen handling, hosted-test no-op), and `WritingLockAppDelegate` (`applicationShouldTerminate → .terminateCancel` while locked).
    +- **`FocusChrome.swift`** grows the chrome lineage (map settle 6): `ColdTurkeySeat` (one bottom-center seat: arm-bar | readout | note), `ColdTurkeyArmBar` (bare mono, selector/steppers/Start, Esc via hidden `.cancelAction` button), `ColdTurkeyReadout` (numerals + 2 px hairline, terracotta @80 % inside the last 20 %), `ColdTurkeyNote`, `ColdTurkeyDot` (bottom-right pip, hover label).
    +- **`MuseionApp.swift`** — `@NSApplicationDelegateAdaptor(WritingLockAppDelegate.self)`; View ▸ Start Cold Turkey… (focus-gated, second path per #160); disabled-while-locked: Toggle Focus Mode (the refusal IS the lock), Toggle Reading Mode, New Post/Outline/Project, Open…, Import…; `AppGateState.writingLock` + `startWritingLock(goal:)` (settles the lock ⇒ focus invariant, baseline = `posts.editorBodyText`).
    +- **`WorkspaceView.swift`** — left-edge focus overlay suppressed while locked; window drop destination refuses while locked.
    +- **`PostsPaneView.swift`** — mentor hover reveal suppressed while locked; CT chrome mounted as overlays on the focused ZStack ONLY (lock transitions never restructure `editorColumn` — the #87 remount hazard); leaving focus drops a stale arm-bar.
    +- **`PostEditorView.swift`** — `ProseTextView.onTextChange` (both modes) feeds `gate.writingLock.feed(text:)` per keystroke.
    +- **`PostsModel.swift`** — `canArmWritingLock` (mirrors the editor branch's outline routing: prose drafts, the guest, prose posts; outline pieces never) + `editorBodyText` (live whole-document text of the surface being shown).
    +- **`GLOSSARY.md`** — the Cold Turkey entry (settle 7: glossary + UI).
    +- **`MuseionTests/WritingLockTests.swift`** (new) — 16 pins: machine transitions, contract shapes (readout/clock/near-goal/note/arm scales), the 7-bit kiosk recipe, the canArm mirror over `makeModelHome`, the guest pins, the lock ⇒ focus invariant.
    +- DOX pass: `Museion/AGENTS.md` (entry point, focus-mode, WorkspaceView/PostsPaneView/PostsModel bullets, WritingLockState bullet) + `MuseionTests/AGENTS.md`.
    +
    +## Decisions & Rationale
    +
    +| Decision | Rationale |
    +|----------|-----------|
    +| ⌘W refusal = NSEvent local monitor, not a menu replacement | `CommandGroupPlacement` has NO `.closeItem` on macOS SwiftUI (compile error, verified against the 27.2 swiftinterface) and SwiftUI owns the stock window delegate, so the #159 `windowShouldClose` delegate approach is unreachable. A local keyDown monitor (the OutlineDrag pattern — monitors run before menu key equivalents) swallows ⌘W only while locked; quiet, no dialog. |
    +| Quit refusal via `@NSApplicationDelegateAdaptor` | Every quit path (⌘Q, Quit menu, AppleEvents) routes through `applicationShouldTerminate` — the factsheet's exact claim, now in SwiftUI's world. The delegate reads `WritingLockState.active` (weak static set in init) instead of holding app-state wiring. |
    +| Chrome mounts as overlays on the focused ZStack only | Lock ⇒ focus never flips `isFocused`, so the branch structure under the editor column is FROZEN during lock/unlock — combined with the probe-verified fullscreen round trip (first-responder identity holds), the typing-continuity AC holds by construction, not by deferral machinery. |
    +| Feed = `ProseTextView.onTextChange`, baseline = `PostsModel.editorBodyText` | One keystroke, one rail: the coordinator already sees every edit (session + draft modes); the model already holds the live text. No new observation machinery (`withObservationTracking` avoided). |
    +| External guest CAN arm | "Posts + drafts, not Outline" settles the outline exclusion; the guest is a prose editing surface the engine counts fine — excluded, it would surprise mid-flow. Calibration gate can flip it with one guard. |
    +| Already-fullscreen windows enter the lock in place | `enter()` records whether WE toggled fullscreen; `exit()` replays only what entry toggled — arming from a fullscreen focus session neither exits nor double-toggles. |
    +| Menu item plain in the View group, not a Focus submenu | A one-item submenu is UI noise; the settle's "Focus ▸ Start Cold Turkey…" reads as a path, the render's caption language. One-line change if Alexander wants nesting. |
    +
    +## Gotchas & Fixes
    +
    +| Problem | Root Cause | Fix |
    +|---------|------------|-----|
    +| `CommandGroup(replacing: .closeItem)` failed to compile | No such placement in macOS SwiftUI 27.2 | Local key monitor (see decisions) |
    +| `nonisolated enum ArmScale` with stored properties | Enums can't have stored properties | `nonisolated struct` with static instances |
    +| deinit couldn't cancel `ticker`/`noteFade` | Swift 6 deinit is nonisolated; the props are MainActor | Deleted the deinit — the tasks hold `weak self` and self-terminate on the next guard |
    +| Switch-expression form tripped `#NoUsage` warnings | New-diagnostic pedantry on tuple/string cases | Plain `switch` + `return` statements |
    +| Test build failed on `.hideDock` statics | MemberImportVisibility — test file lacked `import AppKit` | Added the import |
    +| `lockOptions` unreadable from nonisolated test context | The enum is `@MainActor` | `nonisolated static let` (immutable Sendable data) |
    +| 1 test failure: `words.clamp(4999) == 5000` | MY expectation was wrong — 4999 is in-range; clamp is identity there (steppers stay on the 50-grid) | Fixed the pin: `clamp(4999) == 4999`, added `clamp(5001) == 5000` |
    +| swiftlint error: variable `s` | identifier_name min length in `clockString` | Renamed `total` |
    +
    +## Files Changed
    +
    +| File | Change Summary |
    +|------|---------------|
    +| `Museion/WritingLockState.swift` | NEW — lock machine, kiosk recipe, quit-refusal delegate |
    +| `Museion/FocusChrome.swift` | The CT chrome lineage (seat/arm-bar/readout/note/dot) |
    +| `Museion/MuseionApp.swift` | Delegate adaptor, CT menu item, locked-state refusals, `startWritingLock` |
    +| `Museion/WorkspaceView.swift` | Overlay + drop-destination lock suppression |
    +| `Museion/PostsPaneView.swift` | Mentor-overlay suppression, CT chrome mounts |
    +| `Museion/PostEditorView.swift` | `onTextChange` feed through both editor modes |
    +| `Museion/PostsModel.swift` | `canArmWritingLock` + `editorBodyText` |
    +| `GLOSSARY.md` | Cold Turkey entry |
    +| `MuseionTests/WritingLockTests.swift` | NEW — 16 pins |
    +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass |
    +| `MuseionTests/ACPClientTests.swift` | swiftformat-only import reorder (repo-wide pass caught a pre-existing drift) |
    +
    +## Verification
    +
    +- Build: `xcodebuild … build` — **SUCCEEDED**.
    +- Suite: `xcodebuild … test` — **617 executed / 617 passed / 0 failed**, counted in the xcresult (`Test-Museion-2026.11.04_13-14-24-+0100.xcresult`), never the banner. Baseline was 601 (#161) — +16 new tests.
    +- swiftformat 0 files dirty; swiftlint 0 errors in `Museion/` + `MuseionTests/` (the remaining error-level findings are pre-existing `spike/` territory).
    +- GitNexus: impact analysis ran before edits (all touched symbols roll up to `WorkspaceView.paneContent`, LOW risk); `detect_changes` after — only the intended files.
    +
    +## Open Items & Next Steps
    +
    +- [ ] [#163 Calibration gate](https://git.babylondreams.de/AlexKucera/museion/issues/163) — now unblocked: does the lock rule calm? Live dogfood needed (fullscreen entry/exit, ⌘Tab/⌘Q/⌘W refusals, typing through unlock, the readout's near-goal shift) — the unpinnable-window surfaces.
    +- [ ] Landing: the slice sits as an uncommitted working tree (map rule — no autonomous commits); landing on `main` needs Alexander's go.
    +- [ ] Fog (map #158): preset chips + keyboard arming stay post-calibration; the S5.1 auto-capture tie-in revisits after the gate.
    +- [ ] Accepted edge: the Fix Cards palette window (if open when the lock starts) is a separate space — not covered by the kiosk; the calibration gate can flag it if it ever matters.
    +
    +---
    +
    +*Log written by write-log skill*
    +
    +## Amendment — same day, live dogfood ruling
    +
    +Alexander ran the arm-bar and ruled (screenshot `media_9rFtnT7oxx`): the bare seat let the document text show through and obscure the controls. Three changes:
    +
    +1. The arm-bar carries a **blending chip** — the focus ground's own color, the faintest token hairline (`DesignTokens.border`), no shadow. Ruling 1 of #160 corrected for the arm-bar only; readout + note stay bare (judged at #163).
    +2. The arm value is **directly typeable** (plain `TextField`, parsed + clamped at every read — Start, steppers, submit — so garbage or unsubmitted text can never arm an out-of-range block); ± steppers stay for coarse moves.
    +3. Defaults amended: **250 words / 5 minutes** (were 500/30).
    +
    +Recorded: comment on #160 (the ruling's home), map #158's decision line amended, arm-scales pin updated.
    +
    +
    +## Amendment 2 — same day, second dogfood round
    +
    +1. **Ranges**: what's typed is what arms — words 1…1000, minutes 1…60 (were floors 50/5, ceilings 5000/180; the clamp had bumped a typed 10 up to 50). Floor 1; empty/garbage falls to the default.
    +2. **The "escape" trap**: mid-block ⌃⌘F toggled fullscreen off — the kiosk options hold even windowed (#159's own finding), leaving a windowed kiosk (no menu bar, ⌘W/⌘Q refused) that reads as "escaped" while the block still runs. Fix: the refusal monitor now swallows ⌃⌘F while locked too — fullscreen leaves only via completion. Remaining open doctrine (flagged to #163): a words block that outlives intent has NO exit — quit is refused by design; minutes blocks self-complete ≤ 60 min.
    +3. **Readout + completion note** carry the arm-bar's blending chip (same occlusion over document text).
    +
    +617/617 green (xcresult `Test-Museion-2026.11.04_14-36-55`), lint clean.
    +
    +
    +## Amendment 3 — the quit valve (#163 ruling, same day)
    +
    +⌘Q mid-block now asks once (Alexander's pick from three options): a modal "Walk away from the block?" — Walk Away clears the kiosk and terminates (the block dies quietly, nothing kept); Keep Writing cancels. Unlocked quits pass through untouched. Pinned: the delegate's unlocked path returns `.terminateNow` (the locked branch is a modal — unpinnable headless). 618/618 green (xcresult `Test-Museion-2026.11.04_14-41-55`).
    +
    +
    +## Finish audit (same day)
    +
    +Three-reviewer fanout (ponytail / security / general) over the session tree. Accepted and landed:
    +
    +- **Key-match predicate** (converged MEDIUM, both reviewers): `charactersIgnoringModifiers == "w"` missed Caps-Lock ("W") and non-Latin layouts while AppKit's menus still fired the stock Close → windowless kiosk. Now `refusesKey(keyCode:characters:modifiers:)` matches by physical key code (13/3/45 = W/F/N) with the exact modifier intersection, plus a lowercased character net; ⌘N added (the stock New Window item SwiftUI owns stays enabled mid-lock). Pinned ×9, flip-verified.
    +- **Ticker flake** (general MEDIUM): machine tests pass `spawnsTicker: false` — the real 1 s ticker could complete a met words goal before the injected tick under a main-actor stall.
    +- **Ponytail**: `blendingChip()` dedup (3 sites), model-side `withAnimation` dropped (double fade curve).
    +- **General LOWs**: pane change clears a pending arm-bar (WorkspaceView `onChange(of: selection)`); kiosk captures the ENTERED window for exit; `ArmScale.parse` extracted + pinned (garbage/empty/overflow → default); the #111 mixed-outline guard hold pinned as a canArm disarm.
    +
    +Deferred: ⌘Q modal re-entrancy oddity (idempotent by construction, both reviewers concur); `active` last-wins (latent, fail-open — a DEBUG assert would fire in hosted tests); `DraftStats.words` lowercased-array alloc per keystroke while locked (#161 committed code, out of scope — noted for #163 dogfood).
    +
    +Verification: 620/620 (xcresult `Test-Museion-2026.11.04_15-14-07`, +2 suites), flip cycle failed each pin on its own guard exactly, swiftformat/swiftlint clean.
    +
    diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md
    index a3e86bb..7949c77 100644
    --- a/docs/devlog/INDEX.md
    +++ b/docs/devlog/INDEX.md
    @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
     
     | Date | Type | File | Summary |
     |------|------|------|---------|
    +| 2026-11-04 | issue | [20261104-issue162-cold-turkey-writing-lock-integration_log.md](20261104-issue162-cold-turkey-writing-lock-integration_log.md) | #162: WritingLockState + kiosk + chrome wired; typing AC by construction; ⌘W via key monitor (no .closeItem); 617/617 green |
     | 2026-11-04 | issue | [20261104-issue161-cold-turkey-goal-engine_log.md](20261104-issue161-cold-turkey-goal-engine_log.md) | #161: pure goal engine — WritingGoal enum + run struct, DraftStats.words rail, injected now, 10 pins; 601/601 green |
     | 2026-11-04 | issue | [20261104-issue160-cold-turkey-contract-render_log.md](20261104-issue160-cold-turkey-contract-render_log.md) | #160: contract render ruled — bare mono surfaces, hairline readout, no title, fade ~6s, arming amended dot-first (corner dot) |
     | 2026-11-04 | issue | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](20261104-issue156-mentor-pane-chrome-editorial-voice_log.md) | #156: pane chrome — serif header + green ready dot, mode picker dead (selector + status line), MonoButton actions, crash/starting cards editorial |