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
@@ -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).
|
||||
- `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.
|
||||
- `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).
|
||||
- `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.
|
||||
|
||||
@@ -194,11 +194,97 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws {
|
||||
#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(
|
||||
AppGateState.defaultMuseionHome
|
||||
== FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Documents/Museion", isDirectory: true),
|
||||
AppGateState.cloudDocsURL(under: URL(fileURLWithPath: "/h"))
|
||||
== URL(fileURLWithPath: "/h/Library/Mobile Documents/com~apple~CloudDocs", isDirectory: true),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user