feat(home): pin iCloud Home for fresh installs (#171)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
With no stored Home override, launch resolves once and PINS the winner, so the Home never silently moves: a legacy ~/Documents/Museion directory wins (existing Homes migrate manually, never silently), else <CloudDocs>/Museion when iCloud Drive is present (dynamically resolved unprefixed path, plain FileManager — no ubiquity entitlements, ADR-0009), else the silent Documents fallback. Repoint-only stands (ADR-0004), zero mover code. The ladder + probes live in HomeResolution.swift (own file — MuseionApp.swift stays under the lint line cap); init takes an injectable probe/defaults seam, and default constructions under hosted tests take an early return so the runner app's real iCloud state and defaults are never touched. 9 seam-driven tests replace the old default-Home pin; implement + finish-audit reviews landed the legacy-probe dir gate, the non-destructive hosted no-write guard, and the flip-verified CloudDocs spelling pin. Suite 628/628 (xcresult executed count). DOX: Museion/AGENTS.md, MuseionTests/AGENTS.md, GLOSSARY.md; devlog + INDEX + CHANGELOG. Closes #171 Co-Authored-By: Cipher <cipher@hermes.local>
This commit is contained in:
1 parent
c485cfac60
commit
ad021b5267
10 files changed
+282
-34
No files matched your search
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
|
|||||||
<!-- gitnexus:start -->
|
<!-- gitnexus:start -->
|
||||||
# GitNexus — Code Intelligence
|
# GitNexus — Code Intelligence
|
||||||
|
|
||||||
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.
|
This project is indexed by GitNexus as **museion** (6347 symbols, 27802 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).
|
> 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).
|
||||||
|
|
||||||
@@ -201,14 +201,15 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
|||||||
<!-- write-log: window-start -->
|
<!-- write-log: window-start -->
|
||||||
| Date | Log |
|
| Date | Log |
|
||||||
|------|-----|
|
|------|-----|
|
||||||
| 2026-11-04 | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) |
|
| 2026-11-05 | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](docs/devlog/20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) |
|
||||||
| 2026-11-04 | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) |
|
| 2026-11-04 | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](docs/devlog/20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) |
|
||||||
| 2026-11-04 | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) |
|
| 2026-11-04 | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](docs/devlog/20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) |
|
||||||
| 2026-11-04 | [20261104-issue163-cold-turkey-calibration-gate-calm_log.md](20261104-issue163-cold-turkey-calibration-gate-calm_log.md) |
|
| 2026-11-04 | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](docs/devlog/20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_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-issue163-cold-turkey-calibration-gate-calm_log.md](docs/devlog/20261104-issue163-cold-turkey-calibration-gate-calm_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-issue162-cold-turkey-writing-lock-integration_log.md](docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_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-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_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-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_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-04 | [20261104-issue156-mentor-pane-chrome-editorial-voice_log.md](docs/devlog/20261104-issue156-mentor-pane-chrome-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-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) |
|
||||||
<!-- write-log: window-end -->
|
<!-- write-log: window-end -->
|
||||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
- **home:** Fresh installs default to iCloud (#171, resolution of #170/map #167 — plain build slice for #145) — with no stored Home override, launch resolves once and PINS the winner so the Home never silently moves: a legacy `~/Documents/Museion` directory wins (existing Homes migrate manually, never silently; a stray plain file is not a Home and falls through), else `<CloudDocs>/Museion` when iCloud Drive is present (dynamically resolved unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path, plain FileManager probing — no ubiquity entitlements per ADR-0009), else the silent Documents fallback. No dialog, no rail pill — Settings just shows the resolved path. Repoint-only stands (ADR-0004), zero mover code. The probe/defaults seam is injectable and default constructions under hosted tests neither probe nor pin — the runner app's real iCloud state and defaults are never touched. +9 tests incl. the flip-verified CloudDocs spelling pin and the non-destructive hosted no-write guard. Suite 628 (issue #171)
|
||||||
|
|
||||||
- **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:** 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)
|
- **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)
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@ The Agentic Writing Environment: a native macOS app where the writer, the text,
|
|||||||
### Content
|
### Content
|
||||||
|
|
||||||
**Museion Home**:
|
**Museion Home**:
|
||||||
The single root folder holding all Museion-owned content, learnings, and archive (`~/Documents/Museion` by default; repoint-only — Museion never moves content). One home per writer.
|
The single root folder holding all Museion-owned content, learnings, and archive (fresh installs pin `<CloudDocs>/Museion` when iCloud Drive is present, else `~/Documents/Museion`; an existing legacy `~/Documents/Museion` always wins — Homes migrate manually; repoint-only — Museion never moves content). One home per writer.
|
||||||
_Avoid_: workspace, vault; calling the whole library "a project"
|
_Avoid_: workspace, vault; calling the whole library "a project"
|
||||||
|
|
||||||
**Project**:
|
**Project**:
|
||||||
|
|||||||
+1
-1
@@ -43,7 +43,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
|||||||
- 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 <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` 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 igLine truncated
|
- 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 <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` 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 igLine truncated
|
||||||
- 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.
|
- 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 `<!--S:N-->` 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 <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, 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 `<pre>` (#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.
|
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` 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 <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, 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 `<pre>` (#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).
|
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`; non-file URLs read back as nil — the Home is always a folder). **#171:** fresh installs (no stored override) resolve once and PIN the winner, so the Home never silently moves: (2) legacy `~/Documents/Museion` exists as a directory (`existingDirectory` gate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3) `<CloudDocs>/Museion` when iCloud Drive is present (CloudDocs resolved dynamically at the unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path — never a hard-coded `iCloud~` form; plain FileManager probing, no ubiquity entitlements per ADR-0009), (4) else the silent Documents fallback — no dialog, no rail pill. The ladder + probes live in `HomeResolution.swift` (`resolvedInitialHome`/`liveCloudDocsDir`/`existingDirectory`); init takes injectable probes + defaults — hosted tests drive the ladder without touching the machine's real iCloud state, and the DEFAULT construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched. 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.
|
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
|
||||||
|
|
||||||
## Engine check (gateless launch, #35–#41 + #151, map #148)
|
## Engine check (gateless launch, #35–#41 + #151, map #148)
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
//
|
||||||
|
// HomeResolution.swift
|
||||||
|
// Museion
|
||||||
|
//
|
||||||
|
// #171: fresh-install Home resolution — the ladder + probes AppGateState
|
||||||
|
// pins through at first launch. Own file so MuseionApp.swift stays under
|
||||||
|
// the lint line cap (WritingLockState extraction precedent).
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
extension AppGateState {
|
||||||
|
/// The legacy default Home — `~/Documents/Museion` (#171: still the
|
||||||
|
/// fallback when iCloud is absent; b3daac9: Documents, not the account
|
||||||
|
/// root; TCC note in ADR-0004).
|
||||||
|
nonisolated static let defaultMuseionHome = FileManager.default.homeDirectoryForCurrentUser
|
||||||
|
.appendingPathComponent("Documents/Museion", isDirectory: true)
|
||||||
|
|
||||||
|
/// The stored override, if it decodes to a file URL (existing
|
||||||
|
/// semantics — the Home is always a folder).
|
||||||
|
nonisolated static func fileHomeURL(in defaults: UserDefaults) -> URL? {
|
||||||
|
defaults.string(forKey: "museionHome")
|
||||||
|
.flatMap(URL.init(string:))
|
||||||
|
.flatMap { $0.isFileURL ? $0 : nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #171: the fresh-install ladder — (2) a legacy `~/Documents/Museion`
|
||||||
|
/// (a real directory, per the default probe's `existingDirectory` gate —
|
||||||
|
/// the Home is always a folder) IS the Home (existing Homes migrate
|
||||||
|
/// manually, never silently),
|
||||||
|
/// (3) `<CloudDocs>/Museion` when iCloud Drive is present,
|
||||||
|
/// (4) else the silent Documents fallback. The stored override (1) is
|
||||||
|
/// checked by the caller.
|
||||||
|
nonisolated static func resolvedInitialHome(
|
||||||
|
legacyHomeExists: () -> Bool,
|
||||||
|
cloudDocsDir: () -> URL?,
|
||||||
|
) -> URL {
|
||||||
|
if legacyHomeExists() {
|
||||||
|
return defaultMuseionHome
|
||||||
|
}
|
||||||
|
if let cloudDocs = cloudDocsDir() {
|
||||||
|
return cloudDocs.appendingPathComponent("Museion", isDirectory: true)
|
||||||
|
}
|
||||||
|
return defaultMuseionHome
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #171: CloudDocs resolved dynamically at the unprefixed path — the
|
||||||
|
/// `iCloud~`-prefixed spelling varies per account, never hard-code it.
|
||||||
|
/// Plain FileManager probing; the app has no ubiquity entitlements
|
||||||
|
/// (ADR-0009).
|
||||||
|
nonisolated static func liveCloudDocsDir() -> URL? {
|
||||||
|
existingDirectory(cloudDocsURL(under: FileManager.default.homeDirectoryForCurrentUser))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CloudDocs path — unprefixed (the `iCloud~`-prefixed spelling
|
||||||
|
/// varies per account, never hard-code it); the seam the spelling pin
|
||||||
|
/// drives.
|
||||||
|
nonisolated static func cloudDocsURL(under home: URL) -> URL {
|
||||||
|
home.appendingPathComponent("Library/Mobile Documents/com~apple~CloudDocs", isDirectory: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `url` back only when it exists AND is a directory — the dir-ness
|
||||||
|
/// gate `liveCloudDocsDir` rides.
|
||||||
|
nonisolated static func existingDirectory(_ url: URL) -> URL? {
|
||||||
|
var isDirectory: ObjCBool = false
|
||||||
|
guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue else { return nil }
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when running as the hosted-test runner app (the panes' guard
|
||||||
|
/// pattern) — machine-state writes and probes are skipped there. Tests
|
||||||
|
/// constructing `AppGateState` with DEFAULT arguments hit this via the
|
||||||
|
/// init's early return: neither the real iCloud probes nor the pin run,
|
||||||
|
/// so the runner app's real state is never touched. An injected suite
|
||||||
|
/// is a test's own sandbox and always runs the full ladder + pin.
|
||||||
|
nonisolated static var hostedTestRun: Bool {
|
||||||
|
ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated static func storeHome(_ home: URL, in defaults: UserDefaults) {
|
||||||
|
defaults.set(home.absoluteString, forKey: "museionHome")
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
-16
@@ -44,29 +44,44 @@ final class AppGateState {
|
|||||||
/// locked, `isFocused` cannot leave true (the ⌥⌘F refusal IS the
|
/// locked, `isFocused` cannot leave true (the ⌥⌘F refusal IS the
|
||||||
/// lock), hover-reveal zones stay suppressed, and the kiosk holds.
|
/// lock), hover-reveal zones stay suppressed, and the kiosk holds.
|
||||||
let writingLock = WritingLockState()
|
let writingLock = WritingLockState()
|
||||||
/// #17: the Museion Home — repoint-only (ADR-0004). Defaults to
|
/// #17: the Museion Home — repoint-only (ADR-0004). #171: fresh installs
|
||||||
/// `~/Documents/Museion`; UserDefaults is the persistence floor: a Home is
|
/// resolve once through the ladder below and PIN the winner (UserDefaults
|
||||||
/// a plain folder, nothing app-owned to put in a database. Non-file URLs
|
/// is the persistence floor: a Home is a plain folder, nothing
|
||||||
/// read back as nil (the default wins) — the Home is always a folder.
|
/// app-owned to put in a database). Non-file URLs read back as nil (the
|
||||||
|
/// ladder wins) — the Home is always a folder.
|
||||||
var museionHome: URL {
|
var museionHome: URL {
|
||||||
didSet { UserDefaults.standard.set(museionHome.absoluteString, forKey: "museionHome") }
|
didSet { Self.storeHome(museionHome, in: UserDefaults.standard) }
|
||||||
}
|
}
|
||||||
|
|
||||||
init() {
|
/// #171: fresh-install Home resolution — runs only when no stored
|
||||||
|
/// override exists, then pins so the Home never silently moves (the
|
||||||
|
/// ladder + probes live in HomeResolution.swift). Probes and defaults
|
||||||
|
/// are injectable: hosted tests drive the ladder without touching the
|
||||||
|
/// machine's real iCloud state or the runner's real defaults.
|
||||||
|
/// `defaults` serves resolution + pin only — the repoint `didSet`
|
||||||
|
/// always writes the real standard defaults.
|
||||||
|
init(
|
||||||
|
defaults: UserDefaults = .standard,
|
||||||
|
legacyHomeExists: () -> Bool = { AppGateState.existingDirectory(AppGateState.defaultMuseionHome) != nil },
|
||||||
|
cloudDocsDir: () -> URL? = AppGateState.liveCloudDocsDir,
|
||||||
|
) {
|
||||||
// Explicit init: `Self` in a stored-property initializer trips
|
// Explicit init: `Self` in a stored-property initializer trips
|
||||||
// @ObservationTracked's macro expansion (covariant Self).
|
// @ObservationTracked's macro expansion (covariant Self).
|
||||||
museionHome = UserDefaults.standard.string(forKey: "museionHome")
|
if let stored = Self.fileHomeURL(in: defaults) {
|
||||||
.flatMap(URL.init(string:))
|
museionHome = stored
|
||||||
.flatMap { $0.isFileURL ? $0 : nil }
|
return
|
||||||
?? Self.defaultMuseionHome
|
}
|
||||||
// #70: the six prose-typography slot defaults.
|
// Default construction under hosted tests (WritingLockTests &
|
||||||
|
// friends): skip the real probes and the pin alike.
|
||||||
|
if Self.hostedTestRun, defaults === UserDefaults.standard {
|
||||||
|
museionHome = Self.defaultMuseionHome
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let resolved = Self.resolvedInitialHome(legacyHomeExists: legacyHomeExists, cloudDocsDir: cloudDocsDir)
|
||||||
|
museionHome = resolved
|
||||||
|
Self.storeHome(resolved, in: defaults)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The default Home, absent a stored override — `~/Documents/Museion`
|
|
||||||
/// (b3daac9: Documents, not the account root; TCC note in ADR-0004).
|
|
||||||
nonisolated static let defaultMuseionHome = FileManager.default.homeDirectoryForCurrentUser
|
|
||||||
.appendingPathComponent("Documents/Museion", isDirectory: true)
|
|
||||||
|
|
||||||
/// #151: the gateless launch check — arms the auto-fire chain, then
|
/// #151: the gateless launch check — arms the auto-fire chain, then
|
||||||
/// runs the once-per-launch async check (`beginAutomaticCheck`'s
|
/// runs the once-per-launch async check (`beginAutomaticCheck`'s
|
||||||
/// `hasStarted` preserves #41's one-check-per-launch, first-window-only
|
/// `hasStarted` preserves #41's one-check-per-launch, first-window-only
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ Owned by the root AGENTS.md contract.
|
|||||||
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing. Untouched by #151 (probe/model facts, onPass-fires-per-passing-check, once-per-model). `GatelessLaunchTests.swift` (#151) pins the gateless seam: `startLaunchCheck` no-ops under hosted tests (never probes nor arms the chain — a fired chain would write the REAL profile roots), `wireAutoFire` arms `onPass`, the `EngineStatusSurface.visibility` pill mapping (idle/pass+healthy → hidden, checking → pulse, fail AND pass+provisioning-failed → failed), and the `MentorEngineStatus.state` header mapping (incl. the outrank rule — engine failure beats a lingering provisioning failure).
|
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing. Untouched by #151 (probe/model facts, onPass-fires-per-passing-check, once-per-model). `GatelessLaunchTests.swift` (#151) pins the gateless seam: `startLaunchCheck` no-ops under hosted tests (never probes nor arms the chain — a fired chain would write the REAL profile roots), `wireAutoFire` arms `onPass`, the `EngineStatusSurface.visibility` pill mapping (idle/pass+healthy → hidden, checking → pulse, fail AND pass+provisioning-failed → failed), and the `MentorEngineStatus.state` header mapping (incl. the outrank rule — engine failure beats a lingering provisioning failure).
|
||||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
|
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); every spawn appends its argv line to `<name>-spawn-log` beside the fake (#137 — the which-engine-ran observable) and every `session/prompt` appends its wire line to `<name>-prompt-log` (#122 — the what-the-engine-was-asked observable); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
|
||||||
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. **#143:** the scan-cache pins over `PostScanCache`'s hit/miss observables — cold scan misses once per file, warm scan all hits with identical output, a changed file re-parses (title moves) while untouched files hit, a moved piece re-parses at its new path (path-keying — a folder move keeps bytes and mtime but `isArchived` re-derives), and a late store carrying a stale pre-read stamp never pins stale content (the overlapping-rescan race's end-state, same-size rewrite so the mtime axis alone carries it).
|
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, **#171** fresh-install Home resolution — the ladder (legacy guard first even with iCloud present, `<CloudDocs>/Museion` next, silent Documents fallback), `existingDirectory`'s dir-ness gate over temp paths, stored override wins / non-file stored value falls through to the ladder, and pin-once over an injected UserDefaults suite (per-test sandbox), the hosted no-write guard (`default construction never writes the real defaults under hosted tests` — asserts `.standard` byte-unchanged across a default construction, never a destructive remove/restore), and the unprefixed CloudDocs path spelling (`cloudDocsURL(under:)` — the `iCloud~`-prefix regression fails it). **#143:** the scan-cache pins over `PostScanCache`'s hit/miss observables — cold scan misses once per file, warm scan all hits with identical output, a changed file re-parses (title moves) while untouched files hit, a moved piece re-parses at its new path (path-keying — a folder move keeps bytes and mtime but `isArchived` re-derives), and a late store carrying a stale pre-read stamp never pins stale content (the overlapping-rescan race's end-state, same-size rewrite so the mtime axis alone carries it).
|
||||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern; #147: the shared helpers are internal — PostStorePassTests.swift reuses them): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
|
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern; #147: the shared helpers are internal — PostStorePassTests.swift reuses them): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
|
||||||
- `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`.
|
- `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.
|
- `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.
|
||||||
|
|||||||
@@ -194,11 +194,97 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws {
|
|||||||
#expect(post.title == "After Blank")
|
#expect(post.title == "After Blank")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func `home default is documents museion`() {
|
// MARK: #171 fresh-install Home resolution
|
||||||
|
|
||||||
|
// Scenario: a fresh install with no stored override resolves its Home once —
|
||||||
|
// legacy ~/Documents/Museion wins if it exists (existing Homes migrate
|
||||||
|
// manually, never silently), else <CloudDocs>/Museion when iCloud Drive is
|
||||||
|
// present, else the silent Documents fallback; the winner is PINNED so the
|
||||||
|
// Home never silently moves after.
|
||||||
|
|
||||||
|
/// A throwaway defaults suite per test — the pin must land in the test's
|
||||||
|
/// own sandbox, never the runner app's real defaults.
|
||||||
|
private func homeDefaults(_ name: String) -> UserDefaults {
|
||||||
|
let suite = "home171-\(name)"
|
||||||
|
let defaults = UserDefaults(suiteName: suite)!
|
||||||
|
defaults.removePersistentDomain(forName: suite)
|
||||||
|
return defaults
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `home resolution guards the legacy documents home first`() {
|
||||||
|
// iCloud available AND a legacy Home exists → the legacy Home wins.
|
||||||
|
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { true }, cloudDocsDir: {
|
||||||
|
URL(fileURLWithPath: "/tmp/irrelevant-clouddocs")
|
||||||
|
})
|
||||||
|
#expect(resolved == AppGateState.defaultMuseionHome)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `home resolution pins clouddocs museion without a legacy home`() {
|
||||||
|
let cloudDocs = URL(fileURLWithPath: "/tmp/clouddocs")
|
||||||
|
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { false }, cloudDocsDir: { cloudDocs })
|
||||||
|
#expect(resolved == cloudDocs.appendingPathComponent("Museion", isDirectory: true))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `home resolution silently falls back to documents museion`() {
|
||||||
|
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { false }, cloudDocsDir: { nil })
|
||||||
|
#expect(resolved == AppGateState.defaultMuseionHome)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `clouddocs probe requires a real directory`() throws {
|
||||||
|
// The live probe's dir-ness gate, driven on temp paths — hosted tests
|
||||||
|
// never touch the machine's real iCloud state.
|
||||||
|
let dir = try makeHome { _ in }
|
||||||
|
#expect(AppGateState.existingDirectory(dir) == dir)
|
||||||
|
let file = dir.appendingPathComponent("plain-file")
|
||||||
|
try "not a dir".write(to: file, atomically: true, encoding: .utf8)
|
||||||
|
#expect(AppGateState.existingDirectory(file) == nil)
|
||||||
|
#expect(AppGateState.existingDirectory(dir.appendingPathComponent("missing")) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `stored home override wins over the resolution ladder`() {
|
||||||
|
let defaults = homeDefaults("stored-wins")
|
||||||
|
let custom = URL(fileURLWithPath: "/tmp/museion-custom-home")
|
||||||
|
defaults.set(custom.absoluteString, forKey: "museionHome")
|
||||||
|
let gate = AppGateState(defaults: defaults, legacyHomeExists: { true }, cloudDocsDir: { nil })
|
||||||
|
#expect(gate.museionHome == custom)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `non-file stored home falls through to the ladder`() {
|
||||||
|
let defaults = homeDefaults("non-file-stored")
|
||||||
|
defaults.set("https://not.a/home", forKey: "museionHome")
|
||||||
|
let gate = AppGateState(defaults: defaults, legacyHomeExists: { false }, cloudDocsDir: { nil })
|
||||||
|
#expect(gate.museionHome == AppGateState.defaultMuseionHome)
|
||||||
|
#expect(defaults.string(forKey: "museionHome") == AppGateState.defaultMuseionHome.absoluteString)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `fresh install pins once and never silently moves`() throws {
|
||||||
|
let defaults = homeDefaults("pin-once")
|
||||||
|
let cloudDocs = try makeHome { _ in }
|
||||||
|
let first = AppGateState(defaults: defaults, legacyHomeExists: { false }, cloudDocsDir: { cloudDocs })
|
||||||
|
#expect(first.museionHome == cloudDocs.appendingPathComponent("Museion", isDirectory: true))
|
||||||
|
#expect(defaults.string(forKey: "museionHome") == first.museionHome.absoluteString)
|
||||||
|
// A legacy Home "appears" after the pin — the stored winner stands.
|
||||||
|
let second = AppGateState(defaults: defaults, legacyHomeExists: { true }, cloudDocsDir: { nil })
|
||||||
|
#expect(second.museionHome == first.museionHome)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `default construction never writes the real defaults under hosted tests`() {
|
||||||
|
// The init guard protecting the runner app's real state — pinned
|
||||||
|
// without touching it: whatever .standard holds before a default
|
||||||
|
// construction must hold after (a deleted guard resolves + PINS,
|
||||||
|
// changing the stored value wherever the resolved Home differs).
|
||||||
|
let real = UserDefaults.standard
|
||||||
|
let before = real.string(forKey: "museionHome")
|
||||||
|
_ = AppGateState() // default construction — no probes, no pin
|
||||||
|
#expect(real.string(forKey: "museionHome") == before)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `clouddocs path is the unprefixed mobile documents form`() {
|
||||||
|
// #171: never a hard-coded `iCloud~` form — the prefixed spelling
|
||||||
|
// varies per account and would silently disable iCloud detection.
|
||||||
#expect(
|
#expect(
|
||||||
AppGateState.defaultMuseionHome
|
AppGateState.cloudDocsURL(under: URL(fileURLWithPath: "/h"))
|
||||||
== FileManager.default.homeDirectoryForCurrentUser
|
== URL(fileURLWithPath: "/h/Library/Mobile Documents/com~apple~CloudDocs", isDirectory: true),
|
||||||
.appendingPathComponent("Documents/Museion", isDirectory: true),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# S1 — Default Museion Home flips to iCloud (CloudDocs), pinned once with legacy guard
|
||||||
|
|
||||||
|
> **Date:** 2026-11-05
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [issue #171](https://git.babylondreams.de/AlexKucera/museion/issues/171) (resolution slice of #170/map #167, plain build slice for #145)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Fresh installs resolve their Museion Home once through a legacy-guarded ladder and PIN the winner, so the Home never silently moves: (1) stored override (unchanged semantics — file URLs only), (2) legacy `~/Documents/Museion` directory → pin it (existing Homes migrate manually, never silently), (3) `<CloudDocs>/Museion` when iCloud Drive is present (dynamically resolved unprefixed path, plain FileManager — no ubiquity API, ADR-0009), (4) silent Documents fallback — no dialog, no rail pill. Repoint-only stands (ADR-0004); zero mover code.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- `Museion/HomeResolution.swift` (new) — `extension AppGateState`: the ladder (`resolvedInitialHome(legacyHomeExists:cloudDocsDir:)`), `defaultMuseionHome` (legacy + fallback, unchanged path), `fileHomeURL(in:)` (stored-override read, file-URL gate), `liveCloudDocsDir()` → `existingDirectory(cloudDocsURL(under:))` (dir-gated probes), `cloudDocsURL(under:)` (the unprefixed path construction — spelling-pinned seam), `hostedTestRun`, `storeHome(_:in:)` (the one defaults write).
|
||||||
|
- `Museion/MuseionApp.swift` — `AppGateState.init` takes injectable `defaults` + probes; no stored override → resolve once → pin. Default construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched (WritingLockTests/GatelessLaunchTests construct the model directly). File extracted to keep MuseionApp.swift at 398 lines (lint cap; WritingLockState precedent).
|
||||||
|
- `MuseionTests/PostLibraryTests.swift` — the old `home default is documents museion` pin re-pinned to the seam; 9 tests: ladder ×3 (legacy guard wins over iCloud, CloudDocs without legacy, silent fallback), `existingDirectory` dir-gate edges over temp paths, stored-override wins, non-file stored value falls through to ladder + pins, pin-once/never-silently-moves (legacy "appearing" after the pin doesn't move it), hosted no-write guard (`.standard` byte-unchanged across a default construction), CloudDocs path spelling.
|
||||||
|
- DOX: `Museion/AGENTS.md` (museionHome bullet — the ladder + seam), `MuseionTests/AGENTS.md` (PostLibraryTests line), `GLOSSARY.md` (Home definition: fresh installs pin CloudDocs; legacy always wins).
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Pin-once at init, explicit `storeHome` write | didSet doesn't fire in init; one shared write helper keeps the key + absoluteString shape single-sourced with the repoint didSet. |
|
||||||
|
| Legacy probe requires a DIRECTORY (`existingDirectory`), not bare `fileExists` | Spec says "EXISTS on disk", but a stray plain file is not a Home — "the Home is always a folder" invariant + the repo trust-boundary rule (guard mirrors sink shape exactly). A file at that path falls through to iCloud instead of pinning a broken Home. (Implement-close review catch.) |
|
||||||
|
| Hosted-test guard = early return, not a conditional pin | First shape skipped only the pin write; the finish/implement convergence showed probes still READ real iCloud state. The early return skips probes AND pin — satisfies the ticket's "never touch" literally and is simpler (no `!==` identity tangle in the pin condition). |
|
||||||
|
| Hosted no-write pin asserts `.standard` byte-unchanged, never a destructive remove | The first version removed the real key with a defer restore — the #33 save/restore-around-real-state pattern (finish-audit security + general converged finding). The unchanged-assertion fails exactly when a write occurs; a write requires key-absent + guard-gone, which is also the only harmful case (a write over an existing stored value can't happen — the stored branch returns first). |
|
||||||
|
| `cloudDocsURL(under:)` seam + spelling pin | The unprefixed path is the ticket's explicit "never a hard-coded `iCloud~` form" constraint and had zero coverage — a typo silently disables iCloud detection into the Documents fallback. (Finish-audit general catch.) |
|
||||||
|
| Injection: probes + defaults per-init params, not a probe struct | Three params, all driven by tests; a struct would be abstraction for one caller shape. |
|
||||||
|
| `defaultMuseionHome` kept, not renamed `legacyDefaultHome` | Still the fallback; shortest diff. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| Wrapped `if` condition list reflowed by swiftformat → swiftlint `opening_brace` | The #142 lesson (root AGENTS.md): formatter pushes the brace; don't fight it | Hoisted `hostedTestRun` helper → single-line condition |
|
||||||
|
| `museionHome = defaultMuseionHome` bare in instance init → "static member cannot be used on instance" | Static member needs `Self.` in instance context | `Self.defaultMuseionHome` |
|
||||||
|
| `defer { … }()` → "Consecutive statements on a line must be separated by ';'" | IIFE habit; defer takes a closure, no call | Dropped `()` |
|
||||||
|
| Path-spelling pin failed on EVERY tree | URL equality is string-based: `appendingPathComponent(_, isDirectory: true)` appends a trailing slash; the expected literal had none — the first "flip fail" was this bug, not the flip | Expectation built with the same `isDirectory: true`; gotcha filed to swift wiki (foundation-files rule 2, builder side) |
|
||||||
|
| Flip-run of the hosted no-write pin passed with the guard provably disabled | No observable write to the real domain occurs in this harness even with the guard off (fresh binary proven by the spelling flip firing); the feared hosted-write scenario doesn't reproduce here | Documented as flip-inert in this harness; the pin stays as the correct non-destructive observable (green on good tree; fails by construction when a write occurs) |
|
||||||
|
| `-only-testing` with stacked/free-function names matched zero tests, twice (exit 0 = vacuous green) | The known Swift Testing filter trap (names with spaces; stacked flags) | Tally check from xcresult caught it; full-suite runs used instead |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/HomeResolution.swift` | NEW — ladder, probes, hosted guard helper, defaults write (78 lines) |
|
||||||
|
| `Museion/MuseionApp.swift` | init: injectable seam, resolve-once-pin, hosted early return; didSet via storeHome (398 lines) |
|
||||||
|
| `MuseionTests/PostLibraryTests.swift` | 9 seam-driven Home-resolution tests replacing the old default pin |
|
||||||
|
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `GLOSSARY.md` | DOX pass — ladder contract, test inventory, Home definition |
|
||||||
|
| `CHANGELOG.md` | [Unreleased] → Changed: home entry |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] The 5 pre-existing `XCTestConfigurationFilePath` probe sites can adopt `AppGateState.hostedTestRun` on next touch (deliberate next-touch; drive-by refactor avoided this session).
|
||||||
|
- [ ] The hosted no-write pin is flip-inert in this harness (no observable hosted write even guard-off); if a future environment makes hosted writes observable, the pin discriminates unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Verification:** `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test` — **628/628 passed, 0 failed** (xcresult executed count, `/tmp/verify171.xcresult`); swiftlint clean on changed files; swiftformat idempotent on changed files. GitNexus impact LOW (0 upstream callers of `defaultMuseionHome`), detect-changes scoped to the expected symbols, analyze re-run. Implement-close review (standards + spec) and finish-audit fanout (ponytail 0 / security 1 Low fixed / general 2 nits fixed) both landed fixes; spelling pin flip-verified (fails with `iCloud~` prefix).
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
|||||||
<!-- write-log: full-index -->
|
<!-- write-log: full-index -->
|
||||||
| Date | Type | File | Summary |
|
| Date | Type | File | Summary |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
| 2026-11-05 | issue | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | Fresh installs pin `<CloudDocs>/Museion` with a legacy-dir guard; injectable probe seam, 9 tests (#171) |
|
||||||
| 2026-11-04 | issue | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | #158: Cold Turkey map closed — frontier empty, build on main, hotkey fog parked; #140 ready to close |
|
| 2026-11-04 | issue | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | #158: Cold Turkey map closed — frontier empty, build on main, hotkey fog parked; #140 ready to close |
|
||||||
| 2026-11-04 | issue | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | #166: preset chips ruled NO — typeable value + defaults + steppers cover arming; frontier now empty |
|
| 2026-11-04 | issue | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | #166: preset chips ruled NO — typeable value + defaults + steppers cover arming; frontier now empty |
|
||||||
| 2026-11-04 | issue | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) | #165: S5.1 tie-in ruled NO — capture stays pass-gated; revisit trigger parked in map Out of scope |
|
| 2026-11-04 | issue | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) | #165: S5.1 tie-in ruled NO — capture stays pass-gated; revisit trigger parked in map Out of scope |
|
||||||
|
|||||||
Reference in new issue
Block a user