Compare commits

..
3 Commits
Author SHA1 Message Date
AlexKucera 3193714a61 test(session): finish-audit closeout for #184
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Three-reviewer fanout over PR #184's deferred nil-scope fix:

- pin the titled drain's APPLY half (unpinned suite-wide) over a new
  hangOnPromptLoad rig mode (prompt parks, load answers);
  flip-verified against a nil-only drain guard
- cut the dead Equatable on PendingScope (converged finding)
- name the same-turn pendingRestart ceiling on the drain: respawn's
  .starting window drops the consumed scope; consume-at-apply is the
  upgrade path (follow-up ticket)
- changelog + devlog for the PR; AGENTS.md rails refreshed

Suite 654 executed / 0 failed; swiftformat clean; swiftlint
unchanged (both warnings pre-exist on main).
2026-11-10 16:23:08 +01:00
AlexKucera 836da5833d fix(session): drain a deferred nil scope as an explicit clear
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
pendingScopePieceTitle: String? conflated 'no pending request' with a
pending request whose target is nil (the writer left the piece — New
Post, unsaved draft, external guest, nothing open). Both deferral
branches stored the target and the drain guarded on the optional, so a
deferred nil target was silently dropped: at turn end (sendPrompt,
runOneShot) or replay completion (resumeSession) the old piece's
activeEntry survived under a nothing-open context, contrary to the
scope contract (#176 class).

Pending-ness now rides PendingScope (none | scope(String?)) — a nil
target drains through scopeHostedSession like any titled target and
clears activeEntry. Titled deferrals and the immediate path are
unchanged.

Verified: SessionScopeTests 4/4 green (both RED pins now green in
45 ms — the clear lands at the drain, not a deadline); full unit bundle
653/653 green; swiftformat 0 files; swiftlint exit 0 (two pre-existing
warnings in MentorSessionModel.swift, unchanged kind).
2026-11-10 00:34:30 +01:00
AlexKucera 8531d798bc test(session): pin deferred nil scope lost at stream and replay drain
CI / ci (push) Canceled after 0s
Leaving the piece mid-stream (New Post over a streaming reply) or
mid-replay defers a nil scope request like any switch, but the drain
guards on the optional title — an explicit nil target (clear) is
indistinguishable from no pending request, so activeEntry survives on
the old piece under a nothing-open context.

Two RED pins over the scripted rig: hangOnPrompt (stream parks, cancel
ends it, drain at sendPrompt turn end) and loadReplayHold (replay parks,
releaseHeldLoad completes it, drain at resume). Both fail on this base:
executed 4 / passed 2 / failed 2 (the two new pins).
2026-11-10 00:09:14 +01:00
134 changed files with 2629 additions and 8922 deletions

No files matched your search

-123
View File
@@ -1,123 +0,0 @@
---
name: release
description: "Cut a Museion release: bump, notes, rail, DMG, tag, publish."
platforms: [macos]
version: 0.1.1
author: Hermes
metadata:
hermes:
tags: [Release, Museion, Xcode, Notarization, Gitea, apex]
---
# Cutting a Museion release
Runs a release end to end: refresh the bundled apex renderer, version bump, changelog heading, release notes, the verify rail, sliced commits, an annotated tag, the notarized DMG from `scripts/release.sh`, then push and the Gitea release. The skill decides nothing about signing — `release.sh` and the Account Holder's keychain do that — and it bumps no version on its own. Push and the forge release wait for Alexander's explicit go (root `AGENTS.md`, User Preferences).
## When to Use
- "cut / ship / tag / bump a release", "make a DMG", "X.Y.Z is ready"
- notarization came back `Invalid`, or a bundled binary changed (`Museion/Resources/apex`) — rerun steps 6–9 and move the still-local tag
- release notes or the README have to match what shipped
## Prerequisites
- Clean tree on `main`. `MARKETING_VERSION` is the only version source; read it from build settings, never from the pbxproj text.
- A valid **Developer ID Application** identity: `security find-identity -v -p codesigning`. When it is missing, the fix is Alexander's (developer.apple.com + a Keychain Access CSR — the `scripts/release.sh` header has the route); the agent imports nothing.
- Notary profile `museion-notary`, registered once by the Account Holder. The agent never runs `notarytool store-credentials`.
- `tea` logged in to `git.babylondreams.de` (the default login).
- Budget: ~2 min for `release.sh`, ~7 min for the rail.
## Procedure
Run through the `terminal` tool. Each step ends on a check; the next starts when it passes.
1. **Refresh apex FIRST — every release, no "is it current?" gate.** The bundled renderer is stale by definition between releases; the upgrade is the first step, never a comparison that can be skipped. Both sources are the same official binary; pick one:
**GitHub release (canonical):**
```bash
W=$(mktemp -d) && cd "$W"
curl -fsSL https://api.github.com/repos/ApexMarkdown/apex/releases/latest -o rel.json
TAG=$(python3 -c 'import json;print(json.load(open("rel.json"))["tag_name"])') # v1.1.NN
V=${TAG#v}
curl -fsSLO "https://github.com/ApexMarkdown/apex/releases/download/$TAG/apex-$V-macos-universal.tar.gz"{,.sha256}
awk '{print $1}' apex-$V-macos-universal.tar.gz.sha256 | shasum -a 256 -c - # must print OK — stop otherwise
tar xzf apex-$V-macos-universal.tar.gz
SRC=apex-$V-macos-universal/apex
```
**Homebrew (fallback only — the formula lags GitHub by days; on 0.1.1's cut day it still carried 1.1.58):**
```bash
brew update && brew upgrade apex
SRC=$(brew --prefix)/bin/apex # a symlink; lipo reads through it
```
Either way `lipo -info "$SRC"` must list `arm64` (GitHub ships x86_64+arm64; Homebrew on Apple Silicon is arm64-only — `lipo -thin` still works on a thin file).
**Then the one recipe (ADR-0011 — 1.1.59 still links libyaml dynamically; the vendored `libyaml.bundle` stays):**
```bash
cd <repo root>
SIGNER="Developer ID Application: Alexander Kucera (3M7APDAAC5)"
lipo "$SRC" -thin arm64 -output "$W/apex-arm64"
# strip EVERY rpath the binary carries — list them first and delete each one; a Homebrew build carries $(brew --prefix)/lib instead of the CI paths
otool -l "$W/apex-arm64" | grep -A2 LC_RPATH | grep path
for r in /Users/runner/work/apex/apex/deps/libyaml-universal/lib /usr/local/lib /opt/homebrew/lib "$(brew --prefix)/lib"; do
install_name_tool -delete_rpath "$r" "$W/apex-arm64" 2>/dev/null || true # absent paths are fine to skip; the Done-check catches a survivor
done
install_name_tool -add_rpath '@executable_path/../Resources/libyaml.bundle' "$W/apex-arm64"
codesign -f -s "$SIGNER" --options runtime --timestamp "$W/apex-arm64"
# PROVE it in the shipped layout before it touches the tree
mkdir -p "$W/proof/Resources/libyaml.bundle" && cp "$W/apex-arm64" "$W/proof/Resources/apex" \
&& cp Museion/Resources/libyaml.bundle/libyaml-0.2.dylib "$W/proof/Resources/libyaml.bundle/"
"$W/proof/Resources/apex" --version
printf -- '- a\n\n1. one\n' | "$W/proof/Resources/apex" --no-mixed-lists # two lists, <ul> then <ol> — never one merged <ul>
cp "$W/apex-arm64" Museion/Resources/apex
```
Bump `## apex X.Y.Z` + the `vX.Y.Z` prose in `Museion/Resources/THIRD-PARTY-NOTICES.md`; add a `### Changed` → `- **reading:**` line under the release heading in `CHANGELOG.md`. Done when `otool -l Museion/Resources/apex | grep -A2 LC_RPATH | grep path` prints exactly `@executable_path/../Resources/libyaml.bundle`, `codesign -dvv` shows `flags=0x10000(runtime)` + the Developer ID authority, `Museion/Resources/apex --version` prints the new version, and `--no-mixed-lists` appears in `--help` (ADR-0011's load-bearing flag). If a future apex links libyaml statically (asked upstream), drop the rpath/codesign dylib steps and the `.bundle`, and update this skill. An upgrade found after tagging costs a second rail run and a second notarization.
2. **Bump.** `MARKETING_VERSION` on every target and configuration in `Museion.xcodeproj/project.pbxproj`; `CURRENT_PROJECT_VERSION` stays. Read back: `xcodebuild -project Museion.xcodeproj -scheme Museion -configuration Release -destination 'platform=macOS,arch=arm64' -showBuildSettings | awk -F'= ' '/MARKETING_VERSION = /'`. Done when it prints the new version.
3. **Changelog heading.** `## [X.Y.Z] - YYYY-MM-DD` over the former `[Unreleased]` entries, a fresh empty `[Unreleased]` above, one pointer line to the notes (`CHANGELOG.md` follows Common Changelog). Done when every entry since the last tag sits under the heading.
4. **Release notes** — `docs/releases/X.Y.Z.md`, the CHANGELOG section distilled for humans: what is in it (grouped highlights), the milestones it closes, install, known limits, numbers. Shape precedent: `docs/releases/0.1.0.md`. Written from the shipped surface — every claim traces to a CHANGELOG entry or to source.
5. **README matches what shipped:** install copy, requirements, license pointer; the minimum macOS from `MACOSX_DEPLOYMENT_TARGET`, never from prose.
6. **Verify rail on the tree you will tag.** `./scripts/full-test.sh start`, poll `./scripts/full-test.sh status` (exit 3 = live), counts from `./scripts/full-test.sh summary`. Done when executed == passed == the baseline and the run directory is newer than the last edit. Then `swiftformat . && swiftlint .` clean, and `shellcheck scripts/release.sh` when the script changed.
7. **Commit in slices, then tag.** `docs(readme)` · `build(release)` (tooling + notes + DOX) · `chore(release)` (bump + changelog heading) · later fixes as `fix(scope)`. Plain prose bodies, no trailers. Tag: `git tag -a vX.Y.Z -m "Museion X.Y.Z — <one line>"` on the commit whose tree the DMG is built from. A fix found after tagging: commit it, then `git tag -f vX.Y.Z <fix commit>` while the tag is still local. Done when `git describe --tags --exact-match HEAD` prints the tag and the tree is clean.
8. **Build and prove the DMG.** `./scripts/release.sh` — refuses without the identity, reads the version from build settings, writes `dist/Museion-X.Y.Z.dmg`, and ends with `spctl` → `accepted, source=Notarized Developer ID`. Then mount the image and run `Contents/Resources/apex --version` from it, `xcrun stapler validate dist/Museion-X.Y.Z.dmg`, and record `shasum -a 256 dist/Museion-X.Y.Z.dmg`. Done when all four pass and the sha256 is in the report.
9. **Handoff gate.** Report the tag commit, the sha256, and what changed. Push and the forge release happen on Alexander's go.
10. **On go — push, release, verify.**
```bash
git push origin main vX.Y.Z
{ cat docs/releases/X.Y.Z.md; printf '\n\n[Generated by AI]\n'; } > "$TMPDIR/notes.md" # house rule: the AI marker closes every tea body
tea releases create --tag vX.Y.Z --target <tag-commit-sha> -t "Museion X.Y.Z" -f "$TMPDIR/notes.md" -a ./dist/Museion-X.Y.Z.dmg
tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'
```
Done when the API shows `draft: false`, one asset at the local byte size, and a token-authenticated download of the asset sha256-matches the local file.
11. **Session log + DOX.** `write-log` for the release; the devlog commit follows the tag (the log is the record about the release, not part of it). DOX pass: root `AGENTS.md` (commands block, scripts index, session-log window) and `docs/AGENTS.md`. The log commit rides the next go.
## Quick Reference
- apex: GitHub `releases/latest` → `.sha256` → `lipo -thin arm64 -output` → strip ALL rpaths → add `@executable_path/../Resources/libyaml.bundle` → `codesign --options runtime` → prove in a scratch `Resources/` layout → copy into `Museion/Resources/apex` + bump `THIRD-PARTY-NOTICES.md`. Every release, first. (Homebrew lags GitHub — fallback only.)
- Version: `xcodebuild -showBuildSettings … | awk '/MARKETING_VERSION = /'`
- Rail: `./scripts/full-test.sh start` · `status` · `summary`
- Lint: `swiftformat . && swiftlint .`
- Tag: `git tag -a vX.Y.Z -m "Museion X.Y.Z — <one line>"` · move while local: `git tag -f vX.Y.Z <sha>`
- DMG: `./scripts/release.sh` → `dist/Museion-X.Y.Z.dmg` (`NOTARIZE=0` skips notarize + staple)
- Gatekeeper: `spctl -a -t open --context context:primary-signature -v dist/Museion-X.Y.Z.dmg`
- Push: `git push origin main vX.Y.Z`
- Release: `tea releases create --tag vX.Y.Z --target <sha> -t "Museion X.Y.Z" -f <notes> -a ./dist/Museion-X.Y.Z.dmg`
- Read back: `tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'`
## Pitfalls
- `release.sh` packages whatever `MARKETING_VERSION` says, from the current tree — it bumps and tags nothing.
- The old "compare `--version`, upgrade if stale" step read as optional and got skipped by habit — the refresh is unconditional. A `brew upgrade apex` that prints "already up-to-date" proves nothing: the formula can trail the GitHub release by days (it did on the 0.1.1 cut). GitHub `releases/latest` is the version of record.
- `install_name_tool -delete_rpath` fails loudly on a path the binary does not carry — list the rpaths with `otool -l` first and delete exactly those; the Homebrew build carries `$(brew --prefix)/lib`, the GitHub build the three CI/Homebrew paths. The Done-check (exactly ONE rpath left) catches a survivor before the rail, where `release.sh` would only catch a missing dylib.
- A `cp` over the signed `Resources/apex` must happen AFTER the scratch-layout proof — a binary that fails `--no-mixed-lists` in scratch has already touched nothing.
- A green `full-test.sh status` read right after a resource-only edit can be the PREVIOUS run's summary. Compare run-directory timestamps; zero `SwiftCompile` lines is normal then, and freshness is the `CpResource` line for the changed file plus running it from the test host's built bundle.
- A DMG built before the last binary or script change is stale: rebuild, re-notarize, and the sha256 in the report is the one that ships.
- The tag moves only while local; after the push a fix is a new version.
- `tea releases create` takes the tag via `--tag` OR the positional — both is "ambiguous arguments". `@file` bodies work only on `tea api`; releases take `-f <file>`.
- The release asset download 404s without a token (private repo). Read the token from `~/Library/Application Support/tea/config.yml` into a shell variable for the `curl` — never print it.
- `core.hooksPath=scripts/hooks`: the pre-push hook is the lint gate; the rail is yours to run before tagging.
- A dylib dropped into a synced Resources folder gets linked into the app by Xcode's classifier; vendored libraries ride a `.bundle` folder (ADR-0011).
## Verification
`tea api '/repos/{owner}/{repo}/releases/tags/vX.Y.Z'` → `draft: false`, one asset whose downloaded sha256 equals `shasum -a 256 dist/Museion-X.Y.Z.dmg`; `spctl -a -t open --context context:primary-signature -v dist/Museion-X.Y.Z.dmg` → `accepted, source=Notarized Developer ID`.
-2
View File
@@ -1,8 +1,6 @@
.build/
.swiftpm/
DerivedData/
_build/
dist/
**/xcuserdata/
.DS_Store
CLAUDE.md
-3
View File
@@ -1,3 +0,0 @@
{
"buildPath": "code"
}
-288
View File
@@ -1,288 +0,0 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-11T15:32:43Z",
"title": "Design System: Museion",
"extensions": {
"colorMeta": {
"terracotta-seal": {
"role": "primary",
"displayName": "Terracotta Seal",
"canonical": "#C96442",
"tonalRamp": [
"#382018",
"#683726",
"#984d34",
"#c86442",
"#d3876d",
"#ddab9a",
"#e7cfc6",
"#f2f2f2"
]
},
"pine": {
"role": "semantic",
"displayName": "Pine",
"canonical": "#36664F",
"tonalRamp": [
"#143023",
"#29523e",
"#45705b",
"#6a897a",
"#8fa198",
"#b4bab7",
"#d5d5d5",
"#f2f2f2"
]
},
"field-paper": {
"role": "neutral",
"displayName": "Field Paper",
"canonical": "#FAF9F3",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9a",
"#b9b8b6",
"#d6d5d1",
"#f4f3ed"
]
},
"page": {
"role": "neutral",
"displayName": "Page",
"canonical": "#FFFEFB",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9a",
"#b8b8b7",
"#d6d5d3",
"#f3f2f0"
]
},
"iron-gall-ink": {
"role": "neutral",
"displayName": "Iron-Gall Ink",
"canonical": "#1A1916",
"tonalRamp": [
"#272624",
"#444342",
"#61615f",
"#7e7e7d",
"#9b9b9b",
"#b8b8b8",
"#d5d5d5",
"#f2f2f2"
]
},
"faded-ink": {
"role": "neutral",
"displayName": "Faded Ink",
"canonical": "#6B6964",
"tonalRamp": [
"#272624",
"#454340",
"#62615c",
"#7f7e7a",
"#9c9b98",
"#b9b8b6",
"#d5d5d5",
"#f2f2f2"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"canonical": "#E8E5DF",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7d",
"#9c9b99",
"#bab8b4",
"#d8d5d0",
"#f5f2ed"
]
},
"substrate": {
"role": "neutral",
"displayName": "Substrate",
"canonical": "#F5F5F7",
"tonalRamp": [
"#262626",
"#434343",
"#616161",
"#7e7e7e",
"#9b9b9b",
"#b8b8b9",
"#d5d5d6",
"#f2f2f4"
]
},
"reading-ink": {
"role": "neutral",
"displayName": "Reading Ink",
"canonical": "#1D1D1F"
},
"reading-secondary": {
"role": "neutral",
"displayName": "Reading Secondary",
"canonical": "#48484D"
},
"reading-muted": {
"role": "neutral",
"displayName": "Reading Muted",
"canonical": "#6E6E73"
},
"reading-hairline": {
"role": "neutral",
"displayName": "Reading Hairline",
"canonical": "#D2D2D7"
},
"reading-rule": {
"role": "neutral",
"displayName": "Reading Rule",
"canonical": "#A1A1A6"
}
},
"shadows": [
{
"name": "panel-float",
"value": "0 14px 36px rgba(26,25,22,0.14)",
"purpose": "Floating palettes and popover cards (Fix Cards palette)."
},
{
"name": "overlay-lift",
"value": "0 24px 80px rgba(26,25,22,0.18)",
"purpose": "Modal overlays and large floating surfaces."
}
],
"breakpoints": [
{
"name": "collapse-mentor",
"value": "920px",
"purpose": "Window width below which the mentor column hides."
},
{
"name": "collapse-library",
"value": "1100px",
"purpose": "Window width below which the library column hides."
}
]
},
"components": [
{
"name": "Nav Rail",
"kind": "nav",
"refersTo": "nav-rail",
"description": "The desk's spine: 56px icon rail on Field Paper with the engine-status pill at the foot.",
"html": "<nav class=\"ds-nav-rail\"><button class=\"ds-nav-item ds-active\" aria-label=\"Posts\"><svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\"><rect x=\"2\" y=\"3\" width=\"14\" height=\"12\" rx=\"2\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"M5 7h8M5 10h5\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg></button><button class=\"ds-nav-item\" aria-label=\"Sessions\"><svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\"><path d=\"M3 4.5C3 3.7 3.7 3 4.5 3h9C14.3 3 15 3.7 15 4.5v7c0 .8-.7 1.5-1.5 1.5h-9C3.7 13 3 12.3 3 11.5v-7z\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"M6 15h6\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg></button><div class=\"ds-nav-spacer\"></div><div class=\"ds-nav-pill\"><span class=\"ds-nav-dot\"></span>ready</div></nav>",
"css": ".ds-nav-rail { display: flex; flex-direction: column; align-items: center; gap: 6px; width: 56px; padding: 14px 0; background: #FAF9F3; border-right: 1px solid #E8E5DF; } .ds-nav-item { display: flex; align-items: center; justify-content: center; width: 38px; height: 38px; border: none; border-radius: 10px; background: transparent; color: #6B6964; cursor: pointer; } .ds-nav-item:hover { background: rgba(26,25,22,0.05); } .ds-nav-item:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: 1px; } .ds-nav-item.ds-active { background: #FFFEFB; color: #1A1916; } .ds-nav-spacer { flex: 1; } .ds-nav-pill { display: flex; align-items: center; gap: 5px; padding: 4px 8px; border-radius: 12px; background: #FFFEFB; border: 1px solid #E8E5DF; color: #6B6964; font-family: -apple-system, system-ui, sans-serif; font-size: 10px; } .ds-nav-dot { width: 6px; height: 6px; border-radius: 50%; background: #36664F; }"
},
{
"name": "Library Post Row",
"kind": "custom",
"refersTo": "library-column",
"description": "Library row: 2px leading state strip, ink title, faded metadata, hover tint.",
"html": "<div class=\"ds-library-row\" tabindex=\"0\"><span class=\"ds-row-strip\"></span><div class=\"ds-row-body\"><div class=\"ds-row-title\">The expected value of showing</div><div class=\"ds-row-meta\">Pass-1 Done · 6 min</div></div></div>",
"css": ".ds-library-row { display: flex; align-items: stretch; gap: 10px; padding: 8px 12px 8px 0; border-radius: 10px; cursor: default; } .ds-library-row:hover { background: rgba(26,25,22,0.04); } .ds-library-row:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: -2px; } .ds-row-strip { width: 2px; border-radius: 1px; background: #6B6964; } .ds-row-body { min-width: 0; } .ds-row-title { font-family: -apple-system, system-ui, sans-serif; font-size: 13px; color: #1A1916; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .ds-row-meta { font-family: -apple-system, system-ui, sans-serif; font-size: 11px; color: #6B6964; margin-top: 2px; }"
},
{
"name": "Fix Card",
"kind": "card",
"refersTo": "fix-card",
"description": "The critique made visible: problem → diagnostic → fix on the Page color; Apply is ask-before.",
"html": "<article class=\"ds-fix-card\"><header class=\"ds-card-head\"><span class=\"ds-card-chip\">structure</span><span class=\"ds-card-chip ds-chip-quiet\">engine</span></header><h4 class=\"ds-card-pattern\">Buried thesis</h4><p class=\"ds-card-problem\">The argument arrives in paragraph four; the reader has already guessed a different essay.</p><p class=\"ds-card-diagnostic\">Could a reader state the claim after the first paragraph?</p><p class=\"ds-card-fix\">Move the thesis to the opening; demote its current paragraph to support.</p><div class=\"ds-card-actions\"><button class=\"ds-card-apply\">Apply…</button><button class=\"ds-card-skip\">Skip</button></div></article>",
"css": ".ds-fix-card { background: #FFFEFB; border: 1px solid #E8E5DF; border-radius: 10px; padding: 16px; box-shadow: 0 14px 36px rgba(26,25,22,0.14); max-width: 340px; } .ds-card-head { display: flex; gap: 6px; margin-bottom: 10px; } .ds-card-chip { font-family: -apple-system, system-ui, sans-serif; font-size: 10px; color: #6B6964; border: 1px solid #E8E5DF; border-radius: 6px; padding: 1px 6px; } .ds-chip-quiet { border-style: dashed; } .ds-card-pattern { font-family: -apple-system, system-ui, sans-serif; font-size: 13px; font-weight: 600; color: #1A1916; margin: 0 0 6px; } .ds-card-problem, .ds-card-diagnostic, .ds-card-fix { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; line-height: 1.5; margin: 0 0 6px; color: #1A1916; } .ds-card-diagnostic { color: #6B6964; font-style: italic; } .ds-card-actions { display: flex; gap: 8px; margin-top: 10px; } .ds-card-apply { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; color: #C96442; background: transparent; border: 1px solid rgba(201,100,66,0.45); border-radius: 8px; padding: 4px 12px; cursor: pointer; } .ds-card-apply:hover { background: rgba(201,100,66,0.08); } .ds-card-apply:focus-visible { outline: 2px solid rgba(201,100,66,0.55); outline-offset: 1px; } .ds-card-skip { font-family: -apple-system, system-ui, sans-serif; font-size: 12px; color: #6B6964; background: transparent; border: none; border-radius: 8px; padding: 4px 8px; cursor: pointer; } .ds-card-skip:hover { color: #1A1916; }"
},
{
"name": "Mentor Header",
"kind": "custom",
"refersTo": "mentor-column",
"description": "Serif mentor title with the Pine ready dot and lowercase status.",
"html": "<header class=\"ds-mentor-head\"><h3 class=\"ds-mentor-title\">Mentor</h3><span class=\"ds-mentor-status\"><span class=\"ds-mentor-dot\"></span>ready</span></header>",
"css": ".ds-mentor-head { display: flex; align-items: baseline; gap: 10px; padding: 14px 16px; border-bottom: 1px solid #E8E5DF; } .ds-mentor-title { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 17px; font-weight: 400; color: #1A1916; margin: 0; } .ds-mentor-status { display: inline-flex; align-items: center; gap: 5px; font-family: -apple-system, system-ui, sans-serif; font-size: 11px; color: #6B6964; } .ds-mentor-dot { width: 7px; height: 7px; border-radius: 50%; background: #36664F; }"
},
{
"name": "Editor Page",
"kind": "custom",
"refersTo": "editor-page",
"description": "The Page-colored writing surface: serif body on the 66ch measure.",
"html": "<div class=\"ds-editor-page\"><h1 class=\"ds-doc-title\">The expected value of showing</h1><p class=\"ds-doc-body\">The workshop answer is to show the work. The honest answer is that showing is a wager: you pay in attention you could have spent elsewhere, and the payout is a reader who stays.</p><p class=\"ds-doc-body\">What follows is an accounting of that wager.</p></div>",
"css": ".ds-editor-page { background: #FFFEFB; max-width: 66ch; margin: 0 auto; padding: 24px; } .ds-doc-title { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 22px; font-weight: 400; color: #1A1916; margin: 0 0 16px; line-height: 1.15; } .ds-doc-body { font-family: Iowan Old Style, Charter, Georgia, serif; font-size: 17px; line-height: 1.8; color: #1A1916; margin: 17px 0 0; }"
},
{
"name": "Code Panel",
"kind": "custom",
"refersTo": "code-panel",
"description": "Recessed well for code: Substrate ground, mono 14/1.5.",
"html": "<pre class=\"ds-code-panel\"><code>measure = 66ch\npadding = 24px</code></pre>",
"css": ".ds-code-panel { background: #F5F5F7; border-radius: 8px; padding: 14px 16px; margin: 17px 0 0; font-family: ui-monospace, Menlo, monospace; font-size: 14px; line-height: 1.5; color: #1A1916; white-space: pre-wrap; }"
}
],
"narrative": {
"northStar": "The Scholar's Desk",
"overview": "Museion is one writer's private study rendered in software: warm paper, iron-gall ink, a single enameled accent. The world is two papers — Field Paper for the desk's chrome (rails, pane grounds, the focus field) and Page for everything that is the document (the editor's ground, reading, cards, transcript bubbles). They differ by three points of warmth; that difference is the whole depth system at rest. Hairlines structure, ink speaks, and the Terracotta Seal appears the way a wax seal does on a letter — rarely, and meaningfully.\n\nThe document's voice is serif (Valkyrie OT B for prose, Concourse OT for headings, UbuntuMono for code); the chrome's voice is the platform's system sans, quiet and small. Nothing else gets a personality. The mentor is present but paper-toned — critique arrives as Fix Cards on the same Page color as the writing, never as toasts or chrome-noise. Light-only by design: one palette, live-calibrated with the owner, deliberately departed from the flatter single-surface export palette (#89). Motion is the platform default — nothing is authored, nothing performs.\n\nConfirmed visual anti-references: the sans heading face titling the document (rejected — chrome disconnected from the serif document; the title speaks the document's own voice), and dark mode (the world is one light palette).",
"keyCharacteristics": [
"Two warm papers, never more: Field Paper chrome, Page content",
"Serif document voice on a 66-character measure; system sans chrome",
"One accent (Terracotta Seal) used sparingly; one semantic green with a fixed meaning",
"Flat at rest — hairlines, not shadows; shadows only for floating panels",
"Critique is first-class: cards are content, on the Page color",
"Radius 10 world, light-only, macOS-native controls"
],
"rules": [
{
"name": "The Two-Paper Rule",
"body": "Exactly two papers exist: Field Paper for chrome, Page for content. Editing, reading, and cards share the Page — a third surface color may never be introduced.",
"section": "colors"
},
{
"name": "The One Seal Rule",
"body": "Terracotta Seal is the only accent. If a second hue is needed, the design is wrong.",
"section": "colors"
},
{
"name": "The Meaning-Green Rule",
"body": "Pine appears exclusively as the engine-ready dot. Using it as decoration, success styling, or a second accent is a violation of its meaning.",
"section": "colors"
},
{
"name": "The Document Speaks Serif Rule",
"body": "Anything that is content — the piece, the transcript's agent turns, the document title — wears the serif voice. The sans face titles nothing the writer wrote.",
"section": "typography"
},
{
"name": "The One Measure Rule",
"body": "Prose sets on the 66-character measure (24px side padding). The editor and reading mode agree on it; editing sizes mirror reading.css exactly (px → pt 1:1).",
"section": "typography"
},
{
"name": "The Floating-Panel Rule",
"body": "Shadows belong only to surfaces that float above the desk (palettes, overlays, sheets). Resting chrome never casts one; focus chrome hovers over the measure without pushing it.",
"section": "elevation"
}
],
"dos": [
"Do keep editing, reading, and cards on the same Page color — the Two-Paper Rule is the depth system.",
"Do set anything the writer wrote or the mentor said in the serif voice.",
"Do hold prose to the 66ch measure with 24px side padding.",
"Do keep critique first-class: Fix Cards are content surfaces, rendered and interacted with like the document itself.",
"Do structure with 1px hairlines at rest; reserve the two float shadows for floating surfaces only.",
"Do mirror reading.css values exactly when touching editing typography (px → pt 1:1 at 1×)."
],
"donts": [
"Don't add a dark mode or theme variants — the world is one light palette, live-calibrated.",
"Don't use Pine anywhere but the engine-ready dot — it is a meaning, not a style.",
"Don't introduce a second accent color, gradients, or colored washes; Terracotta Seal is the only hue that isn't paper or ink.",
"Don't put shadows on resting chrome.",
"Don't set a document title or content in the sans face — that was tried and rejected as chrome disconnected from the document.",
"Don't flatten domain modules into generic cards or framework-default styling; the export's geometry and states are the contract."
]
}
}
-1
View File
@@ -1,4 +1,3 @@
--swiftversion 6.3
--language-mode 5
--indent tab
--test-case-name-format preserve # convention is backticked sentence names; filter-safe camelCase exceptions allowed (#195, #31/#134)
-7
View File
@@ -1,14 +1,7 @@
disabled_rules:
- trailing_comma # SE-0439 allows them in Swift 6; SwiftFormat adds them
- identifier_name # short closure params/locals (tv/ns/lo/hi) are idiomatic, not a signal
- inclusive_language # master/masterRoot profile-root vocabulary is deliberate domain naming (2026-11-17)
- file_length # deliberately large cohesive units
- type_body_length # deliberately large cohesive units
- nesting # idiomatic nested CodingKeys/enums
- optional_data_string_conversion # intentional lossy String(decoding:) for process/file output
excluded:
- DerivedData
- spike # throwaway SPM experiments, not built into any target
line_length:
warning: 140
error: 180
+65 -35
View File
@@ -4,7 +4,7 @@
Museion — the Agentic Writing Environment (AWE): a native SwiftUI macOS app where scholars, texts, and AI minds work under a single roof. Named for the Mouseion of Alexandria.
- **Stack**: native Xcode project (`Museion.xcodeproj` at repo root, filesystem-synchronized groups — disk is truth). SwiftUI on macOS 27+ (`MACOSX_DEPLOYMENT_TARGET = 27.0`, Apple Silicon only), latest Xcode/Swift only (ADR-0001). Swift language mode 6 with default MainActor isolation, tabs.
- **Stack**: native Xcode project (`Museion.xcodeproj` at repo root, filesystem-synchronized groups — disk is truth). SwiftUI on macOS 26.5+, latest Xcode/Swift only (ADR-0001). Swift language mode 6 with default MainActor isolation, tabs.
- **Forge**: Gitea @ git.babylondreams.de (`tea` CLI), CI via Gitea Actions (ADR-0003) — needs a self-hosted macOS runner.
- **License**: GPL-3.0-or-later (ADR-0002).
@@ -14,13 +14,8 @@ Commands:
open Museion.xcodeproj # develop in Xcode
./scripts/build-and-run.sh # build + launch from CLI (⌘R equivalent)
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build # build
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # ad-hoc run incl. UI smoke (outside the rail); full-suite verification → full-test.sh below
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # test (unit + UI)
swiftformat . && swiftlint . # lint (run --fix first if dirty)
./scripts/full-test.sh start && ./scripts/full-test.sh status # verify rail (#190): detached full unit suite, xcresult-authoritative counts; status exits 3 while live
./scripts/full-test.sh summary # finished run's executed/passed/failed
./scripts/install-hooks.sh # once per clone: pre-push lint gate + no-push-while-testing
./scripts/test-full-test.sh # pre-push hook acceptance rig (disposable git repo, all ref shapes)
./scripts/release.sh # release packaging: Developer ID export → notarized DMG in dist/ (refuses without the cert)
```
# DOX framework
@@ -114,8 +109,6 @@ When the user requests a durable behavior change, record it here or in the relev
| `Museion/AGENTS.md` | App target — SwiftUI app shell, assets, entitlements |
| `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) |
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
| `scripts/` | Verify rail + hooks + build/deploy/release-packaging scripts — contracts live in each script's header; full-test.sh is the sanctioned verify rail (#190), release.sh cuts the DMG from an already-bumped commit, no child doc |
| `.agents/skills/` | Project-local agent skills (cross-tool convention, committed) — `release/`: the end-to-end release runbook (bump → notes → rail → tag → DMG → go-gated push + Gitea release); no child doc |
| `docs/AGENTS.md` | Durable documentation — ADRs and their conventions |
| `ref/writing skills/AGENTS.md` | Bundled writing-skill set — the G3a payload seeded into the museion profile |
| `GLOSSARY.md` | Binding project glossary — shared vocabulary for app, mentor, and docs |
@@ -134,39 +127,76 @@ Default five canonical roles, label string = role name. See `docs/agents/triage-
Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/domain.md`.
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (6752 symbols, 31140 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).
## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "main"})`.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method without first running `impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/museion/context` | Codebase overview, check index freshness |
| `gitnexus://repo/museion/clusters` | All functional areas |
| `gitnexus://repo/museion/processes` | All execution flows |
| `gitnexus://repo/museion/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
## Project Learnings
<!-- distill-learnings: project-learnings -->
### Tooling & gates
- Repo-wide lint is green (#194 disabled deliberate-style rules; #195/#196 cleared every finding — `spike/` stays excluded as unbuilt experiments): bare `swiftlint .` reports zero violations and `swiftformat .` reformats nothing.
- xcodebuild can serve STALE binaries on a source edited seconds before invocation (zero `SwiftCompile` lines, suite starts 3 s in) — rapid edit→test cycles and flip runs must `touch` the file and verify `SwiftCompile` lines in the run log before trusting any green (#197)
- SwiftFormat's default `swiftTestingTestCaseNames` rewrites camelCase `@Test` names back into backticked sentence style — renaming a test to a filter-safe plain identifier (#195, #31/#134) needs `--test-case-name-format preserve` in `.swiftformat`; `standard-identifiers` would dirty all ~496 backticked test names repo-wide
- git resolves short refs through `refs/tags/` before `refs/remotes/` — hooks and scripts spell `refs/remotes/<remote>/<branch>` in full or a fetched tag named `origin/main` shadows the ref (#190)
- A bash function invoked before its definition no-ops (`command not found`) under `set -uo` without `-e` — hoist definitions above first use and guard rig verdicts by executed-check count, never the banner (#190)
- GitNexus `detect-changes` in this machine's multi-repo registry needs `--repo /absolute/path` — it aborts on ambiguity but rejects the `name (path)` label form it prints (#193)
- When splitting a file, re-derive each side's imports from symbol usage, never copy the old import block — Swift has no unused-import warning, so a stranded import (PostsPaneView's AppKit) survives lint and only a diff review catches it (#193)
### Testing
- Gate-running rules are encoded in `scripts/full-test.sh` (#190) — run `./scripts/full-test.sh start` + `status` polling (`summary` for the finished counts), never hand-rolled xcodebuild/xcresult incantations. The rest of this section is authoring rules the script cannot encode.
- A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162)
- Two FSEvent-burst rescans can double-count one shared `PostScanCache` miss (both snapshot the count before either stamps it) → `contentRevision` double-bumps, benign over-invalidation — tests pinning settled-state revision must quiesce the burst (stability loop ≥ the 0.5 s FSEvents latency) before snapshotting (#197)
- Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30)
- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134)
- `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178)
- A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178)
- Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33)
- A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177)
- Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177)
- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33)
- An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151)
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — and the nested-if escape ALSO fails (swiftformat collapses it into one long line; line_length flags that). Hoist a predicate helper; that's the only stable shape (#142, #179)
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — avoid the wrap (nested ifs / a hoisted helper), don't fight the formatter (#142)
- swiftformat's self-remove strips a load-bearing `self.` when a local hoists a property for a detached capture (`let x = self.x` becomes the self-referential `let x = x`) — rename the local so nothing shadows (#143)
- A `//` note sitting between a `///` doc block and its declaration detaches the doc (swiftlint orphaned_doc_comment) — fold such notes into the `///` block (#143)
- Sequential bounded-poll loops each arm their OWN deadline — a shared one starves the later loop, which then fails on the earlier flush's stale observable (zeros, never nil) (#147)
- A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147)
- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180)
- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181)
### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33)
- Post.frontmatter is LINE-BOUNDED on read — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (stampingFrontmatter), so gate external data before it reaches a stamp, not at scan (#33)
## Session Logs
@@ -174,15 +204,15 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
| --- | --- |
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](docs/devlog/20261201-release-010-readme-notes-packaging_log.md) |
| 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](docs/devlog/20261123-home-repoint-retains-old-editor-target_log.md) |
| 2026-11-19 | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) |
| 2026-11-17 | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](docs/devlog/20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) |
| 2026-11-17 | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) |
| 2026-11-17 | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) |
| 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) |
| 2026-11-17 | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) |
| 2026-11-16 | [20261116-failed-flush-discarded-on-document-switch_log.md](docs/devlog/20261116-failed-flush-discarded-on-document-switch_log.md) |
| 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) |
|------|-----|
| 2026-11-10 | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](docs/devlog/20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) |
| 2026-11-10 | [20261110-issue182-profilelayout-config-set-rail_log.md](docs/devlog/20261110-issue182-profilelayout-config-set-rail_log.md) |
| 2026-11-10 | [20261110-issue181-provider-descriptor-pass-readiness_log.md](docs/devlog/20261110-issue181-provider-descriptor-pass-readiness_log.md) |
| 2026-11-10 | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) |
| 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) |
| 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) |
| 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) |
| 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) |
| 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_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) |
<!-- write-log: window-end -->
-27
View File
@@ -4,39 +4,12 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
## [0.1.1] - 2026-12-03
Human-readable notes: [docs/releases/0.1.1.md](docs/releases/0.1.1.md).
### Fixed
- **editor:** The external guest's file watch compares normalized text (finding `museion/external-watch-compares-unnormalized-text`, argus cycle-6; unticketed fix, brief-32) — `startExternalWatch`'s onEvent read the disk RAW while the session's `text`/`lastFlushedText` came through `readDocument`'s normalizing external branch (BOM strip + CRLF→LF), so `diskDidChange` raised the #67 conflict whenever the raw bytes differed from BOTH normalized snapshots — which they ALWAYS did for a BOM- or CRLF-carrying file, even with content unchanged. The false alarm blocked departures (select/newPost/newOutline/openExternal) and quit (the #200 gate), and re-armed after every sibling directory event (the watch observes the containing folder) and after either alert answer, until the writer's own flush rewrote the file normalized. The external branch is now the ONE shared read — `EditorSession.readExternalDocument(at:)` (raw UTF-8 → BOM strip → CRLF→LF) — called by both the open read (`readDocument`) and the watch's onEvent, so the #67 compare is normalized-to-normalized; what `readDocument` loads is unchanged (no second normalizer at the compare site, and `diskDidChange` itself is untouched). A real foreign write still raises the alert — the departure gate is not blinded. +3 tests over the real watch closure (`externalWatcher.onEvent`): no conflict on an unchanged BOM/CRLF guest (initially and across sibling events), a real write still conflicts, and no re-arm after either alert answer (yes-reload and keep-local); RED-first 3/3 at the pin (11 executed / 8 passed / 3 failed — the three new pins). Suite 720
### Changed
- **reading:** The bundled apex renderer is 1.1.59 (was 1.1.58) — the arm64 slice of the official universal release tarball, `.sha256` verified, the same single `@executable_path/../Resources/libyaml.bundle` rpath and Developer ID + hardened-runtime signature as the 0.1.0 bundling (ADR-0011 recipe unchanged; 1.1.59 still links libyaml dynamically). `--no-mixed-lists` still present.
## [0.1.0] - 2026-12-01
First release. Human-readable notes: [docs/releases/0.1.0.md](docs/releases/0.1.0.md).
### Fixed
- **reading:** The bundled apex renderer is self-contained and notarizable. apex's release build links libyaml through CI/Homebrew rpaths, so on any Mac without Homebrew it failed to launch and reading mode silently fell back to the raw source — the bundle promised "no install gate" (ADR-0011) and didn't deliver; Apple's notary service also rejects an unsigned Mach-O in Resources, which is how the 0.1.0 release run found it. Now `Resources/apex` is the arm64 slice of apex 1.1.58 (the bundle had shipped 1.1.17), Developer ID–signed with the hardened runtime, with one rpath (`@executable_path/../Resources/libyaml.bundle`) that resolves in the bundle and in the checkout alike; `Resources/libyaml.bundle/libyaml-0.2.dylib` (0.2.5, MIT) rides beside it, same team signature — inside a `.bundle` folder because Xcode's synced-folder classifier silently links a bare dylib into the app. `release.sh` now proves the shipped layout: apex must run from the export and the app must not link libyaml, before anything is notarized. `THIRD-PARTY-NOTICES.md` ships in the bundle.
- **editor:** A Home repoint is a guarded document departure (finding `museion/home-repoint-retains-old-editor-target`, argus cycle-5; unticketed fix, brief-28) — Settings → Choose… committed the new Home and flipped `watchedHome` without departing the open session: the session's immutable target kept the OLD Home, so a same-slug piece in the new library made the ID-only reselect return it (autosave/Save/quit wrote the old library while structural operations resolved against the new one), the new library's rescan raised a spurious reload conflict on it, a no-collision piece was torn down by the vanish path with its dirty buffer dropped, and a card scan from the old library could land on the new library's same-slug piece. #198's departure gate never saw this seam. Now `PostsModel.repoint(to:)` runs the SAME gate (`sessionMayDepart`'s three legs — unanswered conflict, failed flush, never-loaded retype; no parallel gate) BEFORE anything commits: a refusal changes nothing (preference, binding, the session's target and buffer stay; the #198 reason spoken once, the #200 quit-refusal posture, since no Posts strip is in sight from Settings), an acceptance lands the edits on the old library first and clears the departed piece's state — nothing auto-reopens. Document identity is (Home, ID) everywhere (`EditorSession.targets`, `PostsModel.openSessionTargets`): every bare `session.postID ==` comparison is retired across select, the structural rail, conversion, the pass guard, Micropub and the card refresh, and async continuations re-validate identity at COMPLETION (the card-scan hop-back; `rescan`'s stale-Home verdict is hoisted to cover the list, the revision and the #67 text, not just the vanish check). The in-memory draft survives a repoint (no Home until first save). +9 tests over a two-Home same-slug rig (the three refusal legs with ordering pinned, same-slug open + save on flush AND quit, no-collision cleanup, stale card scan via the per-model `scanPieceCards` seam — mutation-checked, pass after repoint; review r1: the hoisted `rescan` stale-Home verdict via the `scanLibrary` seam — mutation-checked — and the draft-survives repoint), RED-first 6/6 at the pin. Suite 717 (unticketed fix, brief-28)
- **editor:** Quit no longer bypasses the document departure gate (#200, follow-up to the #198 audit) — `PostsModel.shutdown()` flushed both sessions best-effort and ignored the results, so quitting with an unanswered reload-conflict alert wrote the local text over the foreign disk body (`flush()` holds for conflicts only in the debounce, never itself), and a failed quit-time flush silently dropped the only copy of the edits. Quit now routes through the same departure gate as navigation (`documentsMayDepart` → `sessionMayDepart`): an unanswered conflict never writes over the foreign body, and the failed-flush-at-quit posture is BLOCK QUIT — `WritingLockAppDelegate.applicationShouldTerminate` refuses termination with one spoken reason (running before the Cold Turkey ask, so a refusal never strands a walked-away block), pinned at the pure `quitReply(posts:)` seam. Finish-audit additions: a never-loaded session's retyped words refuse too (their flush is a vacuous success — the same gap closed for navigation), and the external guest's quit-time flush is pinned. +5 tests, all flip-verified. Suite 708
- **acp:** Engine backpressure can no longer defeat request deadlines, Stop, or teardown (finding `museion/acp-backpressure-defeats-timeout-and-shutdown`, argus cycle-4) — a hung engine that stops reading stdin fills the 64 KB pipe, and the ACP client's synchronous send blocked its ONE serial queue, the same queue carrying request-id allocation, pending registration, the timeout deadline, and close()'s bookkeeping barrier: the deadline never fired (a 0.1 s timeout on a 2 MB prompt stayed pending forever), a follow-up request hung at registration, Stop queued behind the stuck write, and close() synced behind it before SIGTERM was ever reachable — on MainActor (restart/quit) that was an app-wide unbounded hang. Stdin writes (and the stdin handle's own close, which a blocked write may still own) now ride a dedicated serial writer queue, leaving the state queue I/O-free: deadlines fire, Stop is accepted, bookkeeping answers, and close() runs SIGTERM → grace → SIGKILL → reap without queueing behind the writer. Wire order preserved (every send funnels through the one serial writer); healthy-engine contract untouched. +4 real-process smokes over two new zsh-fake modes (`neverRead` execs /bin/sleep — the probe's inert non-reading child, never a real profile; `serverPing` pins -32601 reply delivery): 3 RED-first at base on exactly the three mechanisms, healthy-contract pin green at base. Suite 697 (unticketed fix, brief-27)
- **search:** Library search results no longer go stale after library writes (finding `museion/library-search-stale-after-mutation`, the #144/#157 mounted gap) — the search snapshot's only task identity was the trimmed query, so nothing re-ran the sweep when the library moved underneath it: archiving or trashing a piece from a result row's own context menu left it sitting in the non-archived results after the rescan, and new, renamed, or externally edited pieces never entered or left the results until the query changed or the pane remounted. The #179 write rail's rescan now bumps a content revision whenever a scan sees the library change — a Post-list change OR any re-read post.md, so a body-only edit (which parses to an equal Post and is invisible to #143's equality-gated assignment) counts — and the mounted sweep keys on query + Home + that revision, rendering a landed snapshot only while it stays fresh for the current key (stale rows drop to the recompute spinner; panes never regroup — the assignment skip is untouched). +5 tests (pure key/gate pin; controller-level archive, trash, and same-query body-edit pins over the real rescan rail, red-first; an unchanged-rescan guard). Suite 686
- **session:** a deferred nil scope drains as an explicit clear (PR #184, finding class #176) — `pendingScopePieceTitle: String?` let "a scope request is pending" and "which piece it targets" ride the same optionality, so a nil-target request (the writer leaves the piece mid-stream or mid-replay: New Post, unsaved draft, external guest, nothing open) deferred correctly but at drain time read as "no pending request" and returned without touching `activeEntry` — the old piece's conversation stayed live under a nothing-open context, at all four drain sites. Pending-ness now rides `PendingScope` (`.none` | `.scope(String?)`): a nil target is an explicit clear everywhere it drains. Finish-audit fanout (3 reviewers): dead `Equatable` cut, the same-turn `pendingRestart` ceiling documented at the drain (the scope is lost in respawn's `.starting` window — consume-at-apply is the upgrade path), and the titled-apply half pinned for the first time over a new `hangOnPromptLoad` rig mode (prompt parks, load answers; flip-verified). Suite 654 (PR #184)
### Changed
- **cold-turkey:** Live word accounting leaves the per-keystroke path (unticketed opt pass, argus 2026-11-09, digest finding cold-turkey-full-tokenization) — the editor's `onTextChange` feed drove `WritingGoalRun.update` through `DraftStats.words` for every goal type, and `words` built the complete lowercased token array (`split(whereSeparator:)` + `map(lowercased)`) just to return its count: O(document) allocation and lowercasing per keystroke on the main actor, linear in document size (argus probe: ~0.32/3.07/16.64 ms per update at 1k/10k/50k words) — while minutes goals never read the count (verdict, progress, readout, and the completion note all ride the clock). A minutes run now does no word work on feed at all (its accounting freezes at the arm-time baseline — dead state either way), and `words` is a count-only Character pass over maximal isLetter/isNumber runs: the token array is never built, semantics byte-identical (split with omitted empty subsequences yields exactly the maximal runs; pinned against the old split expression over a mixed-script/emoji/punctuation/number corpus). Arm-time baselines still count once per arm through the same rail, now allocation-free; words-goal net accounting unchanged (exactly one rail trip per update, pinned). +3 tests — RED-first minutes zero-trips pin through an injectable word-rail seam on `update` (per-call counting; a global counter would race the hosted suite's parallel DraftStats calls), the words one-trip skip boundary, and the corpus equivalence proof. Suite 684 (unticketed opt pass)
- **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)
-228
View File
@@ -1,228 +0,0 @@
---
name: Museion
description: The Scholar's Desk — warm paper, iron-gall ink, one enameled accent
colors:
terracotta-seal: "#C96442"
pine: "#36664F"
field-paper: "#FAF9F3"
page: "#FFFEFB"
iron-gall-ink: "#1A1916"
faded-ink: "#6B6964"
hairline: "#E8E5DF"
substrate: "#F5F5F7"
reading-ink: "#1D1D1F"
reading-secondary: "#48484D"
reading-muted: "#6E6E73"
reading-hairline: "#D2D2D7"
reading-rule: "#A1A1A6"
typography:
display:
fontFamily: "Valkyrie OT B, Iowan Old Style, Charter, Georgia, serif"
fontSize: "22px"
fontWeight: 400
headline:
fontFamily: "Concourse OT Semibold, Georgia, serif"
fontSize: "30px"
fontWeight: 600
lineHeight: 1.15
title:
fontFamily: "Concourse OT Semibold, Georgia, serif"
fontSize: "22px"
fontWeight: 600
lineHeight: 1.15
subheading:
fontFamily: "Valkyrie OT B, Georgia, serif"
fontSize: "19px"
fontWeight: 700
body:
fontFamily: "Valkyrie OT B, Iowan Old Style, Charter, Georgia, serif"
fontSize: "17px"
fontWeight: 400
lineHeight: 1.8
code:
fontFamily: "UbuntuMono NFM, ui-monospace, monospace"
fontSize: "14px"
lineHeight: 1.5
label:
fontFamily: "-apple-system, system-ui, sans-serif"
rounded:
sm: "8px"
md: "10px"
lg: "12px"
spacing:
list-item: "5px"
branch: "10px"
paragraph: "17px"
page-padding: "24px"
heading-after: "30px"
heading-before: "90px"
components:
nav-rail:
backgroundColor: "{colors.field-paper}"
width: "56px"
library-column:
width: "232px"
mentor-column:
width: "356px"
editor-page:
backgroundColor: "{colors.page}"
width: "66ch"
fix-card:
backgroundColor: "{colors.page}"
textColor: "{colors.iron-gall-ink}"
rounded: "{rounded.md}"
padding: "16px"
code-panel:
backgroundColor: "{colors.substrate}"
rounded: "{rounded.sm}"
padding: "14px 16px"
typography: "{typography.code}"
---
# Design System: Museion
## Overview
**Creative North Star: "The Scholar's Desk"**
Museion is one writer's private study rendered in software: warm paper, iron-gall ink, a single enameled accent. The world is two papers — Field Paper for the desk's chrome (rails, pane grounds, the focus field) and Page for everything that *is* the document (the editor's ground, reading, cards, transcript bubbles). They differ by three points of warmth; that difference is the whole depth system at rest. Hairlines structure, ink speaks, and the Terracotta Seal appears the way a wax seal does on a letter — rarely, and meaningfully.
The document's voice is serif (Valkyrie OT B for prose, Concourse OT for headings, UbuntuMono for code); the chrome's voice is the platform's system sans, quiet and small. Nothing else gets a personality. The mentor is present but paper-toned — critique arrives as Fix Cards on the same Page color as the writing, never as toasts or chrome-noise. Light-only by design: one palette, live-calibrated with the owner, deliberately departed from the flatter single-surface export palette (#89). Motion is the platform default — nothing is authored, nothing performs.
Confirmed visual anti-references: the sans heading face titling the document (rejected — chrome disconnected from the serif document; the title speaks the document's own voice), and dark mode (the world is one light palette).
**Key Characteristics:**
- Two warm papers, never more: Field Paper chrome, Page content
- Serif document voice on a 66-character measure; system sans chrome
- One accent (Terracotta Seal) used sparingly; one semantic green with a fixed meaning
- Flat at rest — hairlines, not shadows; shadows only for floating panels
- Critique is first-class: cards are content, on the Page color
- Radius 10 world, light-only, macOS-native controls
## Colors
A warm paper-and-ink palette: every neutral leans warm, and exactly one accent carries meaning.
### Primary
- **Terracotta Seal** (#C96442): the single accent — enameled copper-terracotta. Interactive emphasis, key actions, focus rings (reading mode's `:focus-visible` outline rides it at 55% opacity). Rare by design.
### Semantic
- **Pine** (#36664F): the mentor's ready dot and nothing else. It means "engine healthy" — a status, never a style color.
### Neutral
- **Field Paper** (#FAF9F3): the desk — workspace root, nav rail, pane chrome grounds, the focus-mode editor ground.
- **Page** (#FFFEFB): the document — editor ground at rest, reading surface, fix cards, transcript bubbles, selected sidebar items.
- **Iron-Gall Ink** (#1A1916): primary text on both papers.
- **Faded Ink** (#6B6964): secondary text, metadata, quiet labels.
- **Hairline** (#E8E5DF): 1px structure — pane separators, card outlines, dividers.
- **Substrate** (#F5F5F7): code panels and recessed wells (reading surface; cooler on purpose — the reading surface has its own cooler ink family below).
- **Reading inks** — Reading Ink #1D1D1F, Reading Secondary #48484D, Reading Muted #6E6E73, Reading Hairline #D2D2D7, Reading Rule #A1A1A6: the reading mode's own slightly cooler micro-palette (reading.css `:root`), used inside the rendered document only.
### Named Rules
**The Two-Paper Rule.** Exactly two papers exist: Field Paper for chrome, Page for content. Editing, reading, and cards share the Page — a third surface color may never be introduced.
**The One Seal Rule.** Terracotta Seal is the only accent. If a second hue is needed, the design is wrong.
**The Meaning-Green Rule.** Pine appears exclusively as the engine-ready dot. Using it as decoration, success styling, or a second accent is a violation of its meaning.
## Typography
**Display Font:** Valkyrie OT B (fallback: Iowan Old Style / Charter / Georgia serif)
**Heading Font:** Concourse OT Semibold (fallback: Georgia serif)
**Body Font:** Valkyrie OT B (fallback: same as display)
**Code Font:** UbuntuMono NFM (fallback: system monospace)
**Chrome/Label Font:** system sans (`-apple-system`)
**Character:** A bookish serif carries everything the writer wrote or the mentor said; a quiet humanist sans carries only the furniture. The pairing is deliberate: the document speaks serif, the desk speaks sans.
### Hierarchy
- **Display** (400, 22px): the open document's title — the serif body face at the h2 rung. Never the sans face.
- **Headline** (600, 30px, 1.15): H1 — Concourse OT Semibold; 90px space before closes the prior section, 30px after.
- **Title** (600, 22px, 1.15): H2 — Concourse OT Semibold.
- **Subheading** (700, 19px): H3 — the serif body face, bold.
- **Body** (400, 17px, 1.8): prose on a 66ch measure; paragraph space 17px; list items 5px apart, branches 10px; blank separators render half-height (9px).
- **Code** (400, 14px, 1.5): inline and fenced, on Substrate panels.
- **Label** (system sans): chrome labels, sentence case; the mentor header's `ready` reads lowercase.
### Named Rules
**The Document Speaks Serif Rule.** Anything that is content — the piece, the transcript's agent turns, the document title — wears the serif voice. The sans face titles nothing the writer wrote.
**The One Measure Rule.** Prose sets on the 66-character measure (24px side padding). The editor and reading mode agree on it; editing sizes mirror reading.css exactly (px → pt 1:1).
## Layout
A fixed four-column workspace: nav rail (56px) | library column (232px) | editor (flexible, 420px min) | mentor column (356px). Columns collapse rather than squeeze — the library hides below 1100px window width, the mentor below 920px — mirroring the export's media queries as pane collapse. Settings runs its own two-column shape: 190px sidebar, detail forms left-anchored with a 480px max width. Reading mode centers the 66ch measure with 24px page padding. The conversation surface wears the editor's typography: Valkyrie for agent turns, Concourse OT Book for the user capsule and composer, UbuntuMono as the quiet mono voice.
## Elevation & Depth
Paper-flat at rest: resting chrome conveys structure with hairlines and the two-paper tonal step, never shadows. Depth is reserved for transient surfaces — the Fix Cards palette (a floating window), overlays, and sheets — which cast the export's two large soft shadows, tinted with ink rather than black.
### Shadow Vocabulary
- **Panel float** (`0 14px 36px rgba(26,25,22,0.14)`): floating palettes and popover cards.
- **Overlay lift** (`0 24px 80px rgba(26,25,22,0.18)`): modal overlays and large floating surfaces.
### Named Rules
**The Floating-Panel Rule.** Shadows belong only to surfaces that float above the desk (palettes, overlays, sheets). Resting chrome never casts one; focus chrome hovers over the measure without pushing it.
## Shapes
A radius-10 world: cards, panels, and interactive containers round at 10px; small controls and reading-surface code/images at 8px; the engine-status pill at 12px. Status dots are full circles. Library rows carry a 2px leading state strip. Borders are 1px hairlines; blockquotes get a 3px rule edge (1.5px for nesting).
## Components
### Navigation Rail
The desk's spine: 56px wide on Field Paper, icon destinations (Posts / Sessions / Learnings / Trends / Archive), the engine-status pill, and Settings at the foot. Icons quiet; the active destination reads by tone, not by a colored block.
### Library Column
232px; project section heads over Pass-State groups, per-view collapse toggle. **Library Post Row**: Page-colored row with a 2px leading strip encoding pass state, `✳` marking outline pieces, title in ink, metadata in Faded Ink; row menu (Rename / Convert / Move / Trash) in the system style. Selected rows fill with Page against the Field Paper ground.
### Editor Page
The Page-colored writing surface: 66ch measure, Valkyrie 17/1.8, autosave. Focus mode repaints the editor's ground to Field Paper — the two papers merge; overlays hover without pushing the measure. Reading mode (⌘R) renders the same Page via the reading pipeline with its own cooler inks.
### Mentor Column
356px; serif header with the engine chip (Pine dot + lowercase `ready`), the shared transcript, and the composer. Agent turns in Valkyrie, user capsule and composer in Concourse OT Book. **PassBar**: Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry their reason inline, the missing-key line links to Settings.
### Fix Cards (signature)
The critique made visible: Page-colored cards, radius 10, hairline border, problem → diagnostic question → fix, with lane and emitter chips and anchored quote. They live in a floating palette window (open cards first) and Apply is ask-before — a blocking sheet shows the exact edit. Never a toast, never auto-applied, never batch.
### Code Panel
Substrate ground, radius 8, 14px/1.5 UbuntuMono, 14px 16px padding. Fenced blocks in the document and code anywhere it appears.
### Sheets
The house ask sheets (Origin ask, Outline guard, Convert, New Project) ride the platform sheet with Page grounds and left-anchored forms — one decision per sheet, refusal keeps buttons visible.
## Do's and Don'ts
### Do:
- **Do** keep editing, reading, and cards on the same Page color — the Two-Paper Rule is the depth system.
- **Do** set anything the writer wrote or the mentor said in the serif voice.
- **Do** hold prose to the 66ch measure with 24px side padding.
- **Do** keep critique first-class: Fix Cards are content surfaces, rendered and interacted with like the document itself.
- **Do** structure with 1px hairlines at rest; reserve the two float shadows for floating surfaces only.
- **Do** mirror reading.css values exactly when touching editing typography (px → pt 1:1 at 1×).
### Don't:
- **Don't** add a dark mode or theme variants — the world is one light palette, live-calibrated.
- **Don't** use Pine anywhere but the engine-ready dot — it is a meaning, not a style.
- **Don't** introduce a second accent color, gradients, or colored washes; Terracotta Seal is the only hue that isn't paper or ink.
- **Don't** put shadows on resting chrome.
- **Don't** set a document title or content in the sans face — that was tried and rejected as chrome disconnected from the document.
- **Don't** flatten domain modules into generic cards or framework-default styling; the export's geometry and states are the contract.
+6 -8
View File
@@ -405,7 +405,6 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
@@ -424,7 +423,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -442,7 +441,6 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
@@ -461,7 +459,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -484,7 +482,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -506,7 +504,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -526,7 +524,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -546,7 +544,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 0.1.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
+8 -45
View File
@@ -75,9 +75,6 @@ nonisolated extension JSONValue {
/// matches responses to pending requests, and delivers notifications in wire
/// order. Requests are expected to be strictly sequential (initialize →
/// session/new → prompt), matching the pane's usage.
/// brief-27: stdin writes ride a dedicated writer queue, so engine
/// backpressure (a full pipe) can stall a send but never a deadline,
/// Stop delivery, or teardown.
///
/// Wire facts baked in (verified against adapter 0.20.6 + the acp SDK):
/// - `session/cancel` is a JSON-RPC *notification* (interfaces.py — CancelNotification).
@@ -97,12 +94,6 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
private let stderrPipe = Pipe()
/// All mutable state below is confined to this serial queue.
private let queue = DispatchQueue(label: "com.babylondreams.Museion.acp-client")
/// brief-27: stdin writes (and the stdin handle's own close) ride this
/// dedicated writer queue. The state queue NEVER touches the pipe — a
/// full pipe (hung engine not reading stdin) blocks only this writer, so
/// request deadlines, Stop delivery, and close()'s bookkeeping stay live
/// behind it. Serial = the wire order every send site already had.
private let writerQueue = DispatchQueue(label: "com.babylondreams.Museion.acp-client-writer")
private var pending: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
private var buffer = Data()
private var currentID = 0
@@ -157,10 +148,6 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Send a JSON-RPC request and await its matching response result.
/// A request that gets no answer within `timeout` fails — a hung engine
/// must surface as an error (→ restart prompt), never an eternal await.
/// brief-27: a timed-out request's bytes may still reach the engine once
/// the child unblocks (the deadline fails the caller, never dequeues the
/// write) — phantom engine work only: ids are never reused and the
/// response path drops unknown ids, so a late reply can never misroute.
/// (No default arguments: the only caller is EngineHost, which rides the
/// seam — `EngineTransport.request`'s convenience owns the default shape.)
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? {
@@ -187,9 +174,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
continuation.resume(throwing: TransportError(message: "engine closed before \(method)"))
return
}
// brief-27: straight to the writer queue — never through the state
// queue, so a blocked write can't pin the deadline armed below.
send(raw)
queue.async { self.send(raw) }
// ponytail: deadline on the same serial queue — fires only if the
// response hasn't already resumed and removed the continuation.
queue.asyncAfter(deadline: .now() + timeout) {
@@ -209,15 +194,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
// brief-27: writer queue, not the state queue (see request).
send(raw)
queue.async { self.send(raw) }
}
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the
/// child never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// brief-27: bounded even when a stdin write is blocked on a full pipe —
/// bookkeeping syncs on the (I/O-free) state queue, and child
/// termination never queues behind the writer.
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the child
/// never outlives the app (same pattern as EngineProbe.terminateAndReap).
func close() {
let alreadyClosed = queue.sync {
if closed {
@@ -246,14 +227,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
}
}
process.waitUntilExit()
// brief-27: the stdin WRITE handle closes on the writer queue — a
// blocked write may still own it (it unblocks only once the child's
// read end died, which the kill above just arranged); closing under
// a live write would race Foundation. The reader handles have no
// writers — their handlers are already off, so they close here.
writerQueue.async {
try? self.stdinPipe.fileHandleForWriting.close()
}
try? stdinPipe.fileHandleForWriting.close()
try? stdoutPipe.fileHandleForReading.close()
try? stderrPipe.fileHandleForReading.close()
}
@@ -262,21 +236,10 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Frame and write one NDJSON line. A failed write (child gone) is dropped:
/// the crash path owns the UX, not the send.
/// brief-27: the write runs on the WRITER queue, never the state queue —
/// a blocked write here starves no deadline and no teardown.
private func send(_ data: Data) {
// ponytail: queued sends are unbounded, and a send racing close() writes
// onto a closed handle (benign — write throws a catchable CocoaError 512
// that try? swallows; probe-verified by two independent reviewers).
// Bounded today by MentorSessionModel's sequential-send discipline (a
// request is awaited before the next; worst case one prompt + one
// cancel). Add a closed/depth guard here if a looping or
// non-MainActor caller ever appears.
writerQueue.async {
var framed = Data(data)
framed.append(0x0A)
try? self.stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
var framed = Data(data)
framed.append(0x0A)
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
/// Fail every pending request and surface the crash — the one exit path
+13 -24
View File
@@ -23,37 +23,28 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in `docs/devlog/`.
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller).
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`.
- `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108).
- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them.
- `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `![alt](assets/…)` builder.
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the immutable pair (origin writer, type post — never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via `stampingFrontmatter` — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility read from the file's own frontmatter (writer/First Draft/post); failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `![alt](assets/…)` builder.
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. `WritingLockAppDelegate` (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — `quitReply(posts:)` is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk.
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session.
- `TrendsPaneView.swift` — per-metric line charts over first-draft captures; only pieces with `firstDraftStats` appear (the view answers "am I getting better", never "is this draft good"); one capture shows a value, no verdict. `TrendMetric` (pure): fixed y-domains (burstiness −1…1, TTR + trigram 0…1, sentenceVariation scaled to 1.2× peak, floor 1), verdict at ±0.01 (trigram inverted), one explain line per metric.
- `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `<home>/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress).
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail.
- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through `sessionMayDepart`/`departOpenDocuments` — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25).
- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal` (`-> Bool` — false holds the departure)/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards (one rail, mentor not mid-turn, engine ready, open saved piece) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal". `blindRead` mirrors the guards; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
- Prose list machinery — `ProseList.swift` (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); `ProseListTextView.swift` — folds are VIEW state (buffer never changes; hidden scopes styled via `foldedAttributes`), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (`rekey`), the newline gate is `\.isNewline` NEVER literal `\n`/`\r` compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through `ProseDropBridge` into `ingestDrop` (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure `dropIndex` (sampling + bracket + binary search; the SwiftUI closure's `location` is unusable under this hosting, off-screen rects return garbage).
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — #181: `ModelProvider` is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire `dialect` (chat/models paths + the SSE decoder selector), `authMode` (Bearer vs Anthropic's header pair), `keyless` (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. `ProviderCredential` = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: surface writes and the base_url write-through ride the HermesConfigRail (#182 — the writer only builds its key list: provider, default, effort set-or-unset, base_url LAST); provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection; paths via ProfileLayout). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot). `PassReadiness.swift` — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + `.env` key through the settings seam and resolves credentials through `ProviderCredential` (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
- Settings — `SettingsPaneView.swift` (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's `binaryPath` and hydrates at open; detail forms left-anchored). `SettingsModel.swift` — `ModelProvider` slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship `anthropic/claude-sonnet-5`, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach `.env`); `hydrate` reads only and never stomps a pending edit. `HermesSettingsWriter.swift` — the real write path: everything through the engine's own CLI, wire-verified `✓ Set` lines; provider keys upsert into ALL THREE profiles' `.env` (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); `model.base_url` written LAST (`config set model.provider` clears it). `ProviderProbe.swift` — Test Connection: every request carries `Content-Type: application/json` (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic `x-api-key` + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions); 512 token cap; errors riding a 2xx decode as the provider error. `onChatSurfaceWrite` → `requestRestart` (chat surface only — pass engines are one-shot).
- Focus mode — transient per-launch (no persistence); `FocusChrome` hover zones + overlay panels float over the measure, never push it; `CaretCentering` is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (`ColdTurkeySeat`/`ColdTurkeyDot`) mounts as overlays on the focused branch only.
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary (arm64, Developer ID–signed with the hardened runtime at commit time, beside `libyaml.bundle/libyaml-0.2.dylib` — self-contained through the single rpath `@executable_path/../Resources/libyaml.bundle`; the `.bundle` wrapper is load-bearing: a bare dylib in the synced folder (with or without extension — Xcode sniffs Mach-O content) becomes the APP's link target; re-sign both when the Developer ID certificate rotates) with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
- Reading mode (ADR-0011) — `ReadingPresenter.swift`: the bundled apex binary with `-t html --no-mixed-lists --embed-images` (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access); `<!--S:N-->` sentinels rewritten to `data-source-line` stamps; `blocks(for:)` = the click→edit line map; stylesheet = `Resources/reading.css` read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. `ReadingSurface.swift` — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
- `AppGateState.museionHome` — fresh installs resolve once and PIN the winner: legacy `~/Documents/Museion` (dir-ness gated) → `<CloudDocs>/Museion` (resolved at the unprefixed path, never a hard-coded `iCloud~` form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.
## Engine check (gateless launch)
@@ -65,14 +56,12 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## Profile provisioning
- `ProfileLayout.swift` — #182: the ONE owner of the Hermes profile layout: `defaultRoot` (`~/.hermes/profiles`) and the per-profile path builders (`profileDir`, `envFile(in:)`, `configuredMarker(in:)`, `gatewayPID(in:)`, `skillsDir(in:)`). The provisioner, the settings writer, and backup derive every path through it — no literal profile-root string lives outside (RESTORE.md prose and the ps-scan grep pattern are text, not paths; pinned in ProfileLayoutTests).
- `HermesConfigRail.swift` — #182: the ONE owner of the `hermes -p <profile> config set/unset` contract: argv shape (set value + `--force`), provider-first ordering (switching providers clears a stale inherited `model.base_url` — the rail hoists `model.provider` first, callers can't order it wrong), ✓-line verification (exit 0 AND `✓ Set`/`✓ Unset` on stdout; unset-of-absent = idempotent success). Callers hand it their own key lists: the provisioner seeds provider/default/max_tokens, the settings writer edits provider/default/effort/base_url. `Failure` carries key/profile/excerpt for both error surfaces; secrets never ride it (argv only carries non-secret keys).
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the HermesConfigRail — provider first, wire-verified; marker-gated by the layout's `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
- `ProfileProvisioner.swift` — `ProfileSurface` (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; `allocatedSkills` per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). `perform` = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at `~/Library/Application Support/Museion/skills/` (`masterRoot` injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): **create** (dir-check first; the adopted `museion` is never re-created), **configure** (the #132 defaults through the engine's own CLI, provider first; success WIRE-VERIFIED `✓ Set` on stdout; marker-gated by `.museion-provisioned` so user Settings changes survive; the adopted museion is NEVER configured), **skills** (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), **register** (museion-tools via `mcp add` CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh `config set` writes not apply). `Outcome.failed` names the profile.
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/`. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation; `ste-writing`/`writing-for-agents` never seed.
## Profile backup
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours; profile + pid paths via ProfileLayout, #182); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
- `ProfileBackup.swift` — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under `~/Library/Application Support/Museion/Backups/`, retention 7; `RESTORE.md` written once. Failure = one os_log line, never an alert.
## museion-tools MCP server
@@ -84,10 +73,10 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## ACP bridge
- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
## Work Guidance
-176
View File
@@ -1,176 +0,0 @@
//
// ArchivePaneView.swift
// Museion
//
// #193: the #108 Archive pane, moved from WorkspaceView.swift
// (file-length ceiling), code unchanged (private → internal:
// WorkspaceView instantiates it cross-file now).
//
import SwiftUI
/// #108: the Archive pane — archive/ as a rail destination (prototype
/// verdict: a destination, not a library disclosure). List-only: clicking a
/// piece selects it and hops to Posts, where the editor column lives.
struct ArchivePaneView: View {
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
let onOpenPiece: () -> Void
@State private var renamingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted
/// (mirrors the library column).
@State private var collapsed: Set<String> = []
private var archivedByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
}
/// #108: the prototype's toggle — click the project name (or chevron).
private func toggle(_ project: String) {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
var body: some View {
VStack(spacing: 0) {
// No New button — things arrive here by being moved, not created.
// r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME
// fixed 720pt column the rows live in — one framed block.
PaneHeader(title: "Archive", hairlineMaxWidth: 720)
if archivedByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order, matching the library's sort.
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = archivedByProject[project] ?? []
// Same section-head shape as the library (#108
// variant B), plus the project-level way out.
// r7 (mercury#55, argon#41 — FINAL, supersedes the
// r6 D24 ladder): the content column is a FIXED
// 720pt frame (width, not maxWidth — the r6
// content-hugging bound let the pill define the
// right edge), left-anchored. TWO axes only, the
// library's r7 ladder: the head row leads at x14
// (chevron in a 14pt slot) with its label at x28 —
// the ONE indent, shared with the entry rows'
// inner text via the shared LibraryPostRow (cards
// lead at x14); the 'Unarchive Group' pill rides
// the header row's trailing edge INSIDE the frame
// (14 → 706), and the row hairlines are bounded by
// the same frame. Nothing spans past it.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
.onTapGesture {
withAnimation { toggle(project) }
}
.accessibilityLabel("Toggle \(project)")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
Text(project)
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.kerning(0.6)
.textCase(.uppercase) // #108: display-only — the folder name keeps its case
.foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final
.lineLimit(1)
.truncationMode(.tail)
.onTapGesture {
withAnimation { toggle(project) }
}
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.padding(.leading, 8)
Spacer(minLength: 8)
// The 'New Post · Fork · Compact' language — a
// bordered mono-11 secondary pill at the
// trailing edge INSIDE the fixed 720pt frame.
// r7 (mercury#55, argon#41): relabeled
// 'Unarchive Group' — it moves the whole
// project, not one piece.
Button("Unarchive Group") {
model.unarchiveProject(project)
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
.help("Move the whole project back to projects/")
.accessibilityLabel("Unarchive \(project)")
}
.padding(.top, 12)
.padding(.horizontal, 14)
.padding(.bottom, 2)
if !collapsed.contains(project) {
ForEach(pieces) { post in
// r7: the shared LibraryPostRow ladder —
// card leads at x14 (PRIMARY), title text
// at x28 (the one indent). The hairline is
// BOUNDED to the fixed frame: x14 → 706.
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id)
onOpenPiece()
}
.overlay(alignment: .bottom) {
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
.padding(.horizontal, 14)
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post)
}
Button("Rename…") { renamingPost = post }
// #114 (S4): works archived too — the piece
// stays where it is, only type + body flip.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post)
}
}
}
}
}
}
}
// r7 (mercury#55, argon#41): the FIXED 720pt reading
// column — width, not maxWidth (the r6 content-hugging
// bound let the pill define the right edge); rows,
// hairlines, and the pill all live inside it.
// ponytail: fixed width clips on panes narrower than
// 720 — a width-floored variant if a small-window
// Archive ever matters.
.frame(width: 720, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 12)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title)
}
}
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("Nothing archived")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
+2 -20
View File
@@ -79,28 +79,10 @@ nonisolated struct DraftStats: Equatable {
/// Word count over the same token semantics every text metric
/// rides (#161: Cold Turkey net-words counts with this — one
/// word rail, no drift). "writer's" is two words here, headings
/// tokenizer, no drift). "writer's" is two words here, headings
/// are body text, frontmatter is not (the editor never shows it).
/// Count-only (opt pass 2026-11-09): one Character pass counting
/// maximal isLetter/isNumber runs — the lowercased [String] the
/// per-keystroke editor feed once paid for is never built. Equal
/// to the tokenizer's split by construction (omitting empty
/// subsequences leaves exactly the maximal runs); pinned against
/// the split expression over a mixed-script corpus.
static func words(in text: String) -> Int {
var count = 0
var inRun = false
for character in text {
if character.isLetter || character.isNumber {
if !inRun {
count += 1
inRun = true
}
} else {
inRun = false
}
}
return count
tokens(in: text).count
}
/// Lowercased runs of Characters where isLetter || isNumber — the
+6 -35
View File
@@ -63,24 +63,6 @@ final class EditorSession {
return nil
}
/// brief-28: document identity — a post session is (Home, ID), never the
/// bare id: two libraries can hold the same slug, and only the pair says
/// which piece the buffer belongs to. The target is immutable, so the
/// Home here is the one the session was BORN under — a model whose
/// `watchedHome` moved past it must treat this session as a foreign
/// document, not as its own open piece.
func targets(postID id: String, home: URL) -> Bool {
guard case let .post(mine, myHome) = target else { return false }
return mine == id && myHome == home
}
/// brief-28: the Home half alone — does this post session live under
/// `home`? External guests never do.
func targets(home: URL) -> Bool {
guard case let .post(_, myHome) = target else { return false }
return myHome == home
}
/// The document's folder — the piece's resolved folder under projects/
/// or archive/ for posts (image resolution #71; resolved once at init,
/// ADR-0012 — a vanished piece still needs some path, so an unresolvable
@@ -157,27 +139,16 @@ final class EditorSession {
private static func readDocument(_ target: SessionTarget) -> String? {
switch target {
case let .post(id, home):
PostStore.readBody(id: id, home: home)
return PostStore.readBody(id: id, home: home)
case let .externalFile(url):
readExternalDocument(at: url)
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") {
text.removeFirst()
}
return text.replacingOccurrences(of: "\r\n", with: "\n")
}
}
/// #67/brief-32: the ONE external-target disk read — raw UTF-8, BOM
/// stripped, CRLF normalized to LF. Every reader of an external file's
/// bytes goes through here (the open read above, the guest watch in
/// PostsModelImports, Yes-reload, keep-local), so the #67 compare is
/// always normalized-to-normalized: the watch used to read raw and
/// raised a false conflict on every directory event over an unchanged
/// BOM/CRLF file.
static func readExternalDocument(at url: URL) -> String? {
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") {
text.removeFirst()
}
return text.replacingOccurrences(of: "\r\n", with: "\n")
}
/// Target-aware write: posts → `PostStore.overwrite` (+ sidecar);
/// external → the whole text, in place, no sidecar (#93).
private func writeDocument() throws {
+2 -2
View File
@@ -422,7 +422,7 @@ nonisolated enum FixCardStore {
.sorted()
return files.compactMap { name in
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8),
LearningDecay.passesHidden(PostFrontmatter.parse(markdown), currentPass: currentPass) == nil
LearningDecay.passesHidden(Post.frontmatter(of: markdown), currentPass: currentPass) == nil
else { return nil }
return (file: name, markdown: markdown)
}
@@ -444,7 +444,7 @@ nonisolated enum FixCardStore {
for _ in 0 ..< 4 {
home.deleteLastPathComponent()
}
return (home, PostFrontmatter.decoded(PostFrontmatter.parse(text)).type)
return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post)
}
// MARK: - Promote (#26, S4.1/S4.3)
+6 -5
View File
@@ -149,7 +149,7 @@ private struct CardRow: View {
.controlSize(.small)
} else {
Button("Done") {
gate.posts.doneCard(card)
gate.posts.doneCard(card, home: gate.museionHome)
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -174,11 +174,11 @@ private struct CardRow: View {
// Apply = ask-before, a BLOCKING ask: the sheet is the only path
// from the Apply button to a write.
.sheet(isPresented: $asking) {
ApplyAskSheet(card: card, posts: gate.posts)
ApplyAskSheet(card: card, posts: gate.posts, home: gate.museionHome)
}
// #26: Promote is its own blocking ask — one confirm, one Learning.
.sheet(isPresented: $promoting) {
PromoteAskSheet(card: card, posts: gate.posts)
PromoteAskSheet(card: card, posts: gate.posts, home: gate.museionHome)
}
}
@@ -217,7 +217,7 @@ private struct SkipButton: View {
var body: some View {
Button("Skip") {
gate.posts.skipCard(card)
gate.posts.skipCard(card, home: gate.museionHome)
}
.buttonStyle(.borderless)
.controlSize(.small)
@@ -232,6 +232,7 @@ private struct SkipButton: View {
private struct ApplyAskSheet: View {
let card: FixCardStore.StoredFixCard
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
@State private var wentStale = false
@@ -288,7 +289,7 @@ private struct ApplyAskSheet: View {
}
private func apply() {
switch posts.applyCard(card) {
switch posts.applyCard(card, home: home) {
case .applied:
dismiss()
case .stale:
-94
View File
@@ -1,94 +0,0 @@
//
// HermesConfigRail.swift
// Museion
//
// #182: the ONE owner of the `hermes -p <profile> config set/unset` CLI
// contract — argv shape, provider-first ordering (switching providers
// clears stale inherited values — live-probed), and ✓-line verification.
// The provisioner (seeds provider/default/max_tokens) and the settings
// writer (edits provider/default/effort/base_url) hand the rail their own
// key lists; the mechanism and ordering rule live only here (pinned once
// in HermesConfigRailTests over the shared fake-hermes double).
//
// Secrets never ride this rail (`ps` reads live command lines) — it only
// ever carries provider/model/effort/base_url values.
//
import Foundation
nonisolated enum HermesConfigRail {
/// One CLI write: a set (key/value, `--force` for keys some engine
/// versions don't recognize), or an unset.
enum Write: Sendable {
case set(key: String, value: String, force: Bool)
case unset(key: String)
}
/// A wire-verified write that failed — structured so each caller keeps
/// its own error surface (the provisioner's Outcome excerpt; the
/// writer's `lastWriteError` text).
struct Failure: Error, Sendable, LocalizedError {
let verb: String
let key: String
let profile: String
let excerpt: String
var errorDescription: String? {
"couldn't \(verb) \(key) on \(profile): \(excerpt)"
}
}
/// Executes the ops provider-first, each wire-verified: exit 0 AND the
/// `✓ Set <key>` / `✓ Unset <key>` line on stdout — a CLI that exits 0
/// while writing nothing must not count as configured. An unset of an
/// absent key is idempotent success (exit 1 + the not-set line).
static func apply(_ writes: [Write], profile: String, binary: String, timeout: TimeInterval) throws {
// Provider first, relative order otherwise preserved: `config set
// model.provider` clears a stale inherited `model.base_url`, so
// everything after it sees the new provider.
let ordered = writes.filter(isProviderSet) + writes.filter { !isProviderSet($0) }
for write in ordered {
switch write {
case let .set(key, value, force):
// Trust boundary: free-text fields (model IDs, endpoints)
// feed this rail, and a leading `-` is an option to the
// child CLI, never a value — no legitimate value starts
// with a dash (learning #6's class: gate at the seam).
guard !value.hasPrefix("-") else {
throw Failure(verb: "set", key: key, profile: profile, excerpt: "value starts with '-' — not written")
}
var arguments = [binary, "-p", profile, "config", "set", key, value]
if force {
arguments.append("--force")
}
let run = EngineProbe.execute(arguments, timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw Failure(verb: "set", key: key, profile: profile, excerpt: excerpt(run))
}
case let .unset(key):
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw Failure(verb: "unset", key: key, profile: profile, excerpt: excerpt(run))
}
}
}
}
private static func isProviderSet(_ write: Write) -> Bool {
if case let .set(key, _, _) = write {
key == "model.provider"
} else {
false
}
}
/// Errors carry CLI output only — key-bearing text never reaches error
/// surfaces. #180 audit: the rail absorbed the two callers' excerpts and
/// keeps the provisioner's 500-char cap (the more-lossless twin; the
/// writer's old 300 was the outlier), a deliberate divergence.
static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
}
}
+55 -27
View File
@@ -79,7 +79,7 @@ struct NoopSettingsWriter: SettingsWriting {
struct HermesSettingsWriter: SettingsWriting {
let hermesBinary: String?
var profileRoot: String = ProfileLayout.defaultRoot
var profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath
struct WriteError: LocalizedError, Equatable {
let message: String
@@ -100,24 +100,18 @@ struct HermesSettingsWriter: SettingsWriting {
}
let binary = hermesBinary, profile = surface.profileName
try await Task.detached(priority: .utility) {
// The rail owns the mechanism and the provider-first rule (#182):
// provider (switching clears a stale base_url — probed), then the
// model, then effort (set or unset), then the z.ai endpoint family.
var ops: [HermesConfigRail.Write] = [
.set(key: "model.provider", value: config.provider.rawValue, force: false),
.set(key: "model.default", value: config.model, force: false),
]
// Provider first (switching clears a stale base_url — probed),
// then the model, then effort, then the z.ai endpoint family.
try Self.setKey("model.provider", config.provider.rawValue, profile: profile, binary: binary, timeout: 30)
try Self.setKey("model.default", config.model, profile: profile, binary: binary, timeout: 30)
if let effort = config.effort {
ops.append(.set(key: "model.reasoning_effort", value: effort.rawValue, force: false))
try Self.setKey("model.reasoning_effort", effort.rawValue, profile: profile, binary: binary, timeout: 30)
} else {
ops.append(.unset(key: "model.reasoning_effort"))
try Self.unsetKey("model.reasoning_effort", profile: profile, binary: binary, timeout: 30)
}
// Whitespace-only = empty (learning #6: mirror the trimmed
// emptiness the model side validates, not raw isEmpty).
if let zaiEndpoint, !zaiEndpoint.trimmingCharacters(in: .whitespaces).isEmpty {
ops.append(.set(key: "model.base_url", value: zaiEndpoint, force: false))
if let zaiEndpoint, !zaiEndpoint.isEmpty {
try Self.setKey("model.base_url", zaiEndpoint, profile: profile, binary: binary, timeout: 30)
}
try HermesConfigRail.apply(ops, profile: profile, binary: binary, timeout: 30)
}.value
}
@@ -134,9 +128,7 @@ struct HermesSettingsWriter: SettingsWriting {
config: ProviderKeyConfig,
profiles: [ProfileSurface],
) async throws {
// Whitespace-only endpoint/key = empty (learning #6: trimmed
// emptiness, never raw isEmpty, at free-text gates).
let writesBaseURL = provider == .zai && !config.endpoint.trimmingCharacters(in: .whitespaces).isEmpty
let writesBaseURL = provider == .zai && !config.endpoint.isEmpty
if writesBaseURL, hermesBinary == nil {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
@@ -145,19 +137,14 @@ struct HermesSettingsWriter: SettingsWriting {
let binary = hermesBinary
try await Task.detached(priority: .utility) {
for surface in ProfileSurface.allCases {
let dir = ProfileLayout.profileDir(surface.profileName, root: root)
let dir = (root as NSString).appendingPathComponent(surface.profileName)
if !key.isEmpty {
try Self.upsertEnvFile(varName: varName, value: key, profileDir: dir, profile: surface.profileName)
}
}
if let endpoint, let binary {
for surface in profiles {
try HermesConfigRail.apply(
[.set(key: "model.base_url", value: endpoint, force: false)],
profile: surface.profileName,
binary: binary,
timeout: 30,
)
try Self.setKey("model.base_url", endpoint, profile: surface.profileName, binary: binary, timeout: 30)
}
}
}.value
@@ -198,7 +185,8 @@ struct HermesSettingsWriter: SettingsWriting {
let root = profileRoot, varName = provider.envVarName
return await Task.detached(priority: .utility) { () -> String? in
for surface in ProfileSurface.allCases {
let envPath = ProfileLayout.envFile(in: ProfileLayout.profileDir(surface.profileName, root: root))
let envPath = ((root as NSString).appendingPathComponent(surface.profileName) as NSString)
.appendingPathComponent(".env")
guard let text = try? String(contentsOfFile: envPath, encoding: .utf8) else { continue }
for line in text.split(separator: "\n") where line.hasPrefix("\(varName)=") {
let value = line.dropFirst("\(varName)=".count).trimmingCharacters(in: .whitespaces)
@@ -211,6 +199,46 @@ struct HermesSettingsWriter: SettingsWriting {
}.value
}
// MARK: CLI rail (wire-verified, the provisioner's posture) — nonisolated:
// they run inside Task.detached, off the actor.
private nonisolated static func setKey(
_ key: String,
_ value: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "set", key, value], timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw WriteError(message: "couldn't set \(key) on \(profile): \(excerpt(run))")
}
}
private nonisolated static func unsetKey(
_ key: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
// Absent already = the desired state (idempotent; exit 1 + not-set line).
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw WriteError(message: "couldn't unset \(key) on \(profile): \(excerpt(run))")
}
}
/// Secrets never ride argv (`ps` reads live command lines) — this rail
/// only ever carries provider/model/effort/base_url. Errors keep the
/// same guarantee: excerpt content is CLI output, key text never
/// reaches `lastWriteError`.
private nonisolated static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))
}
// MARK: .env edit
/// Upsert `VAR=value` preserving every other line (hermes' own .env
@@ -244,7 +272,7 @@ struct HermesSettingsWriter: SettingsWriting {
}
envWriteLock.lock()
defer { envWriteLock.unlock() }
let envPath = ProfileLayout.envFile(in: profileDir)
let envPath = (profileDir as NSString).appendingPathComponent(".env")
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
let updated = upsertEnv(varName: varName, value: value, in: existing)
do {
-15
View File
@@ -80,19 +80,4 @@ extension AppGateState {
nonisolated static func storeHome(_ home: URL, in defaults: UserDefaults) {
defaults.set(home.absoluteString, forKey: "museionHome")
}
/// brief-28 (home-repoint-retains-old-editor-target): the ONE repoint
/// entry at runtime — the departure gate runs FIRST (`posts.repoint`:
/// every open document lands, or nothing changes and `posts.lastError`
/// names the piece); the preference and its persistence (`museionHome`'s
/// didSet) commit only after. True = committed. WorkspaceView's Settings
/// binding routes through here; the root `.task(id: museionHome)` binds
/// the model after the commit, so `watchedHome` can never move past a
/// live session again.
@discardableResult
func repointMuseionHome(to newHome: URL) -> Bool {
guard posts.repoint(to: newHome) else { return false }
museionHome = newHome
return true
}
}
+47 -5
View File
@@ -160,7 +160,7 @@ nonisolated enum LearningDecay {
throw FixCardStore.CardError(message: "learning not found: \(file)")
}
let frontmatter = PostFrontmatter.parse(text)
let frontmatter = Post.frontmatter(of: text)
let clock = passCounts(home: home)[typeDir] ?? 0
if let remaining = passesHidden(frontmatter, currentPass: clock) {
throw FixCardStore.CardError(message: "already dismissed — resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes")")
@@ -168,10 +168,8 @@ nonisolated enum LearningDecay {
// Clamped before +1 — an absurd hand-edited dismiss_count must not
// trap the stamp.
let count = min(dismissCount(in: frontmatter), valueCeiling)
// #180: the codec's update-keys posture (the mechanical walk this
// file used to own); the Learning document shape is unchanged.
let stamped = PostFrontmatter.updating(
text: text,
let stamped = stampingFrontmatter(
of: text,
with: [
("dismissed", FixCardStore.formatted(now, "yyyy-MM-dd")),
("dismiss_count", "\(count + 1)"),
@@ -180,4 +178,48 @@ nonisolated enum LearningDecay {
)
try stamped.write(to: url, atomically: true, encoding: .utf8)
}
/// The surgical frontmatter rewrite (mergedFrontmatter's line-walk,
/// generalized to ordered pairs): set-overwrite the keys in place,
/// insert absent ones before the closing `---`, preserve every other
/// line verbatim (leading hand-edit lines above the opening `---`
/// included), keep the block's trailing newline. No frontmatter
/// block at all → prepend a fresh one. Internal since #31: the
/// first-draft stats capture is the third caller.
// ponytail: PostStore.mergedFrontmatter's line-walk duplicated and
// generalized — extraction would grow PostStore at its type-body
// ceiling; #31's capture is the third caller and it STILL isn't
// extracted (LearningDecay + PostStore stay the two owners; the
// type-body ceilings named above are unchanged).
static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String {
let (block, body) = PostStore.splitFrontmatter(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
}
// Lines ABOVE the opening `---` (a hand-edit blank line —
// Post.frontmatter tolerates one) fall in neither block nor
// body; keep them verbatim so the rewrite loses nothing (#27 review).
let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? ""
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return prefix + lines.joined(separator: "\n") + "\n" + body
}
}
+4 -11
View File
@@ -32,7 +32,7 @@ nonisolated enum LearningsIndex {
let resurfacesIn: Int?
init(file: String, text: String, currentPass: Int? = nil) {
let frontmatter = PostFrontmatter.parse(text)
let frontmatter = Post.frontmatter(of: text)
id = file
pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file)
problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 }
@@ -75,10 +75,8 @@ nonisolated enum LearningsIndex {
) else { return [] }
var groups: [Group] = []
for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."),
let files = try? FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil,
) else { continue }
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
else { continue }
// #27: the pass clock feeds the decay verdict — clocked dirs
// carry their count, foreign dirs nil (no verdict; Entry's audit).
let currentPass = LearningDecay.isClocked(dir.lastPathComponent)
@@ -111,14 +109,9 @@ nonisolated enum LearningsIndex {
return groups
}
/// Parens load-bearing for readability — `&&` out-binds `??` (probed;
/// a finish-audit misread the bare form as a dead symlink clause).
/// lstat semantics: a symlink-to-dir reports isDirectory=false, so
/// both halves refuse it; the link clause is the belt for any future
/// resolved-URL caller.
private static func isPlainDirectory(_ url: URL) -> Bool {
let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
return (values?.isDirectory ?? false) && !(values?.isSymbolicLink ?? false)
return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false)
}
}
-94
View File
@@ -1,94 +0,0 @@
//
// LibraryPostRow.swift
// Museion
//
// #193: the shared post row, moved from PostsPaneView.swift
// (file-length ceiling) — the Archive pane reuses it, code
// unchanged.
//
import SwiftUI
/// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
/// Archive pane reuses it.
struct LibraryPostRow: View {
let post: Post
let selected: Bool
let select: () -> Void
@State private var hover = false
var body: some View {
// `.vB .post-row { border-left: 2px solid transparent;
// border-radius: 0 8px 8px 0 }` — every row: leading corners square
// (the 2px strip below), trailing rounded 8. Only the strip's
// VISIBILITY changes on selection.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) {
HStack(spacing: 0) {
// The leading strip is always 2px wide so hover/selection
// never shifts the title. r6 (mercury#49/52, argon#13):
// the shared SelectedRowStrip capsule — accent, radius-1
// ends, vertically inset 6pt (was 3) so it sits INSIDE
// the card, never pasted on its square leading edge.
SelectedRowStrip()
.opacity(selected ? 1 : 0)
VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text(post.title)
if post.type == .outline {
Text(" ✳")
.foregroundStyle(DesignTokens.muted)
}
}
// ui-polish r8: serif-13 per the row contract — `.callout`
// was the system sans design (the r6/r7 councils pixel-
// verified sans glyphs on the Archive rows).
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
// Origin only — the Pass State already rides the uppercase
// group label above (it stays in the accessibility label).
// r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge.
Text(post.origin.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
}
.clipShape(shape)
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.background {
if selected || hover {
// r8 (mercury#11): the selected row DROPS its gray outline —
// fill + accent capsule read as ONE shape; stacking fill +
// outline + capsule competed. Hover keeps its borderless
// 0.06 wash exactly as before.
shape
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
}
}
// r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
// leads at the PRIMARY inset (x14, the 'Posts' header text's
// edge); its INNER content (title + status micro-label, strip
// 2 + padding 12) lands at x28 — the ONE indent step, shared
// with the head text and the group labels. No other x-axis
// exists in the column. Vertical padding stays the content
// VStack's constant 10 whether or not the row shows its strip.
.padding(.horizontal, 14)
.onHover { hover = $0 }
// help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
}
}
-27
View File
@@ -32,31 +32,4 @@ nonisolated enum LibrarySearch {
}
return titleHits + bodyHits
}
/// #144 (mounted half): the identity of one search sweep — the
/// trimmed query, the Home it ran under, and the library content
/// revision it saw (`PostsModel.contentRevision`). The column's
/// `.task(id:)` re-keys on ANY difference, so a keystroke, a Home
/// repoint, or a library write that landed after the last sweep
/// restarts it instead of serving the stale snapshot.
nonisolated struct SearchKey: Equatable {
var query: String
var homePath: String
var revision: Int
}
/// #144 (mounted half): one landed sweep — the results plus the key
/// that produced them. `isFresh` is the column's stale gate: results
/// render only under the key that computed them, so an archived,
/// trashed, renamed, or since-edited library drops to the recompute
/// state, never stale rows.
nonisolated struct Snapshot: Equatable {
var key: SearchKey
var results: [Post]
/// A snapshot renders only under its own key.
func isFresh(for key: SearchKey) -> Bool {
self.key == key
}
}
}
+6 -5
View File
@@ -92,7 +92,7 @@ struct MentorPaneView: View {
// Pass 2 selector replaced the mode picker; the transcript +
// composer below are the conversation surface, chat is not a
// mode.
PassBarView(posts: posts, model: model, onOpenSettings: onOpenSettings)
PassBarView(posts: posts, home: home, model: model, onOpenSettings: onOpenSettings)
Divider()
if let posts, !posts.openPieceCards.isEmpty {
// #23 follow-up + #156 ruling: a plain mono row — a link,
@@ -385,6 +385,7 @@ private struct PassBarView: View {
/// The selected pass — the bar's own state (nothing outside reads it).
@State private var kind: PassKind = .pass1
let posts: PostsModel?
let home: URL?
let model: MentorSessionModel
/// #137 (S4): the missing-key line's way out — WorkspaceView's pane hop.
let onOpenSettings: (() -> Void)?
@@ -546,8 +547,8 @@ private struct PassBarView: View {
}
private func runPass() {
guard let posts else { return }
Task { await posts.runPass(kind, mentor: model) }
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
}
/// #122: the Blind Read — one purposeful click judges the current
@@ -559,8 +560,8 @@ private struct PassBarView: View {
style: .secondary,
disabled: blindReadBlocked != nil,
) {
guard let posts else { return }
Task { await posts.blindRead(mentor: model) }
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
}
.help(
blindReadBlocked
+63 -28
View File
@@ -149,17 +149,13 @@ nonisolated enum SessionRoster {
let dir = directory ?? defaultDirectory
do {
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json")
try JSONEncoder().encode(entries).write(
to: rosterURL,
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"),
options: .atomic,
)
// Finish-audit: names+ids only, but piece titles are the writer's
// business — the default umask would hand them to every local user.
// ponytail: post-hoc chmod leaves a sub-second world-readable window
// between write and chmod — createFile(0600)+rename if a hostile
// local account ever matters.
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: rosterURL.path)
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path)
} catch {
// ponytail: the roster is a convenience index; a write failure must not crash the gate.
}
@@ -293,17 +289,13 @@ final class MentorSessionModel {
}
private var pendingScope: PendingScope = .none
/// #137: per-pass readiness — refreshed at pane entry (re-entry
/// re-fires the pane's .task — the key-added-in-Settings re-enable
/// path). #181: computed in the PassReadiness module over the provider
/// descriptor (the model reads no keys and no auth files); stored here
/// because the pane observes it. `passReadinessWriter` is the
/// injectable read seam (tests).
/// #137: per-pass readiness (refreshPassReadiness, same-file #137
/// extension) + the injectable read seam (tests). Stored in the class
/// body — extensions carry no stored state.
private(set) var passReadiness: [PassKind: PassReadiness] = [:]
var passReadinessWriter: (any SettingsWriting)?
/// #175: the shared Portal auth store — handed to the readiness
/// module's credential resolution; injectable so tests never read the
/// machine's real login.
/// #175: the shared Portal auth store for the nous keyless readiness
/// fallback — injectable so tests never read the machine's real login.
var portalAuthPath: String = PortalAuth.defaultAuthPath
/// The gate's winning binary path (no re-probe — map decision). Set by
@@ -728,26 +720,69 @@ extension MentorSessionModel {
host.isOneShotRunning
}
// #137 (S4): the Run Pass posture — is the pass profile's provider
// keyed? .unknown NEVER blocks (our own read failure — the spawn's
// honest failure row owns that path); .missingKey names the provider
// so the pane can say what's missing and link to Settings.
// #181: the enum and the refresh live in the PassReadiness module.
/// #137 (S4): the Run Pass posture — is the pass profile's provider
/// keyed? .unknown NEVER blocks (our own read failure — the spawn's
/// honest failure row owns that path); .missingKey names the provider
/// so the pane can say what's missing and link to Settings.
enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
}
// Per-pass readiness (stored in the class body), refreshed at pane
// entry (re-entry re-fires the pane's .task — the key-added-in-
// Settings re-enable path). `passReadinessWriter` is the injectable
// read seam; nil at refresh time → an ad-hoc HermesSettingsWriter
// over the gate's binary (profileRoot default).
func readiness(for kind: PassKind) -> PassReadiness {
passReadiness[kind] ?? .unknown
}
/// #181: thin delegate — the reads and the keyless fallback live in
/// the PassReadiness module over the provider descriptor. No
/// binaryPath and no injected writer → readiness stays empty
/// (.unknown everywhere).
/// Read each pass profile's provider (readSurface, one task group),
/// then each DISTINCT provider's key (readProviderKey). A surface we
/// can't read maps .unknown; a non-empty key maps .ready; no key maps
/// .missingKey with the provider's label. No binaryPath and no
/// injected writer → readiness stays empty (.unknown everywhere).
func refreshPassReadiness() async {
guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return }
passReadiness = await PassReadiness.refresh(
writer: writer,
portalAuthPath: portalAuthPath,
)
var providers: [ProfileSurface: ModelProvider] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in [ProfileSurface.pass1, .pass2] {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
providers[surface] = read?.config.provider
}
}
var keys: [ModelProvider: String] = [:]
for provider in Set(providers.values.compactMap(\.self)) {
var key = await (try? writer.readProviderKey(provider: provider)) ?? ""
// #175: nous runs on the shared Portal login — an empty `.env`
// key is not a blocker when the session's agent_key exists (the
// engine's own credential; API key and subscription bill the
// same account credits).
if provider == .nous, key.isEmpty {
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
}
keys[provider] = key
}
for surface in [ProfileSurface.pass1, .pass2] {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let provider = providers[surface] else {
passReadiness[kind] = .unknown
continue
}
if let key = keys[provider], !key.isEmpty {
passReadiness[kind] = .ready
} else {
passReadiness[kind] = .missingKey(providerLabel: provider.label)
}
}
}
/// Send a prompt and stream the reply into the ACTIVE session's
+2 -10
View File
@@ -244,22 +244,14 @@ extension PostsModel {
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
home: URL,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
// brief-28: identity — the open session must target THIS library's
// selected piece (Home, ID); the wire below reads the session's OWN
// library, never the current Home's same-slug file. The completion
// stamp targets the same captured pair — the piece actually sent,
// wherever the writer has since pointed the app.
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home),
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
@@ -279,7 +271,7 @@ extension PostsModel {
else {
return .refused("Couldn't read the piece before sending.")
}
let body = PostFrontmatter.split(raw).body
let body = PostStore.splitFrontmatter(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
+2 -1
View File
@@ -17,6 +17,7 @@ import SwiftUI
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
@@ -161,7 +162,7 @@ struct MicropubPublishSheet: View {
refusal = nil
phase = .drafting
Task {
switch await posts.micropubSendDraft(token: token) {
switch await posts.micropubSendDraft(home: home, token: token) {
case let .drafted(url, preview):
draftURL = url
previewURL = preview
-3
View File
@@ -67,9 +67,6 @@ final class AppGateState {
) {
// Explicit init: `Self` in a stored-property initializer trips
// @ObservationTracked's macro expansion (covariant Self).
// #200: the app delegate's quit gate reaches the one posts model
// (the WritingLockState.active precedent).
PostsModel.active = posts
if let stored = Self.fileHomeURL(in: defaults) {
museionHome = stored
return
+44 -60
View File
@@ -55,7 +55,10 @@ nonisolated enum OutlinePresenter {
_ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
) -> [Row] {
var rows: [Row] = []
if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) {
if let zoomRootID,
let rootPath = path(of: zoomRootID, in: nodes),
let root = node(at: rootPath, in: nodes)
{
walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows)
} else {
walk(nodes, parent: [], depth: 0, folded: folded, into: &rows)
@@ -773,14 +776,27 @@ extension OutlineEditorView {
}
case let .hop(direction):
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
hopFocus(direction, clearsAnchor: true)
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
if let current = rows.firstIndex(where: { $0.id == focusedID }),
rows.indices.contains(current + direction)
{
focusedID = rows[current + direction].id
selectionAnchor = nil
pendingCaret = nil // caret at end of the target row
}
case let .extend(direction):
// ⇧↑/⇧↓: extend the block selection one visible row. First
// press anchors at the focused row; a bare ↑/↓ or click clears.
if let focusedID {
extendSelection(to: focusedID) // arm the anchor at the current focus
}
hopFocus(direction, clearsAnchor: false)
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
if let current = rows.firstIndex(where: { $0.id == focusedID }),
rows.indices.contains(current + direction)
{
focusedID = rows[current + direction].id
pendingCaret = nil
}
case .deselect:
_ = handleEscape() // selection first, then zoom — same order as the monitor
case .indent, .outdent, .moveUp, .moveDown, .enter:
@@ -788,27 +804,20 @@ extension OutlineEditorView {
}
}
/// Move focus `direction` visible rows from its current position (nil at
/// the list edges — folded subtrees are skipped). `clearsAnchor`
/// distinguishes hop (clears the block-selection anchor) from extend.
private func hopFocus(_ direction: Int, clearsAnchor: Bool) {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
guard let current = rows.firstIndex(where: { $0.id == focusedID }),
rows.indices.contains(current + direction)
else { return }
focusedID = rows[current + direction].id
if clearsAnchor {
selectionAnchor = nil
}
pendingCaret = nil // caret at end of the target row
}
/// Tree-mutating ops (indent/outdent/move/enter). Serialize + route
/// focus only when something actually changed (boundary no-ops are
/// nil and leave the document alone).
private func applyTree(_ op: OutlineRowTextView.StructureOp) {
guard let focusedID else { return }
if applyBatchIfPossible(op, focus: focusedID) {
// Block selection + batchable op → run-wide apply. Moves treat
// the run as a unit (boundary leader no-ops the whole batch).
if let anchor = selectionAnchor,
let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1,
let batchOp = map(op)
{
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
pushToDocument()
}
return
}
guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return }
@@ -824,52 +833,27 @@ extension OutlineEditorView {
case .moveDown:
didChange = OutlineTree.move(&nodes, path: path, up: false) != nil
case let .enter(caretGraphemes):
let enter = applyEnter(caretGraphemes: caretGraphemes, path: path)
didChange = enter.didChange
newFocus = enter.focus
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
case .noOp:
break
case let .outdented(newPath):
didChange = newPath != nil // nil = boundary no-op
case let .newNode(newPath, caret):
didChange = true
if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id {
newFocus = (id, caret)
}
}
case .fold, .unfold, .hop, .extend, .deselect:
return // unreachable — apply(_:) routes those to view state
}
commitIfChanged(didChange, newFocus)
}
/// Serialize + route focus only when something actually changed.
private func commitIfChanged(_ didChange: Bool, _ newFocus: (id: UUID, caret: Int)?) {
guard didChange else { return }
if let newFocus {
focusedID = newFocus.id
pendingCaret = newFocus.caret
}
pushToDocument()
}
/// Block-selection fast path: a batchable op over a multi-row run
/// (moves treat the run as a unit — a boundary leader no-ops the whole
/// batch). Returns true when the batch ran (caller stops here).
private func applyBatchIfPossible(_ op: OutlineRowTextView.StructureOp, focus: UUID) -> Bool {
guard let anchor = selectionAnchor,
let range = selectedRangeIDs(anchor: anchor, focus: focus), range.count > 1,
let batchOp = map(op)
else { return false }
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
if didChange {
if let newFocus {
self.focusedID = newFocus.id
pendingCaret = newFocus.caret
}
pushToDocument()
}
return true
}
/// Split (⏎) at `path`: serialize through OutlineTree.enter; focus
/// follows the NEW node when one was created (nil path = boundary
/// no-op).
private func applyEnter(caretGraphemes: Int, path: [Int]) -> (didChange: Bool, focus: (id: UUID, caret: Int)?) {
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
case .noOp:
return (false, nil)
case let .outdented(newPath):
return (newPath != nil, nil) // nil = boundary no-op
case let .newNode(newPath, caret):
let id = OutlinePresenter.node(at: newPath, in: nodes)?.id
return (true, id.map { ($0, caret) })
}
}
/// The selected row ids in visible order (anchor↔focus, inclusive).
-79
View File
@@ -1,79 +0,0 @@
//
// PassReadiness.swift
// Museion
//
// ## Scenario: pass readiness over the provider descriptor
// From #181
//
// Given the pass profiles' providers read through the settings seam
// When pass readiness refreshes
// Then each pass surface maps to ready / missingKey / unknown through the
// ONE credential resolution (provider key, else the Portal session key
// for keyless providers) — the session model stores the verdicts and
// itself reads no keys and no auth files.
import Foundation
/// #181: per-pass readiness — ready / missingKey / unknown, computed
/// over the provider descriptor. Formerly the session model's #137
/// nested enum: the profile reads (surface provider, `.env` key, Portal
/// auth store) live HERE now; MentorSessionModel stores the verdicts its
/// pane observes.
nonisolated enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
/// Read each pass surface's provider (readSurface, one task group),
/// then resolve each DISTINCT provider's credential through the ONE
/// rail (ProviderCredential — provider key, else the Portal session
/// key for keyless providers). A surface we can't read maps .unknown
/// (our own read failure never blocks — the spawn's honest failure row
/// owns that path); a refused credential maps .missingKey naming the
/// provider. Nil/empty `base_url` means the provider's default family
/// (the family the session key is allowed to ride).
static func refresh(
writer: any SettingsWriting,
portalAuthPath: String,
) async -> [PassKind: PassReadiness] {
let surfaces = [ProfileSurface.pass1, .pass2]
var reads: [ProfileSurface: (config: SurfaceModelConfig, baseURL: String?)] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in surfaces {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
if let read {
reads[surface] = read
}
}
}
var envKeys: [ModelProvider: String] = [:]
for provider in Set(reads.values.map(\.config.provider)) {
envKeys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? ""
}
var verdicts: [PassKind: PassReadiness] = [:]
for surface in surfaces {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let read = reads[surface] else {
verdicts[kind] = .unknown
continue
}
let provider = read.config.provider
let endpoint = read.baseURL.flatMap { $0.isEmpty ? nil : $0 } ?? provider.defaultEndpoint
switch await ProviderCredential.resolve(
provider: provider,
envKey: envKeys[provider] ?? "",
endpoint: endpoint,
portalAuthPath: portalAuthPath,
) {
case .key:
verdicts[kind] = .ready
case .refused:
verdicts[kind] = .missingKey(providerLabel: provider.label)
}
}
return verdicts
}
}
-193
View File
@@ -1,193 +0,0 @@
//
// PostFrontmatter.swift
// Museion
//
// #180: the Post frontmatter codec — the ONE lenient read and the three
// write postures (fresh / merge-import / update-keys) behind one
// known-key table and one insertion-order rule. Absorbs and deletes the
// near-twin writers: PostStore.stamped (fresh), PostStore.mergedFrontmatter
// (merge-import), LearningDecay.stampingFrontmatter (update-keys) — each
// posture is byte-identical to the writer it replaced (merge-import's
// documented prefix-preservation divergence excepted), so existing pieces
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
// of scope (#180); their dismiss stamp rides the generic update posture
// without redesigning its shape.
//
import Foundation
/// #180: one engine for the flat `---`-delimited block every post.md
/// carries. Read leniently (absent or unknown keys decode to their
/// defaults — a bare legacy corpus post is a normal piece), written
/// through exactly three postures:
///
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
/// with our three owned keys winning in place (importFile, #95).
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
/// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss).
///
/// The known-key table and its stamp order (`type`, `pass_state`,
/// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order.
nonisolated enum PostFrontmatter {
/// The leniently-decoded identity triple — one home for the `?? default`
/// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this
/// fourth caller).
struct Stamp: Equatable {
let type: Post.ContentType
let passState: Post.PassState
let origin: Post.Origin
}
// MARK: - Read
/// The `---`-delimited frontmatter block's keys if present; empty
/// otherwise. Quoted scalar values (`origin: "ai"`) are unquoted —
/// lenient YAML. Values are line-bounded by construction (#33).
static func parse(_ text: String) -> [String: String] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] }
var map: [String: String] = [:]
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard let colon = trimmed.firstIndex(of: ":") else { continue }
let key = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func split(_ text: String) -> (block: String, body: String) {
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
all[open].trimmed() == "---",
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
else { return ("", text) }
let block = all[open ... close].joined(separator: "\n") + "\n"
return (block, all[(close + 1)...].joined(separator: "\n"))
}
/// The lenient stamp decode: absent or unknown keys read as their
/// defaults (post / First Draft / writer) — the same verdicts
/// `Post.scan`, `existingStamp`, and the capture gate must agree on.
static func decoded(_ matter: [String: String]) -> Stamp {
Stamp(
type: Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
passState: Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
origin: Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
)
}
// MARK: - Eligibility (#180: named once, consumed twice)
/// The Unaided First Draft immutable pair — writer origin ∧ post type
/// (CONTEXT.md). Never pass_state: that legitimately advances after a
/// capture. This is the pair the scan's read-back gate re-gates on, so
/// `stats_*` keys arriving by import on an ai or outline piece never
/// render, while a migrated writer piece keeps its real arc (#32).
static func isUnaidedFirstDraftPair(_ matter: [String: String]) -> Bool {
let stamp = decoded(matter)
return stamp.origin == .writer && stamp.type == .post
}
/// Unaided First Draft capture eligibility — the immutable pair ∧
/// Pass State First Draft. What the capture gate checks at pass
/// invocation against the file's own frontmatter (#31).
static func isCaptureEligible(_ matter: [String: String]) -> Bool {
let stamp = decoded(matter)
return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft
}
// MARK: - Write postures
/// The known-key table: Museion's three owned keys in stamp order —
/// the ONE insertion-order rule every posture shares.
static func ownedKeys(
type: Post.ContentType, passState: Post.PassState, origin: Post.Origin,
) -> [(key: String, value: String)] {
[
("type", type.rawValue),
("pass_state", passState.rawValue),
("origin", origin.rawValue),
]
}
/// Posture 1 — fresh: the #59 v1 block (+ `type`, #107). Flat keys,
/// the exact shape `parse` reads. Any existing block is replaced by
/// design (writeNew births, bare files normalize, convert rebuilds).
static func stamped(
body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post,
) -> String {
"---\n"
+ ownedKeys(type: type, passState: passState, origin: origin)
.map { "\($0.key): \($0.value)" }.joined(separator: "\n")
+ "\n---\n" + body
}
/// Posture 3 — update-keys: the surgical line-walk. Set-overwrite the
/// pairs in place, insert absent ones before the closing `---` (pair
/// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the
/// pairs.
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
let (block, body) = split(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
}
// Lines ABOVE the opening `---` (a hand-edit blank line — parse
// tolerates one) fall in neither block nor body; keep them verbatim
// so the rewrite loses nothing.
let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? ""
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
// ponytail: flat keys only — an indented `key: value` inside a
// nested YAML block scalar is matched and rewritten unindented;
// the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// if nested frontmatter ever matters.
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return prefix + lines.joined(separator: "\n") + "\n" + body
}
/// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post). The update posture over the known-key table.
///
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
/// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String {
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
}
}
+31 -11
View File
@@ -179,14 +179,15 @@ nonisolated struct Post: Identifiable, Equatable {
/// kept this a pure function of (text, location); the cache memoizes
/// its output, nothing else).
private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post {
let frontmatter = PostFrontmatter.parse(text)
let stamp = PostFrontmatter.decoded(frontmatter)
let frontmatter = frontmatter(of: text)
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
return Post(
id: id,
title: title(of: text),
passState: stamp.passState,
origin: stamp.origin,
type: stamp.type,
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
origin: origin,
type: type,
project: project,
isArchived: isArchived,
// #33: the remembered Micro.blog draft URL —
@@ -198,18 +199,37 @@ nonisolated struct Post: Identifiable, Equatable {
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which
// legitimately advances after the capture. `stats_*`
// keys can arrive by import (external YAML rides
// verbatim), so an imported ai piece or outline
// #32 read-back gate: the capture gate's immutable
// pair (origin writer, type post) — NOT pass_state,
// which legitimately advances after the capture.
// `stats_*` keys can arrive by import (external YAML
// rides verbatim), so an imported ai piece or outline
// carrying hand-stamped keys still never renders;
// a migrated writer piece keeps its real arc.
firstDraftStats: PostFrontmatter.isUnaidedFirstDraftPair(frontmatter)
firstDraftStats: origin == .writer && type == .post
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
)
}
/// The `---`-delimited frontmatter block if present; empty otherwise.
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
static func frontmatter(of text: String) -> [String: String] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] }
var map: [String: String] = [:]
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard let colon = trimmed.firstIndex(of: ":") else { continue }
let key = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
+95 -31
View File
@@ -154,7 +154,7 @@ nonisolated enum PostStore {
origin: Post.Origin = .writer, home: URL,
) throws -> Post {
try materialize(
text: PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: origin, type: type),
text: stamped(body: body, passState: .firstDraft, origin: origin, type: type),
title: Post.title(of: body),
origin: origin,
project: project,
@@ -181,10 +181,11 @@ nonisolated enum PostStore {
raw.removeFirst()
}
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let text = PostFrontmatter.mergingImport(text: raw, origin: origin)
let (block, body) = splitFrontmatter(raw)
let text = mergedFrontmatter(keeping: block, origin: origin) + body
return try materialize(
text: text,
title: Post.title(of: PostFrontmatter.split(raw).body),
title: Post.title(of: body),
origin: origin,
project: project,
type: .post, // #95: our keys win — external `type: outline` still imports as post
@@ -192,6 +193,48 @@ nonisolated enum PostStore {
)
}
/// #95/#107: external frontmatter keys ride along verbatim; `type`,
/// `pass_state` and `origin` are set/overwritten in place — our three
/// keys win, everything else untouched. Absent keys are inserted before
/// the closing `---` (in that order). Returns the block INCLUDING its
/// trailing newline; "" for a bare file (the caller then writes the #59
/// stamp shape via a fresh block).
private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
guard !block.isEmpty else {
return "---\ntype: post\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
}
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
// #107: three our-keys win — type/pass_state/origin set-overwrite in
// place, absent ones insert before the closing --- in stamp order.
// Ordered pairs (a Dictionary's iteration order is unspecified).
let ours: [(key: String, value: String)] = [
("type", "post"),
("pass_state", Post.PassState.firstDraft.rawValue),
("origin", origin.rawValue),
]
let oursByKey = Dictionary(ours.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = ours.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return lines.joined(separator: "\n") + "\n"
}
/// #62/#95: lazily materialize `projects/<project>/<slug>/post.md` with
/// the given (already stamped/merged) text. Shared by `writeNew` and
/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
@@ -232,7 +275,7 @@ nonisolated enum PostStore {
/// file's present `pass_state`/`origin`/`type` are preserved (origin
/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59).
/// **#31 audit fix: blocked files update the three owned keys IN PLACE
/// (PostFrontmatter.updating) and swap in the caller's body — the old
/// (stampingFrontmatter) and swap in the caller's body — the old
/// stamped() round-trip rebuilt the block from three parsed fields,
/// erasing the first-draft stats captured at the pass invocation and
/// any foreign frontmatter on every editor save.** A vanished post
@@ -241,14 +284,13 @@ nonisolated enum PostStore {
static func overwrite(id: String, body: String, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
// #180: the codec's postures — bare files take the fresh stamp,
// blocked files update the owned keys in place (the update walk)
// and swap in the caller's body.
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostFrontmatter.split(PostFrontmatter.updating(text: raw, with: PostFrontmatter.ownedKeys(
type: piece.type, passState: piece.passState, origin: piece.origin,
))).block + body
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostStore.splitFrontmatter(LearningDecay.stampingFrontmatter(of: raw, with: [
("type", piece.type.rawValue),
("pass_state", piece.passState.rawValue),
("origin", piece.origin.rawValue),
])).block + body
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -265,14 +307,13 @@ nonisolated enum PostStore {
else {
throw CocoaError(.fileReadNoSuchFile)
}
let matter = PostFrontmatter.parse(existing)
let stamp = PostFrontmatter.decoded(matter)
let matter = Post.frontmatter(of: existing)
return (
dir,
stamp.passState,
stamp.origin,
stamp.type,
PostFrontmatter.split(existing).body,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
splitFrontmatter(existing).body,
)
}
@@ -282,7 +323,7 @@ nonisolated enum PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return nil }
return PostFrontmatter.split(text).body
return splitFrontmatter(text).body
}
/// #114 (S4): Convert to Post — the one-time in-place transform. The
@@ -293,7 +334,7 @@ nonisolated enum PostStore {
static func convert(id: String, headingsLadder: Bool, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let transformed = headingsLadder ? OutlineTree.headingsLadderBody(piece.body) : piece.body
try PostFrontmatter.stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
try stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -308,7 +349,7 @@ nonisolated enum PostStore {
}
let fileURL = dir.appendingPathComponent("post.md")
let text = try String(contentsOf: fileURL, encoding: .utf8)
let (block, body) = PostFrontmatter.split(text)
let (block, body) = splitFrontmatter(text)
try (block + replacingTitleLine(of: body, with: "# \(title)"))
.write(to: fileURL, atomically: true, encoding: .utf8)
@@ -476,6 +517,24 @@ nonisolated enum PostStore {
return trimmed
}
/// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the
/// #17 reader parses.
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String {
"---\ntype: \(type.rawValue)\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func splitFrontmatter(_ text: String) -> (block: String, body: String) {
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
all[open].trimmed() == "---",
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
else { return ("", text) }
let block = all[open ... close].joined(separator: "\n") + "\n"
return (block, all[(close + 1)...].joined(separator: "\n"))
}
/// Replace the body's Title heading with `line`; a body whose first
/// non-empty line is NOT a heading keeps that line (it's content) and
/// gets the heading inserted above it. An empty body becomes just `line`.
@@ -546,7 +605,7 @@ nonisolated extension PostStore {
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
/// on a Pass-2 Done piece never regresses it. **#31 (S5.1): the state
/// update is an IN-PLACE key stamp (PostFrontmatter.updating), not the
/// update is an IN-PLACE key stamp (stampingFrontmatter), not the
/// existingStamp→stamped block rewrite — the rewrite carried only
/// type/pass_state/origin and silently erased the first-draft stats
/// captured at the invocation (and any foreign frontmatter).** Bare
@@ -556,9 +615,9 @@ nonisolated extension PostStore {
let piece = try existingStamp(id: id, home: home)
let advanced = higherState(piece.passState, kind.doneState)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: PostFrontmatter.updating(text: raw, with: [("pass_state", advanced.rawValue)])
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: LearningDecay.stampingFrontmatter(of: raw, with: [("pass_state", advanced.rawValue)])
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
// The decay clock counts completed passes per content type (#27).
// try?: a failed clock bump must never fail a completed pass, and
@@ -649,7 +708,7 @@ nonisolated extension PostStore {
/// own frontmatter alone (same lenient defaults as Post.scan — a bare
/// legacy post qualifies): origin writer, Pass State First Draft, type
/// post. Not eligible → false, file untouched. The stamp is in place
/// (PostFrontmatter.updating): every non-stats line byte-identical, so a
/// (stampingFrontmatter): every non-stats line byte-identical, so a
/// re-invocation while still First Draft overwrites — latest draft
/// state wins. Any read/write failure → false: a failed capture must
/// never fail the pass (the decay-clock posture).
@@ -658,11 +717,16 @@ nonisolated extension PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
// #180: the named capture predicate — pair ∧ First Draft, leniently
// decoded (a bare legacy post qualifies).
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let matter = Post.frontmatter(of: text)
// ponytail: third copy of the lenient `?? default` stamp decode
// (Post.scan, existingStamp) — extract one shared decode when a
// fourth caller needs it.
guard Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer == .writer,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft == .firstDraft,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post == .post
else { return false }
let stats = DraftStats.compute(body: body)
let stamped = PostFrontmatter.updating(text: text, with: [
let stamped = LearningDecay.stampingFrontmatter(of: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
@@ -688,7 +752,7 @@ nonisolated extension PostStore {
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
try LearningDecay.stampingFrontmatter(of: raw, with: [("micropub_url", url)])
.write(to: file, atomically: true, encoding: .utf8)
}
}
-521
View File
@@ -1,521 +0,0 @@
//
// PostsLibraryColumn.swift
// Museion
//
// #193: the Posts library column, moved from PostsPaneView.swift
// (file-length ceiling) — PostsLibraryColumn with its rename/move
// sheets, the file-scope librarySearch mount (#144), and
// LaunchFocusReset (r8), code unchanged.
//
import AppKit
import SwiftUI
/// #21: the library column, shared by the unfocused layout and the focus-mode
/// left reveal overlay — one implementation, both surfaces. Owns the rename +
/// move sheets and the context menu (they travel with the post rows).
/// #108 variant B: sections per project, Pass-State groups inside.
struct PostsLibraryColumn: View {
let home: URL
var model: PostsModel
@State private var renamingPost: Post?
@State private var movingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted (a
/// fresh open shows everything; the prototype behaved the same).
@State private var collapsed: Set<String> = []
/// #144: the library search — live title+body filter over the
/// non-archived pieces. nil = not searching (sections render).
@State private var query = ""
/// #144 (mounted half): the landed sweep — results plus the key that
/// computed them. nil = not searching or recomputing (the sections /
/// spinner states); a snapshot that isn't `isFresh` for the current
/// key never renders.
@State private var snapshot: LibrarySearch.Snapshot?
/// r5 (argon#44, mercury#52, sol#37): focus state for the field's
/// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7
/// onAppear-unfocus could never work — the launch focus is AppKit
/// assigning the window's INITIAL first responder to its first text
/// input (this field), at window-become-key, AFTER onAppear. FocusState
/// merely mirrors that back as true. LaunchFocusReset (below) resigns
/// it at the first become-key; from then on only the user drives this.
@FocusState private var searchFocused: Bool
private var trimmedQuery: String {
query.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// #144 (mounted half): the sweep's identity — trimmed query, the
/// Home, and the library content revision (`PostsModel.contentRevision`,
/// bumped by the rescan rail on any list change or re-read body). The
/// `.task(id:)` below re-keys on ANY difference, so library writes and
/// Home repoints restart the sweep instead of leaving stale rows; the
/// landed snapshot renders only while `isFresh` for the current key.
private var searchKey: LibrarySearch.SearchKey {
LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision)
}
private var isSearching: Bool {
!trimmedQuery.isEmpty
}
/// Non-archived pieces keyed by project (scan order = title order holds
/// inside each group — filter preserves it).
private var activeByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project)
}
var body: some View {
VStack(spacing: 0) {
PaneHeader(title: "Posts") {
Button {
model.newPost()
} label: {
Image(systemName: "plus")
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.help("New Post")
.accessibilityLabel("New Post")
}
searchField
if isSearching {
// #144 (mounted half): a landed sweep renders only while
// fresh for the CURRENT key — a library write that bumped
// the revision (archive, trash, rename, body edit) or a
// moved query drops to the recompute state, never stale rows.
if let snapshot, snapshot.isFresh(for: searchKey) {
if snapshot.results.isEmpty {
searchEmptyState
} else {
searchResults(snapshot.results)
}
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
} else if activeByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order (scan's own sort), not Unicode-scalar
// order — the heads render lowercased, "Beta" must not read before "apple".
ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = activeByProject[project] ?? []
// #108: the head is the prototype's toggle — click
// collapses the project's pieces (chevron rotates).
Button {
withAnimation {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
} label: {
// r7 (mercury#18, argon#12 — TWO-AXIS ladder,
// the r6 four-step collapse undone): the
// head ROW leads at the column's PRIMARY
// inset (x14) — chevron glyph in a 14pt slot
// — and every nested CONTENT shares the one
// indent step (x28): head text, group
// labels, and the rows' inner text. No third
// or fourth x-axis exists in the column.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
Text(project)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.textCase(.lowercase) // #108: display-only — the folder name keeps its case
.lineLimit(1)
.truncationMode(.tail)
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
}
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.accessibilityLabel("\(project), \(pieces.count) pieces")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
.padding(.top, 16)
.padding(.horizontal, 14)
.padding(.bottom, 6)
if !collapsed.contains(project) {
passStateGroups(pieces)
}
}
}
.padding(.bottom, 12)
}
}
}
.frame(width: DesignTokens.libraryWidth)
// r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7
// onAppear-unfocus — see LaunchFocusReset below for the mechanism.
.background(LaunchFocusReset())
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title)
}
}
.sheet(item: $movingPost) { post in
// #108 audit 2: disk-derived list, localized-sorted — same order
// the library renders (Unicode-scalar sort split them), and it
// includes empty projects (a fresh New Project has no pieces yet —
// it must already be a move target).
MoveToProjectSheet(post: post, projects: model.moveTargets()) { project in
model.moveToProject(post, project: project)
}
}
// #144: keystroke-debounced (250 ms), structured body scan —
// nonisolated search() runs the disk reads off MainActor while
// staying inside this task, so a superseding keystroke or clear
// cancels the sweep between pieces (the in-flight file read
// always finishes — readBody is synchronous). Keyed to the full
// search key: a library write (revision bump) or a Home repoint
// restarts the sweep too. The snapshot lands under the key
// captured at start; a mid-sweep key change cancels here, and
// even a raced assignment can't render — body gates on isFresh.
.task(id: searchKey) {
let key = searchKey
guard !key.query.isEmpty else {
snapshot = nil
return
}
try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return }
let found = await librarySearch(
candidates: model.posts.filter { !$0.isArchived },
matching: key.query,
home: home,
)
guard !Task.isCancelled else { return }
snapshot = LibrarySearch.Snapshot(key: key, results: found)
}
}
/// One piece row + its context menu — sections and search results
/// render the same row (#144: results carry the full menu too).
private func postRow(_ post: Post) -> some View {
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
// #114 (S4): outline pieces only — the ask picks the
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post)
}
Button("Move to Trash", role: .destructive) {
model.trash(post)
}
}
}
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
/// softer, indented under the section head). r2: the label binds to
/// its FIRST row (bottom 1 + stack 4) — it floated closer to the
/// preceding row than to its own children.
private func passStateGroups(_ pieces: [Post]) -> some View {
ForEach(Post.PassState.allCases, id: \.self) { state in
let grouped = pieces.filter { $0.passState == state }
if !grouped.isEmpty {
// mercury#53 (r5): display-only normalization — the stored
// rawValues keep their hyphen ("Pass-1 Done"); the rendered
// label uses the space form so it matches the Pass 1 / Pass 2
// vocabulary everywhere else.
Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " "))
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.kerning(0.6)
// r6 (sol#6/21 — contrast final): group labels are
// informational meta — FULL muted ink, no wash.
.foregroundStyle(DesignTokens.muted)
// r6 ladder: full muted ink. r7 two-axis: x28 — the ONE
// indent step, shared with the head text and the row
// cards' inner content.
.padding(.leading, 28)
.padding(.top, 10)
.padding(.bottom, 1)
ForEach(grouped) { post in
postRow(post)
}
}
}
}
/// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
/// border on the column's chrome, taller than a text row; the placeholder
/// r5 (argon#44, mercury#52, sol#37): the insertion caret tints
/// terracotta (.tint on the field), and the small magnifier glyph sits at
/// the field's leading edge (icon→text spacing rides the HStack's 6pt);
/// the placeholder is the native prompt wearing the palette's muted ink
/// (the composer's pattern).
/// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6,
/// present but never the strongest saturation on screen.
private var searchField: some View {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
.textFieldStyle(.plain)
.font(.system(size: 12))
.focused($searchFocused)
.tint(DesignTokens.accent)
if isSearching {
Button {
query = ""
} label: {
Image(systemName: "xmark.circle.fill")
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.accessibilityLabel("Clear search")
}
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
// r8 (argon#6, mercury#12): quiet focus — accent at 0.6,
// one step down from full strength.
RoundedRectangle(cornerRadius: 8)
.strokeBorder(
searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border,
lineWidth: 1,
),
),
)
// r7 (mercury#18, argon#12 — two-axis ladder): the box spans the
// FULL padded column width at the PRIMARY inset — leading 14
// (aligned with the 'Posts' header text) to trailing 14 — the
// same edges the row cards lead at.
.padding(.horizontal, 14)
.padding(.vertical, 8)
}
/// Flat results, title matches first (stable partition — both halves
/// keep the scan's Finder order). Same row the sections render.
private func searchResults(_ found: [Post]) -> some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
Text("\(found.count) \(found.count == 1 ? "match" : "matches")")
.font(.system(size: 11, design: DesignTokens.mono))
.kerning(0.6)
// r6: full muted ink; r7 two-axis: x28 — the indent
// step, heading the flat result list exactly where
// group labels head their sections.
.foregroundStyle(DesignTokens.muted)
.padding(.leading, 28)
.padding(.top, 12)
.padding(.bottom, 1)
ForEach(found) { post in
postRow(post)
}
}
.padding(.bottom, 12)
}
}
private var searchEmptyState: some View {
VStack(spacing: 8) {
Text("No matches")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("No piece's title or body contains “\(trimmedQuery)”.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("No posts yet")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Posts in this Home's projects/ folders appear here.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #144: the title+body scan — a thin mount for the pure
/// `LibrarySearch` seam (title matches first, stable partition, both
/// halves keep the scan's Finder order; body via readBody — frontmatter
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
/// The reader's per-piece cancellation check stops a superseded sweep's
/// body reads between files; the in-memory title walk itself completes
/// cheaply and the caller's guard discards its result. File scope since
/// r6 (PostsLibraryColumn hit its type-body ceiling).
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
/// posture); a PostScanCache-style body memo if it ever measures hot.
private nonisolated func librarySearch(
candidates: [Post],
matching trimmed: String,
home: URL,
) async -> [Post] {
LibrarySearch.results(for: trimmed, in: candidates) { post in
guard !Task.isCancelled else { return nil }
return PostStore.readBody(id: post.id, home: home)
}
}
/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at
/// the source): the search field is the window's first — and at launch,
/// only — text input, and AppKit assigns the window's initial first
/// responder to it when the window becomes key. That happens AFTER
/// onAppear, so the r6/r7 `searchFocused = false` writes were always
/// overridden (FocusState mirrors the assignment back as true: terracotta
/// ring + caret, the strongest element on screen). This invisible rider
/// rides the library column and, at the window's FIRST become-key,
/// resigns focus back to the window itself (`makeFirstResponder(nil)` —
/// the neutral state; nothing gains focus instead). ONCE per process: a
/// pane-switch remount must never steal a focus the user set on return.
/// The second, next-runloop resign covers an assignment that lands after
/// the notification (the PostEditorView layout-race precedent).
private struct LaunchFocusReset: NSViewRepresentable {
/// Process-wide once-flag — launch is a once-per-process event.
private static var hasRun = false
final class RiderView: NSView {
private var keyObserver: NSObjectProtocol?
override func viewDidMoveToWindow() {
if let keyObserver {
NotificationCenter.default.removeObserver(keyObserver)
}
keyObserver = nil
guard let window else { return }
keyObserver = NotificationCenter.default.addObserver(
forName: NSWindow.didBecomeKeyNotification,
object: window,
queue: .main,
) { _ in
MainActor.assumeIsolated {
// The observer is scoped to `window` (object:), so the
// notification carries nothing we don't already hold —
// reading `note` here would cross a Sendable boundary.
guard !LaunchFocusReset.hasRun else { return }
LaunchFocusReset.hasRun = true
window.makeFirstResponder(nil)
DispatchQueue.main.async { window.makeFirstResponder(nil) }
}
}
}
}
func makeNSView(context _: Context) -> RiderView {
RiderView()
}
func updateNSView(_: RiderView, context _: Context) {}
}
/// #108: Move to Project ask — radio list of the non-archived projects,
/// default = the piece's current project. Matches RenamePostSheet's shape.
struct MoveToProjectSheet: View {
let post: Post
let projects: [String]
let move: (String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var target: String
init(post: Post, projects: [String], move: @escaping (String) -> Void) {
self.post = post
self.projects = projects
self.move = move
_target = State(initialValue: post.project)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Move to Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("“\(post.title)” moves into the chosen project. The file stays post.md.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Project", selection: $target) {
ForEach(projects, id: \.self) { name in
Text(name).tag(name)
}
}
.pickerStyle(.radioGroup)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Move") {
move(target)
dismiss()
}
.keyboardShortcut(.defaultAction)
.disabled(target == post.project)
}
}
.padding(20)
.frame(width: 360)
}
}
/// #60: Explicit Rename dialog — asks the new Title (not a slug).
struct RenamePostSheet: View {
let rename: (String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var title: String
init(post: Post, rename: @escaping (String) -> Void) {
self.rename = rename
_title = State(initialValue: post.title)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Rename Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The folder moves to match the new Title. The file stays post.md.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Title", text: $title)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Rename", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
rename(trimmed)
dismiss()
}
}
+489 -94
View File
@@ -2,19 +2,19 @@
// PostsModel.swift
// Museion
//
// #18 (S1.1): the Posts pane's write side — selection and the New Post
// draft lifecycle (#62). Own ops route through the same rescan: one path.
// #179: every library-reflecting store write rides `performWrite` — the
// one write rail pairing each write with exactly one rescan and owning
// the error strip; the model owns the Home (watchedHome), no method
// takes one.
// #146/#193: the domain extensions live in their own files — guard+
// Convert PostsModelOutline, passes+Blind Read PostsModelPasses, fix
// cards PostsModelCards, write rail+structural ops PostsModelWrites,
// external guest+imports PostsModelImports, watcher+rescan
// PostsModelWatcher.
// #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece
// roots (projects/ + archive/, #107) with a ~0.5 s debounced rescan (#61),
// selection, and the New Post draft lifecycle (#62). Own ops route through
// the same rescan: one path.
// #108: project targeting + the move/archive/restore ops behind the
// variant-B library and the Archive pane.
// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in
// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching
// + rescan sit in the file-scope watcher extension below (type-body
// ceiling).
//
import CoreServices
import Foundation
import Observation
@@ -33,32 +33,63 @@ struct PostDraft {
let mountID = UUID()
}
/// Recursive FSEvents stream on one or more directories (#61): file-level
/// events, so nested `projects/<name>/<id>/post.md` edits from Finder fire
/// too — a plain dir-FD dispatch source only sees direct children and misses
/// them.
final nonisolated class PostsWatcher: @unchecked Sendable {
/// Fired on the main actor when anything under a watched path changes.
var onEvent: (@MainActor @Sendable () -> Void)?
private var stream: FSEventStreamRef?
func start(urls: [URL]) {
stop()
var context = FSEventStreamContext(
version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: nil,
)
// C function pointer — no captures; `self` rides the info pointer.
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
Task { @MainActor in watcher.onEvent?() }
}
guard let stream = FSEventStreamCreate(
kCFAllocatorDefault,
callback,
&context,
urls.map(\.path) as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
) else { return }
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(stream)
self.stream = stream
}
func stop() {
guard let stream else { return }
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
self.stream = nil
}
deinit { stop() }
}
/// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern).
/// The watcher runs while the workspace is open (app-scoped, #61).
@MainActor
@Observable
final class PostsModel {
/// #200: the app's one model, for WritingLockAppDelegate's quit-time
/// departure gate (the WritingLockState.active reachability
/// precedent). Weak; registered by AppGateState's init — bare
/// hosted-test rigs never register, so the delegate's pins inject
/// their model through `quitReply(posts:)`.
weak static var active: PostsModel?
/// The scanned, title-sorted list — mirrors `projects/` + `archive/` at
/// all times (#107).
/// #193: setter internal — PostsModelWatcher's rescan writes it.
var posts: [Post] = []
/// #144 (mounted half): the library content revision — the search
/// snapshot's invalidation signal. The rescan rail bumps it whenever
/// a scan sees the library change: a Post-list change OR any re-read
/// post.md (a body-only edit compares equal as a Post — #143's skip
/// keeps the list still — yet the search must re-sweep). The `posts`
/// assignment skip stays untouched: panes never regroup on bumps,
/// only the mounted search re-keys.
/// #193: setter internal — PostsModelWatcher's rescan bumps it.
var contentRevision = 0
private(set) var posts: [Post] = []
/// The selected Post's id; nil = nothing selected (empty editor).
/// #146: setter internal — the split-out domain extensions set it.
@@ -76,13 +107,11 @@ final class PostsModel {
/// #92: the external buffer's guest slot — one at a time, transient per
/// launch. Takes the editor column; opening a Post or draft dismisses it
/// (flush first).
/// #193: setter internal — PostsModelImports owns the guest slot.
var externalSession: EditorSession?
private(set) var externalSession: EditorSession?
/// #94: a multi-file import waiting on its ONE Origin ask; the sheet
/// answers, then the batch runs.
/// #193: setter internal — PostsModelImports stages the batch.
var pendingImportURLs: [URL]?
private(set) var pendingImportURLs: [URL]?
/// #108: the explicit target for the NEXT new piece — set by New Project
/// once the folder exists; outranks selection. Cleared when the draft
@@ -93,8 +122,7 @@ final class PostsModel {
/// #108: File ▸ New Project… stages its ask here — commands can't
/// present sheets, so the model holds the flag and WorkspaceView
/// presents (the pendingImportURLs pattern, #94).
/// #193: setter internal — PostsModelWrites stages the ask.
var askNewProject = false
private(set) var askNewProject = false
/// #109: the just-saved outline draft's afterglow — the posts list
/// lags one rescan (the FSEvents window), so the freshly-opened
@@ -143,34 +171,35 @@ final class PostsModel {
/// Last failed-op message surfaced in the editor (nil = clean).
/// #146: setter internal — the split-out domain extensions set it.
var lastError: String?
/// #179: the bound Home — the MODEL owns it. `bind` is the only writer,
/// driven by WorkspaceView's root `.task(id: museionHome)` (first frame
/// + every repoint, whichever pane is showing); no public method takes
/// a Home parameter, callers pass none.
/// #193: setter internal — PostsModelWatcher's startWatching (the one
/// writer) is a split-out extension now.
var watchedHome: URL?
var watcher = PostsWatcher()
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
private var watcher = PostsWatcher()
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
/// post.md files, not the library (see PostScanCache).
let scanCache = PostScanCache()
/// brief-28: the card scanner behind `refreshCards` — injectable so the
/// stale-result pin can HOLD an old-library scan past a repoint (a
/// detached disk read is otherwise faster than any test can arrange).
/// Per-model, never static (the hosted suite runs tests in parallel).
var scanPieceCards: @Sendable (URL) -> [FixCardStore.StoredFixCard] = FixCardStore.scan
/// brief-28 r1 (MF-1): the library scanner behind `rescan` — the same
/// injection shape, so the stale-Home pin can HOLD an old library's scan
/// past a repoint and watch its continuation land under the new binding.
var scanLibrary: @Sendable (URL, PostScanCache?) -> [Post] = Post.scan
private let scanCache = PostScanCache()
/// #93: per-file watcher on the open external file — the #67 conflict
/// check reused verbatim for foreign files.
var externalWatcher = PostsWatcher()
private var externalWatcher = PostsWatcher()
/// Bind a Home: ensure both container roots exist (FSEvents on a missing
/// path is unreliable; archive/ is a watcher root now, #107), initial
/// scan + start (or restart) the watcher. Called from
/// `.task(id: home)` — re-fires on Home repoint.
func bind(home: URL) {
startWatching(home: home)
Task { await rescan() }
}
// MARK: Own ops (route through the same rescan, #61)
// ponytail: the PostStore calls here run on MainActor — small single-file
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
// them in Task.detached like rescan.
/// #107: the project a NEW piece lands in — #108: an explicit pending
/// target first, else the selected non-archived post's project, else the
/// default. One home; newPost/importFiles must not drift.
var targetProject: String {
private var targetProject: String {
pendingProject
?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project
?? Post.defaultProject
@@ -180,15 +209,9 @@ final class PostsModel {
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along). #96: quit also
/// flushes the external buffer — same posture, same moment.
/// #200: quit is a document departure — the flush half routes through
/// the departure gate (`documentsMayDepart`): an unanswered #67
/// conflict never writes over the foreign body, a failed flush or a
/// never-loaded retype lands its reason in lastError instead of
/// silently dropping the edits. The verdict itself is quitReply's, at
/// applicationShouldTerminate — this belt runs only at willTerminate.
/// Watchers stop either way — the process is leaving.
func shutdown() {
documentsMayDepart()
session?.flush()
externalSession?.flush()
watcher.stop()
externalWatcher.stop()
}
@@ -198,7 +221,9 @@ final class PostsModel {
/// target the default — new pieces are never born archived).
func newPost() {
let target = targetProject
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
@@ -212,7 +237,9 @@ final class PostsModel {
/// Title keeps prose semantics (raw first line).
func newOutline() {
let target = targetProject
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
dismissExternal()
session?.teardown(flushFirst: true)
session = nil
draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
@@ -221,12 +248,23 @@ final class PostsModel {
openPieceCards = [] // #23: no open piece, no cards
}
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change).
/// #146: internal — the split-out domain extensions dismiss too.
func dismissExternal() {
externalSession?.teardown(flushFirst: true)
externalSession = nil
externalWatcher.stop()
}
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
/// here. The saved post opens straight into an editing session — the
/// writer keeps typing where they were. #179: the write rides the rail.
func saveDraft() {
/// writer keeps typing where they were. Rescans immediately (the watcher
/// would too, after its window).
func saveDraft(home: URL) {
guard let draft else { return }
performWrite { home in
do {
let post = try PostStore.writeNew(body: draft.text, project: draft.project, type: draft.type, home: home)
lastDraftWasOutline = draft.type == .outline // #109: covers the lagging rescan
self.draft = nil
@@ -234,6 +272,10 @@ final class PostsModel {
selectedPostID = post.id
session = EditorSession(postID: post.id, home: home)
wireSession()
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
@@ -241,16 +283,18 @@ final class PostsModel {
/// draft stamped `origin: ai` (never stats-eligible) and open it in
/// Posts (select's open path; the WorkspaceView selection onChange
/// hops the pane). Nil + lastError on failure; Cancel never gets here.
/// #179: the write rides the rail.
@discardableResult
func newPostFromSession(body: String) -> Post? {
var written: Post?
performWrite { home in
func newPostFromSession(body: String, home: URL) -> Post? {
do {
let post = try PostStore.writeNew(body: body, origin: .ai, home: home)
written = post
select(post.id)
select(post.id, home: home)
lastError = nil
Task { await rescan() }
return post
} catch {
lastError = error.localizedDescription
return nil
}
return written
}
/// Select a Post; selecting anything abandons an unsaved draft (the
@@ -262,25 +306,19 @@ final class PostsModel {
/// fires the mixed-content guard — the open is held (routing stays
/// prose) until the writer picks. The old session still ends here:
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
guard dismissExternal() else { return } // brief-25: the guest's edits land or the switch aborts
func select(_ id: String, home: URL) {
dismissExternal()
// A reselect of the already-open piece is a no-op — INCLUDING a
// guarded one: the piece is open under a prior answer, and firing
// the ask again would nil its session without teardown (the armed
// debounce would then flush mid-ask, outside any owned session).
// brief-28: identity, not id — only THIS library's piece counts as
// open; a session born under another Home departs below.
if let session, let home = watchedHome, session.targets(postID: id, home: home) {
if let session, session.postID == id {
return
}
if let session {
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
session.teardown(flushFirst: true)
}
if isGuardedOutline(id) {
if isGuardedOutline(id, home: home) {
outlineGuardPieceID = id
proseOverridePostID = nil
session = nil
@@ -288,13 +326,13 @@ final class PostsModel {
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards() // #23: nil session — the held ask shows no cards
refreshCards(home: home) // #23: nil session — the held ask shows no cards
return
}
// The prior session was torn down above; openUnguarded's guards
// are dead code on this path (session is nil or a different id) —
// kept: one open body answers select and the ask alike.
openUnguarded(id)
openUnguarded(id, home: home)
proseOverridePostID = nil // #111: the override died with the open it covered
}
@@ -317,10 +355,9 @@ final class PostsModel {
if externalSession != nil {
return true
}
// brief-28: this library's piece, by identity (Home, ID).
guard let session, let id = selectedPostID, openSessionTargets(id) else { return false }
let outline = id != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == id })?.type == .outline)
guard let session, session.postID == selectedPostID else { return false }
let outline = session.postID != proseOverridePostID
&& (lastDraftWasOutline || posts.first(where: { $0.id == session.postID })?.type == .outline)
return !outline
}
@@ -334,12 +371,303 @@ final class PostsModel {
if let externalSession {
return externalSession.text
}
if let session, let id = selectedPostID, openSessionTargets(id) { // brief-28: this library's piece, by identity
if let session, session.postID == selectedPostID {
return session.text
}
return nil
}
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
/// first (rename reads the file from disk — unflushed edits must land
/// before the move), then reopens a session at the new id. Sets lastError
/// on failure.
func rename(_ post: Post, to title: String, home: URL) {
// #108 audit 2: rename reads the file from disk — a failed write
// aborts (moving the folder would strand unflushed edits), and the
// session stays up, dirty and honest.
guard flushOrAbort(post.id) else { return }
do {
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
if session?.postID == post.id {
session = EditorSession(postID: moved.id, home: home)
wireSession()
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
/// was the post; the session is torn down (cancel only — the folder is
/// leaving, a flush would resurrect nothing but churn the watcher).
func trash(_ post: Post, home: URL) {
do {
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false)
session = nil
}
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
// MARK: Projects (#108)
/// #108: New Project's confirmed sheet — the folder exists, the next
/// draft targets it, and opens now.
func newProjectPending(named name: String) {
pendingProject = name
newPost()
}
/// #108: raw create — the sheet composes on it. The failure reason on
/// false (shown inline in the sheet; never routed into lastError — the
/// strip behind the sheet must not double-message one error).
func createProject(named name: String, home: URL) -> String? {
do {
try PostStore.createProject(named: name, home: home)
return nil // success
} catch {
return error.localizedDescription
}
}
/// #108: File ▸ New Project… — stage the ask (WorkspaceView presents).
func stageNewProject() {
askNewProject = true
}
/// #108: the ask's Cancel.
func cancelNewProject() {
askNewProject = false
}
/// #108 audit 2: the Move-to-Project list — every project on disk under
/// projects/ plus the default (bind creates the roots, not posts/ — an
/// empty Home must still offer it), localized-sorted to match the
/// library's section order.
func moveTargets(home: URL) -> [String] {
let root = home.appendingPathComponent("projects", isDirectory: true)
let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
names.insert(Post.defaultProject)
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
/// #108 audit: flush the open piece, aborting when the write failed — a
/// folder move must never carry away text that didn't land (the move
/// itself succeeds exactly when a file write fails). Returns false with
/// lastError set; the session stays up, dirty and honest.
/// #33: internal — the Micropub draft flow (Micropub.swift) flushes
/// through the same rail.
func flushOrAbort(_ postID: String) -> Bool {
guard let session, session.postID == postID else { return true }
// #114 audit: an unanswered #67 conflict means disk holds foreign
// text with the session's version unwritten — proceeding would act
// on the foreign body and discard the editor's. Abort; the alert
// stays up for the writer to answer, then the op retries.
if session.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
if !session.flush() {
// Append, don't replace — the flush already routed the write's
// localizedDescription into lastError; only say what was skipped.
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
return false
}
return true
}
/// #108: Move to Project — flush first (move reads disk), then the
/// folder moves under projects/. Id stays the same; the session is
/// reopened anyway so folderURL re-resolves to the new parent.
func moveToProject(_ post: Post, project: String, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.move(post, to: project, home: home)
if session?.postID == post.id {
session = EditorSession(postID: post.id, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: Move to Archive. Archiving the open piece clears it — the
/// editor is empty until the next selection (archived pieces open from
/// the Archive pane, where they're listed).
func archivePost(_ post: Post, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.archive(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
}
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false) // already flushed above
session = nil
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: Move Back — the restored piece lands in its project and opens;
/// the writer stays in the piece they just revived. A session already
/// open on the piece survives `select` — reopen it so folderURL points
/// at projects/, not the archive path it was born with.
func restorePost(_ post: Post, home: URL) {
guard flushOrAbort(post.id) else { return }
do {
try PostStore.restore(post, home: home)
if let open = session, open.postID == post.id {
session = EditorSession(postID: post.id, home: home)
wireSession()
} else {
select(post.id, home: home)
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// #108: whole-project unarchive from the Archive pane's section header.
/// Flush-first like every folder move (a dirty open piece inside the
/// project would otherwise race the move), and its session is reopened so
/// folderURL re-resolves off archive/ (same reason as restorePost).
func unarchiveProject(_ name: String, home: URL) {
/// #108 audit 2: disk-derived membership — the posts snapshot is stale
/// the moment a Finder move lands. Captured BEFORE the move: after it
/// the piece resolves under projects/ and its archive membership is
/// invisible. dir − 1 = project dir (…/archive/<name>), − 2 = root.
func openPieceInArchivedProject() -> String? {
guard let id = session?.postID,
let projectDir = PostStore.folder(of: id, home: home)?.deletingLastPathComponent(),
projectDir.lastPathComponent == name,
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
else { return nil }
return id
}
let openID = openPieceInArchivedProject()
if let openID {
// #108 audit 2: the only #108 folder move that skipped the gate.
guard flushOrAbort(openID) else { return }
}
do {
try PostStore.unarchiveProject(name, home: home)
if let openID {
session = EditorSession(postID: openID, home: home)
wireSession()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
/// #91/#92: open an external markdown file in the guest slot — one at a
/// time; opening anything else (file, Post, draft) flushed and replaced
/// it first. A Post session/draft stands down while the guest is up
/// (the editor column is the guest's; the selection stays for return).
/// Local files only (a dragged web link is not a document) and symlinks
/// resolve to their real target so the in-place write never severs the
/// link (rename over a symlink replaces it).
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
dismissExternal()
session?.teardown(flushFirst: true) // #92: the guest takes the column
session = nil
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
externalSession = nil
return
}
wireSession()
startExternalWatch(url: target)
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. PostsWatcher fires on the
/// main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(urls: [url.deletingLastPathComponent()])
}
/// #94: stage a multi-file import — the ONE Origin ask presents; the
/// sheet's answer runs the batch.
func stageImport(_ urls: [URL]) {
guard !urls.isEmpty else { return }
pendingImportURLs = urls
}
/// #94: dismiss the ask without an answer — the batch drops.
func cancelImport() {
pendingImportURLs = nil
}
/// #94/#95: run the batch after the Origin answer — copy each file in as
/// a Post; a per-file failure continues the batch into lastError (stated
/// default, reversible; never an alert, never an abort). The last
/// imported post opens; a failure anywhere keeps its message up even
/// when other files landed. #107: the batch lands in the selected
/// post's project (newPost's target rule).
func importFiles(origin: Post.Origin, home: URL) {
guard let urls = pendingImportURLs else { return }
pendingImportURLs = nil
let project = targetProject
var last: Post?
var failures = 0
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
} catch {
failures += 1
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
}
}
if let last {
select(last.id, home: home)
}
if failures == 0 {
lastError = nil
}
Task { await rescan() }
}
/// #146: internal — the split-out domain extensions wire sessions too.
func wireSession() {
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
@@ -347,3 +675,70 @@ final class PostsModel {
externalSession?.onError = route
}
}
// MARK: Watcher (#61) — #146: file-scope extension (type_body_length)
extension PostsModel {
private func startWatching(home: URL) {
guard watchedHome != home else { return }
watchedHome = home
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
for root in roots {
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
watcher.start(urls: roots)
}
/// Off-main scan; keeps selection valid across the fresh refresh.
/// FSEvents already coalesces bursts within its 0.5 s latency window —
/// no second debounce on top.
/// #146: internal — the split-out domain extensions trigger rescans.
func rescan() async {
guard let home = watchedHome else { return }
// Scan + the #67 disk read both run off-main (a synced large post.md
// must never stall the UI on a watcher burst).
let openPostID = session?.postID
// #114 audit: identity, not id — a same-id reopen (convert/restore/
// move) must not receive the OLD session's stale disk text as a
// spurious #67 conflict.
let openSession = session
let scanMemo = scanCache // detached capture, not a property read
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = Post.scan(home: home, cache: scanMemo)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
// #143: @Observable invalidates on assignment regardless of equality —
// skip the no-op so panes don't regroup on our own autosave echoes.
if scanned != posts {
posts = scanned
}
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
// current selection — bind's initial rescan (detached scan over the
// empty tree) can land its continuation after a select its scan never
// saw, "vanishing" a piece that exists. Disk is the truth for
// vanished; a stale snapshot must not kill a live session (teardown
// cancels the debounce — unflushed edits would die with it).
// #137 audit (finish): a scan that outlived a Home repoint speaks
// for the OLD tree — never let it kill a session selected under
// the NEW home (the id is missing from the old snapshot by
// construction); the next rescan under the new home owns it.
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil {
selectedPostID = nil // the post vanished (deleted in Finder or here)
if let open = session, open.postID == id {
open.teardown(flushFirst: false) // post is gone; cancel the debounce
session = nil
}
}
// #67: watcher echo check on the open post — equality against the
// session's lastFlushedText suppresses our own writes exactly.
if openSession === session, let openDiskText {
openSession?.diskDidChange(diskText: openDiskText)
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards(home: home)
}
}
+17 -26
View File
@@ -20,31 +20,21 @@ extension PostsModel {
/// transitions — the piece-roots watcher already fires on cards/ writes.
/// #122: the same pass also derives `openPieceHasSnapshot` (the Blind
/// Read's base) — one detached read of the open piece's disk facts.
/// brief-28: identity at BOTH ends. At launch the open session must
/// target (watchedHome, id) — a session born under another Home has no
/// cards here. At COMPLETION the re-check is identity too: the old
/// ID-only guard let a scan started under the previous library land its
/// cards on the new library's same-slug piece after a repoint.
func refreshCards() {
guard let session, let id = session.postID, let home = watchedHome,
session.targets(postID: id, home: home), // brief-28
let folder = PostStore.folder(of: id, home: home)
else {
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
openPieceCards = []
openPieceHasSnapshot = false
return
}
// Plain disk reads re-run on every watcher burst (typing retriggers
// rescan) — keep the I/O off MainActor, same posture as rescan's
// Post.scan. The identity re-check on hop-back drops a scan that
// raced a piece switch or a Home repoint.
let scan = scanPieceCards // detached capture, not a property read
// Post.scan. The id re-check on hop-back drops a scan that raced a
// piece switch.
Task.detached { [weak self] in
let cards = scan(folder)
let cards = FixCardStore.scan(pieceURL: folder)
let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil
await MainActor.run { [weak self] in
// brief-28: (Home, ID) at completion, never the id alone.
guard let self, self.session?.targets(postID: id, home: home) == true else { return }
guard let self, session?.postID == id else { return }
openPieceCards = cards
openPieceHasSnapshot = hasSnapshot
}
@@ -78,7 +68,7 @@ extension PostsModel {
/// flags the card and touches no text. A failed close after a landed
/// edit is reported via lastError, never silent.
@discardableResult
func applyCard(_ card: FixCardStore.StoredFixCard) -> FixCardApplyOutcome {
func applyCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardApplyOutcome {
guard card.status == .open else { return .refused("card already closed") }
guard card.lane == .mechanical else { return .refused("demonstration cards close Done or Skip") }
guard let session, let postID = session.postID else {
@@ -96,29 +86,30 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards()
refreshCards(home: home)
return .stale
}
guard session.adoptText(newText) else { return .refused(lastError ?? "write failed") }
closeCard(card, status: .applied)
closeCard(card, status: .applied, home: home)
return .applied
}
/// #25 (S3.3): Skip — not this instance. Closes the card recording
/// NOTHING beyond the status flip (CONTEXT.md).
func skipCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .skipped)
func skipCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .skipped, home: home)
}
/// #25 (S3.3): Done — the writer rewrote the span themselves. Same
/// flip, different terminal.
func doneCard(_ card: FixCardStore.StoredFixCard) {
closeCard(card, status: .done)
func doneCard(_ card: FixCardStore.StoredFixCard, home: URL) {
closeCard(card, status: .done, home: home)
}
private func closeCard(
_ card: FixCardStore.StoredFixCard,
status: FixCardStore.StoredFixCard.Status,
home: URL,
) {
guard let session else {
lastError = "open the piece to work its cards"
@@ -129,7 +120,7 @@ extension PostsModel {
} catch {
lastError = "card close failed: \(error.localizedDescription)"
}
refreshCards()
refreshCards(home: home)
}
}
@@ -149,7 +140,7 @@ extension PostsModel {
/// counter; the store guarantees the one-stamp rule). Touches no text
/// and flushes nothing: this writes a Learning, not an edit.
@discardableResult
func promoteCard(_ card: FixCardStore.StoredFixCard) -> FixCardPromoteOutcome {
func promoteCard(_ card: FixCardStore.StoredFixCard, home: URL) -> FixCardPromoteOutcome {
guard card.promotedAt == nil else { return .refused("card already promoted") }
guard let session else { return .refused("open the piece to work its cards") }
do {
@@ -158,7 +149,7 @@ extension PostsModel {
lastError = "learning write failed: \(error.localizedDescription)"
return .refused("learning write failed: \(error.localizedDescription)")
}
refreshCards()
refreshCards(home: home)
return .promoted
}
}
-25
View File
@@ -1,25 +0,0 @@
//
// PostsModelIdentity.swift
// Museion
//
// brief-28 (home-repoint-retains-old-editor-target): document identity for
// the open session. Every "is this piece open" question in the model
// routes through here — select, the structural rail, the pass guard, the
// card refresh, Micropub. The bare `session.postID == id` comparison is
// retired: two libraries can hold the same slug, and the id alone matched
// a session retained from another library (the repoint finding's seam).
//
import Foundation
extension PostsModel {
/// brief-28: is the open session THIS library's piece `id`? Identity is
/// (Home, ID) — `watchedHome` is the Home half, so the answer is "the
/// buffer belongs to the piece the current library lists under that id".
/// A session born under another Home (or an external guest) is never
/// the open piece, whatever its id says; nothing bound = nothing open.
func openSessionTargets(_ id: String) -> Bool {
guard let session, let home = watchedHome else { return false }
return session.targets(postID: id, home: home)
}
}
-116
View File
@@ -1,116 +0,0 @@
//
// PostsModelImports.swift
// Museion
//
// #193: the external guest (#91–#93) and the import batch (#94/#95),
// moved from PostsModel.swift (file-length ceiling) — openExternal,
// dismissExternal, the guest watch, and stageImport/cancelImport/
// importFiles, code unchanged.
//
import Foundation
extension PostsModel {
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change). brief-25: the dismissal is GUARDED — a guest
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
/// buffer and watcher live: teardown would drop the only retained
/// copy of the unsaved edits. Callers abort their navigation on
/// false, before clearing anything.
/// #146: internal — the split-out domain extensions dismiss too.
@discardableResult
func dismissExternal() -> Bool {
guard let guest = externalSession else {
externalWatcher.stop()
return true
}
guard sessionMayDepart(guest) else { return false }
guest.teardown(flushFirst: false) // the gate already flushed
externalSession = nil
externalWatcher.stop()
return true
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
/// #91/#92: open an external markdown file in the guest slot — one at a
/// time; opening anything else (file, Post, draft) flushed and replaced
/// it first. A Post session/draft stands down while the guest is up
/// (the editor column is the guest's; the selection stays for return).
/// Local files only (a dragged web link is not a document) and symlinks
/// resolve to their real target so the in-place write never severs the
/// link (rename over a symlink replaces it).
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
externalSession = nil
return
}
wireSession()
startExternalWatch(url: target)
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. The disk read goes through
/// the shared external normalizer (brief-32): the session's text is
/// normalized on open, so a raw read raised a false conflict on every
/// directory event over an unchanged BOM/CRLF file. PostsWatcher fires
/// on the main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = externalSession, let disk = EditorSession.readExternalDocument(at: url) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(urls: [url.deletingLastPathComponent()])
}
/// #94: stage a multi-file import — the ONE Origin ask presents; the
/// sheet's answer runs the batch.
func stageImport(_ urls: [URL]) {
guard !urls.isEmpty else { return }
pendingImportURLs = urls
}
/// #94: dismiss the ask without an answer — the batch drops.
func cancelImport() {
pendingImportURLs = nil
}
/// #94/#95: run the batch after the Origin answer — copy each file in as
/// a Post; a per-file failure continues the batch into lastError (stated
/// default, reversible; never an alert, never an abort). The last
/// imported post opens; a failure anywhere keeps its message up even
/// when other files landed. #107: the batch lands in the selected
/// post's project (newPost's target rule). #179: the batch rides the
/// rail — the strip was cleared up front, so the per-file failure
/// messages the loop sets survive the rail's success tail.
func importFiles(origin: Post.Origin) {
guard let urls = pendingImportURLs else { return }
pendingImportURLs = nil
let project = targetProject
var last: Post?
performWrite { home in
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
} catch {
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
}
}
}
if let last {
select(last.id)
}
}
}
+35 -47
View File
@@ -21,34 +21,33 @@ extension PostsModel {
/// (the same window lastDraftWasOutline covers) — ONE disk read derives
/// both. No watched home yet (pre-bind) = post: nothing to guard.
/// #146: internal — `select` (PostsModel.swift) asks the guard.
func isGuardedOutline(_ id: String) -> Bool {
guard let home = watchedHome,
let dir = PostStore.folder(of: id, home: home),
func isGuardedOutline(_ id: String, home: URL) -> Bool {
guard let dir = PostStore.folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
known
} else {
PostFrontmatter.decoded(PostFrontmatter.parse(text)).type
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
}
return type == .outline && OutlineTree.parsesWithLoss(PostFrontmatter.split(text).body)
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
}
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
/// outliner never mounts, nothing drops); Outline = explicit consent,
/// opens the outliner (saves normalize/drop as today). Cancel = back
/// out (no session); the piece stays guarded on the next open.
func openGuardedOutlineInProse() {
func openGuardedOutlineInProse(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
proseOverridePostID = id // routing: prose until the next open
openUnguarded(id)
openUnguarded(id, home: home)
}
func openGuardedOutlineAsOutline() {
func openGuardedOutlineAsOutline(home: URL) {
guard let id = outlineGuardPieceID else { return }
outlineGuardPieceID = nil
openUnguarded(id)
openUnguarded(id, home: home)
}
/// #111 (S7): the ask's Cancel — the held open dies (no session opens,
@@ -65,24 +64,19 @@ extension PostsModel {
/// explicit choice the ruling requires.
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String) {
guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts
// brief-28: identity — a session born under another Home is never
// "the same piece", whatever its id says; it departs here too.
if let session, !session.targets(postID: id, home: home) {
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
func openUnguarded(_ id: String, home: URL) {
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
}
session = session?.targets(postID: id, home: home) == true ? session : EditorSession(postID: id, home: home)
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
pendingProject = nil
lastDraftWasOutline = false
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards() // #23: the newly opened piece's cards, now
refreshCards(home: home) // #23: the newly opened piece's cards, now
}
}
@@ -101,14 +95,12 @@ extension PostsModel {
/// The open session's text is the truth when the piece is open — disk
/// lags the debounce, and a stale-clean read would drop the warning
/// for prose typed since the last flush (#114 audit).
func stageConversion(_ post: Post) {
func stageConversion(_ post: Post, home: URL) {
guard post.type == .outline else { return }
let body: String = if let session, openSessionTargets(post.id) { // brief-28: identity
let body: String = if let session, session.postID == post.id {
session.text
} else if let home = watchedHome {
PostStore.readBody(id: post.id, home: home) ?? ""
} else {
""
PostStore.readBody(id: post.id, home: home) ?? ""
}
pendingConversion = PendingConversion(id: post.id, lossy: OutlineTree.parsesWithLoss(body))
}
@@ -118,44 +110,40 @@ extension PostsModel {
pendingConversion = nil
}
/// #114 audit: consent recheck — the sheet's warning covered the STAGED
/// body; if the answer-time body went lossy behind the ask (foreign
/// write, late edit) and the writer was never warned, Headings would
/// drop unconsented prose.
private func conversionWentLossyBehindAsk(_ pending: PendingConversion, headingsLadder: Bool) -> Bool {
guard headingsLadder, !pending.lossy, let home = watchedHome,
let body = PostStore.readBody(id: pending.id, home: home)
else { return false }
return OutlineTree.parsesWithLoss(body)
}
/// #114 (S4): the answer. Flush-first when the piece is open (the
/// transform reads disk), flip `type` + transform the body once, then
/// reopen the session routed to prose — proseOverridePostID covers the
/// rescan lag (lastDraftWasOutline's machinery, reversed). A piece that
/// isn't open just converts; nothing else moves. One-way in v1.
/// #179: the write rides the rail.
func convertToPost(headingsLadder: Bool) {
func convertToPost(headingsLadder: Bool, home: URL) {
guard let pending = pendingConversion else { return }
pendingConversion = nil
guard flushOrAbort(pending.id) else { return }
if conversionWentLossyBehindAsk(pending, headingsLadder: headingsLadder) {
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
performWrite { home in
do {
// The sheet's warning covered the STAGED body. If the
// answer-time body went lossy behind the ask (foreign write,
// late edit) and the writer was never warned, Headings would
// drop unconsented prose — abort, nothing converted (#114 audit).
if headingsLadder, !pending.lossy, let body = PostStore.readBody(id: pending.id, home: home), OutlineTree.parsesWithLoss(body) {
lastError = "The outline changed since the sheet opened — nothing was converted."
return
}
try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home)
if let session, openSessionTargets(pending.id) { // brief-28: identity
session.teardown(flushFirst: false) // flushOrAbort already wrote
self.session = nil
if session?.postID == pending.id {
session?.teardown(flushFirst: false) // flushOrAbort already wrote
session = nil
proseOverridePostID = pending.id
openUnguarded(pending.id)
openUnguarded(pending.id, home: home)
}
if outlineGuardPieceID == pending.id {
// Multi-window: the held #111 ask targets an outline that no
// longer is — dismiss it as a cancel (the ask's own teardown).
cancelOutlineGuard()
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
}
+62 -68
View File
@@ -11,53 +11,6 @@ import Foundation
// MARK: Pass orchestration (#24, S3.1)
// MARK: #181: the ONE guard rail behind runPass and blindRead
extension PostsModel {
/// #181: the shared guard grammar every engine run passes before it
/// touches anything — nothing already running (a pass or a Blind
/// Read, named honestly whichever runner asks), the mentor not
/// mid-reply with its engine ready, and an open SAVED piece (never a
/// draft, the external guest, or a held #111 guard ask). The refusal
/// lands in lastError naming the blocker; answers the open piece's id,
/// session and Home — the run's target — or nil (refused).
/// brief-28: identity — the open session must target THIS library's
/// selected piece (Home, ID); a session born under another Home never
/// runs (its snapshot/stats/lint would land in the wrong library).
// swiftlint:disable:next large_tuple
func guardOpenPieceRun(_ action: String, mentor: MentorSessionModel) -> (id: String, session: EditorSession, home: URL)? {
guard runningPass == nil else {
lastError = "A pass is already running."
return nil
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return nil
}
guard let session,
let id = session.postID,
let home = watchedHome,
id == selectedPostID,
session.targets(postID: id, home: home), // brief-28
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run \(action)."
return nil
}
return (id, session, home)
}
}
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
@@ -66,18 +19,40 @@ extension PostsModel {
/// engine's turn ends normally — never on cancel, refusal, or crash,
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, mentor: MentorSessionModel) async {
guard let (id, session, home) = guardOpenPieceRun("a pass", mentor: mentor) else { return }
func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil, !runningBlindRead else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// #137 (S4): the pass profile's provider has no key — name it and
// point at Settings. Nothing has touched disk yet (the snapshot
// comes after this guard).
// point at Settings, BEFORE the open-piece guard so nothing writes
// to disk (not even the pre-pass snapshot).
if case let .missingKey(label) = mentor.readiness(for: kind) {
lastError = "\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity); every write below lands there.
do {
try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home)
} catch {
@@ -107,18 +82,13 @@ extension PostsModel {
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
// #179 audit: the engine ran for minutes — a Settings repoint since
// the snapshot re-bound watchedHome to another library. Advancing
// through the rail would stamp pass-state frontmatter onto THAT
// library (an unrelated same-slug piece on collision — silently).
// Refuse honestly; the snapshot stays in the pass's own library.
guard watchedHome == home else {
lastError = "The library changed while the pass ran — its Pass State was not advanced."
return
do {
_ = try PostStore.advancePassState(id: id, kind: kind, home: home)
lastError = nil
Task { await rescan() } // the library regroups by Pass State
} catch {
lastError = error.localizedDescription
}
// #179: the pass-advance write rides the rail — one rescan, and the
// strip ownership is the rail's (the library regroups by Pass State).
performWrite { try PostStore.advancePassState(id: id, kind: kind, home: $0) }
}
/// #24 (S3.1): the pass bar's Cancel — the existing session/cancel
@@ -139,11 +109,35 @@ extension PostsModel {
/// advance, no cards, no Learnings — the verdict and the reveal live in
/// the transient transcript and die with it. The writer stays judge of
/// record.
func blindRead(mentor: MentorSessionModel) async {
guard let (id, session, home) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return }
func blindRead(home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !runningBlindRead else {
lastError = "A Blind Read is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// Same open-piece rule as a pass: the read judges ONE saved piece.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a Blind Read."
return
}
guard flushOrAbort(id) else { return }
// #179: the model owns the Home — the guard answered the session's
// OWN library (brief-28 identity).
guard let base = PostStore.latestPassSnapshot(id: id, home: home) else {
lastError = "No Pass snapshot yet — run a Pass first."
return
-203
View File
@@ -1,203 +0,0 @@
//
// PostsModelWatcher.swift
// Museion
//
// #193: the watching domain of PostsModel, moved from PostsModel.swift
// (file-length ceiling) — the PostsWatcher FSEvents stream (#61), Home
// binding, startWatching, and the rescan rail, code unchanged.
//
import CoreServices
import Foundation
/// Recursive FSEvents stream on one or more directories (#61): file-level
/// events, so nested `projects/<name>/<id>/post.md` edits from Finder fire
/// too — a plain dir-FD dispatch source only sees direct children and misses
/// them.
final nonisolated class PostsWatcher: @unchecked Sendable {
/// Fired on the main actor when anything under a watched path changes.
var onEvent: (@MainActor @Sendable () -> Void)?
private var stream: FSEventStreamRef?
func start(urls: [URL]) {
stop()
var context = FSEventStreamContext(
version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: nil,
)
// C function pointer — no captures; `self` rides the info pointer.
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
Task { @MainActor in watcher.onEvent?() }
}
guard let stream = FSEventStreamCreate(
kCFAllocatorDefault,
callback,
&context,
urls.map(\.path) as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
) else { return }
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(stream)
self.stream = stream
}
func stop() {
guard let stream else { return }
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
self.stream = nil
}
deinit { stop() }
}
// MARK: Watcher (#61)
extension PostsModel {
/// Bind a Home: ensure both container roots exist (FSEvents on a missing
/// path is unreliable; archive/ is a watcher root now, #107), initial
/// scan + start (or restart) the watcher. Called from WorkspaceView's
/// root `.task(id: museionHome)` — first frame and every Home repoint,
/// pane-independent.
/// brief-28: the dumb binder — it flips `watchedHome` unconditionally.
/// A REPOINT reaches it only after `repoint(to:)` passed its departure
/// gate (the Settings binding runs the gate before committing the
/// preference; the `.task` fires after that commit).
func bind(home: URL) {
startWatching(home: home)
Task { await rescan() }
}
/// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is
/// a DOCUMENT DEPARTURE — the gate runs FIRST, the binding commits
/// after. The Settings path used to flip `watchedHome` under the open
/// session: the session's immutable target kept the OLD Home, a
/// same-slug piece in the new library made the ID-only reselect return
/// it, and autosave/Save/quit wrote the old library while structural
/// operations resolved against the new one (#198's departure gate never
/// saw this seam; a no-collision piece was torn down by the vanish
/// path with its dirty buffer dropped).
/// True = every open document landed through `sessionMayDepart` (the
/// three legs: unanswered #67, failed flush, never-loaded retype) and
/// the departed piece's state is cleared — the caller may bind the new
/// Home. False = `lastError` says why and NOTHING changed: the
/// preference stays A, `watchedHome` stays A, the session keeps its
/// (A, id) target and its buffer. No parallel gate — the same one
/// `select`/`newPost`/quit ride.
/// The in-memory draft survives: it has no Home until first save (#62)
/// and lands in the new library — the only alternative is dropping the
/// only copy. A running pass or Blind Read keeps its own completion
/// guard (#179: the advance refuses once `watchedHome` moved).
@discardableResult
func repoint(to newHome: URL) -> Bool {
guard newHome != watchedHome else { return true } // first bind / the same folder: nothing departs
guard departOpenDocuments() else { return false }
// The departed piece's state dies with it: a stale id under the new
// library is a ghost selection (a same-slug piece would read as
// open over an empty editor) and a stale ask would act on the new
// library's piece. Nothing auto-reopens — the writer picks from
// the new list (the reopen machinery stays where it is).
selectedPostID = nil
openPieceCards = []
openPieceHasSnapshot = false
outlineGuardPieceID = nil
proseOverridePostID = nil
pendingConversion = nil
lastDraftWasOutline = false
pendingProject = nil
return true
}
private func startWatching(home: URL) {
guard watchedHome != home else { return }
watchedHome = home
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
for root in roots {
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
watcher.start(urls: roots)
}
/// Off-main scan; keeps selection valid across the fresh refresh.
/// FSEvents already coalesces bursts within its 0.5 s latency window —
/// no second debounce on top.
/// #146: internal — the split-out domain extensions trigger rescans.
func rescan() async {
guard let home = watchedHome else { return }
// Scan + the #67 disk read both run off-main (a synced large post.md
// must never stall the UI on a watcher burst).
// #114 audit: identity, not id — a same-id reopen (convert/restore/
// move) must not receive the OLD session's stale disk text as a
// spurious #67 conflict.
let openSession = session
// brief-28: the Home half of that identity — the open post's disk
// text is read from the session's OWN library. A session targeting
// another Home has no piece in this scan's tree; reading the
// current Home's same-slug file for it raised a spurious #67 on the
// old session.
let openPostID = openSession?.targets(home: home) == true ? openSession?.postID : nil
let scanMemo = scanCache // detached capture, not a property read
// The search's content signal: a re-read post.md (a cache miss)
// changed library content even when its Post compares equal. Read
// the counter before the scan so the delta after it says "this
// scan saw disk change" (#144's mounted half).
let missesBefore = scanMemo.misses
let scan = scanLibrary // detached capture, not a property read
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = scan(home, scanMemo)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.value
guard !Task.isCancelled else { return }
// Stale-scan guard (#137 suite find / finish): the snapshot can
// PREDATE the current selection, and a scan that outlived a Home
// repoint speaks for the OLD tree — bind's initial rescan (detached
// scan over the empty tree) can land its continuation after a
// select its scan never saw, "vanishing" a piece that exists, and a
// pre-repoint scan would land the old library's list under the new
// binding. Disk is the truth for vanished; a stale snapshot must
// not kill a live session (teardown cancels the debounce —
// unflushed edits would die with it); the new Home's own rescan
// owns everything (brief-28: hoisted — the list, the revision and
// the #67 text ride the same verdict, not just the vanish check).
guard watchedHome == home else { return }
// #143: @Observable invalidates on assignment regardless of equality —
// skip the no-op so panes don't regroup on our own autosave echoes.
let listChanged = scanned != posts
if listChanged {
posts = scanned
}
// #144's mounted half: any list change OR any re-read file bumps the
// content revision — the search snapshot's invalidation signal.
// Archive/trash/rename arrive as list changes; a body-only edit as
// a cache miss (metadata-equal — the skip above keeps the panes
// still, the bump alone re-keys the mounted search).
if listChanged || scanMemo.misses > missesBefore {
contentRevision += 1
}
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), PostStore.folder(of: id, home: home) == nil {
selectedPostID = nil // the post vanished (deleted in Finder or here)
if let open = session, open.targets(postID: id, home: home) {
open.teardown(flushFirst: false) // post is gone; cancel the debounce
session = nil
}
}
// #67: watcher echo check on the open post — equality against the
// session's lastFlushedText suppresses our own writes exactly.
if openSession === session, let openDiskText {
openSession?.diskDidChange(diskText: openDiskText)
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards()
}
}
-288
View File
@@ -1,288 +0,0 @@
//
// PostsModelWrites.swift
// Museion
//
// #193: the #179 write rail and the structural library ops, moved from
// PostsModel.swift (file-length ceiling) — performWrite, flushOrAbort,
// rename/trash, the #108 project ops, and move/archive/restore, code
// unchanged.
//
import Foundation
extension PostsModel {
// MARK: Own ops (route through the same rescan, #61)
// ponytail: the PostStore calls here run on MainActor — small single-file
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
// them in Task.detached like rescan.
/// #179: the write rail — ONE seam pairs every library store write with
/// exactly one rescan and owns the error strip. A verb passes its
/// PostStore write (plus any post-write state surgery); a throw lands
/// its reason in the strip with nothing rescanned, a clean run rescans
/// once. The strip clears BEFORE the write, so a batch write that sets
/// its own per-file failure messages mid-closure (importFiles) keeps
/// them. The editor's debounced flush stays OUTSIDE the rail — its
/// error semantics are the session's own (EditorSession.onError).
/// Returns nil when the write landed; the failure reason otherwise
/// (createProject hands that to its sheet).
@discardableResult
func performWrite(_ write: (URL) throws -> Void) -> String? {
guard let home = watchedHome else {
lastError = "No library is open yet — nothing was changed."
return lastError
}
lastError = nil
do {
try write(home)
Task { await rescan() }
return nil
} catch {
lastError = error.localizedDescription
return lastError
}
}
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
/// first (rename reads the file from disk — unflushed edits must land
/// before the move), then reopens a session at the new id. #179: the
/// write rides the rail.
func rename(_ post: Post, to title: String) {
// #108 audit 2: rename reads the file from disk — a failed write
// aborts (moving the folder would strand unflushed edits), and the
// session stays up, dirty and honest.
guard flushOrAbort(post.id) else { return }
performWrite { home in
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
if openSessionTargets(post.id) { // brief-28: identity
session = EditorSession(postID: moved.id, home: home)
wireSession()
}
}
}
}
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
/// was the post; the session is torn down (cancel only — the folder is
/// leaving, a flush would resurrect nothing but churn the watcher).
/// #179: the write rides the rail.
func trash(_ post: Post) {
performWrite { home in
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
if let open = session, openSessionTargets(post.id) { // brief-28: identity
open.teardown(flushFirst: false)
session = nil
}
}
}
}
// MARK: Projects (#108)
/// #108: New Project's confirmed sheet — the folder exists, the next
/// draft targets it, and opens now.
func newProjectPending(named name: String) {
pendingProject = name
newPost()
}
/// #108: raw create — the sheet composes on it. #179: rides the write
/// rail (one rescan pairs the new folder); the failure reason is BOTH
/// returned for the sheet's inline display AND owned by the strip —
/// the rail posture replaces the old sheet-only rule.
func createProject(named name: String) -> String? {
performWrite { try PostStore.createProject(named: name, home: $0) }
}
/// #108: File ▸ New Project… — stage the ask (WorkspaceView presents).
func stageNewProject() {
askNewProject = true
}
/// #108: the ask's Cancel.
func cancelNewProject() {
askNewProject = false
}
/// #108 audit 2: the Move-to-Project list — every project on disk under
/// projects/ plus the default (bind creates the roots, not posts/ — an
/// empty Home must still offer it), localized-sorted to match the
/// library's section order.
func moveTargets() -> [String] {
guard let home = watchedHome else { return [Post.defaultProject] }
let root = home.appendingPathComponent("projects", isDirectory: true)
let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
names.insert(Post.defaultProject)
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
/// #108 audit: flush the open piece, aborting when the write failed — a
/// folder move must never carry away text that didn't land (the move
/// itself succeeds exactly when a file write fails). Returns false with
/// lastError set; the session stays up, dirty and honest.
/// #33: internal — the Micropub draft flow (Micropub.swift) flushes
/// through the same rail.
func flushOrAbort(_ postID: String) -> Bool {
// brief-28: identity — only THIS library's open piece flushes here; a
// session born under another Home is not the caller's piece.
guard let session, openSessionTargets(postID) else { return true }
return sessionMayDepart(session)
}
/// brief-25 (failed-flush-discarded-on-document-switch): the departure
/// gate for ONE outgoing session — flushOrAbort's two gates lifted to
/// document departure. An unanswered #67 conflict means disk holds
/// foreign text with the session's version unwritten (#114 audit); a
/// failed flush means the edits never landed. Either way the document
/// may not leave: the caller aborts its navigation BEFORE clearing
/// document-specific state, so the dirty session stays retained and
/// honest while lastError says why (the structural rail's #108
/// posture — now the navigation sites' too).
/// #146: internal — PostsModelOutline's openUnguarded gates too.
func sessionMayDepart(_ outgoing: EditorSession) -> Bool {
if outgoing.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
// #200 finish-audit (LOW): a never-loaded session's flush reports
// a vacuous success — its retyped words would die with the
// departure (quit AND navigation). Block instead: never silently
// drop the only copy.
if outgoing.loadFailed, outgoing.saveState == .changed {
lastError = "This piece's file never loaded — the retyped text in the editor can't be saved. Copy it out first."
return false
}
if !outgoing.flush() {
// Append, don't replace — the flush already routed the write's
// localizedDescription into lastError; only say what was skipped.
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
return false
}
return true
}
/// brief-25: the shared departure run for a full document switch —
/// the external guest and the post session both leave (newPost,
/// newOutline, openExternal). Each flushes through the departure gate
/// first; a failure retains BOTH exactly as they are and the
/// navigation aborts with nothing cleared.
@discardableResult
func departOpenDocuments() -> Bool {
guard dismissExternal() else { return false }
if let open = session {
guard sessionMayDepart(open) else { return false }
open.teardown(flushFirst: false) // the gate already flushed
session = nil
}
return true
}
/// #200 (gate quit-time flushes through the departure gate): the quit
/// run of the same gate — `shutdown`'s flush half, shared with
/// WritingLockAppDelegate's `applicationShouldTerminate` (willTerminate
/// can no longer refuse a quit). Both open documents route through
/// `sessionMayDepart`; false = the quit must not proceed, lastError
/// says why. The failed-flush-at-quit posture is BLOCK QUIT (the
/// WritingLock refusal precedent) — never silently drop the only copy
/// of the edits, never write over an unanswered #67 foreign body.
func documentsMayDepart() -> Bool {
var departed = true
if let guest = externalSession, !sessionMayDepart(guest) {
departed = false
}
if let open = session, !sessionMayDepart(open) {
departed = false
}
return departed
}
/// #108: Move to Project — flush first (move reads disk), then the
/// folder moves under projects/. Id stays the same; the session is
/// reopened anyway so folderURL re-resolves to the new parent.
/// #179: the write rides the rail.
func moveToProject(_ post: Post, project: String) {
guard flushOrAbort(post.id) else { return }
performWrite { home in
try PostStore.move(post, to: project, home: home)
if openSessionTargets(post.id) { // brief-28: identity
session = EditorSession(postID: post.id, home: home)
wireSession()
}
}
}
/// #108: Move to Archive. Archiving the open piece clears it — the
/// editor is empty until the next selection (archived pieces open from
/// the Archive pane, where they're listed). #179: the write rides the
/// rail.
func archivePost(_ post: Post) {
guard flushOrAbort(post.id) else { return }
performWrite { home in
try PostStore.archive(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
}
if let open = session, openSessionTargets(post.id) { // brief-28: identity
open.teardown(flushFirst: false) // already flushed above
session = nil
}
}
}
/// #108: Move Back — the restored piece lands in its project and opens;
/// the writer stays in the piece they just revived. A session already
/// open on the piece survives `select` — reopen it so folderURL points
/// at projects/, not the archive path it was born with.
/// #179: the write rides the rail.
func restorePost(_ post: Post) {
guard flushOrAbort(post.id) else { return }
performWrite { home in
try PostStore.restore(post, home: home)
if openSessionTargets(post.id) { // brief-28: identity
session = EditorSession(postID: post.id, home: home)
wireSession()
} else {
select(post.id)
}
}
}
/// #108: whole-project unarchive from the Archive pane's section header.
/// Flush-first like every folder move (a dirty open piece inside the
/// project would otherwise race the move), and its session is reopened so
/// folderURL re-resolves off archive/ (same reason as restorePost).
/// #179: the write rides the rail.
func unarchiveProject(_ name: String) {
// #108 audit 2: disk-derived membership — the posts snapshot is stale
// the moment a Finder move lands. Captured BEFORE the move: after it
// the piece resolves under projects/ and its archive membership is
// invisible. dir − 1 = project dir (…/archive/<name>), − 2 = root.
guard let boundHome = watchedHome else { return }
func openPieceInArchivedProject() -> String? {
guard let id = session?.postID, openSessionTargets(id), // brief-28: identity
let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(),
projectDir.lastPathComponent == name,
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
else { return nil }
return id
}
let openID = openPieceInArchivedProject()
if let openID {
// #108 audit 2: the only #108 folder move that skipped the gate.
guard flushOrAbort(openID) else { return }
}
performWrite { home in
try PostStore.unarchiveProject(name, home: home)
if let openID {
session = EditorSession(postID: openID, home: home)
wireSession()
}
}
}
}
+579 -7
View File
@@ -7,13 +7,11 @@
// trash. #19: the TextKit2 editor core (PostEditorView) replaces the stub;
// mentor column (#14).
// #108 (variant B, ref/prototypes/wf104-library-ui-prototype.html): sections
// per project (serif-15 head + mono count), Pass-State groups inside, and
// a 2px accent edge bar on the selected row.
// #193: the split-out files — the library column + its sheets + the
// launch focus rider PostsLibraryColumn.swift, the shared
// LibraryPostRow.swift.
// per project (serif-15 head + mono count), Pass-State groups inside, and a
// 2px accent edge bar on the selected row.
//
import AppKit
import SwiftUI
/// The Posts destination: the workspace's full four-column layout
@@ -87,10 +85,14 @@ struct PostsPaneView: View {
}
}
}
.task(id: home) {
// Bind: initial off-main scan + (re)start the FSEvents watcher (#61).
model.bind(home: home)
}
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
MicropubPublishSheet(posts: model)
MicropubPublishSheet(posts: model, home: home)
}
}
@@ -110,7 +112,7 @@ struct PostsPaneView: View {
draftText: draft.text,
draftEdited: { model.updateDraft($0) },
draftSave: {
model.saveDraft()
model.saveDraft(home: home)
},
outline: draft.type == .outline,
)
@@ -183,3 +185,573 @@ struct PostsPaneView: View {
.frame(width: DesignTokens.mentorWidth)
}
}
/// #21: the library column, shared by the unfocused layout and the focus-mode
/// left reveal overlay — one implementation, both surfaces. Owns the rename +
/// move sheets and the context menu (they travel with the post rows).
/// #108 variant B: sections per project, Pass-State groups inside.
struct PostsLibraryColumn: View {
let home: URL
var model: PostsModel
@State private var renamingPost: Post?
@State private var movingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted (a
/// fresh open shows everything; the prototype behaved the same).
@State private var collapsed: Set<String> = []
/// #144: the library search — live title+body filter over the
/// non-archived pieces. nil = not searching (sections render).
@State private var query = ""
@State private var matches: [Post]?
/// r5 (argon#44, mercury#52, sol#37): focus state for the field's
/// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7
/// onAppear-unfocus could never work — the launch focus is AppKit
/// assigning the window's INITIAL first responder to its first text
/// input (this field), at window-become-key, AFTER onAppear. FocusState
/// merely mirrors that back as true. LaunchFocusReset (below) resigns
/// it at the first become-key; from then on only the user drives this.
@FocusState private var searchFocused: Bool
private var trimmedQuery: String {
query.trimmingCharacters(in: .whitespacesAndNewlines)
}
private var isSearching: Bool {
!trimmedQuery.isEmpty
}
/// Non-archived pieces keyed by project (scan order = title order holds
/// inside each group — filter preserves it).
private var activeByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project)
}
var body: some View {
VStack(spacing: 0) {
PaneHeader(title: "Posts") {
Button {
model.newPost()
} label: {
Image(systemName: "plus")
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.help("New Post")
.accessibilityLabel("New Post")
}
searchField
if isSearching {
if let matches {
if matches.isEmpty {
searchEmptyState
} else {
searchResults(matches)
}
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
} else if activeByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order (scan's own sort), not Unicode-scalar
// order — the heads render lowercased, "Beta" must not read before "apple".
ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = activeByProject[project] ?? []
// #108: the head is the prototype's toggle — click
// collapses the project's pieces (chevron rotates).
Button {
withAnimation {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
} label: {
// r7 (mercury#18, argon#12 — TWO-AXIS ladder,
// the r6 four-step collapse undone): the
// head ROW leads at the column's PRIMARY
// inset (x14) — chevron glyph in a 14pt slot
// — and every nested CONTENT shares the one
// indent step (x28): head text, group
// labels, and the rows' inner text. No third
// or fourth x-axis exists in the column.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
Text(project)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.textCase(.lowercase) // #108: display-only — the folder name keeps its case
.lineLimit(1)
.truncationMode(.tail)
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
}
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.accessibilityLabel("\(project), \(pieces.count) pieces")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
.padding(.top, 16)
.padding(.horizontal, 14)
.padding(.bottom, 6)
if !collapsed.contains(project) {
passStateGroups(pieces)
}
}
}
.padding(.bottom, 12)
}
}
}
.frame(width: DesignTokens.libraryWidth)
// r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7
// onAppear-unfocus — see LaunchFocusReset below for the mechanism.
.background(LaunchFocusReset())
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
}
}
.sheet(item: $movingPost) { post in
// #108 audit 2: disk-derived list, localized-sorted — same order
// the library renders (Unicode-scalar sort split them), and it
// includes empty projects (a fresh New Project has no pieces yet —
// it must already be a move target).
MoveToProjectSheet(post: post, projects: model.moveTargets(home: home)) { project in
model.moveToProject(post, project: project, home: home)
}
}
// #144: keystroke-debounced (250 ms), structured body scan —
// nonisolated search() runs the disk reads off MainActor while
// staying inside this task, so a superseding keystroke or clear
// cancels the sweep between pieces (the in-flight file read
// always finishes — readBody is synchronous).
.task(id: trimmedQuery) {
guard !trimmedQuery.isEmpty else {
matches = nil
return
}
try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return }
let found = await librarySearch(
candidates: model.posts.filter { !$0.isArchived },
matching: trimmedQuery,
home: home,
)
guard !Task.isCancelled else { return }
matches = found
}
}
/// One piece row + its context menu — sections and search results
/// render the same row (#144: results carry the full menu too).
private func postRow(_ post: Post) -> some View {
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
// #114 (S4): outline pieces only — the ask picks the
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post, home: home)
}
Button("Move to Trash", role: .destructive) {
model.trash(post, home: home)
}
}
}
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
/// softer, indented under the section head). r2: the label binds to
/// its FIRST row (bottom 1 + stack 4) — it floated closer to the
/// preceding row than to its own children.
private func passStateGroups(_ pieces: [Post]) -> some View {
ForEach(Post.PassState.allCases, id: \.self) { state in
let grouped = pieces.filter { $0.passState == state }
if !grouped.isEmpty {
// mercury#53 (r5): display-only normalization — the stored
// rawValues keep their hyphen ("Pass-1 Done"); the rendered
// label uses the space form so it matches the Pass 1 / Pass 2
// vocabulary everywhere else.
Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " "))
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.kerning(0.6)
// r6 (sol#6/21 — contrast final): group labels are
// informational meta — FULL muted ink, no wash.
.foregroundStyle(DesignTokens.muted)
// r6 ladder: full muted ink. r7 two-axis: x28 — the ONE
// indent step, shared with the head text and the row
// cards' inner content.
.padding(.leading, 28)
.padding(.top, 10)
.padding(.bottom, 1)
ForEach(grouped) { post in
postRow(post)
}
}
}
}
/// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
/// border on the column's chrome, taller than a text row; the placeholder
/// r5 (argon#44, mercury#52, sol#37): the insertion caret tints
/// terracotta (.tint on the field), and the small magnifier glyph sits at
/// the field's leading edge (icon→text spacing rides the HStack's 6pt);
/// the placeholder is the native prompt wearing the palette's muted ink
/// (the composer's pattern).
/// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6,
/// present but never the strongest saturation on screen.
private var searchField: some View {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
.textFieldStyle(.plain)
.font(.system(size: 12))
.focused($searchFocused)
.tint(DesignTokens.accent)
if isSearching {
Button {
query = ""
} label: {
Image(systemName: "xmark.circle.fill")
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.accessibilityLabel("Clear search")
}
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
// r8 (argon#6, mercury#12): quiet focus — accent at 0.6,
// one step down from full strength.
RoundedRectangle(cornerRadius: 8)
.strokeBorder(
searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border,
lineWidth: 1,
),
),
)
// r7 (mercury#18, argon#12 — two-axis ladder): the box spans the
// FULL padded column width at the PRIMARY inset — leading 14
// (aligned with the 'Posts' header text) to trailing 14 — the
// same edges the row cards lead at.
.padding(.horizontal, 14)
.padding(.vertical, 8)
}
/// Flat results, title matches first (stable partition — both halves
/// keep the scan's Finder order). Same row the sections render.
private func searchResults(_ found: [Post]) -> some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
Text("\(found.count) \(found.count == 1 ? "match" : "matches")")
.font(.system(size: 11, design: DesignTokens.mono))
.kerning(0.6)
// r6: full muted ink; r7 two-axis: x28 — the indent
// step, heading the flat result list exactly where
// group labels head their sections.
.foregroundStyle(DesignTokens.muted)
.padding(.leading, 28)
.padding(.top, 12)
.padding(.bottom, 1)
ForEach(found) { post in
postRow(post)
}
}
.padding(.bottom, 12)
}
}
private var searchEmptyState: some View {
VStack(spacing: 8) {
Text("No matches")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("No piece's title or body contains “\(trimmedQuery)”.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("No posts yet")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Posts in this Home's projects/ folders appear here.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #144: the title+body scan — a thin mount for the pure
/// `LibrarySearch` seam (title matches first, stable partition, both
/// halves keep the scan's Finder order; body via readBody — frontmatter
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
/// The reader's per-piece cancellation check stops a superseded sweep's
/// body reads between files; the in-memory title walk itself completes
/// cheaply and the caller's guard discards its result. File scope since
/// r6 (PostsLibraryColumn hit its type-body ceiling).
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
/// posture); a PostScanCache-style body memo if it ever measures hot.
private nonisolated func librarySearch(
candidates: [Post],
matching trimmed: String,
home: URL,
) async -> [Post] {
LibrarySearch.results(for: trimmed, in: candidates) { post in
guard !Task.isCancelled else { return nil }
return PostStore.readBody(id: post.id, home: home)
}
}
/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at
/// the source): the search field is the window's first — and at launch,
/// only — text input, and AppKit assigns the window's initial first
/// responder to it when the window becomes key. That happens AFTER
/// onAppear, so the r6/r7 `searchFocused = false` writes were always
/// overridden (FocusState mirrors the assignment back as true: terracotta
/// ring + caret, the strongest element on screen). This invisible rider
/// rides the library column and, at the window's FIRST become-key,
/// resigns focus back to the window itself (`makeFirstResponder(nil)` —
/// the neutral state; nothing gains focus instead). ONCE per process: a
/// pane-switch remount must never steal a focus the user set on return.
/// The second, next-runloop resign covers an assignment that lands after
/// the notification (the PostEditorView layout-race precedent).
private struct LaunchFocusReset: NSViewRepresentable {
/// Process-wide once-flag — launch is a once-per-process event.
private static var hasRun = false
final class RiderView: NSView {
private var keyObserver: NSObjectProtocol?
override func viewDidMoveToWindow() {
if let keyObserver {
NotificationCenter.default.removeObserver(keyObserver)
}
keyObserver = nil
guard let window else { return }
keyObserver = NotificationCenter.default.addObserver(
forName: NSWindow.didBecomeKeyNotification,
object: window,
queue: .main,
) { _ in
MainActor.assumeIsolated {
// The observer is scoped to `window` (object:), so the
// notification carries nothing we don't already hold —
// reading `note` here would cross a Sendable boundary.
guard !LaunchFocusReset.hasRun else { return }
LaunchFocusReset.hasRun = true
window.makeFirstResponder(nil)
DispatchQueue.main.async { window.makeFirstResponder(nil) }
}
}
}
}
func makeNSView(context _: Context) -> RiderView {
RiderView()
}
func updateNSView(_: RiderView, context _: Context) {}
}
/// #108: Move to Project ask — radio list of the non-archived projects,
/// default = the piece's current project. Matches RenamePostSheet's shape.
struct MoveToProjectSheet: View {
let post: Post
let projects: [String]
let move: (String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var target: String
init(post: Post, projects: [String], move: @escaping (String) -> Void) {
self.post = post
self.projects = projects
self.move = move
_target = State(initialValue: post.project)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Move to Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("“\(post.title)” moves into the chosen project. The file stays post.md.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Project", selection: $target) {
ForEach(projects, id: \.self) { name in
Text(name).tag(name)
}
}
.pickerStyle(.radioGroup)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Move") {
move(target)
dismiss()
}
.keyboardShortcut(.defaultAction)
.disabled(target == post.project)
}
}
.padding(20)
.frame(width: 360)
}
}
/// #60: Explicit Rename dialog — asks the new Title (not a slug).
struct RenamePostSheet: View {
let rename: (String) -> Void
@Environment(\.dismiss) private var dismiss
@State private var title: String
init(post: Post, rename: @escaping (String) -> Void) {
self.rename = rename
_title = State(initialValue: post.title)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Rename Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The folder moves to match the new Title. The file stays post.md.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Title", text: $title)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Rename", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
rename(trimmed)
dismiss()
}
}
/// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
/// Archive pane reuses it.
struct LibraryPostRow: View {
let post: Post
let selected: Bool
let select: () -> Void
@State private var hover = false
var body: some View {
// `.vB .post-row { border-left: 2px solid transparent;
// border-radius: 0 8px 8px 0 }` — every row: leading corners square
// (the 2px strip below), trailing rounded 8. Only the strip's
// VISIBILITY changes on selection.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) {
HStack(spacing: 0) {
// The leading strip is always 2px wide so hover/selection
// never shifts the title. r6 (mercury#49/52, argon#13):
// the shared SelectedRowStrip capsule — accent, radius-1
// ends, vertically inset 6pt (was 3) so it sits INSIDE
// the card, never pasted on its square leading edge.
SelectedRowStrip()
.opacity(selected ? 1 : 0)
VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text(post.title)
if post.type == .outline {
Text(" ✳")
.foregroundStyle(DesignTokens.muted)
}
}
// ui-polish r8: serif-13 per the row contract — `.callout`
// was the system sans design (the r6/r7 councils pixel-
// verified sans glyphs on the Archive rows).
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
// Origin only — the Pass State already rides the uppercase
// group label above (it stays in the accessibility label).
// r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge.
Text(post.origin.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
}
.clipShape(shape)
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.background {
if selected || hover {
// r8 (mercury#11): the selected row DROPS its gray outline —
// fill + accent capsule read as ONE shape; stacking fill +
// outline + capsule competed. Hover keeps its borderless
// 0.06 wash exactly as before.
shape
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
}
}
// r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
// leads at the PRIMARY inset (x14, the 'Posts' header text's
// edge); its INNER content (title + status micro-label, strip
// 2 + padding 12) lands at x28 — the ONE indent step, shared
// with the head text and the group labels. No other x-axis
// exists in the column. Vertical padding stays the content
// VStack's constant 10 whether or not the row shows its strip.
.padding(.horizontal, 14)
.onHover { hover = $0 }
// help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
}
}
+8 -6
View File
@@ -54,19 +54,19 @@ nonisolated enum ProfileBackup {
/// hasn't landed yet) is simply absent from the stamp; only NO profile
/// at all skips.
/// - Parameters:
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - backupsRoot: snapshots base dir (tests inject; default Museion's
/// Application Support / Backups).
/// - now: clock injection for the age check (tests pass fixed dates).
static func perform(
profileRoot: String = ProfileLayout.defaultRoot,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
backupsRoot: String = defaultBackupsRoot(),
now: Date = Date(),
psScan: () -> Bool = psContainsMuseion,
) -> Outcome {
let fileManager = FileManager.default
let sources = ProfileSurface.allCases
.map { ProfileLayout.profileDir($0.profileName, root: profileRoot) }
.map { (profileRoot as NSString).appendingPathComponent($0.profileName) }
.filter { fileManager.fileExists(atPath: $0) }
guard !sources.isEmpty else {
logInfo("skipped — no profile found")
@@ -84,7 +84,9 @@ nonisolated enum ProfileBackup {
// Age check against the newest existing snapshot (#15: skips record no
// state; the normal age check governs retry).
if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval {
if let newest = sortedSnapshots(in: backupsRoot).first,
now.timeIntervalSince(newest.timestamp) < snapshotInterval
{
return .skippedFresh
}
@@ -172,7 +174,7 @@ nonisolated enum ProfileBackup {
/// the ps scan is global (one scan answers for every surface profile),
/// so the caller evaluates it once.
private static func idleProfileDir(_ profileDir: String) -> Bool {
let pidPath = ProfileLayout.gatewayPID(in: profileDir)
let pidPath = (profileDir as NSString).appendingPathComponent("gateway.pid")
if let pid = parsePID(fromFile: pidPath), kill(pid, 0) == 0 {
return false
}
@@ -309,7 +311,7 @@ final class BackupModel {
guard !running else { return }
running = true
defer { running = false }
let profileRoot = profileRoot ?? ProfileLayout.defaultRoot
let profileRoot = profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath
let backupsRoot = backupsRoot ?? ProfileBackup.defaultBackupsRoot()
lastOutcome = await Task.detached(priority: .utility) {
ProfileBackup.perform(profileRoot: profileRoot, backupsRoot: backupsRoot)
-48
View File
@@ -1,48 +0,0 @@
//
// ProfileLayout.swift
// Museion
//
// #182: the ONE owner of the Hermes profile layout — the root default and
// every per-profile path derivation. The provisioner, the settings writer,
// and backup/restore build paths only through here; no literal
// profile-root string lives outside this module (pinned in
// ProfileLayoutTests — a layout change is this module + that one suite).
//
// Deliberately NOT layout-owned: the RESTORE.md copy names
// `~/.hermes/profiles` as prose (static text that must outlive the app),
// and the backup ps scan greps argv text, not filesystem paths.
//
import Foundation
nonisolated enum ProfileLayout {
/// The profiles base dir (`~/.hermes/profiles`; tests inject their own root).
static let defaultRoot = ("~/.hermes/profiles" as NSString).expandingTildeInPath
/// `<root>/<profileName>` — the profile's home dir.
static func profileDir(_ profile: String, root: String) -> String {
(root as NSString).appendingPathComponent(profile)
}
/// The profile's `.env` — provider keys (the writer's fan-out surface).
static func envFile(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent(".env")
}
/// The configured marker — written by the provisioner after the config
/// rail completes; marker-gating keeps a re-pass from stomping a user's
/// later Settings change.
static func configuredMarker(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent(".museion-provisioned")
}
/// The engine gateway's pid file (the backup liveness gate reads it).
static func gatewayPID(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent("gateway.pid")
}
/// The profile's skills dir — the symlink farm into the ONE master copy.
static func skillsDir(in profileDir: String) -> String {
(profileDir as NSString).appendingPathComponent("skills")
}
}
+72 -71
View File
@@ -107,7 +107,7 @@ nonisolated enum ProfileProvisioner {
/// museion-tools (#23). First failure wins; the next pass heals.
/// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default the layout's root).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle).
/// - masterRoot: the ONE master skills copy (#133; tests inject; default
/// Application Support — never a symlink into the bundle, which moves
@@ -116,7 +116,7 @@ nonisolated enum ProfileProvisioner {
/// `--serve-mcp` (tests inject; nil skips registration).
static func perform(
hermesBinary: String?,
profileRoot: String = ProfileLayout.defaultRoot,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
payloadRoot: String = defaultPayloadRoot(),
masterRoot: String = defaultMasterRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
@@ -139,16 +139,16 @@ nonisolated enum ProfileProvisioner {
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
}
let env = SurfaceEnv(
hermesBinary: hermesBinary,
profileRoot: profileRoot,
masterRoot: masterRoot,
manifest: manifest,
serverBinaryPath: serverBinaryPath,
timeout: timeout,
)
for surface in ProfileSurface.allCases {
switch provisionSurface(surface, env: env) {
switch provisionSurface(
surface,
hermesBinary: hermesBinary,
profileRoot: profileRoot,
masterRoot: masterRoot,
manifest: manifest,
serverBinaryPath: serverBinaryPath,
timeout: timeout,
) {
case let .seeded(deltaCopied, deltaPresent):
copied += deltaCopied
present += deltaPresent
@@ -165,27 +165,20 @@ nonisolated enum ProfileProvisioner {
return .seeded(copied: copied, present: present)
}
/// Per-`perform` context threaded into every surface pass — everything
/// except the surface itself (the loop variable), so the per-surface
/// seam stays under the parameter-count ceiling.
private struct SurfaceEnv {
let hermesBinary: String?
let profileRoot: String
let masterRoot: String
let manifest: [String]
let serverBinaryPath: String?
let timeout: TimeInterval
}
/// Phases 1–4 for ONE surface profile (#134): create (or adopt), write
/// defaults on fresh profiles via the CLI rail, link skills per
/// allocation, register museion-tools (#23).
private static func provisionSurface(
_ surface: ProfileSurface,
env: SurfaceEnv,
hermesBinary: String?,
profileRoot: String,
masterRoot: String,
manifest: [String],
serverBinaryPath: String?,
timeout: TimeInterval,
) -> Outcome {
let fileManager = FileManager.default
let profileDir = ProfileLayout.profileDir(surface.profileName, root: env.profileRoot)
let profileDir = (profileRoot as NSString).appendingPathComponent(surface.profileName)
// Phase 1 — profile create. Dir-check first; spawn only when
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
@@ -193,18 +186,18 @@ nonisolated enum ProfileProvisioner {
// carry only Museion's curated set — coding and writing never mix, G3).
var createdFresh = false
if !fileManager.fileExists(atPath: profileDir) {
guard let binary = env.hermesBinary else {
guard let binary = hermesBinary else {
return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found")
}
let run = EngineProbe.execute(
[binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"],
timeout: env.timeout,
timeout: timeout,
)
// #43: exit 1 + "already exists" on stdout = success (a
// concurrent create — not ours, so not fresh); all errors print on stdout.
let alreadyExists = run.exitCode == 1 && run.stdout.contains("already exists")
guard run.exitCode == 0 || alreadyExists, fileManager.fileExists(atPath: profileDir) else {
return .failed(profile: surface.profileName, phase: .create, excerpt: HermesConfigRail.excerpt(run))
return .failed(profile: surface.profileName, phase: .create, excerpt: excerpt(run))
}
createdFresh = run.exitCode == 0
}
@@ -215,10 +208,10 @@ nonisolated enum ProfileProvisioner {
// profile (interrupted before its marker landed) is healed, and
// the adopted museion is never touched — its model is the user's.
if createdFresh || (surface != .chat && !markerExists(at: profileDir)) {
guard let binary = env.hermesBinary else {
guard let binary = hermesBinary else {
return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found")
}
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: env.timeout) {
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: timeout) {
return failure
}
// A marker we couldn't record = configure incomplete — surface it
@@ -231,7 +224,7 @@ nonisolated enum ProfileProvisioner {
// Phase 3 — per-profile skills: symlinks per allocation + the
// copy-era → symlink migration (#133).
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: env.masterRoot, manifest: env.manifest)
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: masterRoot, manifest: manifest)
if case .failed = linked {
return linked
}
@@ -239,7 +232,7 @@ nonisolated enum ProfileProvisioner {
// Phase 4 — museion-tools registration per profile (ADR-0008
// amendment). nil on either binary is the test-injection seam;
// production always has both after a gate pass.
guard let hermesBinary = env.hermesBinary, let serverBinaryPath = env.serverBinaryPath else {
guard let hermesBinary, let serverBinaryPath else {
Logger(subsystem: subsystem, category: "provisioning")
.info("museion-tools registration skipped: engine or server binary missing")
return linked
@@ -248,7 +241,7 @@ nonisolated enum ProfileProvisioner {
profile: surface.profileName,
hermesBinary: hermesBinary,
serverBinaryPath: serverBinaryPath,
timeout: env.timeout,
timeout: timeout,
) {
return failure
}
@@ -270,19 +263,20 @@ nonisolated enum ProfileProvisioner {
private static let subsystem = "com.babylondreams.Museion"
/// Configured marker: written only by us, after the config rail
/// completes. This is what makes a re-pass a no-op without stomping a
/// later Settings-written model block. The path derivation lives in the
/// layout (#182); the marker-gating policy stays here.
/// Configured-marker filename inside a profile dir — written only by us,
/// after the `config set` rail completes. This is what makes a re-pass a
/// no-op without stomping a later Settings-written model block.
private static let configuredMarker = ".museion-provisioned"
private static func markerExists(at profileDir: String) -> Bool {
FileManager.default.fileExists(atPath: ProfileLayout.configuredMarker(in: profileDir))
FileManager.default.fileExists(atPath: (profileDir as NSString).appendingPathComponent(configuredMarker))
}
/// Records the configured marker; nil on success, a configure-phase
/// failure when the write fails — an unrecorded configure must not count
/// as done (the next pass would re-stomp the defaults).
private static func markConfigured(_ profileDir: String, profile: String) -> Outcome? {
let marker = ProfileLayout.configuredMarker(in: profileDir)
let marker = (profileDir as NSString).appendingPathComponent(configuredMarker)
do {
try Data().write(to: URL(fileURLWithPath: marker))
return nil
@@ -291,34 +285,39 @@ nonisolated enum ProfileProvisioner {
}
}
/// One `config set` write: key, value, and whether it needs `--force`
/// (the budget key is unrecognized by some engine versions).
private struct ConfigWrite {
let key: String
let value: String
let force: Bool
}
/// #128/#132: write the per-surface defaults through the engine's own
/// CLI rail (#182) — provider first (switching providers clears a stale
/// inherited base_url — live-probed), then the model, then the output
/// budget (`--force`: the budget key is unrecognized by some engine
/// versions).
/// CLI. Provider first (switching providers clears a stale inherited
/// base_url — live-probed), then the model, then the output budget.
/// Verified wire: exit 0, `✓ Set <key> = <value> in …config.yaml`.
private static func configureDefaults(
profile: String,
hermesBinary: String,
timeout: TimeInterval,
) -> Outcome? {
do {
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
.set(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
.set(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
],
profile: profile,
binary: hermesBinary,
timeout: timeout,
)
} catch {
let failure = error as? HermesConfigRail.Failure
return .failed(
profile: profile,
phase: .configure,
excerpt: failure?.excerpt ?? error.localizedDescription,
)
let writes: [ConfigWrite] = [
ConfigWrite(key: "model.provider", value: ProfileSurface.defaultModelProvider, force: false),
ConfigWrite(key: "model.default", value: ProfileSurface.defaultModelID, force: false),
ConfigWrite(key: "model.extra_body.max_tokens", value: "\(ProfileSurface.outputBudgetTokens)", force: true),
]
for write in writes {
var arguments = [hermesBinary, "-p", profile, "config", "set", write.key, write.value]
if write.force {
arguments.append("--force")
}
let run = EngineProbe.execute(arguments, timeout: timeout)
// Wire-verified success, not exit code alone (finish-audit): a CLI
// that exits 0 while writing nothing must not count as configured.
guard run.exitCode == 0, run.stdout.contains("✓ Set \(write.key)") else {
return .failed(profile: profile, phase: .configure, excerpt: excerpt(run))
}
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -392,7 +391,7 @@ nonisolated enum ProfileProvisioner {
manifest: [String],
) -> Outcome {
let fileManager = FileManager.default
let skillsDir = ProfileLayout.skillsDir(in: profileDir)
let skillsDir = (profileDir as NSString).appendingPathComponent("skills")
sweepOrphanedTemps(skillsDir)
var linked = 0
var present = 0
@@ -471,7 +470,7 @@ nonisolated enum ProfileProvisioner {
)
// Verified wire contract: exit 0 + "Saved 'museion-tools'" on stdout.
guard add.exitCode == 0, add.stdout.contains("Saved 'museion-tools'") else {
return .failed(profile: profile, phase: .register, excerpt: HermesConfigRail.excerpt(add))
return .failed(profile: profile, phase: .register, excerpt: excerpt(add))
}
Logger(subsystem: subsystem, category: "provisioning")
.info("""
@@ -493,6 +492,12 @@ nonisolated enum ProfileProvisioner {
}
return outcome
}
/// Create-phase errors print on stdout (#43); copy-phase on stderr — take both.
private static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
}
}
/// Pure payload/tree filesystem helpers — same-file extension so the
@@ -518,12 +523,6 @@ nonisolated extension ProfileProvisioner {
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" }
}
/// True when `path` is a symlink (lstat-true, before any open) — the
/// payload never ships one, so a linked entry refuses the tree match.
private static func isSymlinked(_ path: String) -> Bool {
(try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil
}
/// Recursive byte-comparison of two dir trees — same entry names, every
/// file byte-identical. `.DS_Store` is filtered from BOTH listings before
/// the name-equality check (Finder noise, not a user edit — a
@@ -545,7 +544,9 @@ nonisolated extension ProfileProvisioner {
let rhsPath = (rhs as NSString).appendingPathComponent(name)
// Neither side may carry a symlink at this entry (lstat-true,
// before any open) — the payload never ships one.
if isSymlinked(lhsPath) || isSymlinked(rhsPath) {
if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil
|| (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil
{
return false
}
var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false
@@ -644,7 +645,7 @@ final class ProvisioningModel {
let outcome = await Task.detached(priority: .utility) {
ProfileProvisioner.perform(
hermesBinary: hermesBinary,
profileRoot: profileRoot ?? ProfileLayout.defaultRoot,
profileRoot: profileRoot ?? ("~/.hermes/profiles" as NSString).expandingTildeInPath,
payloadRoot: payloadRoot ?? ProfileProvisioner.defaultPayloadRoot(),
masterRoot: masterRoot ?? ProfileProvisioner.defaultMasterRoot(),
)
+2 -1
View File
@@ -17,6 +17,7 @@ import SwiftUI
struct PromoteAskSheet: View {
let card: FixCardStore.StoredFixCard
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
@State private var refusal: String?
@@ -107,7 +108,7 @@ struct PromoteAskSheet: View {
}
private func promote() {
switch posts.promoteCard(card) {
switch posts.promoteCard(card, home: home) {
case .promoted:
dismiss()
case let .refused(reason):
+1 -6
View File
@@ -121,13 +121,8 @@ nonisolated enum ProseList {
let hiddenLineCount: Int
}
/// `observeLines` (brief-24): reports how many lines the scan visited —
/// the typing-budget instrument. Nil in production; tests inject it to
/// pin that single-line typing edits scan ZERO lines (the #142 in-place
/// re-key) while full passes scan O(lines). Per-call, no shared state.
static func parents(in text: String, observeLines: ((Int) -> Void)? = nil) -> [ParentHint] {
static func parents(in text: String) -> [ParentHint] {
let scanned = lines(in: text)
observeLines?(scanned.count)
var out: [ParentHint] = []
for (idx, line) in scanned.enumerated() where line.isList {
let bounds = blockBounds(scanned, from: idx, indent: line.indent)
+8 -15
View File
@@ -90,12 +90,6 @@ final class ProseListTextView: NSTextView {
/// rejected, or none) → the full pass.
var pendingPlainEdit: (range: NSRange, delta: Int)?
/// Brief-24 typing-budget window for paths that call `refreshFolds()`
/// bare (the PostEditorView coordinator's textDidChange tail) — a
/// per-instance, test-owned hook; nil in production. The per-call
/// `observeScan` parameter takes precedence when both are set.
var onLineScan: ((Int) -> Void)?
override func shouldChangeText(in affectedRange: NSRange, replacementString: String?) -> Bool {
let accepted = super.shouldChangeText(in: affectedRange, replacementString: replacementString)
pendingPlainEdit = nil
@@ -208,11 +202,7 @@ final class ProseListTextView: NSTextView {
/// recorded single-line edit takes the in-place re-key (no rescan, no
/// storage swap); no folds → chrome-only refresh, everything else → the
/// full pass.
/// `observeScan` (brief-24): the typing-budget instrument — reports the
/// line count of every full-buffer scan this refresh performs. Nil in
/// production; the typing-budget pins inject it to prove single-line
/// edits take the in-place re-key (zero scans) at any buffer size.
func refreshFolds(observeScan: ((Int) -> Void)? = nil) {
func refreshFolds() {
defer { pendingPlainEdit = nil }
if let edit = pendingPlainEdit, !folds.isEmpty, rekeyAfterPlainEdit(edit) {
return
@@ -221,7 +211,7 @@ final class ProseListTextView: NSTextView {
chrome.refresh()
return
}
refreshFoldRendering(observeScan: observeScan)
refreshFoldRendering()
}
func toggleFold(_ parent: ProseList.ParentHint) {
@@ -237,8 +227,8 @@ final class ProseListTextView: NSTextView {
/// same marker text; no match → the fold dies), restyle the document,
/// re-hide every live scope, and park a caret that landed inside a
/// hidden scope at its parent's marker end.
func refreshFoldRendering(observeScan: ((Int) -> Void)? = nil) {
let parents = ProseList.parents(in: string, observeLines: observeScan ?? onLineScan)
func refreshFoldRendering() {
let parents = ProseList.parents(in: string)
// ponytail: nearest-same-marker re-key can move a fold across duplicate
// marker texts — track the edit delta in shouldChangeText if that bites.
var seenKeys = Set<Int>()
@@ -377,7 +367,10 @@ final class ProseListTextView: NSTextView {
guard let scalar = Unicode.Scalar(Int(char)) else { return false }
return CharacterSet.whitespacesAndNewlines.contains(scalar)
}
if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) {
if index > 0, index < length,
!isGap(buffer.character(at: index - 1)),
!isGap(buffer.character(at: index))
{
while index < length, !isGap(buffer.character(at: index)) {
index += 1
}
+102 -177
View File
@@ -38,39 +38,6 @@ nonisolated enum ProsePresenter {
classify(line, inFence: false)
}
/// A fence delimiter line (``` or ~~~ prefix) — delimiter lines are
/// fences even inside a fence (they close it).
static func isFenceDelimiter(_ trimmed: Substring) -> Bool {
trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~")
}
/// Pure rule/mark syntax (horizontal rules, dinkus) — no content.
static func isRuleSyntax(_ trimmed: Substring) -> Bool {
trimmed.allSatisfy { $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }
}
/// CommonMark ATX heading level (1–6) of a trimmed line — a heading
/// needs 1–6 hashes followed by a space or end-of-line; 7+ hashes or a
/// glued-on word is body text.
static func headingLevel(of trimmed: Substring) -> Int? {
let hashes = trimmed.prefix(while: { $0 == "#" }).count
guard hashes > 0, hashes <= 6 else { return nil } // CommonMark caps at 6; 7+ is body
let after = trimmed.dropFirst(hashes)
guard after.hasPrefix(" ") || after.isEmpty else { return nil }
return hashes
}
/// Heading ladder for a valid ATX level — 1–3 are named steps, 4–6
/// share the h4+ rung (CommonMark).
private static func headingKind(_ hashes: Int) -> LineKind {
switch hashes {
case 1: .heading1
case 2: .heading2
case 3: .heading3
default: .heading4Plus
}
}
/// Delimiter lines are fences even inside a fence (they close it) — so the
/// delim test runs before the inFence shortcut and `applyStyles` toggles
/// on `kind == .fence` instead of re-deriving the prefix.
@@ -79,19 +46,28 @@ nonisolated enum ProsePresenter {
if trimmed.isEmpty {
return .blank
}
if isFenceDelimiter(trimmed) {
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
return .fence
}
if inFence {
return .fenceInterior
}
if let hashes = headingLevel(of: trimmed) {
return headingKind(hashes)
let hashes = trimmed.prefix(while: { $0 == "#" }).count
if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body
let after = trimmed.dropFirst(hashes)
if after.hasPrefix(" ") || after.isEmpty {
switch hashes {
case 1: return .heading1
case 2: return .heading2
case 3: return .heading3
default: return .heading4Plus
}
}
}
if trimmed.hasPrefix(">") {
return .quote
}
if isRuleSyntax(trimmed) {
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
return .syntaxOnly
}
if line.firstMatch(of: listMarkerPattern) != nil {
@@ -126,7 +102,7 @@ nonisolated enum ProsePresenter {
var count = 0
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
if isFenceDelimiter(trimmed) {
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
count += 1
}
}
@@ -195,76 +171,58 @@ nonisolated enum ProsePresenter {
/// Count unclosed fences before `end` (``` or ~~~ delim lines toggle).
private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool {
var inFence = false
let prefix = NSRange(location: 0, length: min(end, nsText.length))
for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence {
inFence.toggle()
for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) {
if classify(line.text, inFence: inFence) == .fence {
inFence.toggle()
}
}
return inFence
}
/// The #…​ ATX marker of a heading line, dimmed to the code face.
private static func dimHeadingMarker(_ out: NSMutableAttributedString, line: Line) {
let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
if marker.length > 0 {
out.addAttributes(ProseTypography.codeAttributes, range: marker)
}
}
/// Kinds whose text content carries inline trait styling (bold/italic/
/// code/link spans).
static func carriesInlineTraits(_ kind: LineKind) -> Bool {
kind == .body || kind == .quote || kind == .listMarker
}
/// Non-empty UTF-16 marker range of `pattern` at the line start, or nil.
private static func markerRange(_ pattern: Regex<Substring>, in line: Line) -> NSRange? {
guard let marker = markerRangeUTF16(pattern, in: line.text), marker.length > 0 else { return nil }
return marker
}
/// List marker dim + hanging indent: wrapped list lines align with the
/// item's text, not the paragraph margin — the marker prefix (leading
/// whitespace + "- "/"1. ") sets headIndent, mirroring reading.css's
/// hanging lists (padding-left + outside markers; #ui-r1, sol#13; #ui-r2
/// argon#53 flush fix). Nested items hang at their own prefix width.
/// The prefix is measured in the EXACT attributes it renders in
/// (listMarkerAttributes — the line's face and size), so the
/// continuation lands flush; a different measuring face drifts
/// per-glyph (~4pt left in r1). ponytail: a tab in the prefix measures
/// at the default tab stop; the corpus uses spaces — widen if tabbed
/// lists drift.
private static func applyListMarker(_ out: NSMutableAttributedString, line: Line) {
guard let marker = markerRange(listMarkerPattern, in: line) else { return }
out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content))
let prefix = String(line.text.prefix(NSMaxRange(marker)))
let indent = NSAttributedString(
string: prefix,
attributes: ProseTypography.listMarkerAttributes,
).size().width
let hanging = NSMutableParagraphStyle()
hanging.setParagraphStyle(paragraph(.body))
hanging.headIndent = indent
// #ui-r7 sol#29: inter-item rhythm (reading.css list margins)
// — before-space only, the CSS block has no bottom margin.
hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore
out.addAttribute(.paragraphStyle, value: hanging, range: line.full)
}
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) {
guard line.full.length > 0 else { return }
out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full)
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
switch kind {
case .heading1, .heading2, .heading3, .heading4Plus:
dimHeadingMarker(out, line: line)
let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
if marker.length > 0 {
out.addAttributes(dim, range: marker)
}
case .quote:
if let marker = markerRange(quoteMarkerPattern, in: line) {
if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content))
}
case .listMarker:
applyListMarker(out, line: line)
if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 {
out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content))
// Hanging indent (#ui-r1, sol#13; #ui-r2 argon#53 flush
// fix): wrapped list lines align with the item's text, not
// the paragraph margin — the marker prefix (leading
// whitespace + "- "/"1. ") sets headIndent, mirroring
// reading.css's hanging lists (padding-left + outside
// markers). Nested items hang at their own prefix width.
// The prefix is measured in the EXACT attributes it
// renders in (listMarkerAttributes — the line's face and
// size), so the continuation lands flush; a different
// measuring face drifts per-glyph (~4pt left in r1).
// ponytail: a tab in the prefix measures at the default tab
// stop; the corpus uses spaces — widen if tabbed lists drift.
let prefix = String(line.text.prefix(NSMaxRange(marker)))
let indent = NSAttributedString(
string: prefix,
attributes: ProseTypography.listMarkerAttributes,
).size().width
let hanging = NSMutableParagraphStyle()
hanging.setParagraphStyle(paragraph(.body))
hanging.headIndent = indent
// #ui-r7 sol#29: inter-item rhythm (reading.css list margins)
// — before-space only, the CSS block has no bottom margin.
hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore
out.addAttribute(.paragraphStyle, value: hanging, range: line.full)
}
case .syntaxOnly:
if line.content.length > 0 {
out.addAttributes(dim, range: line.content)
@@ -274,7 +232,7 @@ nonisolated enum ProsePresenter {
case .fenceInterior, .blank, .body:
break
}
if carriesInlineTraits(kind) {
if kind == .body || kind == .quote || kind == .listMarker {
styleInline(out, content: line.content, text: line.text)
}
}
@@ -298,119 +256,98 @@ nonisolated enum ProsePresenter {
private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/
/// Trait-style inline constructs. Marks dim; content gets real traits.
/// Priority: code > link > bold > italic; later matches skip claimed
/// spans (`claim` is the shared overlap gate, so each family's loop
/// stays honest about the ones before it).
/// Priority: code > link > bold > italic; later matches skip claimed spans.
private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
guard content.length > 0 else { return }
var claimed: [Range<Int>] = []
styleCodeAndLinks(out, content: content, text: text, claimed: &claimed)
styleEmphasis(out, content: content, text: text, claimed: &claimed)
dimStraySyntax(out, content: content, text: text, claimed: &claimed)
}
/// Claim `span` unless an earlier (higher-priority) match overlaps it.
private static func claim(_ claimed: inout [Range<Int>], _ span: Range<Int>) -> Bool {
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
claimed.append(span)
return true
}
func claim(_ span: Range<Int>) -> Bool {
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
claimed.append(span)
return true
}
/// Dim a utf16 span in the code face (marks, brackets, stray syntax).
private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(ProseTypography.codeAttributes, range: range)
}
func dim(_ utf16: Range<Int>) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(ProseTypography.codeAttributes, range: range)
}
/// Apply `attrs` to a utf16 span.
private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(attrs, range: range)
}
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(attrs, range: range)
}
/// Inline code + links (priority 1–2). Code: marks + content in the code
/// face, content at ink. Links: label ink + underline (CSS: ink text,
/// muted rule); the brackets, ]( and the URL dim (reading hides them;
/// dim is the editor's closest parity move).
private static func styleCodeAndLinks(
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
) {
let boldFont = ProseTypography.boldBodyFont
let italicFont = ProseTypography.italicBodyFont
let codeFont = ProseTypography.codeFont
let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor]
let linkAttrs: [NSAttributedString.Key: Any] = [
.underlineStyle: NSUnderlineStyle.single.rawValue,
.underlineColor: ProseTypography.mutedColor,
]
// inline code — marks + content in the code face, content at ink
for match in text.matches(of: codePattern) {
let span = match.range.utf16Range(in: text)
guard claim(&claimed, span) else { continue }
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
guard claim(span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
}
// links — label ink + underline (CSS: ink text, muted rule); the
// brackets, ]( and the URL dim (reading hides them; dim is the
// editor's closest parity move).
for match in text.matches(of: linkPattern) {
let span = match.range.utf16Range(in: text)
guard claim(&claimed, span) else { continue }
guard claim(span) else { continue }
let whole = match.output // whole match (no capture groups)
guard let sep = whole.firstRange(of: "](") else { continue }
// sep indices are valid in text (Substring shares indices)
let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!)
let label = span.lowerBound + 1 ..< sepOffset
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [
attr(out, content: content, label, linkAttrs)
dim(out, content: content, sepOffset ..< span.upperBound) // ](url)
dim(span.lowerBound ..< span.lowerBound + 1) // [
attr(label, linkAttrs)
dim(sepOffset ..< span.upperBound) // ](url)
}
}
/// Bold + italic (priority 3–4). CommonMark: intraword `_` never
/// emphasizes (file_name_here); intraword `*` does. No lookbehind in
/// swift-regex, so boundary chars are checked by hand.
private static func styleEmphasis(
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
) {
let boldFont = ProseTypography.boldBodyFont
let italicFont = ProseTypography.italicBodyFont
// bold
for match in text.matches(of: boldPattern) {
let span = match.range.utf16Range(in: text)
guard claim(&claimed, span) else { continue }
dim(out, content: content, span.lowerBound ..< span.lowerBound + 2)
dim(out, content: content, span.upperBound - 2 ..< span.upperBound)
attr(out, content: content, span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
guard claim(span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 2)
dim(span.upperBound - 2 ..< span.upperBound)
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
}
// italic — two forms. CommonMark: intraword `_` never emphasizes
// (file_name_here); intraword `*` does. No lookbehind in swift-regex,
// so boundary chars are checked by hand.
for match in text.matches(of: emStarPattern) {
let span = match.range.utf16Range(in: text)
guard claim(&claimed, span) else { continue }
guard claim(span) else { continue }
let lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound)
if isMarkAdjacent(lo, hi) {
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
continue
}
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
}
for match in text.matches(of: emUnderPattern) {
let span = match.range.utf16Range(in: text)
guard claim(&claimed, span) else { continue }
guard claim(span) else { continue }
let lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound)
if isMarkAdjacent(lo, hi) {
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
continue
}
if isIntraword(lo, hi) {
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true {
continue
}
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
}
}
/// Fallback: dim stray syntax chars outside claimed spans.
private static func dimStraySyntax(
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
) {
// fallback: dim stray syntax chars outside claimed spans
let syntax = inlineSyntax
for (offset, codeUnit) in text.utf16.enumerated() {
guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue }
@@ -418,22 +355,10 @@ nonisolated enum ProsePresenter {
if claimed.contains(where: { $0.overlaps(unit) }) {
continue
}
dim(out, content: content, unit)
dim(unit)
}
}
/// True when the char at either boundary of an emphasis span is itself
/// a mark (`**foo**`'s inner `*` is bold, not emphasis).
private static func isMarkAdjacent(_ lo: Character?, _ hi: Character?) -> Bool {
lo == "*" || hi == "*" || lo == "_" || hi == "_"
}
/// True when an `_…_` span sits inside a word (file_name_here never
/// emphasizes).
private static func isIntraword(_ lo: Character?, _ hi: Character?) -> Bool {
lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true
}
// MARK: Base attributes
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
+2 -4
View File
@@ -31,12 +31,10 @@ nonisolated enum ProseTypography {
/// Headings = Concourse OT (the designer's own pairing with Valkyrie);
/// Semibold carries heading weight better than Book on screen.
nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size)
?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold)
nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold)
/// h2 = the headings face at CSS's 0.85× ladder step (#77).
nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size)
?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold)
nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold)
/// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B
/// cut has no 600 member — the bold trait (700, real or synthesized) is
+22 -18
View File
@@ -142,19 +142,24 @@ nonisolated enum ProviderProbe {
/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
/// chat-completions is the retired path). Nous (#175, live-probed
/// 2026-11-05) is plain OpenAI chat-completions on a versioned base.
/// #181: the paths live on the descriptor's dialect — a trailing slash
/// on a hand-edited endpoint never doubles up. A non-URL endpoint is
/// nil (URL(string:) happily percent-encodes "not a url" — the scheme
/// check is what actually rejects garbage; probe reports unreachable,
/// never traps).
/// A trailing slash on a hand-edited endpoint never doubles up. A
/// non-URL endpoint is nil (URL(string:) happily percent-encodes "not a
/// url" — the scheme check is what actually rejects garbage; probe
/// reports unreachable, never traps).
static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.chatPath)
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = switch provider {
case .anthropic: "/v1/messages"
case .openaiAPI: "/responses"
case .zai, .nous: "/chat/completions"
}
return httpURL(base + path)
}
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.modelsPath)
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
let path = provider == .anthropic ? "/v1/models" : "/models"
return httpURL(base + path)
}
private static func httpURL(_ string: String) -> URL? {
@@ -167,15 +172,14 @@ nonisolated enum ProviderProbe {
/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
/// `anthropic-version` (factsheet §2.1 — never send none). Nous rides
/// Bearer too — the portal accepts the session agent_key and an API
/// key interchangeably (#175). #181: the shape keys off the
/// descriptor's auth mode.
/// key interchangeably (#175).
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
switch provider.authMode {
case .bearer:
switch provider {
case .zai, .openaiAPI, .nous:
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
case let .headerKey(version):
case .anthropic:
request.setValue(key, forHTTPHeaderField: "x-api-key")
request.setValue(version, forHTTPHeaderField: "anthropic-version")
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
}
}
@@ -251,10 +255,10 @@ nonisolated enum ProviderProbe {
return failure
}
let (text, finish): (String, String?)
switch provider.dialect {
switch provider {
case .anthropic: (text, finish) = anthropicStream(events)
case .responses: (text, finish) = responsesStream(events)
case .chatCompletions: (text, finish) = chatCompletionsStream(events)
case .openaiAPI: (text, finish) = responsesStream(events)
case .zai, .nous: (text, finish) = chatCompletionsStream(events)
}
if !text.isEmpty {
return .works(latencyMS: latencyMS, modelCount: modelCount)
+2 -3
View File
@@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter {
// swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
let mutable = NSMutableString(string: html)
regex.replaceMatches(in: mutable, range: NSRange(location: 0, length: mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
return mutable as String
}
@@ -207,8 +207,7 @@ nonisolated enum ReadingPresenter {
/// apex failure / missing binary → editing-treated source text (#69's
/// fallback rule: fallback = the source, not a second renderer).
static func fallbackPage(_ text: String) -> String {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head>" +
"<body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
}
static func escapeHTML(_ text: String) -> String {
+3 -8
View File
@@ -172,13 +172,6 @@ struct ReadingSurface: NSViewRepresentable {
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
}
/// True for our own loadHTMLString main-frame load (file URL or
/// about:blank) — the only navigation reading allows in-app.
private func isOwnMainFrameLoad(_ nav: WKNavigationAction) -> Bool {
guard nav.targetFrame?.isMainFrame == true, let url = nav.request.url else { return false }
return url.scheme == "file" || url.absoluteString == "about:blank"
}
/// Allow our own loadHTMLString main-frame load (about:blank); a
/// blanket .cancel would kill the page before it paints. Everything
/// else is cancelled — reading never navigates in-app (#74 lesson).
@@ -187,7 +180,9 @@ struct ReadingSurface: NSViewRepresentable {
decidePolicyFor nav: WKNavigationAction,
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void,
) {
if isOwnMainFrameLoad(nav) {
if nav.targetFrame?.isMainFrame == true,
let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank"
{
decisionHandler(.allow)
return
}
-41
View File
@@ -1,41 +0,0 @@
# Third-Party Notices
Museion is GPL-3.0-or-later. It bundles the two components below, both under
the MIT License; the full license text follows.
## apex 1.1.59 (`apex`)
Markdown → HTML converter, used for reading mode.
Copyright (c) 2026 Brett Terpstra — https://github.com/ApexMarkdown/apex
Redistributed as the arm64 slice of the v1.1.59 release binary (checksum
verified against the published `.sha256`), re-signed for Developer ID
distribution; rpath rewritten to load the libyaml beside it.
## libyaml 0.2.5 (`libyaml.bundle/libyaml-0.2.dylib`)
YAML parser linked by apex.
Copyright (c) 2017-2020 Ingy döt Net
Copyright (c) 2006-2016 Kirill Simonov — https://github.com/yaml/libyaml
Re-signed for Developer ID distribution (the hardened runtime's library
validation requires the team's own signature); shipped inside a `.bundle`
folder so Xcode copies it as a resource instead of linking it into the app.
## MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -340,8 +340,8 @@ struct SessionsPaneView: View {
/// opened); a failed write keeps the sheet up with the draft intact
/// (ApplyAskSheet posture — the edited draft is never destroyed).
private func newPostFromSession() -> String? {
guard let posts else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "") == nil {
guard let posts, let home else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil {
return posts.lastError ?? "The piece couldn't be written."
}
sessionDraft = nil
+36 -130
View File
@@ -89,78 +89,6 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
case .nous: "NOUS_API_KEY"
}
}
/// #181: the wire family the probe speaks. The SELECTOR is data —
/// endpoint paths, auth shape, and the SSE decoder pick ride the
/// dialect; the per-family code (request bodies, stream decoders)
/// stays separate functions, not switch clothing.
nonisolated enum Dialect: Sendable {
/// Anthropic `/v1/messages`, header-key auth, Anthropic SSE.
case anthropic
/// OpenAI Responses `/responses`, Bearer, Responses SSE.
case responses
/// OpenAI chat-completions (`/chat/completions` — z.ai and the
/// Nous Portal), Bearer, chat-completions SSE.
case chatCompletions
/// The chat-call path appended to the endpoint base (callers trim
/// a trailing slash off the base first).
var chatPath: String {
switch self {
case .anthropic: "/v1/messages"
case .responses: "/responses"
case .chatCompletions: "/chat/completions"
}
}
var modelsPath: String {
switch self {
case .anthropic: "/v1/models"
case .responses, .chatCompletions: "/models"
}
}
}
/// #181: the provider's wire family (the probe's dialect selector).
var dialect: Dialect {
switch self {
case .zai, .nous: .chatCompletions
case .anthropic: .anthropic
case .openaiAPI: .responses
}
}
/// #181: the auth-header shape (factsheet §2.1) — Bearer everywhere
/// except Anthropic's `x-api-key` + a pinned `anthropic-version`
/// (never send none).
nonisolated enum AuthMode: Sendable {
/// `Authorization: Bearer <key>`.
case bearer
/// `x-api-key: <key>` plus the pinned version header.
case headerKey(version: String)
}
var authMode: AuthMode {
switch self {
case .zai, .openaiAPI, .nous: .bearer
case .anthropic: .headerKey(version: "2023-06-01")
}
}
/// #175: keyless providers run on the shared Hermes Portal login —
/// the engine's own credential stands in when no API key is pasted
/// (API key and subscription bill the same account credits).
var keyless: Bool {
self == .nous
}
/// The endpoint with any trailing slash trimmed — the ONE
/// normalization every endpoint consumer (the probe's URL builders,
/// the credential rail's official-endpoint gate) compares against;
/// divergent trims would gate or route differently in silence.
nonisolated static func trimmedEndpoint(_ endpoint: String) -> String {
endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
}
}
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
@@ -241,44 +169,6 @@ nonisolated enum PortalAuth {
}
}
/// #181: THE credential resolution — the provider's own API key, else the
/// shared Portal session key for keyless providers. Settings' Test
/// Connection and pass readiness both call this ONE function, so the
/// fallback can no longer drift between them. The implicit session
/// credential only ever rides the OFFICIAL endpoint (#175 finish-audit:
/// cleartext http / foreign host = silent exfiltration with no on-screen
/// cue) — a keyless provider on any other endpoint refuses with the
/// paste-a-key path. Nonisolated async, so the auth-store read never runs
/// on the main actor.
nonisolated enum ProviderCredential {
enum Resolved: Equatable {
case key(String)
case refused(String)
}
static func resolve(
provider: ModelProvider,
envKey: String,
endpoint: String,
portalAuthPath: String,
) async -> Resolved {
if !envKey.isEmpty {
return .key(envKey)
}
guard provider.keyless else {
return .refused("no API key set — paste the key first")
}
let trimmed = ModelProvider.trimmedEndpoint(endpoint)
guard trimmed == provider.defaultEndpoint else {
return .refused("custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)")
}
guard let sessionKey = PortalAuth.sessionKey(authJSONPath: portalAuthPath) else {
return .refused("no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`")
}
return .key(sessionKey)
}
}
/// The Settings page's state (#135): per-surface model configs, per-provider
/// keys, the registry the model combobox reads, and the write path every
/// committed change flows through. #136: hydrated from the profiles at pane
@@ -477,30 +367,46 @@ final class SettingsModel {
/// One probe per provider over the CURRENT key/endpoint state. Guarded
/// against stacking; the empty-key precondition makes an unkeyed probe
/// fail fast without touching the network. #181: the credential —
/// provider key, else the shared Portal session key for keyless
/// providers — resolves through the ONE rail pass readiness also calls.
/// fail fast without touching the network. #175: an unkeyed NOUS probe
/// falls back to the shared Portal session key — the engine's own
/// credential — and names the login path when neither exists.
func testConnection(for provider: ModelProvider) async {
guard testStates[provider] != .running else { return }
testStates[provider] = .running
let keyConfig = keyConfig(for: provider)
switch await ProviderCredential.resolve(
provider: provider,
envKey: keyConfig.apiKey,
endpoint: keyConfig.endpoint,
portalAuthPath: portalAuthPath,
) {
case let .key(key):
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig.endpoint,
apiKey: key,
model: probeModel(for: provider),
)
testStates[provider] = await .done(ProviderProbe.probe(config, transport: probeTransport))
case let .refused(message):
testStates[provider] = .done(.authFailed(message))
var key = keyConfig(for: provider).apiKey
if provider == .nous, key.isEmpty {
// Finish-audit #175: the session agent_key is an IMPLICIT
// credential (never pasted, field reads empty) — it only ever
// rides the official https endpoint, never a hand-edited one
// (cleartext http / foreign host = silent exfiltration with no
// on-screen cue). Custom endpoints get the paste-a-key refusal.
let endpoint = keyConfig(for: .nous).endpoint
let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
guard trimmed == ModelProvider.nous.defaultEndpoint else {
testStates[provider] = .done(.authFailed(
"custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)",
))
return
}
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
if key.isEmpty {
testStates[provider] = .done(.authFailed(
"no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`",
))
return
}
}
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig(for: provider).endpoint,
apiKey: key,
model: probeModel(for: provider),
)
let transport = probeTransport
testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport))
}
/// The model the probe proves generation on: the first surface on this
+1 -2
View File
@@ -251,11 +251,10 @@ private struct ProviderKeyBlock: View {
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
if provider.keyless {
if provider == .nous {
// #175: the engine auths nous through hermes' own Portal
// login (device-code, shared across profiles) — the key
// field is optional and bills the same account credits.
// #181: keyed off the descriptor, like every provider fact.
Text(
"Chats ride your Hermes Portal login — no key needed once hermes is signed in (hermes auth add nous). "
+ "A pasted key bills the same account credits (API or subscription).",
-96
View File
@@ -1,96 +0,0 @@
//
// WorkspaceChrome.swift
// Museion
//
// #193: the shared workspace chrome, moved from WorkspaceView.swift
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
// PaneHeader; every pane reuses them, code unchanged.
//
import SwiftUI
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
/// reservation keeps layout constant.
struct SelectedRowStrip: View {
var body: some View {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 6)
}
}
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
/// Choose…). 36pt tall by default — a real hit target, not a text-size
/// pill; pass a smaller `minHeight` where the row is compact.
struct BorderedSecondaryButtonStyle: ButtonStyle {
var minHeight: CGFloat = 36
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.foreground)
.padding(.horizontal, 12)
.frame(minHeight: minHeight)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border),
),
)
.opacity(configuration.isPressed ? 0.7 : 1)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<Trailing: View>: View {
let title: String
/// Leading inset of the title row. Export default 14; the Learnings pane
/// passes 26 so its title shares one leading edge with headings + rows.
var titleInset: CGFloat = 14
/// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom
/// hairline is bounded to the same column the pane's content sits in
/// (Archive/Learnings' 720pt reading column) — title, hairline, and
/// content read as one framed block instead of a full-width rule over
/// a bounded column. nil = full width (every other pane's default).
var hairlineMaxWidth: CGFloat?
@ViewBuilder var trailing: () -> Trailing
init(
title: String,
titleInset: CGFloat = 14,
hairlineMaxWidth: CGFloat? = nil,
@ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() },
) {
self.title = title
self.titleInset = titleInset
self.hairlineMaxWidth = hairlineMaxWidth
self.trailing = trailing
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text(title)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer()
trailing()
}
.padding(.horizontal, titleInset)
.frame(minHeight: 52)
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
// r8: the bound shares the content column's leading edge
// (x0) and width — leading-aligned, never centered.
.frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading)
}
}
}
+435 -50
View File
@@ -7,12 +7,8 @@
// rail 56 | library 232 | editor min 420 | mentor 356.
// #108: the Archive rail destination (box icon, above Settings) + the
// New Project ask both live here.
// #193: the split-out files — ArchivePaneView.swift, the house ask
// sheets WorkspaceViewSheets.swift, the shared chrome
// WorkspaceChrome.swift; RailButton stays (the rail is its only caller).
//
import AppKit
import SwiftUI
/// The post-gate main surface. Posts shows the full four-column workspace;
@@ -121,14 +117,14 @@ struct WorkspaceView: View {
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin)
gate.posts.importFiles(origin: origin, home: gate.museionHome)
}
}
// #108: File ▸ New Project… ask — commands can't present sheets, so
// the model stages and this window presents (OriginAsk pattern).
.sheet(isPresented: newProjectAskBinding) {
NewProjectSheet { name in
if let reason = gate.posts.createProject(named: name) {
if let reason = gate.posts.createProject(named: name, home: gate.museionHome) {
return reason
}
gate.posts.newProjectPending(named: name)
@@ -141,9 +137,9 @@ struct WorkspaceView: View {
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse()
gate.posts.openGuardedOutlineInProse(home: gate.museionHome)
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline()
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
}
}
// #114 (S4): the Convert to Post ask — which body the outline
@@ -151,17 +147,10 @@ struct WorkspaceView: View {
// is the default: lossless. Esc/Cancel converts nothing.
.sheet(isPresented: convertAskBinding) {
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
gate.posts.convertToPost(headingsLadder: headingsLadder)
gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome)
}
}
}
// #179 follow-up: the model bind rides the ROOT task — the Archive
// pane and every root sheet (import / new project / convert) call
// library verbs from any pane; a pane-local bind left `watchedHome`
// stale after a Home repoint until Posts remounted.
.task(id: gate.museionHome) {
gate.posts.bind(home: gate.museionHome)
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #151: every failure arrival auto-expands the card — a fresh
@@ -249,37 +238,6 @@ struct WorkspaceView: View {
)
}
/// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a
/// document departure. The binding's setter IS the gate —
/// `repointMuseionHome` runs the departure gate first and commits the
/// preference (and its persistence) only when every open document
/// landed; the root `.task(id: museionHome)` binds the model after that
/// commit. A refusal keeps Home A and every buffer, and speaks the #198
/// reason the way #200's quit refusal does — the Posts strip that shows
/// `lastError` is not in sight from Settings.
private var homeRepointBinding: Binding<URL> {
Binding(
get: { gate.museionHome },
set: { newHome in
guard gate.repointMuseionHome(to: newHome) else {
presentRepointRefusal()
return
}
},
)
}
/// Hosted tests never present (the quit refusal's guard convention).
private func presentRepointRefusal() {
guard !AppGateState.hostedTestRun else { return }
let alert = NSAlert()
alert.messageText = "Home not changed — a piece needs you first"
alert.informativeText = gate.posts.lastError
?? "An open piece could not be saved. Tend to it, then choose the folder again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
/// #151: the pill/card state — the gate's phase machine plus the
/// provisioning failure verdict.
private var statusVisibility: EngineStatusSurface.Visibility {
@@ -291,6 +249,7 @@ struct WorkspaceView: View {
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate
switch selection {
case .posts:
// #14: mentor column hands in the app-scoped model + gate's winner.
@@ -327,16 +286,15 @@ struct WorkspaceView: View {
case .archive:
// #108: list-only pane — clicking a row selects the piece and
// hops to Posts where its editor lives.
ArchivePaneView(model: gate.posts) {
ArchivePaneView(home: gate.museionHome, model: gate.posts) {
selection = .posts
}
case .settings:
// #137 (S4): a committed Chat model change restarts the resident
// chat engine in place (slice A's engine-side API; deferred to
// turn end while streaming).
// brief-28: the Home control binds through the repoint gate.
SettingsPaneView(
home: homeRepointBinding,
home: $gate.museionHome,
binaryPath: gate.gateModel.currentBinaryPath,
onChatSurfaceWrite: { gate.mentor.requestRestart() },
)
@@ -390,6 +348,347 @@ struct WorkspaceView: View {
}
}
/// #108: the Archive pane — archive/ as a rail destination (prototype
/// verdict: a destination, not a library disclosure). List-only: clicking a
/// piece selects it and hops to Posts, where the editor column lives.
private struct ArchivePaneView: View {
let home: URL
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
let onOpenPiece: () -> Void
@State private var renamingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted
/// (mirrors the library column).
@State private var collapsed: Set<String> = []
private var archivedByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
}
/// #108: the prototype's toggle — click the project name (or chevron).
private func toggle(_ project: String) {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
var body: some View {
VStack(spacing: 0) {
// No New button — things arrive here by being moved, not created.
// r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME
// fixed 720pt column the rows live in — one framed block.
PaneHeader(title: "Archive", hairlineMaxWidth: 720)
if archivedByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order, matching the library's sort.
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = archivedByProject[project] ?? []
// Same section-head shape as the library (#108
// variant B), plus the project-level way out.
// r7 (mercury#55, argon#41 — FINAL, supersedes the
// r6 D24 ladder): the content column is a FIXED
// 720pt frame (width, not maxWidth — the r6
// content-hugging bound let the pill define the
// right edge), left-anchored. TWO axes only, the
// library's r7 ladder: the head row leads at x14
// (chevron in a 14pt slot) with its label at x28 —
// the ONE indent, shared with the entry rows'
// inner text via the shared LibraryPostRow (cards
// lead at x14); the 'Unarchive Group' pill rides
// the header row's trailing edge INSIDE the frame
// (14 → 706), and the row hairlines are bounded by
// the same frame. Nothing spans past it.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
.onTapGesture {
withAnimation { toggle(project) }
}
.accessibilityLabel("Toggle \(project)")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
Text(project)
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.kerning(0.6)
.textCase(.uppercase) // #108: display-only — the folder name keeps its case
.foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final
.lineLimit(1)
.truncationMode(.tail)
.onTapGesture {
withAnimation { toggle(project) }
}
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.padding(.leading, 8)
Spacer(minLength: 8)
// The 'New Post · Fork · Compact' language — a
// bordered mono-11 secondary pill at the
// trailing edge INSIDE the fixed 720pt frame.
// r7 (mercury#55, argon#41): relabeled
// 'Unarchive Group' — it moves the whole
// project, not one piece.
Button("Unarchive Group") {
model.unarchiveProject(project, home: home)
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
.help("Move the whole project back to projects/")
.accessibilityLabel("Unarchive \(project)")
}
.padding(.top, 12)
.padding(.horizontal, 14)
.padding(.bottom, 2)
if !collapsed.contains(project) {
ForEach(pieces) { post in
// r7: the shared LibraryPostRow ladder —
// card leads at x14 (PRIMARY), title text
// at x28 (the one indent). The hairline is
// BOUNDED to the fixed frame: x14 → 706.
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
onOpenPiece()
}
.overlay(alignment: .bottom) {
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
.padding(.horizontal, 14)
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post, home: home)
}
Button("Rename…") { renamingPost = post }
// #114 (S4): works archived too — the piece
// stays where it is, only type + body flip.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
}
}
}
}
}
// r7 (mercury#55, argon#41): the FIXED 720pt reading
// column — width, not maxWidth (the r6 content-hugging
// bound let the pill define the right edge); rows,
// hairlines, and the pill all live inside it.
// ponytail: fixed width clips on panes narrower than
// 720 — a width-floored variant if a small-window
// Archive ever matters.
.frame(width: 720, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 12)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
}
}
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("Nothing archived")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
private struct OriginAskSheet: View {
let count: Int
let answer: (Post.Origin) -> Void
@Environment(\.dismiss) private var dismiss
@State private var origin: Post.Origin = .writer
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Who wrote this?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(count == 1
? "Importing 1 file as a Post — the original is untouched."
: "Importing \(count) files as Posts — the originals are untouched.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Origin", selection: $origin) {
Text("I wrote it (writer)").tag(Post.Origin.writer)
Text("AI-assisted (ai)").tag(Post.Origin.ai)
}
.pickerStyle(.radioGroup)
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
.font(.caption)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Import") {
answer(origin)
dismiss()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 380)
}
}
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
/// lines the outliner can't show — opening it as an outline would drop
/// them on the next save. Prose = nothing drops; Outline = the explicit
/// choice the ruling requires.
private struct OutlineGuardSheet: View {
let openInProse: () -> Void
let openAsOutline: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelOutlineGuard) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Open as Outline") {
openAsOutline()
}
Button("Open in Prose") {
openInProse()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 420)
}
}
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
/// to headings. On mixed content the ladder would drop prose lines —
/// the sheet says so.
private struct ConvertSheet: View {
let lossy: Bool
/// false = verbatim bullets, true = headings ladder — one decision,
/// one model call.
let convert: (Bool) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Convert to Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if lossy {
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelConversion) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Headings") {
convert(true)
}
Button("Verbatim Bullets") {
convert(false)
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 440)
}
}
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
/// future materialize path). Create runs through the model's raw op; the
/// thrown reason is shown inline and the sheet stays up.
private struct NewProjectSheet: View {
/// Create + open a draft in it; nil = success, a string = the failure
/// reason to show inline (keeps the sheet up).
let create: (String) -> String?
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var failure: String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("New Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Pieces land here when it's selected.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
if let failure {
Text(failure)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
}
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
if let reason = create(trimmed) {
failure = reason
} else {
dismiss()
}
}
}
/// Rail button: 44×44 muted icon, hover wash, the current pane raised as
/// a tile. NO visible edge bar — ui-polish r2 re-ruling: the export's
/// `::before` selection bar paints behind the app border in the export's
@@ -456,3 +755,89 @@ private struct RailButton: View {
.accessibilityLabel(label)
}
}
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
/// reservation keeps layout constant.
struct SelectedRowStrip: View {
var body: some View {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 6)
}
}
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
/// Choose…). 36pt tall by default — a real hit target, not a text-size
/// pill; pass a smaller `minHeight` where the row is compact.
struct BorderedSecondaryButtonStyle: ButtonStyle {
var minHeight: CGFloat = 36
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.foreground)
.padding(.horizontal, 12)
.frame(minHeight: minHeight)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border),
),
)
.opacity(configuration.isPressed ? 0.7 : 1)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<Trailing: View>: View {
let title: String
/// Leading inset of the title row. Export default 14; the Learnings pane
/// passes 26 so its title shares one leading edge with headings + rows.
var titleInset: CGFloat = 14
/// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom
/// hairline is bounded to the same column the pane's content sits in
/// (Archive/Learnings' 720pt reading column) — title, hairline, and
/// content read as one framed block instead of a full-width rule over
/// a bounded column. nil = full width (every other pane's default).
var hairlineMaxWidth: CGFloat?
@ViewBuilder var trailing: () -> Trailing
init(
title: String,
titleInset: CGFloat = 14,
hairlineMaxWidth: CGFloat? = nil,
@ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() },
) {
self.title = title
self.titleInset = titleInset
self.hairlineMaxWidth = hairlineMaxWidth
self.trailing = trailing
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text(title)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer()
trailing()
}
.padding(.horizontal, titleInset)
.frame(minHeight: 52)
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
// r8: the bound shares the content column's leading edge
// (x0) and width — leading-aligned, never centered.
.frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading)
}
}
}
-189
View File
@@ -1,189 +0,0 @@
//
// WorkspaceViewSheets.swift
// Museion
//
// #193: the house ask sheets, moved from WorkspaceView.swift
// (file-length ceiling) — OriginAskSheet (#94), OutlineGuardSheet
// (#111), ConvertSheet (#114), NewProjectSheet (#108) — code
// unchanged (private → internal: WorkspaceView presents them
// cross-file now).
//
import SwiftUI
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
struct OriginAskSheet: View {
let count: Int
let answer: (Post.Origin) -> Void
@Environment(\.dismiss) private var dismiss
@State private var origin: Post.Origin = .writer
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Who wrote this?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(count == 1
? "Importing 1 file as a Post — the original is untouched."
: "Importing \(count) files as Posts — the originals are untouched.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Origin", selection: $origin) {
Text("I wrote it (writer)").tag(Post.Origin.writer)
Text("AI-assisted (ai)").tag(Post.Origin.ai)
}
.pickerStyle(.radioGroup)
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
.font(.caption)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Import") {
answer(origin)
dismiss()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 380)
}
}
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
/// lines the outliner can't show — opening it as an outline would drop
/// them on the next save. Prose = nothing drops; Outline = the explicit
/// choice the ruling requires.
struct OutlineGuardSheet: View {
let openInProse: () -> Void
let openAsOutline: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(
"This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline " +
"drops them on the next save. Prose mode shows everything.",
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelOutlineGuard) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Open as Outline") {
openAsOutline()
}
Button("Open in Prose") {
openInProse()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 420)
}
}
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
/// to headings. On mixed content the ladder would drop prose lines —
/// the sheet says so.
struct ConvertSheet: View {
let lossy: Bool
/// false = verbatim bullets, true = headings ladder — one decision,
/// one model call.
let convert: (Bool) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Convert to Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if lossy {
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelConversion) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Headings") {
convert(true)
}
Button("Verbatim Bullets") {
convert(false)
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 440)
}
}
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
/// future materialize path). Create runs through the model's raw op; the
/// thrown reason is shown inline and the sheet stays up.
struct NewProjectSheet: View {
/// Create + open a draft in it; nil = success, a string = the failure
/// reason to show inline (keeps the sheet up).
let create: (String) -> String?
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var failure: String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("New Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Pieces land here when it's selected.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
if let failure {
Text(failure)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
}
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
if let reason = create(trimmed) {
failure = reason
} else {
dismiss()
}
}
}
+8 -19
View File
@@ -24,9 +24,9 @@ nonisolated enum WritingGoal: Equatable {
/// (typing, deleting, pasting, undo all land as whole-document
/// text), and `now` is injected, so the countdown can never be
/// paused or deferred from inside the engine. Word counting rides
/// `DraftStats.words` — the one word-count rail all text metrics
/// share, so net-words can never drift from first-draft stats
/// ("writer's" is two words there, headings are body text; frontmatter is not body
/// `DraftStats.words` — the one tokenizer all text metrics share, so
/// net-words can never drift from first-draft stats ("writer's" is
/// two words there, headings are body text; frontmatter is not body
/// text — the editor never shows it, so it never counts).
nonisolated struct WritingGoalRun: Equatable {
let goal: WritingGoal
@@ -35,9 +35,7 @@ nonisolated struct WritingGoalRun: Equatable {
let armedAt: Date
/// Whole-document word count at arm.
let baselineWords: Int
/// Whole-document word count as of the last `update(text:)` —
/// words goals only; a minutes run freezes at the arm-time
/// count (the verdict never reads it).
/// Whole-document word count as of the last `update(text:)`.
private(set) var currentWords: Int
init(goal: WritingGoal, armedAt: Date, body: String) {
@@ -48,19 +46,10 @@ nonisolated struct WritingGoalRun: Equatable {
currentWords = words
}
/// Record the live editor text — words goals only. The caller
/// passes the whole document every time; the net falls out of
/// the delta. A minutes run never re-counts: its verdict and
/// progress ride the clock alone, so the per-keystroke feed
/// does no word work at all (opt pass 2026-11-09 — the feed
/// once tokenized the whole document per keystroke for a count
/// nothing read). `countWords` is the injectable word rail —
/// the pins count rail trips through this seam (a global
/// counter would race the hosted suite's parallel DraftStats
/// calls).
mutating func update(text: String, countWords: (String) -> Int = DraftStats.words(in:)) {
guard case .words = goal else { return }
currentWords = countWords(text)
/// Record the live editor text. The caller passes the whole
/// document every time; the net falls out of the delta.
mutating func update(text: String) {
currentWords = DraftStats.words(in: text)
}
/// Net new words since arm. Deleting costs — net, not gross; a
+3 -43
View File
@@ -299,19 +299,12 @@ enum WritingLockKiosk {
return false
}
private static func shouldRefuse(_ event: NSEvent) -> Bool {
WritingLockState.active?.isLocked == true
&& refusesKey(
keyCode: event.keyCode,
characters: event.charactersIgnoringModifiers,
modifiers: event.modifierFlags,
)
}
private static func installRefusalMonitor() {
guard refusalMonitor == nil else { return }
refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
if Self.shouldRefuse(event) {
if WritingLockState.active?.isLocked == true,
Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags)
{
return nil // swallowed — the lock holds
}
return event
@@ -332,19 +325,9 @@ enum WritingLockKiosk {
/// unlocked quits proceed, a held block gets ONE modal ask — walk away
/// (the block dies quietly with the process, nothing kept — #158 settle
/// 3) or keep writing.
/// #200: quit is also a document departure — the posts gate runs FIRST
/// (never walk away from a block the quit then refuses to complete): an
/// open document that can't depart (unanswered #67 conflict, failed
/// flush) refuses termination with one spoken reason.
@MainActor
final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
// #200: the departure gate — before the lock ask, so a refusal
// never strands a walked-away block in a still-running app.
guard quitReply(posts: PostsModel.active) == .terminateNow else {
presentQuitRefusal()
return .terminateCancel
}
guard WritingLockState.active?.isLocked == true else { return .terminateNow }
let alert = NSAlert()
alert.messageText = "Walk away from the block?"
@@ -360,27 +343,4 @@ final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
}
return .terminateCancel
}
/// #200: the quit-time departure gate — the pure decision, no UI (the
/// pins' seam; the refusal alert below is hosted-guarded like the
/// kiosk). nil posts (no model alive) passes: nothing is open,
/// nothing to lose.
func quitReply(posts: PostsModel?) -> NSApplication.TerminateReply {
guard let posts else { return .terminateNow }
guard posts.documentsMayDepart() else { return .terminateCancel }
return .terminateNow
}
/// #200: the refusal speaks (#163's ruling — self-aware friction, not
/// silence): one alert naming the strip's reason. Hosted tests never
/// present (the startLaunchCheck guard convention).
private func presentQuitRefusal() {
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
let alert = NSAlert()
alert.messageText = "Quit stopped — a piece needs you first"
alert.informativeText = PostsModel.active?.lastError
?? "An open piece could not be saved. Tend to it, then quit again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
}
-17
View File
@@ -49,13 +49,6 @@ import Testing
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
/// the finish-audit interleaving pin's in-flight observable.
/// Mode `neverRead` (brief-27): execs /bin/sleep 30 without reading one
/// line — the inert non-reading child of the backpressure smokes (the
/// pipe fills, the client's writer blocks; the finding's probe shape).
/// Mode `serverPing` (brief-27): full behaviour PLUS one server→client
/// request (id 900) emitted at initialize — the client must answer -32601
/// over the wire; the fake logs our reply line to `<name>-reply-log`
/// (the reply-delivery pin).
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
@@ -76,11 +69,6 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
mode="full"
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran
if [[ "$mode" == "neverRead" ]]; then
# brief-27: /bin/sleep never reads stdin — the pipe fills and the client's writer blocks.
# exec keeps sleep the DIRECT child (close SIGTERMs it; no orphan holds the pipe open).
exec /bin/sleep 30
fi
card=$(print -- '\(fixCardB64)' | base64 -d)
research=$(print -- '\(researchB64)' | base64 -d)
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
@@ -92,12 +80,7 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
[[ -z "$line" ]] && continue
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$mode" == "serverPing" && "$rid" == "900" && -z "$method" ]]; then
print -r -- "$line" >> "${0:h}/\(name)-reply-log" # brief-27: the client's -32601 reply to our server request, on the wire
continue
fi
if [[ "$method" == "initialize" ]]; then
[[ "$mode" == "serverPing" ]] && echo '{"jsonrpc":"2.0","id":900,"method":"client/ping"}'
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then
+6 -9
View File
@@ -12,7 +12,6 @@ Owned by the root AGENTS.md contract.
- Uses Swift Testing (`@Test`, `#expect`) — not XCTest.
- Always give `@Suite` its string argument — bare `@Suite` is stripped by this repo's swiftformat.
- `@Test` names: backticked sentence style is the convention; plain lowercase-camel identifiers are the deliberate exception where name-level `-only-testing` addressability matters (#195) — `.swiftformat` sets `--test-case-name-format preserve`, so both shapes are format-clean.
- Imports `@testable import Museion`; app code is default-MainActor, so cross-actor tests need `@MainActor` or nonisolated declarations in app code.
- Deployment target and versions follow the app target; leave `CURRENT_PROJECT_VERSION = 1` here.
@@ -32,27 +31,25 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched).
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates).
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests` — scan, write side, pass substrate, stats capture, research notes.
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
- `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline.
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests`, `ProviderCredentialTests` — settings model, real CLI write path, probe decode + request builders, the #181 ONE credential resolution (pasted key wins, keyless fallback on the official endpoint, custom-endpoint and no-login refusals).
- `SettingsModelTests`, `SettingsModelWritePathTests`, `HermesSettingsWriterTests`, `ProviderProbeTests`, `ProviderProbeTransportTests` — settings model, real CLI write path, probe decode + request builders.
- `WordBoundaryTruncationTests`, `PolishSeamTests`, `ResearchCandidateTests`, `PersonaLoadOrderTests` — UI pure seams, research candidates, persona payload contract (the four-shared-sections + load-order pins).
## Verification
- `./scripts/full-test.sh start` + `status` polling is the sanctioned verify rail (#190): detached run, per-run pinned bundle, counts from `xcresulttool` only, zero-match filters FAIL (vacuous-green trap), `--serialized` rerun for parallel-load flakes, per-test timeouts naming wedged tests.
- `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -only-testing:MuseionTests test` — verify by the xcresult EXECUTED count, never the SUCCEEDED banner.
## Child DOX Index
+7 -7
View File
@@ -117,7 +117,7 @@ struct BlindReadTests {
private func openJudgedPiece(on model: PostsModel, home: URL, snapshot: String, current: String) async throws -> String {
let post = try PostStore.writeNew(body: current, home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: snapshot, home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -199,14 +199,14 @@ struct BlindReadTests {
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let run = Task { await rig.model.blindRead(mentor: rig.mentor) }
let run = Task { await rig.model.blindRead(home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningBlindRead)
// Mutual exclusion — a pass refuses while the read owns the rail.
await rig.model.runPass(.pass1, mentor: rig.mentor)
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("already running") == true)
// The pass bar's Cancel rail ends the held read — no reveal,
@@ -237,7 +237,7 @@ struct BlindReadTests {
snapshot: "MARKER-the-older-text", current: "# Judged\n\nMARKER-the-newer-text",
)
await rig.model.blindRead(mentor: rig.mentor)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
// The prompt carried BOTH bodies inline — and no path: the judge
// cannot learn which file is which (the engines' prompt log).
@@ -262,20 +262,20 @@ struct BlindReadTests {
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", home: rig.home)
rig.model.select(post.id)
rig.model.select(post.id, home: rig.home)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// No pass ever ran — refuse, spawn nothing beyond the resident engine.
await rig.model.blindRead(mentor: rig.mentor)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("run a Pass") == true)
#expect(museionSpawns(rig) == 1)
// Snapshot exists but the document is unchanged since — a vacuous
// read refuses honestly.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Fresh\n\nNo pass yet.", home: rig.home)
await rig.model.blindRead(mentor: rig.mentor)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("No edits") == true)
}
-37
View File
@@ -75,40 +75,3 @@ import Testing
#expect(abs(DraftStats.compute(body: "Dog dog DOG").typeTokenRatio - 1.0 / 3.0) < 0.001)
#expect(abs(DraftStats.compute(body: "writer's note writer").typeTokenRatio - 3.0 / 4.0) < 0.001)
}
@Test func `word rail equals the split tokenizer over a mixed corpus`() {
/// The count-only word rail (opt pass 2026-11-09) must answer exactly
/// what the lowercased-token array answered: split on
/// !(isLetter || isNumber), empty subsequences omitted. The reference
/// IS the old implementation — the corpus (mixed scripts, emoji,
/// punctuation, numbers, empties) makes any semantic drift (e.g. a
/// whitespace count) fail here.
func reference(_ text: String) -> Int {
text.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).count
}
let corpus = [
"",
" \t\n ",
"\n\n\n",
"— — !!!",
"one two three",
"writer's note",
"## Chapter Two — draft 3",
"abc123def",
"3.14 and 2,718,281",
"$5,000 USD",
"naïve café Zürich",
"Привет мир",
"日本語のテキストです",
"مرحبا بالعالم",
"emoji 👨‍👩‍👧‍👦 are not words",
"word—word, word; word: word",
"One two three. Four five! Six?",
]
for text in corpus {
#expect(
DraftStats.words(in: text) == reference(text),
"corpus mismatch for \(text.debugDescription)",
)
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ private func makeSessionHome() -> URL {
private func seedPost(_ home: URL, id: String, body: String) {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try? PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: .writer)
try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer)
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
+8 -8
View File
@@ -51,7 +51,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
let chatBefore = rig.mentor.host.chat
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home)
rig.model.select(post.id)
rig.model.select(post.id, home: rig.home)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -59,7 +59,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// In a Task — a full-mode scripted pass can complete inside one poll
// sleep (no child-process latency anymore), so the pass ENGINE is
// captured after the run from the spawn records, not polled mid-flight.
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
_ = await run.value
let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" }
let passEngineClosed = try #require(passEngine, "pass engine never spawned")
@@ -104,9 +104,9 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Held Pass\n\nCancel me.", home: rig.home)
rig.model.select(post.id)
rig.model.select(post.id, home: rig.home)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
let heldEngine = try #require(await pollOneShot(of: rig.mentor), "pass engine never spawned")
#expect(rig.mentor.isPassEngineRunning)
@@ -291,7 +291,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
rig.mentor.passReadinessWriter = writer
await rig.mentor.refreshPassReadiness()
let post = try PostStore.writeNew(body: "# No Key\n\nPass me.", home: rig.home)
rig.model.select(post.id)
rig.model.select(post.id, home: rig.home)
for _ in 0 ..< 250 where rig.model.session?.postID != post.id {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -299,7 +299,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// this pin vacuously.
try #require(rig.model.session?.postID == post.id)
await rig.model.runPass(.pass1, mentor: rig.mentor)
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError == "Pass 1 needs a z.ai API key — add it in Settings → Provider Keys.")
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
@@ -320,7 +320,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
_ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active
let target = try #require(rig.mentor.roster.last) // sess-1, NOT active
let post = try PostStore.writeNew(body: "# Held Load\n\nResume races a pass.", home: rig.home)
rig.model.select(post.id)
rig.model.select(post.id, home: rig.home)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -338,7 +338,7 @@ private func pollOneShot(of mentor: MentorSessionModel) async throws -> Scripted
// pass prompt then HOLDS, so isStreaming is guaranteed when the parked
// load completes, and the #124 Cancel rail frees it afterwards.
rig.engines.mode = "hangOnPrompt"
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
try await Task.sleep(nanoseconds: 20_000_000)
}
+2 -174
View File
@@ -9,11 +9,6 @@
// Then exactly one real-process end-to-end smoke per surface (chat on museion,
// pass1, pass2) drives the real ACPEngineClient + the zsh fake — the only
// child-spawning tests left in the suite.
// brief-27 (acp-backpressure): plus the blocked-writer regression rig — a
// never-reading /bin/sleep child (the finding probe's shape) pins that a full
// stdin pipe cannot defeat the request deadline, Stop delivery, or a bounded
// reaping close; a serverPing fake pins the healthy contract (round trip,
// -32601 reply delivery, idempotent clean close).
//
import Foundation
@@ -179,7 +174,7 @@ struct EngineSmokeTests {
await mentor.openSession() // the resident chat engine
let chatPid = try #require(mentor.childProcessIdentifier)
let post = try PostStore.writeNew(body: "# Smoke Pass\n\nVerdict me.", home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -187,7 +182,7 @@ struct EngineSmokeTests {
// In a Task — the pass child's pid is only observable while it runs
// (the old EngineLifecycleTests poll; the zsh wire latency holds the
// turn open long enough to catch it).
let run = Task { await model.runPass(kind, mentor: mentor) }
let run = Task { await model.runPass(kind, home: home, mentor: mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
@@ -219,171 +214,4 @@ struct EngineSmokeTests {
#expect(kill(chatPid, 0) == 0)
#expect(mentor.phase.isReady)
}
// MARK: - brief-27 backpressure smokes (blocked-writer regression rig)
/// brief-27: await an operation that may HANG on the unfixed transport
/// (the RED shape) and report what it answered — nil when the window leg
/// won. One deadline per call (the house rule). The bound is `window`
/// only in the green world: withTaskGroup awaits stragglers at scope
/// exit and `await task.value` is cancellation-blind, so a HUNG task
/// holds this helper until IT settles — the real RED-world watchdog is
/// the fake's `exec /bin/sleep 30` exit (~30 s, inside the rail's 60 s
/// per-test timeout). Keep the fake's sleep short.
@MainActor
private func awaitBounded<T: Sendable>(_ task: Task<T, Never>, window: TimeInterval) async -> T? {
await withTaskGroup(of: T?.self) { group in
group.addTask { await task.value }
group.addTask {
try? await Task.sleep(nanoseconds: UInt64(window * 1_000_000_000))
return nil
}
let first = await group.next() ?? nil
group.cancelAll()
return first
}
}
/// brief-27: run one request on a task and string-encode its outcome
/// ("returned" or the error) — the observable the pins match on.
@MainActor
private func requestOutcome(
_ client: ACPEngineClient, method: String, params: JSONValue?, timeout: TimeInterval,
) -> Task<String, Never> {
Task<String, Never> {
do {
_ = try await client.request(method, params: params, timeout: timeout)
return "returned"
} catch {
return String(describing: error)
}
}
}
/// brief-27: the blocked-writer rig — a real ACPEngineClient over the
/// zsh fake in `neverRead` mode, which execs /bin/sleep without ever
/// reading stdin (the finding's inert non-reading child; no real
/// profile is anywhere near it). The oversized prompt fills the 64 KB
/// pipe and wedges the writer.
@MainActor
private func makeBlockedWriterRig(label: String) throws -> (client: ACPEngineClient, pid: pid_t) {
let dir = acpTempDir(label)
let fake = makeFakeACP(at: dir, mode: "neverRead")
let client = ACPEngineClient(binaryPath: fake)
client.onMessage = { _, _ in }
try client.start()
return (client, client.childProcessIdentifier)
}
/// The pipe-filling payload: a 2,000,000-char prompt (the probe's size;
/// the pipe holds 64 KB).
private var blockedWriterPayload: JSONValue {
.object(["prompt": .string(String(repeating: "x", count: 2_000_000))])
}
/// brief-27 regression 1: the request deadline FIRES while the stdin
/// write is blocked. On the unfixed transport the deadline sits on the
/// same serial queue as the blocked send and never runs — the request
/// stays pending forever (the finding's executed probe).
@MainActor
@Test func `request deadline fires while the stdin write is blocked`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-deadline")
defer {
kill(pid, SIGKILL) // settle the blocked pipe FIRST — close's boundedness is the next smoke's pin, not this one's
client.close()
}
let outcome = requestOutcome(client, method: "session/prompt", params: blockedWriterPayload, timeout: 0.5)
let result = await awaitBounded(outcome, window: 5)
#expect(
result?.contains("timed out") == true,
"deadline did not fire while the write was blocked: \(result ?? "still blocked after 5 s")",
)
}
/// brief-27 regression 2: Stop/cancellation stays deliverable while the
/// write is blocked. The bytes cannot reach a non-reading child (the
/// pipe is full — physics), so deliverable means the seam ACCEPTS the
/// notification and lifecycle bookkeeping still answers: session/cancel
/// is taken (a blocking notify would never let this test reach its
/// assertion), and a follow-up request gets registered and reaches its
/// OWN deadline. On the unfixed transport the follow-up's registration
/// queues behind the stuck writer and never runs.
@MainActor
@Test func `stop notification and bookkeeping answer while the stdin write is blocked`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-stop")
defer {
kill(pid, SIGKILL)
client.close()
}
// Wedge the writer: the oversized prompt fills the pipe (outcome unobserved).
Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) }
// Let the oversized write reach the pipe and wedge the writer first.
try await Task.sleep(nanoseconds: 200_000_000)
client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")]))
let second = requestOutcome(
client,
method: "session/new",
params: .object(["cwd": .string("/tmp"), "mcpServers": .array([])]),
timeout: 0.5,
)
let result = await awaitBounded(second, window: 5)
#expect(
result?.contains("timed out") == true,
"bookkeeping starved behind the blocked writer: \(result ?? "no answer within 5 s")",
)
}
/// brief-27 regression 3: close RETURNS BOUNDED while the write is
/// blocked — child reaped, the SIGTERM→grace→SIGKILL escalation inside
/// close actually reachable — without waiting on the blocked writer.
/// On the unfixed transport close begins with a queue.sync behind the
/// stuck send and never returns (the probe's watchdog hang).
@MainActor
@Test func `close returns bounded while the stdin write is blocked and reaps the child`() async throws {
let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-close")
defer {
kill(pid, SIGKILL)
client.close()
}
// Wedge the writer: the oversized prompt fills the pipe (outcome unobserved).
Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) }
// The write is in the pipe and the writer wedged before close runs.
try await Task.sleep(nanoseconds: 200_000_000)
let closeTask = Task<Void, Never> { client.close() }
let finished = await awaitBounded(closeTask, window: 5)
#expect(finished != nil, "close did not return within 5 s — the blocked writer defeats teardown")
#expect(try await pollReaped(pid), "child not reaped after the bounded close")
}
/// brief-27 regression 4: the healthy-child contract is unchanged —
/// round trip (initialize → version), reply delivery (the engine's
/// server→client request answered -32601 over the wire; the fake logs
/// our reply), and a clean idempotent close that reaps the child.
@MainActor
@Test func `healthy engine round trip, server request answered, clean close`() async throws {
let dir = acpTempDir("smoke-healthy-brief27")
let fake = makeFakeACP(at: dir, mode: "serverPing")
let client = ACPEngineClient(binaryPath: fake)
client.onMessage = { _, _ in }
try client.start()
let pid = client.childProcessIdentifier
defer { client.close() }
let version = try await client.request("initialize", params: nil, timeout: 5)
#expect(version?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9")
let replyLog = (dir as NSString).appendingPathComponent("hermes-acp-reply-log")
var reply: String?
for _ in 0 ..< 250 where reply == nil {
reply = try? String(contentsOfFile: replyLog, encoding: .utf8)
if reply == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(
reply?.contains("-32601") == true,
"our -32601 reply to the server request never reached the engine: \(reply ?? "no reply logged")",
)
client.close()
client.close() // idempotent
#expect(try await pollReaped(pid))
}
}
+20 -20
View File
@@ -23,7 +23,7 @@ import Testing
/// hop-back instead of asserting synchronously (PostsModelTests convention).
/// The post-loop expect makes a silent timeout a failure, not a pass.
@MainActor
func pollUntil(_ condition: @MainActor () -> Bool) async throws {
private func pollUntil(_ condition: @MainActor () -> Bool) async throws {
for _ in 0 ..< 250 where !condition() {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -51,7 +51,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id)
model.select(post.id, home: home)
let session = try #require(model.session)
let generation = session.loadGeneration
@@ -59,7 +59,7 @@ struct FixCardApplyTests {
// buffer first (flush-first, like every op that reads the piece).
session.edit("# Carded\n\nThe anchor sentence.\nPlus a typed line.\n")
#expect(model.applyCard(written[0].card) == .applied)
#expect(model.applyCard(written[0].card, home: home) == .applied)
// Disk carries the replacement over the flushed buffer...
#expect(PostStore.readBody(id: post.id, home: home) == "# Carded\n\nThe replaced sentence.\nPlus a typed line.\n")
@@ -80,14 +80,14 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id)
model.select(post.id, home: home)
// The Post changed after the card was issued — the quote is gone.
model.session?.edit("# Carded\n\nThe sentence changed.\n")
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
#expect(model.applyCard(written[0].card) == .stale)
#expect(model.applyCard(written[0].card, home: home) == .stale)
#expect(try Data(contentsOf: postURL) == before) // nothing selected, nothing changed
let diskCard = try #require(FixCardStore.scan(pieceURL: folder).first)
@@ -104,11 +104,11 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(pattern: "Demo", fix: "The replaced sentence.", quote: "The anchor sentence.", lane: .demonstration)],
)
model.select(post.id)
model.select(post.id, home: home)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card)
let outcome = model.applyCard(written[0].card, home: home)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -127,7 +127,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id)
model.select(post.id, home: home)
// A foreign write lands on disk underneath the writer (#67) — the
// reload question is up and unanswered.
let postURL = folder.appendingPathComponent("post.md")
@@ -135,7 +135,7 @@ struct FixCardApplyTests {
model.session?.diskDidChange(diskText: "foreign text on disk")
let before = try Data(contentsOf: postURL)
let outcome = model.applyCard(written[0].card)
let outcome = model.applyCard(written[0].card, home: home)
guard case let .refused(why) = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -157,15 +157,15 @@ struct FixCardApplyTests {
card(pattern: "Telling", quote: "The anchor sentence."),
],
)
model.select(post.id)
model.select(post.id, home: home)
let postURL = folder.appendingPathComponent("post.md")
let before = try Data(contentsOf: postURL)
model.skipCard(written[0].card)
model.skipCard(written[0].card, home: home)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.status == .skipped }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[0].card.id })?.status == .skipped)
model.doneCard(written[1].card)
model.doneCard(written[1].card, home: home)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[1].card.id })?.status == .done }
#expect(try FixCardStore.scan(pieceURL: folder).first(where: { $0.id == written[1].card.id })?.status == .done)
@@ -241,7 +241,7 @@ struct FixCardApplyTests {
piecePath: folder.path,
cards: [card(fix: "The replaced sentence.", quote: "The anchor sentence.")],
)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Carded\n\nThe sentence changed.\n") // stale the anchor
model.session?.flush()
let postURL = folder.appendingPathComponent("post.md")
@@ -252,7 +252,7 @@ struct FixCardApplyTests {
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: cardsDir.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cardsDir.path) }
#expect(model.applyCard(written[0].card) == .stale) // the primary contract holds…
#expect(model.applyCard(written[0].card, home: home) == .stale) // the primary contract holds…
#expect(model.lastError?.contains("card close failed") == true) // …and the flag failure is loud
#expect(try Data(contentsOf: postURL) == before) // still nothing selected or changed
}
@@ -270,12 +270,12 @@ struct FixCardApplyTests {
)
try FileManager.default.removeItem(at: folder.appendingPathComponent("post.md")) // the read will fail
model.select(post.id)
model.select(post.id, home: home)
#expect(model.session?.loadFailed == true)
// The writer typed the anchor into the empty failed-session buffer.
model.session?.edit("The anchor sentence. typed nowhere durable.")
let outcome = model.applyCard(written[0].card)
let outcome = model.applyCard(written[0].card, home: home)
guard case .refused = outcome else {
Issue.record("expected refusal, got \(outcome)")
return
@@ -295,9 +295,9 @@ struct FixCardApplyTests {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
model.select(post.id)
model.select(post.id, home: home)
#expect(model.promoteCard(written[0].card) == .promoted)
#expect(model.promoteCard(written[0].card, home: home) == .promoted)
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
@@ -306,7 +306,7 @@ struct FixCardApplyTests {
// Already promoted → refused, no second file (one confirm = one entry).
let scanned = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(model.promoteCard(scanned) == .refused("card already promoted"))
#expect(model.promoteCard(scanned, home: home) == .refused("card already promoted"))
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
}
@@ -316,7 +316,7 @@ struct FixCardApplyTests {
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
#expect(model.promoteCard(written[0].card) == .refused("open the piece to work its cards"))
#expect(model.promoteCard(written[0].card, home: home) == .refused("open the piece to work its cards"))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path))
#expect(model.lastError == nil)
}
-139
View File
@@ -1,139 +0,0 @@
//
// HermesConfigRailTests.swift
// MuseionTests
//
// #182 — the config-set CLI contract's ONE pinning suite, over the shared
// fake-hermes double (makeFakeHermes, ProfileProvisionerTests.swift). The
// callers' suites pin only their own key lists.
//
// Scenario: The config-set wire is owned once — From user story #182
// Given the provisioner and the settings writer both write config keys
// through `hermes -p <profile> config set`
// When either hands the rail its key list
// Then every write rides the exact argv (with --force where asked), is
// verified against the `✓ Set` line (not exit code alone), executes
// provider-first (switching providers clears stale inherited values),
// and a failed write surfaces key + profile + CLI excerpt.
//
import Foundation
@testable import Museion
import Testing
@Suite("HermesConfigRailTests")
struct HermesConfigRailTests {
@Test func `set argv rides the exact wire with force`() throws {
let binDir = provTempDir("rail")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply(
[
.set(key: "model.provider", value: "anthropic", force: false),
.set(key: "model.extra_body.max_tokens", value: "24000", force: true),
],
profile: "museion-pass1",
binary: binary,
timeout: 5,
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider anthropic",
"-p museion-pass1 config set model.extra_body.max_tokens 24000 --force",
])
}
@Test func `provider goes first whatever the caller s list order`() throws {
// model.provider clears a stale inherited base_url — the rail owns
// the rule; a caller can't order it wrong. Relative order holds.
let binDir = provTempDir("rail-order")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply(
[
.set(key: "model.base_url", value: "https://x", force: false),
.unset(key: "model.reasoning_effort"),
.set(key: "model.default", value: "m", force: false),
.set(key: "model.provider", value: "zai", force: false),
],
profile: "museion",
binary: binary,
timeout: 5,
)
#expect(fakeHermesLog(binDir, "config-set-museion") == [
"-p museion config set model.provider zai",
"-p museion config set model.base_url https://x",
"-p museion config set model.default m",
])
#expect(fakeHermesLog(binDir, "config-unset-museion") == [
"-p museion config unset model.reasoning_effort",
])
}
@Test func `unset of an absent key is idempotent success`() throws {
let binDir = provTempDir("rail-unset")
let binary = makeFakeHermes(at: binDir, mode: "ok")
try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5)
}
@Test func `a failed set throws naming key and profile with the cli excerpt`() {
let binDir = provTempDir("rail-fail")
try? "".write(toFile: binDir + "/config-set-fails", atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply(
[.set(key: "model.default", value: "m", force: false)],
profile: "museion-pass2",
binary: binary,
timeout: 5,
)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.key == "model.default")
#expect(failure?.profile == "museion-pass2")
#expect(failure?.excerpt == "Error: config set exploded")
#expect(failure?.errorDescription == "couldn't set model.default on museion-pass2: Error: config set exploded")
}
}
@Test func `a failed unset throws the structured failure`() {
// The fourth branch: neither ✓ Unset nor the not-set line.
let binDir = provTempDir("rail-unset-fail")
try? "".write(toFile: binDir + "/config-unset-fails", atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply([.unset(key: "model.reasoning_effort")], profile: "museion", binary: binary, timeout: 5)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.verb == "unset")
#expect(failure?.key == "model.reasoning_effort")
#expect(failure?.excerpt == "Error: config unset exploded")
}
}
@Test func `a value that looks like an option is refused before any spawn`() {
// Free-text fields (model IDs, endpoints) feed the rail; a leading
// `-` is an option to the child CLI, never a value.
let binDir = provTempDir("rail-dash")
let binary = makeFakeHermes(at: binDir, mode: "ok")
do {
try HermesConfigRail.apply(
[.set(key: "model.default", value: "--force", force: false)],
profile: "museion",
binary: binary,
timeout: 5,
)
Issue.record("expected a throw")
} catch {
let failure = error as? HermesConfigRail.Failure
#expect(failure?.key == "model.default")
#expect(failure?.excerpt == "value starts with '-' — not written")
}
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty) // nothing reached the CLI
}
@Test func `excerpt caps at 500 chars`() {
// The #180 deliberate divergence (writer's old 300 is gone): pinned,
// not just commented.
let output = EngineProbe.ProcessOutput(exitCode: 1, stdout: String(repeating: "x", count: 900))
#expect(HermesConfigRail.excerpt(output).count == 500)
}
}
@@ -173,30 +173,6 @@ struct HermesSettingsWriterTests {
}
}
@Test func `whitespace-only endpoint is treated as empty at both gates`() async throws {
// Learning #6's class: raw isEmpty passes whitespace through; the
// gates mirror the trimmed emptiness the model side validates.
let (binDir, writer) = makeRig()
// Surface gate: a blank endpoint never rides base_url.
try await writer.writeSurface(
.pass1,
config: SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil),
zaiEndpoint: " ",
)
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
"-p museion-pass1 config set model.provider zai",
"-p museion-pass1 config set model.default glm-5.3",
])
// Key gate: a blank zai endpoint skips the write-through (the key
// still fans out to .env).
try await writer.writeProviderKey(
provider: .zai,
config: ProviderKeyConfig(endpoint: " ", apiKey: "sk-z"),
profiles: [.chat],
)
#expect(fakeHermesLog(binDir, "config-set-museion").isEmpty)
}
@Test func `non-zai key write only touches env`() async throws {
let (binDir, writer) = makeRig()
let root = binDir + "/profiles"
-86
View File
@@ -25,16 +25,6 @@ private func writeExternal(_ name: String, _ body: String) throws -> URL {
return url
}
/// brief-32: the guest-watch pins' own temp dir — `startExternalWatch`
/// observes the file's CONTAINING folder, so their guest must live where
/// no sibling test ever writes.
private func watchedDir() throws -> URL {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-watch-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir
}
@Suite(.serialized)
@MainActor
struct ImportExternalTests {
@@ -200,80 +190,4 @@ struct ImportExternalTests {
#expect(!session.conflictAlert)
#expect(session.text == "# C\n\nForeign edit.")
}
// MARK: - The guest watch (brief-32: the #67 compare's disk read)
@Test func `external watch raises no 67 conflict on an unchanged BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("watched.md")
// Windows-authored file: BOM + CRLF. The open read normalizes
// (readDocument's external branch); the watch must read in the
// SAME representation or every directory event reads as #67.
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
#expect(session.text == "# Title\n\nBody line.\n")
// Sibling directory events re-fire the compare (the watch observes
// the containing folder): representation alone must never raise.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch still conflicts on a real write and never re-arms after yes-reload`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("foreign.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
// A REAL external modification (different content, same BOM/CRLF
// representation): the departure gate must still see it.
try "\u{FEFF}# Title\r\n\r\nRewritten underneath.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// Yes-reload takes the foreign content, normalized:
session.reloadFromDisk()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nRewritten underneath.\n")
// The next directory event reads the same unchanged bytes — the
// false conflict must not re-arm.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch never re-arms after keep-local on a BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("kept.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
try "\u{FEFF}# Title\r\n\r\nForeign body.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// No: keep local — the disk state is seen, the local buffer stays
// and stays pending.
session.keepLocal()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nBody line.\n")
#expect(session.saveState == .changed)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
}
+13 -13
View File
@@ -74,7 +74,7 @@ struct LearningDecayTests {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file, now: now)
let stampedText = try readLearning(home, file)
let frontmatter = PostFrontmatter.parse(stampedText)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismissed"] == FixCardStore.formatted(now, "yyyy-MM-dd"))
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "1")
@@ -85,7 +85,7 @@ struct LearningDecayTests {
#expect(frontmatter["promoted"] == "2026-10-21")
#expect(frontmatter["from_card"] == "6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0")
// The body is byte-identical.
#expect(PostFrontmatter.split(stampedText).body == PostFrontmatter.split(learning).body)
#expect(PostStore.splitFrontmatter(stampedText).body == PostStore.splitFrontmatter(learning).body)
// Hidden from the pass rail.
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
}
@@ -125,7 +125,7 @@ struct LearningDecayTests {
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // resurfaced
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let frontmatter = try PostFrontmatter.parse(readLearning(home, file))
let frontmatter = try Post.frontmatter(of: readLearning(home, file))
#expect(frontmatter["dismiss_count"] == "2")
#expect(frontmatter["dismissed_at_pass"] == "10") // re-anchored at the current clock
@@ -221,7 +221,7 @@ struct LearningDecayTests {
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: hugeHome, typeDir: "posts", file: "20261021-huge.md")
}
#expect(try PostFrontmatter.parse(readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
#expect(try Post.frontmatter(of: readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
}
/// Scenario: dismiss is a write-path trust boundary — traversal-shaped
@@ -251,7 +251,7 @@ struct LearningDecayTests {
// Nothing escaped the learnings tree; the real learning is untouched.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("x.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings/x.md").path))
#expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == nil)
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == nil)
}
/// Scenario: a pre-planted symlinked learnings component must not
@@ -326,7 +326,7 @@ struct LearningDecayTests {
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
}
#expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == "1")
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == "1")
// A negative hand-edited count clamps to 0 at parse → stamp writes 1.
let negHome = try toolsHome()
@@ -338,7 +338,7 @@ struct LearningDecayTests {
---
""")
try LearningDecay.dismiss(home: negHome, typeDir: "posts", file: file)
#expect(try PostFrontmatter.parse(readLearning(negHome, file))["dismiss_count"] == "1")
#expect(try Post.frontmatter(of: readLearning(negHome, file))["dismiss_count"] == "1")
}
/// Scenario: decay is defined per pass-clocked content type — a foreign
@@ -360,11 +360,11 @@ struct LearningDecayTests {
contentsOf: home.appendingPathComponent("learnings/essays/\(file)"),
encoding: .utf8,
)
#expect(PostFrontmatter.parse(text)["dismiss_count"] == nil)
#expect(Post.frontmatter(of: text)["dismiss_count"] == nil)
}
/// Scenario: a Learning with NO frontmatter (a hand-made file) still
/// dismisses — the update walk prepends a fresh block and the body
/// dismisses — stampingFrontmatter prepends a fresh block and the body
/// rides verbatim below it (#27 audit: the prepend branch pinned).
@Test func `dismiss prepends a fresh block on a frontmatter-less file`() throws {
let home = try toolsHome()
@@ -375,14 +375,14 @@ struct LearningDecayTests {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
let frontmatter = PostFrontmatter.parse(stampedText)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "0")
#expect(PostFrontmatter.split(stampedText).body == body)
#expect(PostStore.splitFrontmatter(stampedText).body == body)
}
/// Scenario: lines ABOVE the opening `---` (a hand-edit blank —
/// PostFrontmatter.parse tolerates any count) belong to neither block nor body;
/// Post.frontmatter tolerates one) belong to neither block nor body;
/// the stamp keeps them — the "every other line verbatim" contract
/// (#27 review pin).
@Test func `dismiss preserves lines above the frontmatter block`() throws {
@@ -394,7 +394,7 @@ struct LearningDecayTests {
let stampedText = try readLearning(home, file)
#expect(stampedText.hasPrefix("\n---\n")) // the leading blank survived
#expect(PostFrontmatter.parse(stampedText)["dismiss_count"] == "1")
#expect(Post.frontmatter(of: stampedText)["dismiss_count"] == "1")
#expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched
}
}
-19
View File
@@ -124,25 +124,6 @@ struct LearningsPaneTests {
#expect(LearningsIndex.scan(home: home).isEmpty)
}
/// Scenario: the skip posture Post.scan pins, on this scan — a symlinked
/// type dir must not be followed. Defended in depth: the lstat guard
/// (a symlink reports isDirectory=false) AND contentsOfDirectory's own
/// refusal of a symlinked entry — flip-verified: the pin fails only when
/// BOTH go traversal-shaped (fileExists guard + resolved-URL listing).
@Test func `a symlinked type dir never surfaces`() throws {
let home = try makeHome { home in
try writeLearning(home, "posts", "20261021-one-real-entry.md", "# real\n")
}
let learnings = home.appendingPathComponent("learnings", isDirectory: true)
try FileManager.default.createSymbolicLink(
at: learnings.appendingPathComponent("linked", isDirectory: true),
withDestinationURL: learnings.appendingPathComponent("posts", isDirectory: true),
)
let groups = LearningsIndex.scan(home: home)
#expect(groups.map(\.type) == ["posts"]) // the link's alias never groups
#expect(groups.flatMap(\.entries).count == 1) // its view of posts never doubles
}
// MARK: Decay surface (#27, S4.2)
/// Scenario: Entry carries the decay verdict — visible learnings read
-124
View File
@@ -89,127 +89,3 @@ struct LibrarySearchTests {
#expect(byBody.map(\.id) == ["b-morning-pages"])
}
}
/// #144 (mounted half): the snapshot invalidation the pure seam can't
/// see — PostsLibraryColumn keys its `.task(id:)` to query + Home +
/// `PostsModel.contentRevision` and renders a landed snapshot only
/// while it `isFresh` for the CURRENT key. The controller pins drive
/// the real rescan rail (write verbs + the rail's own rescan Task) and
/// prove archive, trash, and a same-query body edit each move the
/// revision, and an unchanged rescan over a quiesced FSEvent burst
/// keeps it — without that signal a standing snapshot outlives the
/// library it searched (archived rows linger in the results; edited
/// bodies never enter or leave them until the query changes).
@Suite("library search snapshot invalidation")
struct LibrarySearchSnapshotTests {
@Test func `a snapshot renders only under the key that computed it`() {
let swept = LibrarySearch.Snapshot(
key: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4),
results: [piece("a", title: "Quartz Harbor")],
)
#expect(swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "harbor", homePath: "/users/a/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/b/museion", revision: 4)))
#expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 5)))
}
/// The sweep a mounted column would have landed before the archive:
/// key = (query, home, revision at sweep time), results from the
/// real seam + readBody rail.
@MainActor
private func standingSweep(_ model: PostsModel, home: URL, query: String) -> LibrarySearch.Snapshot {
LibrarySearch.Snapshot(
key: LibrarySearch.SearchKey(query: query, homePath: home.path, revision: model.contentRevision),
results: LibrarySearch.results(for: query, in: model.posts.filter { !$0.isArchived }) {
PostStore.readBody(id: $0.id, home: home)
},
)
}
@Test @MainActor func `archiving a result invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.map(\.id) == [post.id]) // the sweep found it
model.archivePost(post)
try await pollUntil { model.posts.contains { $0.id == post.id && $0.isArchived } }
// Same query, same Home — the library moved under the sweep.
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `trashing a result invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.map(\.id) == [post.id])
model.trash(post)
try await pollUntil { !model.posts.contains { $0.id == post.id } }
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `a same-query body edit invalidates the standing snapshot`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Quiet Study\n\nplain body", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
let standing = standingSweep(model, home: home, query: "quartz")
#expect(standing.results.isEmpty) // nothing matches yet
// The body gains the needle with NO Post metadata change — the
// #143 equality skip's blind spot: the list itself never moves.
let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
try PostFrontmatter.stamped(
body: "# Quiet Study\n\nthe quartz lamp", passState: .firstDraft, origin: .writer, type: .post,
).write(to: file, atomically: true, encoding: .utf8)
let before = model.posts
await model.rescan()
#expect(model.posts == before) // metadata equal — the scan's skip held
let reswept = LibrarySearch.results(for: "quartz", in: model.posts.filter { !$0.isArchived }) {
PostStore.readBody(id: $0.id, home: home)
}
#expect(reswept.map(\.id) == [post.id]) // a fresh sweep WOULD find it now
#expect(!standing.isFresh(for: LibrarySearch.SearchKey(
query: "quartz",
homePath: home.path,
revision: model.contentRevision,
)))
}
@Test @MainActor func `an unchanged rescan keeps the revision`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Settled\n", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
// The FSEvent burst can still hold a sibling rescan that snapshotted
// its miss count BEFORE the landing scan stamped the shared
// PostScanCache — both count the same first read, each bumps the
// revision (#144's counter; an extra bump only over-invalidates a
// search snapshot). This pin is the SETTLED contract: wait out the
// burst (FSEvents latency is 0.5 s) before snapshotting.
var quiet = false
for _ in 0 ..< 20 where !quiet {
let seen = model.contentRevision
try await Task.sleep(nanoseconds: 500_000_000)
quiet = model.contentRevision == seen
}
#expect(quiet) // endless revision churn would never settle
let settled = model.contentRevision
await model.rescan() // nothing changed since the burst — all cache hits
#expect(model.contentRevision == settled)
}
}
+23 -23
View File
@@ -19,12 +19,12 @@ struct MicropubModelTests {
@Test @MainActor func `sendDraft flushes the open piece and sends the disk body with the title`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Flush Me\n\nOriginal.", home: home)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
)
@@ -40,10 +40,10 @@ struct MicropubModelTests {
}
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
let (model, _) = try makeModelHome()
let (model, home) = try makeModelHome()
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -54,11 +54,11 @@ struct MicropubModelTests {
}
@Test @MainActor func `sendDraft refuses an unsaved draft`() async throws {
let (model, _) = try makeModelHome()
let (model, home) = try makeModelHome()
model.newPost() // staged draft — no folder, no session
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -73,11 +73,11 @@ struct MicropubModelTests {
// All-whitespace body — no Title, no content (a heading-only
// piece DOES send: the Title line is content on Micro.blog).
let post = try PostStore.writeNew(body: " \n", home: home)
model.select(post.id)
model.select(post.id, home: home)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
guard case .refused = outcome else {
@@ -91,7 +91,7 @@ struct MicropubModelTests {
@Test @MainActor func `frontmatter category never travels`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
model.select(post.id)
model.select(post.id, home: home)
// The writer's own category frontmatter — permitted, inert.
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
let raw = try String(contentsOf: fileURL, encoding: .utf8)
@@ -100,7 +100,7 @@ struct MicropubModelTests {
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
)
@@ -113,11 +113,11 @@ struct MicropubModelTests {
@Test @MainActor func `a failed draft stamps nothing`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Fails\n\nBody.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(500, body: "{}", log: log),
)
@@ -127,15 +127,15 @@ struct MicropubModelTests {
@Test @MainActor func `re-drafting overwrites the remembered url`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
)
_ = await model.micropubSendDraft(
token: "tok",
home: home, token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
)
@@ -147,7 +147,7 @@ struct MicropubModelTests {
/// Plants a PNG beside the piece; returns the piece's post.md URL.
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id)
model.select(post.id, home: home)
let dir = try #require(PostStore.folder(of: post.id, home: home))
try FileManager.default.createDirectory(at: dir.appendingPathComponent("assets", isDirectory: true), withIntermediateDirectories: true)
try micropubPNG().write(to: dir.appendingPathComponent("assets/path.png"))
@@ -162,7 +162,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// The three hops, in order: q=config → upload → create.
@@ -197,7 +197,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -228,7 +228,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -246,7 +246,7 @@ struct MicropubModelTests {
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// config + ONE upload + create — the FILE uploads once, not once per ref.
@@ -266,7 +266,7 @@ struct MicropubModelTests {
) // path.png planted, ghost.png never
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
@@ -278,10 +278,10 @@ struct MicropubModelTests {
@Test @MainActor func `a piece without illustrations sends exactly one request`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Plain\n\nBody.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
_ = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
// The #33 path unchanged: no config round-trip, straight to the create.
#expect(log.requests.count == 1)
+33 -33
View File
@@ -42,14 +42,14 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id)
model.select(post.id, home: home)
// Wait for the bind rescan to surface the piece — the pass label reads
// the library's title for it (the PostsModelTests poll pattern).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
@@ -73,9 +73,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home)
model.select(post.id)
model.select(post.id, home: home)
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
// Pre-pass is unconditional — the snapshot landed anyway.
@@ -91,9 +91,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home)
model.select(post.id)
model.select(post.id, home: home)
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -108,9 +108,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
await mentor.openSession()
model.newPost() // draft staged — no folder exists
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
#expect(model.lastError == "Open a saved post to run a pass.")
#expect(model.lastError?.contains("post") == true)
// Nothing landed on disk — the draft never even materialized a folder.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts").path))
}
@@ -120,15 +120,15 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nMid-pass.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let first = Task { await model.runPass(.pass1, mentor: mentor) }
let first = Task { await model.runPass(.pass1, home: home, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.runningPass == .pass1)
await model.runPass(.pass1, mentor: mentor) // one pass at a time
await model.runPass(.pass1, home: home, mentor: mentor) // one pass at a time
#expect(model.lastError?.contains("already running") == true)
model.cancelPass(mentor: mentor) // the pass bar's Cancel rail
@@ -147,9 +147,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nCancel me.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let run = Task { await model.runPass(.pass1, mentor: mentor) }
let run = Task { await model.runPass(.pass1, home: home, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
@@ -177,7 +177,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Busy\n\nMentor chatting.", home: home)
model.select(post.id)
model.select(post.id, home: home)
let chat = Task { await mentor.sendPrompt("just chatting") }
for _ in 0 ..< 250 where !mentor.isStreaming {
@@ -185,7 +185,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
}
#expect(mentor.isStreaming)
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
#expect(model.lastError?.contains("mid-reply") == true)
// The guard fired before the snapshot — nothing on disk.
#expect(!FileManager.default.fileExists(
@@ -199,9 +199,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
let (model, home, mentor) = try makePassRig() // never opened — engine idle
defer { mentor.shutdown() }
let post = try PostStore.writeNew(body: "# Cold\n\nNo engine yet.", home: home)
model.select(post.id)
model.select(post.id, home: home)
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
#expect(model.lastError?.contains("isn't ready") == true)
#expect(!FileManager.default.fileExists(
@@ -214,10 +214,10 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
@@ -231,9 +231,9 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home)
model.select(post.id)
model.select(post.id, home: home)
await model.runPass(.pass2, mentor: mentor)
await model.runPass(.pass2, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -248,18 +248,18 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Stats Piece\n\nOne two three. Four five! Six?", home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Capture fired at the invocation — the five keys ride post.md…
let matter = PostFrontmatter.parse(onDisk)
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
#expect(matter["stats_type_token_ratio"] != nil)
@@ -275,15 +275,15 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancelled Stats\n\nOne two three. Four five!", home: home)
model.select(post.id)
model.select(post.id, home: home)
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Stats fire at INVOCATION, not completion — a cancelled pass has them anyway…
let matter = PostFrontmatter.parse(onDisk)
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
// …while the Pass State never advanced.
@@ -295,12 +295,12 @@ func textRows(of model: MentorSessionModel) -> [String] {
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# AI Piece\n\nMachine-born prose.", origin: .ai, home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
@@ -308,7 +308,7 @@ func textRows(of model: MentorSessionModel) -> [String] {
// The pass ran (origin alone decides, never the outcome)…
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// …but nothing was stamped — ai-origin is never stats-eligible.
let matter = PostFrontmatter.parse(onDisk)
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] == nil)
#expect(matter["stats_burstiness"] == nil)
}
@@ -326,12 +326,12 @@ struct DeslopLintWiringTests {
let body = "# Lint Piece\n\nUtilize the index — and delve twice — notably once, and again — "
+ "and again — and once more — to clear the dash budget. Utilize it twice."
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let cards = FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md"))
@@ -339,7 +339,7 @@ struct DeslopLintWiringTests {
#expect(cards.contains { $0.pattern == "utilize" && $0.lane == .mechanical })
// Stats capture fired at the same invocation — both hooks, one seam.
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
let matter = PostFrontmatter.parse(onDisk)
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
}
+2 -2
View File
@@ -18,7 +18,7 @@ struct PolishSeamTests {
/// whitespace-only buffer has none (nil); a buffer with no leading
/// blanks returns 0. The same walker styles the title line and hops
/// programmatic carets past the invisible blank fragment.
@Test func firstContentLocationSkipsLeadingBlanks() {
@Test func `firstContentLocation skips leading blanks`() {
let plain = "Title\n\nbody" as NSString
#expect(ProsePresenter.firstContentLocation(plain) == 0)
let blankLead = "\n\n \nTitle\nbody" as NSString
@@ -31,7 +31,7 @@ struct PolishSeamTests {
/// The ladder keeps the full path, then each shorter variant with one
/// more leading component kept whole; ≤2 components has nothing to
/// elide. `elide` picks the longest candidate that fits.
@Test func elidedPathTextCandidateLadderAndElision() {
@Test func `ElidedPathText candidate ladder and elision`() {
let path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion"
let ladder = ElidedPathText.candidates(path)
#expect(ladder.first == path)
-117
View File
@@ -1,117 +0,0 @@
//
// PostFrontmatterTests.swift
// MuseionTests
//
// #180: the Post frontmatter codec — one lenient read, three write
// postures (fresh / merge-import / update-keys), one known-key table.
// Pins: the foreign-keys-verbatim round trip through every posture
// (the class of bug that lost captured stats once, un-reintroducible),
// the lenient unknown-type decode, and the two named eligibility
// predicates the capture gate and the scan read-back gate share.
//
import Foundation
@testable import Museion
import Testing
// Scenario: One frontmatter codec behind every post read and write —
// from #180. Given a library whose post.md blocks were written by the
// old per-site writers, when any posture (import, save, advance,
// capture, publish-stamp) runs over a piece carrying foreign frontmatter
// keys, then the one PostFrontmatter engine keeps those keys verbatim,
// inserts owned keys in the one known order, reads unknown types
// leniently as post, and both eligibility gates agree on the same named
// predicates.
struct PostFrontmatterTests {
/// A block with foreign keys above and below our owned keys — every
/// posture must keep `foreign_key: keep-me` byte-identical.
private let withForeign = "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Body"
@Test func `fresh stamp is the 59 shape in known-key order`() {
#expect(PostFrontmatter.stamped(body: "# T", passState: .firstDraft, origin: .writer)
== "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# T")
#expect(PostFrontmatter.stamped(body: "- Root", passState: .pass2Done, origin: .ai, type: .outline)
== "---\ntype: outline\npass_state: Pass-2 Done\norigin: ai\n---\n- Root")
}
@Test func `merge-import keeps foreign keys verbatim and ours win in place`() {
// External block with foreign keys around ours; `origin` present
// (overwritten in place), `type`/`pass_state` absent (inserted
// before the closing --- in table order).
let external = "---\ntitle: Outside\norigin: ai\ndate: 2026-10-11\n---\n# Body"
#expect(PostFrontmatter.mergingImport(text: external, origin: .writer)
== "---\ntitle: Outside\norigin: writer\ndate: 2026-10-11\ntype: post\npass_state: First Draft\n---\n# Body")
// #95: an external `type: outline` still imports as post.
#expect(PostFrontmatter.mergingImport(text: "---\ntype: outline\n---\nB", origin: .writer)
== "---\ntype: post\npass_state: First Draft\norigin: writer\n---\nB")
// Bare file → the fresh block, body verbatim below.
#expect(PostFrontmatter.mergingImport(text: "# Bare", origin: .ai)
== "---\ntype: post\npass_state: First Draft\norigin: ai\n---\n# Bare")
// #180: a hand-edit blank above the `---` survives import (the old
// writer dropped it — lossless through every posture is the contract).
#expect(PostFrontmatter.mergingImport(text: "\n---\ntitle: Outside\n---\n# B", origin: .writer)
== "\n---\ntitle: Outside\ntype: post\npass_state: First Draft\norigin: writer\n---\n# B")
}
@Test func `update-keys stamps in place and keeps every other line byte-identical`() {
// An existing key overwrites in place; foreign keys and the body
// never move.
#expect(PostFrontmatter.updating(text: withForeign, with: [("pass_state", "Pass-1 Done")])
== "---\nforeign_key: keep-me\ntype: post\npass_state: Pass-1 Done\norigin: writer\n---\n# Body")
// An absent key inserts before the closing --- (pair order).
#expect(PostFrontmatter.updating(text: withForeign, with: [("micropub_url", "https://micro.blog/x")])
== "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\nmicropub_url: https://micro.blog/x\n---\n# Body")
// Bare text → a fresh block prepends, body rides verbatim.
#expect(PostFrontmatter.updating(text: "# Bare", with: [("pass_state", "Pass-1 Done")])
== "---\npass_state: Pass-1 Done\n---\n# Bare")
}
@Test func `update-keys preserves hand-edit lines above the block`() {
// The #27 review contract, codec-level: lines above the opening
// --- belong to neither block nor body; the stamp keeps them. The
// inserted key lands before the closing --- (after existing keys).
#expect(PostFrontmatter.updating(text: "\n---\ntype: post\n---\n# B", with: [("dismiss_count", "1")])
.hasPrefix("\n---\ntype: post\ndismiss_count: 1\n---\n"))
}
@Test func `foreign keys ride verbatim through every posture chained`() {
// The #180 round-trip pin: import → editor save (owned keys) →
// pass advance → micropub stamp, foreign keys intact at every hop.
var text = PostFrontmatter.mergingImport(text: "---\nforeign: keep\norigin: ai\n---\n# Chain", origin: .writer)
for pairs in [
[("type", "post"), ("pass_state", "First Draft"), ("origin", "writer")],
[("pass_state", "Pass-1 Done")],
[("micropub_url", "https://micro.blog/x")],
] {
text = PostFrontmatter.updating(text: text, with: pairs)
#expect(text.contains("\nforeign: keep\n")) // the line never moved
}
#expect(PostFrontmatter.parse(text)["foreign"] == "keep")
#expect(text.hasSuffix("---\n# Chain")) // body untouched throughout
}
@Test func `unknown type reads leniently as post`() {
#expect(PostFrontmatter.decoded(PostFrontmatter.parse("---\ntype: alien\norigin: writer\npass_state: First Draft\n---\nB")).type == .post)
// The lenient defaults: a bare legacy corpus post is a normal piece.
#expect(PostFrontmatter.decoded([:])
== PostFrontmatter.Stamp(type: .post, passState: .firstDraft, origin: .writer))
}
@Test func `eligibility predicates name the pair and the capture gate`() {
func matter(type: String? = nil, passState: String? = nil, origin: String? = nil) -> [String: String] {
["type": type, "pass_state": passState, "origin": origin].compactMapValues { $0 }
}
// The immutable pair: writer ∧ post, independent of pass_state —
// a writer piece that legitimately advanced still carries its arc.
#expect(PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", passState: "Pass-1 Done", origin: "writer")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "Pass-1 Done", origin: "writer")))
// Capture: the pair ∧ First Draft.
#expect(PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "First Draft", origin: "writer")))
#expect(PostFrontmatter.isCaptureEligible([:])) // bare legacy post qualifies
// Neither gate opens for ai or outline pieces.
#expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", origin: "ai")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", origin: "ai")))
#expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "outline", origin: "writer")))
#expect(!PostFrontmatter.isCaptureEligible(matter(type: "outline", origin: "writer")))
}
}
+1 -1
View File
@@ -182,7 +182,7 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws {
@Test func `unterminated frontmatter is untitled, never leaked`() {
// No closing ---: frontmatter lines must never leak as the Title.
#expect(Post.title(of: "---\npass_state: First Draft\norigin: writer\n") == "untitled")
#expect(PostFrontmatter.parse("---\npass_state: First Draft\n")["pass_state"] == "First Draft")
#expect(Post.frontmatter(of: "---\npass_state: First Draft\n")["pass_state"] == "First Draft")
}
@Test func `leading blank line still opens frontmatter`() throws {
+11 -11
View File
@@ -309,7 +309,7 @@ private func threeDecimals(_ value: String) -> Bool {
let withForeign = try String(contentsOf: url, encoding: .utf8)
.replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post")
try withForeign.write(to: url, atomically: true, encoding: .utf8)
let bodyBefore = PostFrontmatter.split(withForeign).body
let bodyBefore = PostStore.splitFrontmatter(withForeign).body
let captured = PostStore.captureFirstDraftStats(
id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home,
@@ -317,7 +317,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(captured)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = PostFrontmatter.parse(after) // the trend-view readiness read
let matter = Post.frontmatter(of: after) // the trend-view readiness read
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable
#expect(matter["stats_burstiness"].map(threeDecimals) == true)
@@ -328,7 +328,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
// Body byte-identical — the stamp never touches content (#31 in-place proof).
#expect(PostFrontmatter.split(after).body == bodyBefore)
#expect(PostStore.splitFrontmatter(after).body == bodyBefore)
}
@Test func `capture refuses an ai origin piece untouched`() throws {
@@ -369,7 +369,7 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home))
#expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home))
let matter = try PostFrontmatter.parse(String(
let matter = try Post.frontmatter(of: String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
))
#expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won
@@ -394,7 +394,7 @@ private func threeDecimals(_ value: String) -> Bool {
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8,
)
let matter = PostFrontmatter.parse(after)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil)
#expect(after.contains("# Bare")) // the body survived the fresh-block prepend
}
@@ -416,14 +416,14 @@ private func threeDecimals(_ value: String) -> Bool {
#expect(advanced == .pass1Done)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = PostFrontmatter.parse(after)
let matter = Post.frontmatter(of: after)
#expect(matter["pass_state"] == "Pass-1 Done")
#expect(matter["stats_captured"] != nil) // survived the advance
#expect(matter["stats_trigram_repetition"] != nil)
#expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostFrontmatter.split(after).body == "# Kept\n\nBody stays.")
#expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.")
}
@Test func `overwrite preserves stats and foreign keys while swapping the body`() throws {
@@ -442,13 +442,13 @@ private func threeDecimals(_ value: String) -> Bool {
try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home)
let after = try String(contentsOf: url, encoding: .utf8)
let matter = PostFrontmatter.parse(after)
let matter = Post.frontmatter(of: after)
#expect(matter["stats_captured"] != nil) // survived the editor save
#expect(matter["foreign_key"] == "keep-me")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(matter["type"] == "post")
#expect(PostFrontmatter.split(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
#expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed
}
@Test func `overwrite normalizes a bare post with the full stamp`() throws {
@@ -465,9 +465,9 @@ private func threeDecimals(_ value: String) -> Bool {
let after = try String(
contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8,
)
let matter = PostFrontmatter.parse(after)
let matter = Post.frontmatter(of: after)
#expect(matter["type"] == "post")
#expect(matter["pass_state"] == "First Draft")
#expect(matter["origin"] == "writer")
#expect(PostFrontmatter.split(after).body == "Bare body, edited.")
#expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.")
}
+3 -4
View File
@@ -532,8 +532,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
withIntermediateDirectories: true,
)
}
// two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract
#expect(!decomposed.utf8.elementsEqual("한국".utf8))
#expect(!decomposed.utf8.elementsEqual("한국".utf8)) // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract
#expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2")
}
@@ -576,7 +575,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
#expect(verbatim.hasPrefix("---\ntype: post\n"))
#expect(verbatim.contains("pass_state: First Draft"))
#expect(verbatim.contains("origin: writer"))
#expect(PostFrontmatter.split(verbatim).body == "# Chapter\n- one\n - nested")
#expect(PostStore.splitFrontmatter(verbatim).body == "# Chapter\n- one\n - nested")
// folder never moved; scan reads the new type on rescan
#expect(Post.scan(home: home).first?.id == post.id)
#expect(Post.scan(home: home).first?.type == .post)
@@ -585,7 +584,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws
try PostStore.convert(id: post.id, headingsLadder: true, home: home)
let ladder = try readPost(home, post.id)
#expect(ladder.hasPrefix("---\ntype: post\n"))
#expect(PostFrontmatter.split(ladder).body == "# Chapter\n## one\n### nested")
#expect(PostStore.splitFrontmatter(ladder).body == "# Chapter\n## one\n### nested")
// a vanished piece throws, never resurrects
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
-264
View File
@@ -1,264 +0,0 @@
//
// PostsModelDepartureTests.swift
// MuseionTests
//
// brief-25 (failed-flush-discarded-on-document-switch): document
// departure is guarded. A navigation whose outgoing flush fails (write
// error, or an unanswered #67 conflict) aborts and retains the dirty
// session — teardown used to discard the flush result and drop the only
// retained copy of unsaved prose. Both navigation families (saved-post
// session, external guest) pinned with injected write failures: a
// read-only piece folder / read-only guest directory (atomic writes
// stage their temp file beside the destination), the permission-
// injection convention of FixCardApplyTests.
//
// #200 (gate quit-time flushes through the departure gate): quitting is
// the one departure that used to bypass the gate — shutdown() flushed
// both sessions best-effort. Pins: a quit-time shutdown with an
// unanswered #67 conflict leaves the foreign disk body untouched (the
// #114 harm); the open external guest's edits ride the shutdown flush;
// a never-loaded session with retyped words refuses (its flush would
// report a vacuous success and drop the only copy — finish-audit LOW).
// The block-quit posture itself (applicationShouldTerminate's refusal)
// is pinned in WritingLockTests at the delegate seam.
//
import Foundation
@testable import Museion
import Testing
@Suite("PostsModelDepartureTests")
@MainActor
struct PostsModelDepartureTests {
private func denyWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
}
private func allowWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
}
@Test func `new post aborts when the dirty session flush fails and keeps its text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
model.select(post.id)
model.session?.edit("# Keeper\n\nunique failed-flush paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newPost()
// The switch aborted: the dirty session is retained, not replaced
// by the draft — its text is the only copy of the edits.
#expect(model.session?.postID == post.id)
#expect(model.session?.text == "# Keeper\n\nunique failed-flush paragraph")
#expect(model.session?.saveState == .failed)
#expect(model.draft == nil)
#expect(model.selectedPostID == post.id)
#expect(model.lastError != nil)
// Writability restored → the retry lands the edits, then switches.
try allowWrites(to: pieceDir)
model.newPost()
#expect(model.draft != nil)
#expect(model.session == nil)
#expect(model.lastError == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nunique failed-flush paragraph")
}
@Test func `new outline aborts when the dirty session flush fails`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
model.newOutline()
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.newOutline()
#expect(model.draft?.type == .outline)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `switching pieces aborts when the outgoing session flush fails`() throws {
let (model, home) = try makeModelHome()
let postA = try PostStore.writeNew(body: "# A\n", home: home)
let postB = try PostStore.writeNew(body: "# B\n", home: home)
model.select(postA.id)
model.session?.edit("# A\n\noutgoing paragraph")
let dirA = try #require(PostStore.folder(of: postA.id, home: home))
try denyWrites(to: dirA)
defer { try? allowWrites(to: dirA) }
model.select(postB.id)
// The switch aborted before replacing the session (select's own
// teardown AND the second one through openUnguarded both gated).
#expect(model.session?.postID == postA.id)
#expect(model.session?.text == "# A\n\noutgoing paragraph")
#expect(model.selectedPostID == postA.id)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n")
try allowWrites(to: dirA)
model.select(postB.id)
#expect(model.session?.postID == postB.id)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `open external aborts when the dirty session flush fails`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
model.select(post.id)
model.session?.edit("# Host\n\noutgoing paragraph")
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
// The guest did not take the column: the switch aborted with the
// dirty session retained.
#expect(model.session?.postID == post.id)
#expect(model.externalSession == nil)
#expect(model.lastError != nil)
try allowWrites(to: pieceDir)
model.openExternal(extFile)
#expect(model.externalSession != nil)
#expect(model.session == nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# Host\n\noutgoing paragraph")
}
@Test func `select aborts when the dirty guest flush fails and keeps the guest`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Host\n", home: home)
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
defer { try? allowWrites(to: extDir) }
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
model.externalSession?.edit("# Foreign\n\nguest paragraph that must survive")
try denyWrites(to: extDir)
model.select(post.id)
// The guest stays: its buffer is the only copy of the edits.
#expect(model.externalSession != nil)
#expect(model.externalSession?.text == "# Foreign\n\nguest paragraph that must survive")
#expect(model.session == nil) // the switch aborted before opening the post
#expect(model.selectedPostID == nil)
#expect(model.lastError != nil)
try allowWrites(to: extDir)
model.select(post.id)
#expect(model.externalSession == nil)
#expect(model.session?.postID == post.id)
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest paragraph that must survive")
}
@Test func `new post aborts while the conflict alert is unanswered`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlocal paragraph")
// #67: a foreign disk body arrived — the alert is up, unanswered.
model.session?.diskDidChange(diskText: "foreign body from disk")
model.newPost()
// Departure mirrors flushOrAbort: the unanswered conflict holds the
// navigation (and never overwrites the foreign disk body).
#expect(model.session?.postID == post.id)
#expect(model.draft == nil)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n")
}
@Test func `quit-time shutdown leaves the foreign disk body untouched while the conflict alert is unanswered`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlocal paragraph")
// #67, for real this time: the foreign body is ON disk (quit's
// flush() never held for a conflict — only the debounce did, so
// shutdown used to write the local text over it, #114's harm).
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
model.session?.diskDidChange(diskText: "foreign body from disk")
model.shutdown()
// AC #200: the foreign disk body survives the quit-time flush and
// the strip says why instead of pretending it saved.
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
#expect(model.lastError != nil)
}
@Test func `quit-time shutdown flushes a clean dirty session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
model.select(post.id)
model.session?.edit("# A\n\nlast words before quitting")
model.shutdown()
// No conflict, no failure: the edits land and quit proceeds clean.
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown flushes the open external guest`() throws {
let (model, _) = try makeModelHome()
let extDir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-departure-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: extDir, withIntermediateDirectories: true)
defer { try? allowWrites(to: extDir) }
let extFile = extDir.appendingPathComponent("notes.md")
try "# Foreign\n".write(to: extFile, atomically: true, encoding: .utf8)
model.openExternal(extFile)
model.externalSession?.edit("# Foreign\n\nguest words that must land before quitting")
model.shutdown()
// The guest leg of the quit gate: its edits ride the shutdown
// flush, exactly as the old best-effort shutdown did.
#expect(try String(contentsOf: extFile, encoding: .utf8) == "# Foreign\n\nguest words that must land before quitting")
#expect(model.lastError == nil)
}
@Test func `quit-time shutdown refuses over a never-loaded session with retyped text`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# A\n", home: home)
// The file turns unreadable between scan and open: the session
// opens empty (loadFailed), the writer retypes into it.
let file = try #require(PostStore.folder(of: post.id, home: home))
.appendingPathComponent("post.md")
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) }
model.select(post.id)
#expect(model.session?.loadFailed == true)
model.session?.edit("# Retyped words over a file that never loaded")
model.shutdown()
// flush() reports a vacuous success for a never-loaded session —
// the gate must refuse instead of letting the retype die quietly.
#expect(model.lastError != nil)
#expect(model.session?.text == "# Retyped words over a file that never loaded")
}
}
-351
View File
@@ -1,351 +0,0 @@
//
// PostsModelRepointTests.swift
// MuseionTests
//
// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a
// document departure. Settings used to commit the new Home and flip
// `watchedHome` (bind → startWatching) without departing the open
// session: the session's immutable target kept the OLD Home, a same-slug
// piece in the new library made the ID-only reselect return it, and
// autosave/Save/quit wrote the old library while structural operations
// resolved against the new one (#198's departure gate never saw this
// seam). Pins: the gate runs BEFORE anything changes (a refused repoint
// leaves Home A, the binding, the session's (Home, ID) target and its
// buffer untouched — all three `sessionMayDepart` legs), an accepted
// repoint lands the edits on A first and leaves no live session targeting
// an A piece under B, the same-slug piece opens from B and saves there
// (flush AND quit), a no-collision repoint tears down cleanly (the old
// vanish path dropped the dirty buffer), a card scan from the old library
// never lands on the new library's piece (identity re-check at
// COMPLETION — the scan seam holds it past the repoint), and a pass
// started after the repoint runs against the new library.
//
// Two-Home rig: `projects/posts/shared/post.md` in BOTH libraries — the
// collision shape the finding names; differing bodies so a wrong-library
// read is observable. The Settings path in these pins is the model's two
// steps — `repoint(to:)` (the gate) then `bind` (the commit) — exactly as
// WorkspaceView's binding and root `.task(id:)` drive them.
// r1 (athena MF-1/N-1): the hoisted stale-Home verdict in `rescan` (the
// library-scan sibling of the card hop-back — the per-model `scanLibrary`
// seam holds it past the repoint) and the draft-survives decision are
// pinned too.
//
import Foundation
@testable import Museion
import Testing
/// brief-28 rig: a Sendable one-shot flag the stale card-scan pin's park
/// probe reads (the detached scanner sets it from off-main; pollUntil's
/// per-iteration probe must not consume anything).
private final class ParkedFlag: @unchecked Sendable {
private let lock = NSLock()
private var value = false
var isSet: Bool {
lock.withLock { value }
}
func set() {
lock.withLock { value = true }
}
}
@Suite("PostsModelRepointTests")
@MainActor
struct PostsModelRepointTests {
private func denyWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
}
private func allowWrites(to dir: URL) throws {
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
}
/// Two Homes holding the SAME slug — `writeNew` derives `shared` from
/// the `# Shared` title in both (a non-Shared bodyA makes a unique
/// slug instead: the no-collision shape). The model is bound to A.
// swiftlint:disable:next large_tuple
private func makeTwoHomes(bodyA: String, bodyB: String) throws -> (model: PostsModel, homeA: URL, homeB: URL) {
let base = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true)
let homeA = base.appendingPathComponent("A", isDirectory: true)
let homeB = base.appendingPathComponent("B", isDirectory: true)
for home in [homeA, homeB] {
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
}
_ = try PostStore.writeNew(body: bodyA, home: homeA)
_ = try PostStore.writeNew(body: bodyB, home: homeB)
let model = PostsModel()
model.bind(home: homeA)
return (model, homeA, homeB)
}
@Test func `a same-slug piece opens from the new library after a repoint and saves there, never the old one`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
#expect(model.session?.text == "# Shared\n\nA body\n")
model.session?.edit("# Shared\n\nA body, typed in A\n")
// The Settings repoint: the gate first, the binding after.
#expect(model.repoint(to: homeB))
// Ordering: the departure landed on A and NOTHING has moved yet —
// watchedHome is still A until the binding commits, and no live
// session targets an A piece.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
#expect(model.watchedHome == homeA)
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
model.bind(home: homeB)
#expect(model.watchedHome == homeB)
model.select("shared")
// B's piece opened from B — not the retained A session (whose
// ID-only reselect used to return it under the new UI).
#expect(model.session?.text == "# Shared\n\nB body\n")
#expect(model.session?.targets(postID: "shared", home: homeB) == true)
model.session?.edit("# Shared\n\nB body, typed in B\n")
model.session?.flush() // ⌘S — the debounce's own sink
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B\n")
// A holds exactly what the departure flushed — never B's edits.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
model.session?.edit("# Shared\n\nB body, typed in B again\n")
model.shutdown() // quit rides the departure gate (#200)
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B again\n")
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
}
@Test func `repoint refuses when the open piece's flush fails and changes nothing`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
model.session?.edit("# Shared\n\nA body, typed in A\n")
let pieceDir = try #require(PostStore.folder(of: "shared", home: homeA))
try denyWrites(to: pieceDir)
defer { try? allowWrites(to: pieceDir) }
// The Settings repoint — refused: the gate fires before any change.
#expect(model.repoint(to: homeB) == false)
// ORDERING: the gate fired before ANY state changed — the binding,
// the selection, the session's (Home, ID) target and its buffer.
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.postID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.text == "# Shared\n\nA body, typed in A\n")
#expect(model.session?.saveState == .failed)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n")
// Writability restored → the edits land on A first (watchedHome
// still A until the binding commits), then the repoint departs.
try allowWrites(to: pieceDir)
#expect(model.repoint(to: homeB))
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n")
#expect(model.watchedHome == homeA)
model.bind(home: homeB)
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
#expect(model.watchedHome == homeB)
}
@Test func `repoint refuses while the conflict alert is unanswered`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("shared")
model.session?.edit("# Shared\n\nA body, typed in A\n")
// #67: a foreign disk body arrived — the alert is up, unanswered.
model.session?.diskDidChange(diskText: "foreign body from disk")
// The Settings repoint — refused.
#expect(model.repoint(to: homeB) == false)
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.postID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.conflictAlert == true)
#expect(model.session?.text == "# Shared\n\nA body, typed in A\n")
#expect(model.lastError != nil)
// Never over the foreign body, never into the new library.
#expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body\n")
#expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n")
}
@Test func `repoint refuses over a never-loaded session with retyped text`() throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
// The file turns unreadable between scan and open: the session
// opens empty (loadFailed), the writer retypes into it (#200's leg).
let file = try #require(PostStore.folder(of: "shared", home: homeA))
.appendingPathComponent("post.md")
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path)
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) }
model.select("shared")
#expect(model.session?.loadFailed == true)
model.session?.edit("# Retyped words over a file that never loaded")
// The Settings repoint — refused: the retype is the only copy.
#expect(model.repoint(to: homeB) == false)
#expect(model.watchedHome == homeA)
#expect(model.selectedPostID == "shared")
#expect(model.session?.targets(postID: "shared", home: homeA) == true)
#expect(model.session?.text == "# Retyped words over a file that never loaded")
#expect(model.lastError != nil)
}
@Test func `a no-collision repoint lands the open piece's edits first and tears it down cleanly`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Unique\n\nA body\n", bodyB: "# Shared\n\nB body\n")
model.select("unique")
model.session?.edit("# Unique\n\nA body, typed in A\n")
// The Settings repoint — accepted: the old session's edits landed
// on A BEFORE anything moved (the vanish path used to tear it down
// without a flush).
#expect(model.repoint(to: homeB))
#expect(PostStore.readBody(id: "unique", home: homeA) == "# Unique\n\nA body, typed in A\n")
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
model.bind(home: homeB)
// No ghost: the new library's rescan leaves nothing selected, nothing open.
try await pollUntil { model.posts.contains { $0.id == "shared" } }
#expect(model.session == nil)
#expect(model.selectedPostID == nil)
#expect(model.watchedHome == homeB)
}
@Test func `a card scan from the old library never lands on the new library's same-slug piece`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n")
let folderA = try #require(PostStore.folder(of: "shared", home: homeA))
let folderB = try #require(PostStore.folder(of: "shared", home: homeB))
_ = try FixCardStore.submit(piecePath: folderA.path, cards: [card(pattern: "Hedging", quote: "A body")])
_ = try FixCardStore.submit(piecePath: folderB.path, cards: [card(pattern: "Telling", quote: "B body")])
// HOLD the old library's scan past the repoint: the injected scanner
// parks on A's folder until the test releases it (a detached disk
// read is otherwise faster than any arrangement); B's scans run
// free. The park probe is a flag, never a consuming semaphore wait —
// pollUntil re-evaluates its condition per iteration.
let parked = ParkedFlag()
let release = DispatchSemaphore(value: 0)
model.scanPieceCards = { url in
if url == folderA {
parked.set()
_ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread
}
return FixCardStore.scan(pieceURL: url)
}
model.select("shared") // the A scan parks inside the detached read
try await pollUntil { parked.isSet }
// The repoint, then B's same-slug piece opens and ITS scan lands.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
model.select("shared")
try await pollUntil { model.openPieceCards.map(\.pattern) == ["Telling"] }
#expect(model.openPieceCards.map(\.pattern) == ["Telling"])
// Release the stale A scan: its continuation completes AFTER the new
// library's piece is open — identity at completion, never the id.
release.signal()
release.signal() // a second A scan, if one ever queued, must not park the teardown
try await Task.sleep(nanoseconds: 200_000_000) // let the hop-back land
#expect(model.openPieceCards.map(\.pattern) == ["Telling"]) // never A's cards
}
@Test func `a pass started after the repoint runs against the new library`() async throws {
let (model, homeA, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
_ = try PostStore.writeNew(body: "# Shared\n\nA body\n", home: homeA)
let homeB = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-pass-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true)
_ = try PostStore.writeNew(body: "# Shared\n\nB body\n", home: homeB)
model.select("shared")
#expect(model.session?.text == "# Shared\n\nA body\n")
// The Settings repoint: gate, then binding.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
model.select("shared")
#expect(model.session?.text == "# Shared\n\nB body\n")
await model.runPass(.pass1, mentor: mentor)
// Snapshot and the advance landed on B's piece with B's body — the
// retained A session used to hand its text to the new library.
let snapshot = try String(
contentsOf: homeB.appendingPathComponent("projects/posts/shared/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot.contains("B body"))
let onDiskB = try String(contentsOf: homeB.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8)
#expect(onDiskB.contains("pass_state: Pass-1 Done"))
let onDiskA = try String(contentsOf: homeA.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8)
#expect(onDiskA.contains("pass_state: First Draft"))
#expect(!FileManager.default.fileExists(atPath: homeA.appendingPathComponent("projects/posts/shared/passes/pass-1.md").path))
}
/// r1 (MF-1): the hoisted stale-Home verdict in `rescan` — the sibling
/// continuation of the card hop-back, and the one guard still observable
/// in production after the gate. A scan started under A sits in its
/// detached hop while the gate passes and `bind` flips to B; landing
/// after B's own scan it would put A's list under the B binding until
/// the next B-side event — which, with nothing open, can be never.
@Test func `a library scan from the old Home lands nothing under the new binding`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Alpha\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// The rig's first rescan lands first: posts is A's list, steady state.
try await pollUntil { model.posts.map(\.id) == ["alpha"] }
// HOLD the next A scan past the repoint (the card pin's shape).
let parked = ParkedFlag()
let release = DispatchSemaphore(value: 0)
model.scanLibrary = { home, cache in
if home == homeA {
parked.set()
_ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread
}
return Post.scan(home: home, cache: cache)
}
Task { await model.rescan() } // parks inside the detached scan
try await pollUntil { parked.isSet }
// The Settings repoint: gate, then binding; B's own scan lands.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
try await pollUntil { model.posts.map(\.id) == ["bravo"] }
let revision = model.contentRevision
// Release the stale A scan: its continuation completes AFTER B's scan
// — the hoisted verdict applies nothing it found (list, revision).
release.signal()
release.signal() // a second A scan, if one ever queued, must not park the teardown
try await Task.sleep(nanoseconds: 200_000_000) // let the continuation land
#expect(model.posts.map(\.id) == ["bravo"]) // never A's list under the B binding
#expect(model.contentRevision == revision) // and no revision bump for it
}
/// r1 (N-1): the draft-survives decision, pinned — a draft has no Home
/// until first save (#62), so the repoint leaves its buffer alone and
/// the lazy folder lands under B, in the draft's OWN project even when
/// B does not have it yet (materialize creates with intermediates).
@Test func `an in-memory draft survives a repoint and first-saves into the new library only`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Piece\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// A holds `projects/alpha/in-alpha` — a project B does not have.
let alphaPiece = try PostStore.writeNew(body: "# In Alpha\n\nA body\n", project: "alpha", home: homeA)
try await pollUntil { model.posts.contains { $0.id == alphaPiece.id } } // the list must know the piece (targetProject reads it)
model.select(alphaPiece.id)
model.newPost() // targets the selected piece's project
#expect(model.draft?.project == "alpha")
model.updateDraft("# Draft Words\n\nTyped in A, saved in B")
// The Settings repoint: gate, then binding — the draft rides along.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
#expect(model.draft?.text == "# Draft Words\n\nTyped in A, saved in B") // intact
model.saveDraft()
#expect(PostStore.readBody(id: "draft-words", home: homeB) == "# Draft Words\n\nTyped in A, saved in B")
#expect(PostStore.readBody(id: "draft-words", home: homeA) == nil) // never A
#expect(Post.scan(home: homeB).contains { $0.id == "draft-words" && $0.project == "alpha" }) // B-absent project created
#expect(model.session?.targets(postID: "draft-words", home: homeB) == true) // and it opens there
#expect(model.draft == nil)
}
}
+62 -179
View File
@@ -5,9 +5,6 @@
// #108 audit: the model-layer lifecycle the store tests can't see —
// archive clearing the open session, move reopening it at the new parent,
// restore keeping the writer in the piece, New Project's draft targeting.
// #179: the write-rail pins — one seam pairs every library store write
// with exactly one rescan and owns the error strip; the model owns the
// Home (no method takes one).
//
import Foundation
@@ -30,10 +27,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
@Test @MainActor func `archiving the open piece clears selection and session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home)
model.select(post.id)
model.select(post.id, home: home)
#expect(model.session?.postID == post.id)
model.archivePost(post)
model.archivePost(post, home: home)
#expect(model.selectedPostID == nil)
#expect(model.session == nil)
@@ -44,10 +41,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
@Test @MainActor func `moving the open piece reopens its session at the new parent`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Traveler\n", project: "essays", home: home)
model.select(post.id)
model.select(post.id, home: home)
#expect(model.session?.folderURL.path.contains("projects/essays") == true)
model.moveToProject(post, project: "posts")
model.moveToProject(post, project: "posts", home: home)
#expect(model.session?.postID == post.id) // same piece, fresh session
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
@@ -58,10 +55,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Revived\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id) // opened from the Archive pane
model.select(post.id, home: home) // opened from the Archive pane
#expect(model.session?.folderURL.path.contains("archive/") == true)
model.restorePost(post)
model.restorePost(post, home: home)
#expect(model.selectedPostID == post.id) // the writer stays in it
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
@@ -76,7 +73,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
#expect(model.draft?.project == "essays")
model.updateDraft("# Fresh\n")
model.saveDraft()
model.saveDraft(home: home)
let scanned = Post.scan(home: home)
#expect(scanned.first?.project == "essays")
@@ -103,10 +100,10 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Keeper\n\nDirty.") // inside the debounce window
model.unarchiveProject("posts")
model.unarchiveProject("posts", home: home)
// The edits landed on disk (readBody resolves by id — through the move).
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nDirty.")
@@ -124,7 +121,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
model.select(post.id)
model.select(post.id, home: home)
model.newOutline()
@@ -145,7 +142,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
model.newOutline()
model.saveDraft()
model.saveDraft(home: home)
#expect(model.draft == nil)
#expect(model.lastError == nil)
@@ -160,7 +157,7 @@ func makeModelHome() throws -> (PostsModel, URL) {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home) // empty — no pieces
#expect(model.moveTargets() == ["essays", "posts"])
#expect(model.moveTargets(home: home) == ["essays", "posts"])
// "posts" exists too (bind created it); a dot-project never shows.
}
@@ -180,7 +177,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id)
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the ask is up
#expect(model.session == nil) // nothing editable while it's up
@@ -194,8 +191,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id)
model.openGuardedOutlineInProse()
model.select(post.id, home: home)
model.openGuardedOutlineInProse(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
@@ -212,8 +209,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id)
model.openGuardedOutlineAsOutline()
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == post.id)
@@ -229,13 +226,13 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id)
model.select(post.id, home: home)
model.cancelOutlineGuard()
#expect(model.outlineGuardPieceID == nil)
#expect(model.session == nil)
// Still guarded: the next open re-fires the ask, file untouched.
model.select(post.id)
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id)
}
@@ -245,12 +242,12 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id)
model.openGuardedOutlineAsOutline() // consent; disk still mixed
model.select(post.id, home: home)
model.openGuardedOutlineAsOutline(home: home) // consent; disk still mixed
let session = try #require(model.session)
session.edit("- one\n- two\nedited") // dirty; debounce armed
model.select(post.id) // muscle-memory re-click on the open row
model.select(post.id, home: home) // muscle-memory re-click on the open row
#expect(model.outlineGuardPieceID == nil) // no re-ask over a prior answer
#expect(model.session === session) // the open session survives, dirty state intact
@@ -260,15 +257,15 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id) // ask up
model.select(post.id, home: home) // ask up
model.newPost() // ⌘N fires while the sheet is up
#expect(model.outlineGuardPieceID == nil) // the ask died with the displacement
#expect(model.draft != nil)
model.updateDraft("# Keep me\n")
// Answering the (now-gone) ask is inert — the draft survives.
model.openGuardedOutlineInProse()
model.openGuardedOutlineAsOutline()
model.openGuardedOutlineInProse(home: home)
model.openGuardedOutlineAsOutline(home: home)
#expect(model.draft != nil)
#expect(model.selectedPostID == nil) // the draft still owns the editor
}
@@ -282,7 +279,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
}
#expect(model.posts.contains(where: { $0.id == post.id }))
model.select(post.id)
model.select(post.id, home: home)
#expect(model.outlineGuardPieceID == post.id) // the scan path guards too
}
@@ -291,11 +288,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
let clean = try PostStore.writeNew(body: "# Clean\n\n- one\n- two\n", type: .outline, home: home)
let prose = try PostStore.writeNew(body: "# Plain\n\nA paragraph.\n", home: home)
model.select(clean.id)
model.select(clean.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == clean.id)
model.select(prose.id)
model.select(prose.id, home: home)
#expect(model.outlineGuardPieceID == nil)
#expect(model.session?.postID == prose.id)
}
@@ -305,12 +302,12 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `convert reopens the open piece routed to prose`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home)
model.select(post.id)
model.select(post.id, home: home)
model.stageConversion(post)
model.stageConversion(post, home: home)
#expect(model.pendingConversion?.id == post.id)
#expect(model.pendingConversion?.lossy == false) // clean outline
model.convertToPost(headingsLadder: true)
model.convertToPost(headingsLadder: true, home: home)
#expect(model.pendingConversion == nil)
#expect(model.session?.postID == post.id) // reopened on the converted body
@@ -324,10 +321,10 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let open = try PostStore.writeNew(body: "# Stay\n", home: home)
let outline = try PostStore.writeNew(body: "- a\n - b", type: .outline, home: home)
model.select(open.id)
model.select(open.id, home: home)
model.stageConversion(outline)
model.convertToPost(headingsLadder: false)
model.stageConversion(outline, home: home)
model.convertToPost(headingsLadder: false, home: home)
#expect(model.session?.postID == open.id) // untouched
#expect(model.selectedPostID == open.id)
@@ -347,9 +344,9 @@ private func writeMixedOutline(home: URL) throws -> Post {
}
#expect(model.posts.first(where: { $0.id == post.id })?.type == .outline)
model.select(post.id)
model.stageConversion(post)
model.convertToPost(headingsLadder: false) // VERBATIM
model.select(post.id, home: home)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home) // VERBATIM
#expect(model.proseOverridePostID == post.id)
#expect(model.session?.postID == post.id)
@@ -365,11 +362,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `dirty open piece flushes before the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Chapter\n- one\n - typed child") // unflushed edit
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8)
#expect(onDisk.contains("type: post"))
@@ -379,11 +376,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `staging warns from the session text when the piece is dirty`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
model.select(post.id)
model.select(post.id, home: home)
// prose typed since the last flush — disk still clean, session is not
model.session?.edit("# Clean\n- one\nA paragraph between bullets.\n- two")
model.stageConversion(post)
model.stageConversion(post, home: home)
#expect(model.pendingConversion?.lossy == true) // from session.text, not stale disk
}
@@ -392,7 +389,7 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home) // closed piece — disk is the truth
model.stageConversion(post)
model.stageConversion(post, home: home)
#expect(model.pendingConversion?.lossy == true)
}
@@ -401,15 +398,13 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one\n- two", type: .outline, home: home)
model.stageConversion(post) // staged clean, no warning shown
model.stageConversion(post, home: home) // staged clean, no warning shown
// a foreign write makes the body mixed while the sheet was up
let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false)
try PostFrontmatter.stamped(
body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline,
)
.write(to: file, atomically: true, encoding: .utf8)
try PostStore.stamped(body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline)
.write(to: file, atomically: true, encoding: .utf8)
model.convertToPost(headingsLadder: true)
model.convertToPost(headingsLadder: true, home: home)
#expect(model.lastError?.contains("nothing was converted") == true)
#expect(model.session?.postID == nil || model.session?.postID != post.id)
@@ -418,8 +413,8 @@ private func writeMixedOutline(home: URL) throws -> Post {
#expect(onDisk.contains("A paragraph between bullets."))
// the consented path still converts: a WARNED mixed piece + Headings proceeds
model.stageConversion(post) // now stages lossy from disk
model.convertToPost(headingsLadder: true)
model.stageConversion(post, home: home) // now stages lossy from disk
model.convertToPost(headingsLadder: true, home: home)
let converted = try String(contentsOf: file, encoding: .utf8)
#expect(converted.contains("type: post"))
#expect(!converted.contains("A paragraph between bullets.")) // dropped, as consented
@@ -428,14 +423,14 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `unanswered conflict aborts the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Clean\n- one", type: .outline, home: home)
model.select(post.id)
model.select(post.id, home: home)
// #67 conflict up: disk holds foreign text, the editor's version unwritten
model.session?.diskDidChange(diskText: "# Foreign rewrite\nbody")
#expect(model.session?.conflictAlert == true)
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
#expect(model.lastError?.contains("reload question") == true)
#expect(model.session?.conflictAlert == true) // still answerable, not trampled
@@ -446,13 +441,13 @@ private func writeMixedOutline(home: URL) throws -> Post {
@Test @MainActor func `failed flush aborts the convert`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Chapter\n- one", type: .outline, home: home)
model.select(post.id)
model.select(post.id, home: home)
model.session?.edit("# Chapter\n- one\n - child") // dirty
// vanish the piece: the flush throws (never resurrects), convert must abort
try FileManager.default.removeItem(at: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true))
model.stageConversion(post)
model.convertToPost(headingsLadder: true)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: true, home: home)
#expect(model.lastError?.contains("nothing was changed") == true)
#expect(model.session?.postID == post.id) // session stays up, dirty and honest
@@ -462,11 +457,11 @@ private func writeMixedOutline(home: URL) throws -> Post {
let (model, home) = try makeModelHome()
let post = try writeMixedOutline(home: home)
model.select(post.id) // guard fires, open held
model.select(post.id, home: home) // guard fires, open held
#expect(model.outlineGuardPieceID == post.id)
model.stageConversion(post)
model.convertToPost(headingsLadder: false)
model.stageConversion(post, home: home)
model.convertToPost(headingsLadder: false, home: home)
#expect(model.outlineGuardPieceID == nil) // the stale ask died with the outline
#expect(model.selectedPostID == nil) // cancel teardown: nothing was open
@@ -488,125 +483,13 @@ private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
}
}
// #179: the rail's rescan lands via Task — bounded poll (FixCardApplyTests'
// pollUntil, made internal; the post-loop expect makes a silent timeout a
// failure, not a pass).
/// Scenario: one write rail for every library verb (from #179).
/// Given a model bound to a Home, when a verb's store write runs, then it
/// lands through the ONE seam — the library reflects it via exactly one
/// rescan and a stale error strip is cleared on success.
/// Suite member (not free function): suite-name filters must reach the
/// rail pins (MuseionTests/AGENTS.md rule).
@Suite("write rail #179")
struct PostsModelWriteRailTests {
@Test @MainActor func `pairs the write with the library refresh and clears the strip`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Rail Pin\n", home: home)
try await pollUntil { model.posts.contains { $0.id == post.id } }
model.lastError = "stale strip" // the rail owns the strip from here
model.rename(post, to: "Rail Pin Two")
#expect(model.lastError == nil)
try await pollUntil { model.posts.contains { $0.id == "rail-pin-two" } }
#expect(model.posts.contains { $0.id == post.id } == false)
}
/// Scenario: the rail owns the error strip on a failed write (from #179).
/// Given a bound model and a store write that throws, the verb's failure
/// reason lands in the strip AND rides the return for the sheet.
@Test @MainActor func `owns the strip when the write throws`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "dup", home: home) // the store already has it
let reason = model.createProject(named: "dup")
#expect(reason != nil)
#expect(model.lastError == reason)
}
/// Scenario: the rail refuses cleanly with no Home bound (from #179).
/// Given a model that was never bound, a write verb refuses with a reason
/// and nothing reaches any disk.
@Test @MainActor func `refuses cleanly before a home is bound`() {
let model = PostsModel()
let reason = model.createProject(named: "nowhere")
#expect(reason != nil)
#expect(model.lastError == reason)
#expect(model.posts.isEmpty)
}
/// Scenario: a mid-batch import failure keeps its strip message while
/// the good files land (from #179 — the rail clears the strip BEFORE
/// the write exactly so the per-file failures set inside the closure
/// survive the success tail).
@Test @MainActor func `import batch keeps per-file failure messages on the strip`() async throws {
let (model, _) = try makeModelHome()
let scratch = FileManager.default.temporaryDirectory
.appendingPathComponent("import-batch-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)
let good = scratch.appendingPathComponent("good.md")
try "# Good Piece\n".write(to: good, atomically: true, encoding: .utf8)
let missing = scratch.appendingPathComponent("missing.md") // never written — the read throws
model.stageImport([good, missing])
model.importFiles(origin: .writer)
#expect(model.lastError?.contains("Import failed — missing.md") == true)
// the library refresh rides the rail's rescan Task — poll for it
try await pollUntil { model.posts.contains { $0.id == "good-piece" } }
#expect(model.selectedPostID == "good-piece") // …and opened (synchronous select)
}
/// Scenario: a Home repoint while a pass runs refuses the pass advance
/// (from #179 audit — the rail resolves watchedHome at call time, and
/// the engine's turn spans minutes). Given a pass that ends normally
/// after its library was repointed, the advance is refused with the
/// honest strip message, both libraries keep their pass states, and
/// nothing was written into the new library.
@Test @MainActor func `home repoint mid-pass refuses the advance`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Repoint\n", home: rig.home)
rig.model.select(post.id)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
try await pollUntil { rig.model.runningPass == .pass1 } // the engine holds the turn
let homeB = FileManager.default.temporaryDirectory
.appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true)
// the Settings repoint, mid-pass — brief-28: gate first (the open
// piece departs cleanly), then the binding commits.
#expect(rig.model.repoint(to: homeB))
rig.model.bind(home: homeB)
// Release the held turn as a NORMALLY ended one — .ended + no refusal.
// Poll for the PARK first: runningPass flips before the one-shot
// engine spawns, so ending the hold in that window false-fails
// under load (the #30/#147 flake family). #require afterwards:
// nothing held after the poll means the parked prompt hit its
// deadline — fail loudly, not on a confusing nil strip.
let engine = try #require(rig.mentor.host.oneShot as? ScriptedEngine)
try await pollUntil { engine.hasHeldPrompt }
try #require(engine.endHeldPrompt())
await run.value
#expect(rig.model.lastError == "The library changed while the pass ran — its Pass State was not advanced.")
#expect(Post.scan(home: rig.home).first?.passState == .firstDraft) // the pass's own library: not advanced
#expect(Post.scan(home: homeB).isEmpty) // the new library: nothing stamped
}
}
@Test @MainActor func `opening a piece surfaces its stored fix cards`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id)
model.select(post.id, home: home)
try await waitForCards(model, 1)
#expect(model.openPieceCards.map(\.pattern) == ["Hedging"])
@@ -618,7 +501,7 @@ struct PostsModelWriteRailTests {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id)
model.select(post.id, home: home)
try await waitForCards(model, 1)
// An MCP client submits another card while the piece stays open —
@@ -637,7 +520,7 @@ struct PostsModelWriteRailTests {
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id)
model.select(post.id, home: home)
try await waitForCards(model, 1)
model.newPost()
@@ -653,7 +536,7 @@ struct PostsModelWriteRailTests {
#expect(folder.path.contains("/archive/"))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id) // opened from the Archive pane
model.select(post.id, home: home) // opened from the Archive pane
try await waitForCards(model, 1)
#expect(model.openPieceCards.count == 1)
-35
View File
@@ -1,35 +0,0 @@
//
// ProfileLayoutTests.swift
// MuseionTests
//
// #182 — the profile layout's one pinning suite.
//
// Scenario: A layout change is one module + one suite — From user story #182
// Given the Hermes profile layout (root, per-profile dir, .env, marker,
// gateway pid, skills dir) is owned by ProfileLayout alone
// When any layout fact moves (root renamed, a file renamed)
// Then ProfileLayout.swift plus exactly this suite change — the provisioner,
// the settings writer, and backup/restore derive every path through it and
// no literal profile-root string exists outside the layout module.
//
import Foundation
@testable import Museion
import Testing
@Suite("ProfileLayoutTests")
struct ProfileLayoutTests {
/// Pinned against LITERALS (not the layout's own inputs) so a fact change
/// fails here — this suite is the layout contract of record.
@Test func `root default is the hermes profiles dir`() {
#expect(ProfileLayout.defaultRoot == NSHomeDirectory() + "/.hermes/profiles")
}
@Test func `per-profile path builders pin every layout fact`() {
#expect(ProfileLayout.profileDir("museion-pass1", root: "/r") == "/r/museion-pass1")
#expect(ProfileLayout.envFile(in: "/r/museion") == "/r/museion/.env")
#expect(ProfileLayout.configuredMarker(in: "/r/museion") == "/r/museion/.museion-provisioned")
#expect(ProfileLayout.gatewayPID(in: "/r/museion") == "/r/museion/gateway.pid")
#expect(ProfileLayout.skillsDir(in: "/r/museion") == "/r/museion/skills")
}
}
@@ -44,17 +44,14 @@ struct ProfileProvisionerFailureTests {
func configUntouched() -> Bool {
(try? String(contentsOfFile: configPath, encoding: .utf8)) == config
}
// Shared per-phase runner: same binary/root/payload master, the
// server seam varying per phase (default = perform's own default).
func pass(_ payload: String, server: String? = Bundle.main.executableURL?.path) -> ProfileProvisioner.Outcome {
ProfileProvisioner.perform(
hermesBinary: binary, profileRoot: profileRoot, payloadRoot: payload,
masterRoot: master, serverBinaryPath: server,
)
}
// Failed pass: registration never reached, config untouched.
let failed = pass(badPayload)
let failed = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: badPayload,
masterRoot: master,
)
guard case .failed = failed else {
Issue.record("expected copy failure, got \(failed)")
return
@@ -64,7 +61,13 @@ struct ProfileProvisionerFailureTests {
// Skipped pass: nil serverBinaryPath is the test seam — nothing
// registers, config untouched. (The failed pass already seeded the
// shared master — 2 present there, only the 6 profile links copy.)
let skipped = pass(goodPayload, server: nil)
let skipped = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: nil,
)
#expect(skipped == .seeded(copied: 6, present: 2))
#expect(configUntouched())
for profile in ["museion", "museion-pass1", "museion-pass2"] {
@@ -74,7 +77,13 @@ struct ProfileProvisionerFailureTests {
// Registering pass: the CLI rail ran (markers + invocations per
// profile) and still not one byte of config.yaml is written by the
// provisioner — the entry lands through the CLI, or not at all.
let registered = pass(goodPayload, server: "/fake/Museion.app/Contents/MacOS/Museion")
let registered = ProfileProvisioner.perform(
hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
masterRoot: master,
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
#expect(registered == .seeded(copied: 0, present: 8))
#expect(configUntouched())
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered-museion")))
+34 -70
View File
@@ -35,8 +35,8 @@ struct SeedSkill {
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` / `config-unset-fails`
/// force the matching failure. Every `profile create` name appends to
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` force the matching
/// failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
/// #136: `config set` also records KEY=VALUE into
/// `<binaryDir>/config-store-<profile>` (dedup per key), and the fake speaks
@@ -44,8 +44,8 @@ struct SeedSkill {
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line,
/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins.
/// #136: the config rail (set/get/unset over the config-store map) — its
/// own literal so makeFakeHermes stays under its function-body ceiling.
// #136: the config rail (set/get/unset over the config-store map) — its
// own literal so makeFakeHermes stays under its function-body ceiling.
private func fakeHermesConfigCLI() -> String {
"""
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then
@@ -77,10 +77,6 @@ private func fakeHermesConfigCLI() -> String {
fi
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "unset" ]]; then
PROFILE="$2"; KEY="$5"
if [[ -f "${0:h}/config-unset-fails" ]]; then
print "Error: config unset exploded"
exit 1
fi
print -r -- "$*" >> "${0:h}/config-unset-$PROFILE"
STORE="${0:h}/config-store-$PROFILE"
if [[ -f "$STORE" && -n "$(grep -m1 "^${KEY}=" "$STORE")" ]]; then
@@ -94,67 +90,6 @@ private func fakeHermesConfigCLI() -> String {
"""
}
/// #23: the mcp rail (list/add over marker files) — its own literal so
/// makeFakeHermes stays under its function-body ceiling (config-rail
/// precedent directly above).
private func fakeHermesMcpCLI() -> String {
"""
if [[ "$1" == "-p" && "$3" == "mcp" ]]; then
PROFILE="$2"
if [[ "$4" == "list" ]]; then
if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then
print "museion-tools enabled"
exit 0
fi
print "No MCP servers configured."
exit 0
fi
if [[ "$4" == "add" ]]; then
if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then
print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9"
exit 1
fi
if [[ -f "${0:h}/mcp-add-fails" ]]; then
print "Error: mcp add exploded"
exit 1
fi
read -r ANSWER
if [[ "$ANSWER" != "y" ]]; then
print "Cancelled."
exit 1
fi
print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE"
touch "${0:h}/mcp-registered-$PROFILE"
print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
fi
"""
}
/// Fake `hermes`: `profile create <name>` behaves per `mode` (#43 semantics).
/// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on
/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1.
/// stderr-only: error on stderr with empty stdout (#48 fallback).
///
/// Also speaks `mcp` and `config set` behind the `-p <profile>` global flag
/// (#23, #134): `mcp list` prints "museion-tools" iff
/// `<binaryDir>/mcp-registered-<profile>` exists, else "No MCP servers
/// configured."; `mcp add` verifies its argv, reads ONE "y" line from stdin
/// (mismatch/EOF → "Cancelled.", exit 1 — nothing saved), records the exact
/// invocation in `<binaryDir>/mcp-add-invocation-<profile>`, drops the
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
/// strings). `config set <key> <value> [--force]` appends the exact argv to
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` / `config-unset-fails`
/// force the matching failure. Every `profile create` name appends to
/// `<binaryDir>/profile-create-log`.
/// #136: `config set` also records KEY=VALUE into
/// `<binaryDir>/config-store-<profile>` (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 `<binaryDir>/config-unset-<profile>`,
/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line,
/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins.
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
let path = (dir as NSString).appendingPathComponent(name)
let createBlock = switch mode {
@@ -189,7 +124,36 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
print -r -- "$NAME" >> "${0:h}/profile-create-log"
\(createBlock)
fi
\(fakeHermesMcpCLI())
if [[ "$1" == "-p" && "$3" == "mcp" ]]; then
PROFILE="$2"
if [[ "$4" == "list" ]]; then
if [[ -f "${0:h}/mcp-registered-$PROFILE" ]]; then
print "museion-tools enabled"
exit 0
fi
print "No MCP servers configured."
exit 0
fi
if [[ "$4" == "add" ]]; then
if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then
print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9"
exit 1
fi
if [[ -f "${0:h}/mcp-add-fails" ]]; then
print "Error: mcp add exploded"
exit 1
fi
read -r ANSWER
if [[ "$ANSWER" != "y" ]]; then
print "Cancelled."
exit 1
fi
print -r -- "$*" > "${0:h}/mcp-add-invocation-$PROFILE"
touch "${0:h}/mcp-registered-$PROFILE"
print "Saved 'museion-tools' to ${0:h}/profiles/$PROFILE/config.yaml"
exit 0
fi
fi
\(fakeHermesConfigCLI())
exit 97
"""
+1 -2
View File
@@ -343,8 +343,7 @@ struct ProfileSurfaceTests {
)
#expect(outcome == .seeded(copied: 8, present: 0))
for profile in ProfileSurface.allCases {
let invocation = (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)")
#expect(!FileManager.default.fileExists(atPath: invocation))
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation-\(profile.profileName)")))
}
}
+1 -5
View File
@@ -58,11 +58,7 @@ struct ProsePresenterTests {
// sample at the heading TEXT, not offset 0 (the dimmed marker)
let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont
#expect(h1?.pointSize == 30)
#expect(
h1?.fontName.contains("ConcourseOT") == true
|| h1?.fontName.contains("Semibold") == true
|| h1?.fontName.contains("Bold") == true,
)
#expect(h1?.fontName.contains("ConcourseOT") == true || h1?.fontName.contains("Semibold") == true || h1?.fontName.contains("Bold") == true)
let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont
#expect(h2?.pointSize == 22)
let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont
-106
View File
@@ -261,109 +261,3 @@ struct ProseRekeyMathTests {
#expect(result.park == 15) // caret parks at the marker line's content end
}
}
// MARK: - #142 typing budget (brief-24: fold-typing-budget-pin)
/// The typing-cost guard the landed re-key optimization never had: a quiet
/// regression that routes single-line typing edits back to the full pass
/// would keep every correctness pin above green (the full pass re-derives
/// CORRECT folds — it is only O(buffer) per keystroke). These pins count
/// scanned LINES through the real keystroke pipeline (shouldChangeText →
/// storage mutate → refreshFolds) — an operation count, never wall-time —
/// and hold the budget flat as the buffer doubles: the cheap path's cost
/// rides the fold count, not the document size.
extension ProseFoldRekeyTests {
/// One folded list + `filler` plain lines below it. Plain filler lines
/// are not list markers, so they add buffer without adding parents.
private func budgetText(filler: Int) -> String {
"intro\n\n- parent\n - child\n" + (0 ..< filler).map { "filler line \($0)\n" }.joined()
}
/// Type one character through the real pipeline at N and 2N filler lines
/// and return each run's scanned-line total.
private func typingScans(filler: Int) -> Int {
let text = budgetText(filler: filler)
let textView = makeView(text)
guard let parent = ProseList.parents(in: text).first else {
preconditionFailure("fixture must arm a parent")
}
textView.toggleFold(parent)
var scanned = 0
// The coordinator's keystroke tail with the budget instrument armed.
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x")
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x")
textView.refreshFolds { scanned += $0 }
return scanned
}
@Test func `typing beside a fold scans zero lines at N and 2N`() {
let atN = typingScans(filler: 200)
let at2N = typingScans(filler: 400)
#expect(atN == 0, "single-line typing edit took the full pass at N: \(atN) lines scanned")
#expect(at2N == 0, "single-line typing edit took the full pass at 2N: \(at2N) lines scanned")
// The budget itself: doubling the buffer must not move it.
#expect(atN == at2N)
}
@Test func `coordinator keystroke pipeline scans zero lines beside a fold`() throws {
// The through-seam pin (aegis ruling): the REAL entry — insertText
// through the PostEditorView coordinator's delegate tail
// (shouldChangeText → storage → textDidChange → refreshFolds) —
// never a direct test call. The instance hook (onLineScan) is the
// budget window for paths that call refreshFolds() bare.
let text = budgetText(filler: 200)
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
var scanned = 0
textView.onLineScan = { scanned += $0 }
let session = EditorSession(
target: .externalFile(URL(fileURLWithPath: "/dev/null")),
debounce: .seconds(3600),
)
let coordinator = ProseTextView.Coordinator(
representable: ProseTextView(session: session, dropBridge: ProseDropBridge()),
)
textView.delegate = coordinator // production wiring (PostEditorView)
textView.setSelectedRange(NSRange(location: 0, length: 0))
textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
#expect(scanned == 0, "real keystroke took the full pass: \(scanned) lines")
#expect(textView.folds.count == 1) // and the fold survived the real pipeline
// Liveness in the same harness: a structural insert through the same
// coordinator MUST scan the whole buffer (206 — see the control's
// arithmetic) — proving the instance window counts real work.
scanned = 0
textView.setSelectedRange(NSRange(location: 0, length: 0))
textView.insertText("y\n\n", replacementRange: NSRange(location: 0, length: 0))
#expect(scanned == 206, "instance window lost exact accounting: \(scanned)")
}
@Test func `full pass scans scale with the buffer at N and 2N`() {
/// The control that keeps the zero-pin honest: route the SAME edit
/// shape to the full pass (a multi-line replacement — structural
/// edits never take the cheap path) and the instrument must report
/// the whole buffer, growing with it. If the observer ever goes
/// dead (unwired, wrong seam), this fails — the zero-pin above can
/// never pass vacuously.
func fullPassScans(filler: Int) -> Int {
let text = budgetText(filler: filler)
let textView = makeView(text)
guard let parent = ProseList.parents(in: text).first else {
preconditionFailure("fixture must arm a parent")
}
textView.toggleFold(parent)
var scanned = 0
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x\n\n")
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n")
textView.refreshFolds { scanned += $0 }
return scanned
}
let atN = fullPassScans(filler: 200)
let at2N = fullPassScans(filler: 400)
// 4 fixture lines + filler + 2 from the split intro line ("x\n\n"
// turns intro into three lines) — exactly the buffer's line count.
#expect(atN == 206, "control lost exact line accounting: \(atN)")
#expect(at2N == 406, "control lost exact line accounting: \(at2N)")
#expect(at2N > atN, "the instrument must scale with the buffer")
}
}
-117
View File
@@ -1,117 +0,0 @@
//
// ProviderCredentialTests.swift
// MuseionTests
//
// ## Scenario: one credential resolution behind probe and readiness
// From #181
//
// Given a provider, its `.env` key (possibly empty), and the endpoint the
// key would ride
// When the ONE credential resolution runs — Settings' Test Connection and
// pass readiness both call it
// Then a pasted key always wins, a keyless provider on its official
// endpoint borrows the shared Portal session key, and every other empty
// case refuses honestly — the implicit session credential never rides a
// user-set URL.
import Foundation
@testable import Museion
import Testing
@Suite("Provider credential resolution")
struct ProviderCredentialTests {
/// Writes a portal auth store carrying `agent_key` and answers its path.
private func makeAuthFile(key: String) throws -> String {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("cred-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let path = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"\#(key)"}}}"#.write(toFile: path, atomically: true, encoding: .utf8)
return path
}
/// A pasted key always wins — no provider's resolution touches the
/// Portal auth store when its own key is set.
@Test func `pasted key wins for every provider`() async {
let missingAuth = FileManager.default.temporaryDirectory
.appendingPathComponent("cred-missing-\(UUID().uuidString)").path
for provider in ModelProvider.allCases {
let resolved = await ProviderCredential.resolve(
provider: provider,
envKey: "sk-pasted",
endpoint: provider.defaultEndpoint,
portalAuthPath: missingAuth,
)
#expect(resolved == .key("sk-pasted"))
}
}
/// A keyed provider with no key refuses the paste path — the probe's
/// old empty-key precondition, now the shared rail's.
@Test func `keyed provider without a key refuses the paste path`() async {
let resolved = await ProviderCredential.resolve(
provider: .anthropic,
envKey: "",
endpoint: ModelProvider.anthropic.defaultEndpoint,
portalAuthPath: "/nonexistent/auth.json",
)
guard case let .refused(message) = resolved else {
Issue.record("expected a refusal, got \(resolved)")
return
}
#expect(message == "no API key set — paste the key first")
}
/// The keyless fallback: nous on the official endpoint (trailing slash
/// tolerated) borrows the session's agent_key.
@Test func `keyless provider borrows the portal session key on the official endpoint`() async throws {
let authPath = try makeAuthFile(key: "ak-shared-123")
for endpoint in [
ModelProvider.nous.defaultEndpoint,
ModelProvider.nous.defaultEndpoint + "/",
] {
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: endpoint,
portalAuthPath: authPath,
)
#expect(resolved == .key("ak-shared-123"))
}
}
/// Finish-audit #175, on the shared rail: the implicit session
/// credential never rides a user-set URL — a custom endpoint with an
/// empty key refuses even though the login exists.
@Test func `the session key never rides a custom endpoint`() async throws {
let authPath = try makeAuthFile(key: "ak-shared-123")
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: "http://proxy.example/v1",
portalAuthPath: authPath,
)
guard case let .refused(message) = resolved else {
Issue.record("expected the custom-endpoint refusal, got \(resolved)")
return
}
#expect(message.contains("paste an API key"))
}
/// Keyless with neither key nor login names the portal login path,
/// not a bare "no key".
@Test func `keyless without key or login names the portal path`() async {
let resolved = await ProviderCredential.resolve(
provider: .nous,
envKey: "",
endpoint: ModelProvider.nous.defaultEndpoint,
portalAuthPath: "/nonexistent/auth.json",
)
guard case let .refused(message) = resolved else {
Issue.record("expected a refusal, got \(resolved)")
return
}
#expect(message.contains("hermes auth add nous"))
}
}
+1 -2
View File
@@ -27,8 +27,7 @@ struct ReadingPresenterTests {
@Test
func `stamper rewrites attributes`() {
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
let expected = "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>"
#expect(ReadingPresenter.stampHTML(html) == expected)
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>")
}
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
-25
View File
@@ -157,14 +157,6 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable {
queue.sync { heldLoad != nil }
}
/// True while a hangOnPrompt prompt is parked — the #179 repoint pin
/// polls for the PARK (runningPass flips before the one-shot engine
/// even spawns; ending the hold in that window false-fails under load,
/// the #30/#147 flake family).
var hasHeldPrompt: Bool {
queue.sync { heldPromptID != nil }
}
// MARK: EngineTransport
/// The fake always spawns cleanly — there is no process.
@@ -242,23 +234,6 @@ final class ScriptedEngine: EngineTransport, @unchecked Sendable {
}
}
/// Test hook (#179 audit): release a held prompt as a NORMALLY ended
/// turn — session/cancel answers "cancelled"; the mid-pass repoint pin
/// needs the turn to end .ended after the hold. Returns false (and
/// no-ops) when nothing is held — e.g. the parked request already hit
/// its deadline under machine load — so the caller can fail loudly
/// instead of reading a confusing nil strip.
@discardableResult
func endHeldPrompt() -> Bool {
queue.sync {
guard let id = self.heldPromptID,
let continuation = self.parked.removeValue(forKey: id) else { return false }
self.heldPromptID = nil
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return true
}
}
/// Test hook: the kill(pid, SIGKILL) rail's in-process twin (#178 B2) —
/// the engine dies unexpectedly: onCrash fires, every pending request
/// fails. The crash-restart pins drive real crashes through this.
+5 -5
View File
@@ -31,12 +31,12 @@ struct SessionLifecycleTests {
let defaultSession = try #require(mentor.activeEntry)
let rosterBefore = mentor.roster.count
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
await model.runPass(.pass1, home: home, mentor: mentor)
// The roster never grew — the pass entry is transient.
#expect(mentor.roster.count == rosterBefore)
@@ -69,7 +69,7 @@ struct SessionLifecycleTests {
/// newest-first, active; a non-nil pieceTitle rides the entry —
/// association by convention only.
@Test @MainActor func `freeform new session is rostered newest-first and active`() async throws {
let (_, _, mentor) = try makePassRig()
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
#expect(!mentor.canStartSession) // never opened — nothing may start
await mentor.openSession()
@@ -200,7 +200,7 @@ struct SessionLifecycleTests {
/// renders, the raw slash command never does, the summary streams into
/// the transcript — and is refused while a turn streams.
@Test @MainActor func `compact sends the labeled command and is refused while streaming`() async throws {
let (_, _, mentor) = try makePassRig()
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
@@ -330,7 +330,7 @@ struct SessionLifecycleTests {
#expect(SessionsPaneView.openPiece(in: nil) == nil) // no Posts at all
let post = try PostStore.writeNew(body: "# Open Piece\n", home: home)
model.select(post.id)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more