From cbe16f0442c1fb059ad88e98da1b11c689935be9 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Thu, 19 Nov 2026 13:18:26 +0100 Subject: [PATCH] docs(issue-200): log, changelog, AGENTS contracts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Session log + INDEX row + rolling window, CHANGELOG Fixed entry, and the #200 quit-gate contracts in the Museion/AGENTS.md chain (delegate's two refusals, PostsModel shutdown/active, gate family, wiring) plus the MuseionTests suite map rows — including the PR #198 gap (PostsModelDepartureTests had never been listed) and the gitnexus index-count refresh. --- AGENTS.md | 4 +- CHANGELOG.md | 2 + Museion/AGENTS.md | 8 +- MuseionTests/AGENTS.md | 3 +- ...time-flushes-through-departure-gate_log.md | 99 +++++++++++++++++++ docs/devlog/INDEX.md | 1 + 6 files changed, 110 insertions(+), 7 deletions(-) create mode 100644 docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md diff --git a/AGENTS.md b/AGENTS.md index 404faf7..930a1f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,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** (7072 symbols, 36395 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** (7133 symbols, 36787 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). @@ -217,6 +217,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | | --- | --- | +| 2026-11-19 | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) | | 2026-11-17 | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | | 2026-11-17 | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | | 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | @@ -226,5 +227,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-11-11 | [20261111-fix-library-search-stale-after-mutation_log.md](docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md) | | 2026-11-10 | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](docs/devlog/20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) | | 2026-11-10 | [20261110-issue182-profilelayout-config-set-rail_log.md](docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md) | -| 2026-11-10 | [20261110-issue181-provider-descriptor-pass-readiness_log.md](docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index e203f10..65516ed 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 ### Fixed +- **editor:** Quit no longer bypasses the document departure gate (#200, follow-up to the #198 audit) — `PostsModel.shutdown()` flushed both sessions best-effort and ignored the results, so quitting with an unanswered reload-conflict alert wrote the local text over the foreign disk body (`flush()` holds for conflicts only in the debounce, never itself), and a failed quit-time flush silently dropped the only copy of the edits. Quit now routes through the same departure gate as navigation (`documentsMayDepart` → `sessionMayDepart`): an unanswered conflict never writes over the foreign body, and the failed-flush-at-quit posture is BLOCK QUIT — `WritingLockAppDelegate.applicationShouldTerminate` refuses termination with one spoken reason (running before the Cold Turkey ask, so a refusal never strands a walked-away block), pinned at the pure `quitReply(posts:)` seam. Finish-audit additions: a never-loaded session's retyped words refuse too (their flush is a vacuous success — the same gap closed for navigation), and the external guest's quit-time flush is pinned. +5 tests, all flip-verified. Suite 708 + - **acp:** Engine backpressure can no longer defeat request deadlines, Stop, or teardown (finding `museion/acp-backpressure-defeats-timeout-and-shutdown`, argus cycle-4) — a hung engine that stops reading stdin fills the 64 KB pipe, and the ACP client's synchronous send blocked its ONE serial queue, the same queue carrying request-id allocation, pending registration, the timeout deadline, and close()'s bookkeeping barrier: the deadline never fired (a 0.1 s timeout on a 2 MB prompt stayed pending forever), a follow-up request hung at registration, Stop queued behind the stuck write, and close() synced behind it before SIGTERM was ever reachable — on MainActor (restart/quit) that was an app-wide unbounded hang. Stdin writes (and the stdin handle's own close, which a blocked write may still own) now ride a dedicated serial writer queue, leaving the state queue I/O-free: deadlines fire, Stop is accepted, bookkeeping answers, and close() runs SIGTERM → grace → SIGKILL → reap without queueing behind the writer. Wire order preserved (every send funnels through the one serial writer); healthy-engine contract untouched. +4 real-process smokes over two new zsh-fake modes (`neverRead` execs /bin/sleep — the probe's inert non-reading child, never a real profile; `serverPing` pins -32601 reply delivery): 3 RED-first at base on exactly the three mechanisms, healthy-contract pin green at base. Suite 697 (unticketed fix, brief-27) - **search:** Library search results no longer go stale after library writes (finding `museion/library-search-stale-after-mutation`, the #144/#157 mounted gap) — the search snapshot's only task identity was the trimmed query, so nothing re-ran the sweep when the library moved underneath it: archiving or trashing a piece from a result row's own context menu left it sitting in the non-archived results after the rescan, and new, renamed, or externally edited pieces never entered or left the results until the query changed or the pane remounted. The #179 write rail's rescan now bumps a content revision whenever a scan sees the library change — a Post-list change OR any re-read post.md, so a body-only edit (which parses to an equal Post and is invisible to #143's equality-gated assignment) counts — and the mounted sweep keys on query + Home + that revision, rendering a landed snapshot only while it stays fresh for the current key (stale rows drop to the recompute spinner; panes never regroup — the assignment skip is untouched). +5 tests (pure key/gate pin; controller-level archive, trash, and same-query body-edit pins over the real rescan rail, red-first; an unchanged-rescan guard). Suite 686 diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index c1f0edb..0bfd909 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -35,15 +35,15 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `![alt](assets/…)` builder. - `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift). - `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets). -- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. +- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. `WritingLockAppDelegate` (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — `quitReply(posts:)` is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk. - `TrendsPaneView.swift` — per-metric line charts over first-draft captures; only pieces with `firstDraftStats` appear (the view answers "am I getting better", never "is this draft good"); one capture shows a value, no verdict. `TrendMetric` (pure): fixed y-domains (burstiness −1…1, TTR + trigram 0…1, sentenceVariation scaled to 1.2× peak, floor 1), verdict at ±0.01 (trigram inverted), one explain line per metric. - `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress). - `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4). - `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends. - Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept. -- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). +- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register. - `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail. -- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive). +- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive). - `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal`/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`). - `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID. - `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load. @@ -87,7 +87,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p `; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown. - `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable). - `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm). -- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). +- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop). ## Work Guidance diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 78bbc21..7881c91 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -37,7 +37,8 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness). - `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates). - `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts. -- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them). +- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded. +- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap). - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. - `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay. - `FixCardApplyTests` — fix-card apply/skip/done lifecycle. diff --git a/docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md b/docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md new file mode 100644 index 0000000..ae3bd7a --- /dev/null +++ b/docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md @@ -0,0 +1,99 @@ +# #200 — Gate quit-time flushes through the departure gate + +> **Date:** 2026-11-19 +> **Type:** issue +> **Reference:** AlexKucera/museion#200 (follow-up from the PR #198 finish audit) + +## Goal + +Quitting was the one document departure that bypassed the brief-25 gate: +`PostsModel.shutdown()` flushed both sessions best-effort and ignored the +results. Two harms: quitting with an unanswered #67 conflict wrote local text +over the foreign disk body (`flush()` holds for conflicts only in the debounce, +not itself — the #114 harm), and a failed quit-time flush silently dropped the +only copy of the edits. Deliver the conflict hold at quit, plus an explicit +pinned product decision for the failed-flush-at-quit posture. + +## What Was Done + +- `PostsModel.shutdown()` (PostsModel.swift) now routes both sessions through + the departure gate via `documentsMayDepart()` and is `void` — the verdict + channel is `quitReply`'s, at `applicationShouldTerminate` (finish-audit + ponytail finding: a `-> Bool` shutdown had no production reader). +- `documentsMayDepart()` (PostsModelWrites.swift, beside `sessionMayDepart` / + `departOpenDocuments`): the gate's quit run — external guest then post + session, both through `sessionMayDepart`, no early exit (a clean sibling + still saves while a conflicted one holds). +- BLOCK-QUIT at `WritingLockAppDelegate.applicationShouldTerminate` + (WritingLockState.swift): new pure seam `quitReply(posts:)` (nil model + passes; the pins inject here) runs BEFORE the Cold Turkey lock ask — never + walk away from a block the quit then refuses to complete. The refusal + speaks once via a hosted-guarded alert (startLaunchCheck/kiosk convention) + naming `lastError`. +- `PostsModel.active` weak static (the `WritingLockState.active` + reachability precedent), registered ONLY by `AppGateState.init` + (MuseionApp.swift) — bare test rigs never register, so parallel suites + can't flake the delegate through the static. +- Finish-audit fixes: `sessionMayDepart` refuses a never-loaded session's + retyped words (`loadFailed && saveState == .changed` — its `flush()` is a + vacuous success; the security reviewer's LOW data-loss gap, closed for quit + AND navigation at the one shared seam); guest quit-flush pin added (the + guest leg of `documentsMayDepart` was unpinned — deleting it kept the rail + green). +- Pins (5 total): conflict hold at shutdown (foreign body on disk, byte + unchanged), clean dirty session flushes, guest flushes, never-loaded + refusal (PostsModelDepartureTests), delegate refusal/proceed across all + phases incl. chmod-injected flush failure (WritingLockTests). +- DOX: Museion/AGENTS.md (WritingLock delegate bullet, PostsModel bullet, + PostsModelWrites bullet, Wiring bullet), MuseionTests/AGENTS.md suite map + (also added the PR #198 gap: PostsModelDepartureTests had never been + listed). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| BLOCK QUIT (vs silently drop / rescue file) | The ticket's three options. Drop keeps the audited harm; rescue strands a buffer in a recovery file with no discovery UX. Block quit reuses both existing seams (`sessionMayDepart` + the `applicationShouldTerminate` refusal precedent) and is the only posture that never silently destroys the only copy — "edits land or the departure aborts" extended to termination. | +| `quitReply(posts:)` injectable pure seam, static written only by `AppGateState.init` | The delegate needs model reachability (`WritingLockState.active` precedent), but a static written by every `PostsModel` init would let parallel test rigs flake the delegate pin. Registration at the real construction site keeps hosted tests deterministic; pins inject the model directly. | +| Gate before the Cold Turkey ask | Refusing AFTER "walk away" would strand a walked-away block in a still-running app. | +| Never-loaded guard in `sessionMayDepart` (not in `flush()` or callers) | The vacuous success is `flush()`'s correct safety rule (a failed read must never become a destructive write); the gap is the gate trusting it. One guard at the shared seam closes quit AND navigation. | +| `shutdown()` void, willTerminate stays as belt | The belt double-flush is idempotent (clean no-op); the Bool return had no production reader. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Flip cycle: the guest pin passed with its guard "off" | The `, false` suffix on `if let guest = externalSession, !sessionMayDepart(guest), false` still CALLS `sessionMayDepart` — the flush is a side effect inside the condition, so the pin's observable survived; only the verdict assignment was skipped | Flip by deleting the block, which models the actual threat ("the leg is gone"); then the pin failed by name. Restore re-inserted the block byte-exact. | +| `git log` piped output hid merge commits / phantom staged file | The rtk terminal wrapper mangles piped git output (known trap) | Settled facts with `git show -s --format`, `git diff --cached --name-only` direct reads, and count-only greps. | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostsModel.swift` | `shutdown()` void + routes through the gate; `PostsModel.active` weak static | +| `Museion/PostsModelWrites.swift` | `documentsMayDepart()`; never-loaded guard in `sessionMayDepart` | +| `Museion/WritingLockState.swift` | `quitReply(posts:)` pure seam; gate-first quit; hosted-guarded refusal alert | +| `Museion/MuseionApp.swift` | `AppGateState.init` registers `PostsModel.active` | +| `MuseionTests/PostsModelDepartureTests.swift` | 5 quit-time pins (conflict, clean, guest, never-loaded + navigation family) | +| `MuseionTests/WritingLockTests.swift` | Delegate pin: refuses while a piece can't depart, proceeds once it can | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass (quit-gate contracts, suite map) | + +## Open Items & Next Steps + +- [ ] #201 (consented brief-25 AGENTS.md sentences) — open, promoted, next in line. +- [ ] Follow-ups from PR #198's audit are otherwise exhausted. + +## Verification + +- Full verify rail (`./scripts/full-test.sh`): **708 executed / 708 passed / + 0 failed** (706 pre-audit + the 2 audit pins), xcodebuild exit 0. +- swiftformat 0/150 reformatted; swiftlint 0 violations in 139 files. +- Finish-audit flips: both new pins fail by name on their guards + (loadFailed `, false` suffix; guest-leg block deletion), 8 siblings green, + restored byte-exact, 28/0 on both suites post-restore. +- GitNexus: analyze 7,134 nodes; detect-changes HIGH = the gate's deliberate + fan-in (every departure flow), all affected flows covered by the rail. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 1df0b52..29dc47a 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-19 | fix | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) | Quit routes through the departure gate (#200): conflict-held shutdown, BLOCK-QUIT at applicationShouldTerminate, never-loaded-retype guard; finish-audit fixes; rail 708/708 | | 2026-11-17 | fix | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) | Unticketed fix (brief-27, argus cycle-4): stdin writes move to a dedicated writer queue — engine backpressure can no longer defeat the request deadline, Stop, or a bounded reaping close; neverRead/serverPing fake modes, 3 RED-first smokes + healthy-contract pin, suite 697/697 | | 2026-11-17 | issue | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | Three most-re-read files split into 8 domain-extension files, move-only (three audits concur); 693/693 | | 2026-11-17 | issue | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | Root gate-running learnings collapse into the full-test.sh pointer; 8 deletions mapped to script/hook behavior; authoring rules retained; 693/693 |