Compare commits
28
Commits
822b1b562e
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6db4cf8cf1 | ||
|
|
6aa31a419a | ||
|
|
6938826101 | ||
|
|
9aa0314564 | ||
|
|
dd8637e7c7 | ||
|
|
97893147a6 | ||
|
|
d183d735d7 | ||
|
|
c959b67f14 | ||
|
|
653ca69d1f | ||
|
|
1b0c23ae5b | ||
|
|
46e87e678c | ||
|
|
64a7eaa37e | ||
|
|
d5a515091a | ||
|
|
4a056f9c53 | ||
|
|
570abb32c0 | ||
|
|
bba4688dcb | ||
|
|
2d5073e421 | ||
|
|
07da076f41 | ||
|
|
3197b9276e | ||
|
|
23afcdf3b6 | ||
|
|
fd806e9e76 | ||
|
|
5f92241308 | ||
|
|
217a87324e | ||
|
|
d470615ac7 | ||
|
|
58355aa292 | ||
|
|
c10477da35 | ||
|
|
3bb178220f | ||
|
|
1df46a816f |
No files matched your search
@@ -0,0 +1,166 @@
|
|||||||
|
---
|
||||||
|
name: release
|
||||||
|
description: "Cut a Museion release: bump, notes, rail, DMG, tag, publish."
|
||||||
|
platforms: [macos]
|
||||||
|
version: 0.3.0
|
||||||
|
author: Hermes
|
||||||
|
metadata:
|
||||||
|
hermes:
|
||||||
|
tags: [Release, Museion, Xcode, Notarization, Gitea, apex, Micro.blog, BuyMeACoffee]
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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, then the announcements — Micro.blog and Buy Me a Coffee — each left as a **draft** for Alexander to publish. 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); neither announcement is ever published by the agent.
|
||||||
|
|
||||||
|
## 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).
|
||||||
|
- Micro.blog announcement token in the login keychain: `security find-generic-password -a micro.blog -s com.babylondreams.Museion.release-announce -w` prints it (step 11 has the one-time `add-generic-password`). When missing, Alexander generates an App Token (Micro.blog → Account → App Tokens) and the agent stores it — never the other way around.
|
||||||
|
- Ego Browser running and logged in to Buy Me a Coffee — `buymeacoffee-post` has the one-time check.
|
||||||
|
- 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.** Patch for a bug-fix cut (`X.Y.0` → `X.Y.1`), minor for a feature cut (`X.Y.1` → `X.Y+1.0`) — `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. **Micro.blog announcement — a DRAFT, never a publish.** The post goes to Micro.blog as `post-status: draft` so Alexander reviews and publishes it himself (the `preview` link lands in the report). Token: a Micro.blog **App Token** (Account → App Tokens) stored ONCE in the login keychain under its own service — never the app's production slot (`com.babylondreams.Museion.micropub`, account `micro.blog` — that is the app's live credential, see MuseionTests/AGENTS.md), never a file in the repo:
|
||||||
|
```bash
|
||||||
|
security add-generic-password -U -a micro.blog -s com.babylondreams.Museion.release-announce -w '<app token>' </dev/null
|
||||||
|
```
|
||||||
|
(The `</dev/null` is load-bearing: without it `security` prompts for a retype.) Then:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
TOK=$(security find-generic-password -a micro.blog -s com.babylondreams.Museion.release-announce -w)
|
||||||
|
curl -sS -H "Authorization: Bearer $TOK" 'https://micro.blog/micropub?q=config' # read destinations + channels
|
||||||
|
```
|
||||||
|
**`mp-destination` is mandatory on this account**: `q=config` lists three microblogs and `microblog-default` is `false` on every one, so a post without it is ambiguous. The main blog is `https://AlexKucera.micro.blog/` (name `alexanderkucera.com`); the other two are a tweets cross-post and a test blog. Article posts take `mp-channel: default` (the `channels` list: `default` = Posts, `pages` = Pages). Post:
|
||||||
|
```bash
|
||||||
|
python3 - "$TOK" <<'PY'
|
||||||
|
import json, sys, urllib.request
|
||||||
|
tok = sys.argv[1]
|
||||||
|
payload = {"type": ["h-entry"], "properties": {
|
||||||
|
"name": ["Museion X.Y.Z"],
|
||||||
|
"content": ["<the announcement, markdown>"],
|
||||||
|
"post-status": ["draft"],
|
||||||
|
"mp-destination": ["https://AlexKucera.micro.blog/"],
|
||||||
|
"mp-channel": ["default"]}}
|
||||||
|
req = urllib.request.Request("https://micro.blog/micropub", data=json.dumps(payload).encode(),
|
||||||
|
headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"}, method="POST")
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as r:
|
||||||
|
print(r.status, r.headers.get("Location"), r.read().decode())
|
||||||
|
PY
|
||||||
|
```
|
||||||
|
Body: `docs/releases/X.Y.Z.md` is too long for a microblog post — distill it to a short announcement (what was fixed in plain words, the download link, the release-page link, "Developer ID signed and notarized"). A draft does NOT syndicate, so the `syndicate-to` targets in `q=config` (Mastodon/Bluesky/Threads) are not touched until Alexander publishes. Read back before reporting: `GET '/micropub?q=source&url=<Location>'` must show `post-status: draft` and the content intact — a 2xx alone is not a result. Done when the read-back says draft and the report carries the `url` (the post's final address) and the `preview` link. `preview` is display-only — never the publish/update target. A token pasted into chat is in the transcript: recommend rotation after the run.
|
||||||
|
12. **Buy Me a Coffee announcement — a DRAFT, never a publish.** The step-11 announcement as a BMC post, left for Alexander to publish. The mechanics (Ego Browser, the `scripts/bmc.js` driver, selectors, pitfalls) live in the `buymeacoffee-post` skill; the release only fixes the `INPUT`:
|
||||||
|
```js
|
||||||
|
action: "create", mode: "draft", audience: "public",
|
||||||
|
title: "Museion X.Y.Z",
|
||||||
|
html: <the step-11 announcement as HTML>,
|
||||||
|
```
|
||||||
|
Done when `RESULT.mode` is `"draft"` and `RESULT.editUrl` is a `https://buymeacoffee.com/posts/<id>/edit` URL — the script prints `null` when the drafts list does not show the row, and that is not done. The edit URL goes in the report beside the Micro.blog `preview` link.
|
||||||
|
13. **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'` (Gitea spells it `tag_name`, not `tag`)
|
||||||
|
- Micro.blog: `POST https://micro.blog/micropub` JSON `h-entry` + `post-status: draft` + `mp-destination` (mandatory — no default blog) + `mp-channel: default` → `202` + `Location`; read back `q=source&url=…` → `post-status: draft`. Token: Keychain service `com.babylondreams.Museion.release-announce`. Never publish.
|
||||||
|
- Buy Me a Coffee: `buymeacoffee-post` → `create` + `mode: "draft"` + `audience: "public"` → `RESULT.editUrl` into the report. Never publish.
|
||||||
|
|
||||||
|
## 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. `grep -E '^\s*token:'` + `sed` is enough; PyYAML is not installed on the system python.
|
||||||
|
- `tea releases create` prints NOTHING on success (exit 0, empty output). The `tea api` read-back is the only proof — and Gitea's release JSON has `tag_name`, not GitHub's `tag`.
|
||||||
|
- `security add-generic-password -w <value>` without `</dev/null` prompts for a retype and fails with "passwords don't match" when stdin is not a tty; the item is NOT stored and the next read returns 0 chars. Always `</dev/null`, always read the length back.
|
||||||
|
- A Micro.blog post without `mp-destination` is a gamble on this account — `q=config` shows three microblogs and none is `microblog-default`. Read `q=config` before every announcement; the destination set can change.
|
||||||
|
- `q=source&url=…` read-back does not echo `mp-destination` or `mp-channel`; the post's `Location` host (`alexanderkucera.com`) is the evidence the destination took.
|
||||||
|
- `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`. Micro.blog: `GET https://micro.blog/micropub?q=source&url=<Location>` → `post-status: draft`, content intact. Buy Me a Coffee: `RESULT.mode: "draft"` + `RESULT.editUrl` in the report. Both drafts sit in Alexander's queues awaiting his publish.
|
||||||
@@ -2,9 +2,11 @@
|
|||||||
.swiftpm/
|
.swiftpm/
|
||||||
DerivedData/
|
DerivedData/
|
||||||
_build/
|
_build/
|
||||||
|
dist/
|
||||||
**/xcuserdata/
|
**/xcuserdata/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
.claude/
|
.claude/
|
||||||
*.profraw
|
*.profraw
|
||||||
.secrets
|
.secrets
|
||||||
|
.hermes
|
||||||
@@ -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.
|
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 26.5+, 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 27+ (`MACOSX_DEPLOYMENT_TARGET = 27.0`, Apple Silicon only), 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.
|
- **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).
|
- **License**: GPL-3.0-or-later (ADR-0002).
|
||||||
|
|
||||||
@@ -20,6 +20,7 @@ swiftformat . && swiftlint . # lint (r
|
|||||||
./scripts/full-test.sh summary # finished run's executed/passed/failed
|
./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/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/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
|
# DOX framework
|
||||||
@@ -113,7 +114,8 @@ 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 |
|
| `Museion/AGENTS.md` | App target — SwiftUI app shell, assets, entitlements |
|
||||||
| `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) |
|
| `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) |
|
||||||
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
|
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
|
||||||
| `scripts/` | Verify rail + hooks + build/deploy scripts — contracts live in each script's header; full-test.sh is the sanctioned verify rail (#190), no child doc |
|
| `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 (apex refresh → bump → notes → rail → tag → DMG → go-gated push + Gitea release → Micro.blog + Buy Me a Coffee announcements as drafts); no child doc |
|
||||||
| `docs/AGENTS.md` | Durable documentation — ADRs and their conventions |
|
| `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 |
|
| `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 |
|
| `GLOSSARY.md` | Binding project glossary — shared vocabulary for app, mentor, and docs |
|
||||||
@@ -132,50 +134,6 @@ 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`.
|
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** (7133 symbols, 36787 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
|
||||||
|
|
||||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
|
||||||
|
|
||||||
## 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
|
## Project Learnings
|
||||||
|
|
||||||
<!-- distill-learnings: project-learnings -->
|
<!-- distill-learnings: project-learnings -->
|
||||||
@@ -188,12 +146,16 @@ This project is indexed by GitNexus as **museion** (7133 symbols, 36787 relation
|
|||||||
- 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)
|
- 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)
|
- 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)
|
- 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)
|
||||||
|
- A wedged TUI shell plus `execute_code` blocked in an unattended turn still leaves a child's terminal — delegate the rail or flip run to it (detached subprocesses as fallback) (#207)
|
||||||
|
|
||||||
### Testing
|
### 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.
|
- 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.
|
||||||
|
- macOS 27.2 (verified on 27.2.1) routes a drag to the DEEPEST destination — a LIVE NSTextView registers itself for drag types (a bare `NSTextView(frame:)` reads `registeredDraggedTypes == []`, so a standalone probe lies; lldb on the running app shows the list), matches Finder drags via `NSFilenamesPboardType`, and its stock `performDragOperation` pastes the file path; the window-level SwiftUI `.dropDestination` never fires over it — the inverse of the 27.0.1 ruling #141 was verified on. Drag routing is an OS-version claim: own the drop at the view (override the `NSDraggingDestination` methods without super) and re-dogfood after every OS point release; instrumented real handlers + one human drag settle which destination fires (#141 follow-up, 2026-12-03)
|
||||||
|
- A pin that drives a seam introduced WITH the fix has no broken-build past to fail on — drive the framework entry point itself (`DragInfoStub` for `NSDraggingDestination`, the scripted transport for the ACP wire), or the pin passes with the fix reverted (#141 follow-up, `image-drop-27-2-drag-routing-pastes-path`)
|
||||||
- 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)
|
- 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)
|
- 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)
|
||||||
- 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)
|
- 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)
|
||||||
|
- A subscript after a count expectation (`log.requests[2]` after `#expect(count == 3)`) traps the hosted runner — every queued test reports `Crash:` too; read elements through an optional accessor (#206)
|
||||||
- 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)
|
- 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)
|
- 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)
|
- 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)
|
||||||
@@ -205,10 +167,15 @@ This project is indexed by GitNexus as **museion** (7133 symbols, 36787 relation
|
|||||||
- 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)
|
- 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)
|
- 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)
|
- 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)
|
||||||
|
- `value of type 'X' has no member` while the emitted module DOES carry the symbol is a spelling drift between targets, not a stale build — grep the exact name across app AND tests before hunting binaries: a fresh test file's `microblogStatus` against the code's `micropubStatus` reads exactly like the stale-binary signature above and cost a DerivedData dive (#206)
|
||||||
|
- A flip proves a guard only when it SOLELY causes a red pin — two flips on one pin mask each other (split-off hid dedupe; never-append hid `finished`); re-flip masked guards alone (#207)
|
||||||
### Trust boundaries
|
### 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 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)
|
- 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)
|
- 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)
|
||||||
|
- A format gate is not an ownership gate — when a change raises a sink's stakes (status flip → content replace), re-ask who may write the value, not merely whether it is well-formed (#206)
|
||||||
|
- Escape the escape character first (`\\` before `\"`) — a renderer that escapes only its delimiter breaks once the scanner honors a generic escape: a trailing backslash swallows the separator (#207)
|
||||||
|
- A later step targets what the earlier step touched, never the caller's copy — publishing the sheet's stale URL would stamp a dead address over the real memory (#207)
|
||||||
|
|
||||||
## Session Logs
|
## Session Logs
|
||||||
|
|
||||||
@@ -216,15 +183,15 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
|||||||
|
|
||||||
<!-- write-log: window-start -->
|
<!-- write-log: window-start -->
|
||||||
| Date | Log |
|
| Date | Log |
|
||||||
| --- | --- |
|
|------|-----|
|
||||||
| 2026-11-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-12-04 | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_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-12-04 | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_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-12-04 | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_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-12-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_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-12-03 | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) |
|
||||||
| 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) |
|
| 2026-12-03 | [20261203-release-012-image-drop-fix_log.md](20261203-release-012-image-drop-fix_log.md) |
|
||||||
| 2026-11-13 | [20261113-cold-turkey-full-tokenization_log.md](docs/devlog/20261113-cold-turkey-full-tokenization_log.md) |
|
| 2026-12-03 | [20261203-image-drop-27-2-drag-routing-pastes-path_log.md](20261203-image-drop-27-2-drag-routing-pastes-path_log.md) |
|
||||||
| 2026-11-11 | [20261111-fix-library-search-stale-after-mutation_log.md](docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md) |
|
| 2026-12-03 | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_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-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_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-30 | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) |
|
||||||
<!-- write-log: window-end -->
|
<!-- write-log: window-end -->
|
||||||
@@ -4,10 +4,49 @@ All notable changes to this project will be documented in this file. The format
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **publish:** Micro.blog categories travel (#207) — the piece's `category:` frontmatter line rides the send (one line, `category: [Tech, Notes]`; a bare `category: Essays` is one category). A first send carries the list beside the title and content; a re-send replaces the post's categories with exactly the piece's list — but only when the piece has the line at all (no line leaves whatever the blog has; an empty `category: []` clears them). Naming a category Micro.blog doesn't know creates it there, so there is no separate create step. The publish sheet has a **Categories** field: comma-separated, with the system completion menu over your blog's existing categories (fetched when the sheet opens; a failed fetch stays silent and a typed new name still works). Clicking any number of categories adds them all — the menu stays open — a half-typed word is replaced by the pick, and a name already in the field is never offered again. The edit lands on the piece when you send (Cancel/Done discard it); Publish with a pending category edit applies it first — to the post the piece remembers, never a stale address — and never publishes after a failed update. +39 tests (the wire contract, the codec incl. its backslash escaping, the model's write-then-send order and the sanitized name, the blog's category list, publish-applies-first and targeting the post the send touched, the sheet field's picks-add completion and menu, the import keeping the line), each seen red first. Suite 791
|
||||||
|
|
||||||
|
- **publish:** the library shows where each piece stands on Micro.blog (#206) — a published piece's row reads `published <date>` and its menu opens the live post; a sent-but-unpublished one reads `draft on Micro.blog`. Publish is remembered now (`micropub_published` stamped in the piece's frontmatter — the sheet used to flip the draft and forget, so nothing on disk ever said a piece was out). Sending a piece again no longer duplicates it: a piece that remembers its post updates that post in place (same URL — a draft refreshes for review, a published piece edits live via **Update Live Post**), and an image whose bytes haven't changed rides its earlier upload instead of uploading a second copy (a per-piece `.museion-uploads.json` memo keyed by content hash). When Micro.blog answers 404 — the post was deleted there — the piece forgets the dead link and the sheet offers a fresh draft instead of failing forever. A file brought in by Import carries no Micro.blog memory: its `micropub_url`/`micropub_published` lines are dropped at the boundary, so a file from someone else can never aim a send at one of your existing posts. Pieces published before this build read as drafts until their next Publish (or the `micropub_published` key is added to the frontmatter by hand — `yyyy-MM-dd'T'HH:mm:ss`, local time). The row's micro-label shows the status in origin's place (the 178pt row cannot hold both); VoiceOver reads both.
|
||||||
|
|
||||||
|
- **settings:** **Micro.blog** page in Settings — the app token's home (unticketed; owner report 2026-12-04) — the token could only be entered in the publish sheet, and that field came back only after a 401/403, so a saved token had no standing way to be replaced or removed (a 503 left the writer stuck with whatever was stored). The new sidebar destination, after Provider Keys, writes the SAME login-keychain slot the sheet reads (`MicropubTokenStore`): a status row under the field (✓ Token saved in your Keychain / No token saved), a Save field that replaces the stored token, and a Remove button while one is stored. `saved` is read back from the Keychain after every write instead of assumed — a locked keychain fails the save and the status row says so rather than claiming "stored". The publish sheet picks up a Settings-saved token unchanged, and names it when it sends with the stored one (the field's absence alone never said which token a send carried). No new pins (a view over the already-pinned token store; the repo pins pure seams, not SwiftUI). Suite 736
|
||||||
|
|
||||||
|
- **library:** **Reveal in Finder** and **Copy Path** on every piece row — the library column's menu and the Archive pane's (#205) — one shared `FinderHandOffButtons` fragment in the workspace chrome over a model-resolved path: `PostsModel.fileURL(for:)` answers the piece's `post.md` through the one `PostStore.folder(of:home:)` resolver against the watched Home (never the scan snapshot), and a vanished piece answers nil so both entries no-op instead of revealing a stale path. Reveal selects the file in Finder; Copy Path puts the POSIX path on the pasteboard (Finder's own form; the pasteboard is cleared first). Library placement sits between Move to Archive and the destructive Trash behind a divider; the Archive menu appends after Convert. +3 tests (projects/ resolve, archive/ resolve, vanished → nil), flip-verified — bypassing the resolver reddens exactly the vanished and archive pins. Suite 735
|
||||||
|
|
||||||
|
- **fix cards:** **Jump** on a Fix Card selects the anchor's span in the piece's editor and makes the main window key (#204) — the borderless button sits in every non-stale card's action row (closed cards keep it; a stale anchor has nothing to land on); the span is the card's quote at its 1-based occurrence, resolved against the LIVE session text so a dirty buffer still lands, and it rides the reading flip-back's caret rail (one token counter; a zero-length hint stays a bare caret, a non-zero range selects). A jump leaves reading mode first, writes nothing, and re-fires on every click. Two review rounds closed the view-layer gaps the pure pins could not see: a jump dropped in reading mode, a main window that never became key (`NSApp.activate` is a no-op once the palette's click activated the app), a leading-blank caret hop that moved a span onto the title, and a cursor record taken before the scroll. +3 tests (`anchorRange` occurrence math with a UTF-16 fixture, the model's reveal stamp, the editor's `landingSpan`), all flip-verified. Suite 732
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **publish:** A Micro.blog 5xx names their outage instead of a bare `HTTP 503` (unticketed; owner report 2026-12-04) — their errors arrive as HTML pages, never Micropub JSON, so `decodeFailure` fell through to the status code and the sheet read "Micro.blog said 503: HTTP 503", which says nothing about whose side it is on. A live probe at report time found the endpoint healthy (25/25 tokenless POSTs answered the usual 400; their news feed logs repeated 503 incidents), so the 503 was theirs and transient. The decode now answers `unavailable on their side — retry in a few minutes (status.micro.blog)` for any 5xx that carries no JSON description — ONE decode, so create, publish, q=config, and media uploads all speak it; a described 5xx keeps its description, a 4xx keeps the bare status. +1 test (a 503 over an HTML body → the their-side wording; a 422 over the same body → `HTTP 422`; a 502 with `error_description` → the description), flip-verified — the guard off reddens exactly that pin with `detail → "HTTP 503"`. Suite 736
|
||||||
|
|
||||||
|
## [0.1.2] - 2026-12-03
|
||||||
|
|
||||||
|
Human-readable notes: [docs/releases/0.1.2.md](docs/releases/0.1.2.md).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **editor:** Dropping an image file on the prose editor pastes the file path instead of ingesting it (#141 follow-up; macOS 27.2.1 dogfood 2026-12-03; unticketed fix) — #141 was field-verified on 27.0.1, where the window-level SwiftUI `.dropDestination` starved every deeper destination; 27.2 routes a drag to the DEEPEST destination, and a live NSTextView registers itself for drag types (it matches Finder drags through `NSFilenamesPboardType`), so its stock `performDragOperation` → `readSelection` pasted the path and the window destination never fired — the same for a markdown file dropped on the editor (path instead of guest). The editor text views now share a `FileDropTextView` base that owns the drops landing on them: URL-bearing drags route (never `super`) — the prose editor through the one new `AppGateState.routeFileDrop` (Cold Turkey guard → markdown → guest, anything else → `ingestDrop`), which the window destination also uses for drops landing outside the editor (one router, one surface per drag; a landed drop hops to Posts as markdown always did); the outline rows have no route and bounce instead of pasting the path; text-only drags keep the stock drop; URL-less drags bounce. The pasteboard probe is memoized per `changeCount` (a 20k-URL drag measured 137 ms per mouse-move uncached). `ingestDrop` refuses web URLs loudly with the type strip (a browser image drag has no file to copy), and a file that vanished between drag and drop refuses as missing, not as a folder. +9 tests — the drag overrides driven through a real `NSDraggingInfo` mock (a Finder-shaped drag routes and never pastes the path, an unrouted view claims nothing, a text drag keeps the stock drop, raw image data bounces, the probe follows the pasteboard, the outline rows bounce, web URLs and vanished files refuse with the right notice) and the router's own pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal); all 9 flip-verified. Verified with one real Finder drag on 27.2.1. Suite 729
|
||||||
|
|
||||||
|
## [0.1.1] - 2026-12-03
|
||||||
|
|
||||||
|
Human-readable notes: [docs/releases/0.1.1.md](docs/releases/0.1.1.md).
|
||||||
|
|
||||||
### Fixed
|
### 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
|
- **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:** 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
|
- **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
|
||||||
|
|||||||
+20
@@ -123,6 +123,10 @@ _Avoid_: reject, dismiss
|
|||||||
Accepting a mechanical Fix Card so its edit lands in the file. Demonstration cards never offer it — they close Done or Skip.
|
Accepting a mechanical Fix Card so its edit lands in the file. Demonstration cards never offer it — they close Done or Skip.
|
||||||
_Avoid_: accept, fix (verb)
|
_Avoid_: accept, fix (verb)
|
||||||
|
|
||||||
|
**Jump**:
|
||||||
|
Selecting a Fix Card's anchor span in the piece's editor — the span the card points at, revealed and selected, the editor made key. A view act: records nothing, writes nothing. A stale anchor offers none.
|
||||||
|
_Avoid_: go to, scroll to, reveal
|
||||||
|
|
||||||
**Done**:
|
**Done**:
|
||||||
Closing a Fix Card because the writer rewrote the span — the demonstration lane's terminal, beside Apply and Skip. Records nothing.
|
Closing a Fix Card because the writer rewrote the span — the demonstration lane's terminal, beside Apply and Skip. Records nothing.
|
||||||
_Avoid_: applied, complete
|
_Avoid_: applied, complete
|
||||||
@@ -152,3 +156,19 @@ _Avoid_: permission mode
|
|||||||
**Provenance**:
|
**Provenance**:
|
||||||
The origin record carried by a Fix Card or Learning (piece, date, engine).
|
The origin record carried by a Fix Card or Learning (piece, date, engine).
|
||||||
_Avoid_: metadata
|
_Avoid_: metadata
|
||||||
|
|
||||||
|
## Discovered Terms
|
||||||
|
|
||||||
|
<!-- distill-learnings: discovered-terms -->
|
||||||
|
|
||||||
|
### Publish Record
|
||||||
|
What a Piece remembers about Micro.blog in its frontmatter: `micropub_url` (the post it was sent to) and, once Publish succeeded from here, `micropub_published` (the stamp, local time). Museion bookkeeping — written only by the app or the writer's own hand; Import drops both keys. A remembered URL without the stamp is a draft on Micro.blog.
|
||||||
|
_Avoid_: publish state (it is a record on disk, never a live query), status (that is Pass State)
|
||||||
|
|
||||||
|
### Upload Memo
|
||||||
|
The per-Piece sidecar `.museion-uploads.json` mapping an illustration's bytes (`sha256`) to the URL Micro.blog returned, so an unchanged image uploads once. Finder-invisible, dies with the Piece folder, never trusted from outside — a symlinked memo or an untrustworthy entry is no memory.
|
||||||
|
_Avoid_: upload cache (it is Piece-local bookkeeping, not a shared cache)
|
||||||
|
|
||||||
|
### Category
|
||||||
|
A Micro.blog classification carried as the Piece's one-line `category:` frontmatter list (`category: [Tech, Notes]`; a bare scalar is one category, `[]` is explicitly none). Travels with every send; a name Micro.blog does not know is created there at the send. Import keeps it — the writer's classification, unlike the Publish Record keys — and a re-send replaces the post's categories only when the line exists.
|
||||||
|
_Avoid_: type (that is Content Type), tag
|
||||||
@@ -405,6 +405,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||||
|
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
@@ -423,7 +424,7 @@
|
|||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
REGISTER_APP_GROUPS = YES;
|
REGISTER_APP_GROUPS = YES;
|
||||||
@@ -441,6 +442,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||||
|
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
@@ -459,7 +461,7 @@
|
|||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
REGISTER_APP_GROUPS = YES;
|
REGISTER_APP_GROUPS = YES;
|
||||||
@@ -482,7 +484,7 @@
|
|||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||||
@@ -504,7 +506,7 @@
|
|||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||||
@@ -524,7 +526,7 @@
|
|||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||||
@@ -544,7 +546,7 @@
|
|||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 0.1.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||||
|
|||||||
+18
-17
@@ -15,7 +15,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
|||||||
- `AppMetadata` is the single source for displayed name/tagline; members `nonisolated`.
|
- `AppMetadata` is the single source for displayed name/tagline; members `nonisolated`.
|
||||||
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
||||||
- App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no `.entitlements` file.
|
- App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no `.entitlements` file.
|
||||||
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007).
|
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007), and the per-piece Finder-invisible sidecars that die with the piece folder — the cursor state `.museion-state.json` (#66) and the Micro.blog upload memo `.museion-uploads.json` (#206).
|
||||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
|
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
|
||||||
|
|
||||||
## Workspace shell
|
## Workspace shell
|
||||||
@@ -23,16 +23,16 @@ 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/`.
|
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).
|
- `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).
|
- `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`: the drop surface for drags that land OUTSIDE the editor — macOS 27.2.1 routes a drag to the DEEPEST destination, so over the editor the text view takes the drag itself (`FileDropTextView`'s drag handlers) and this destination never fires (the inverse of the 27.0.1 ruling #141 was verified on); both route through `AppGateState.routeFileDrop` — the ONE file-drop router (pure-markdown → external guest, anything else → `ingestDrop`, Cold Turkey–guarded; a mixed md+image set and web URLs refuse loudly). A landed drop hops to Posts (unreachable for images today — the editor mounts only there). 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`.
|
- `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`. Row menu: Move Back / Rename / Convert, plus #205 Reveal in Finder / Copy Path and #206 Open on Micro.blog.
|
||||||
- `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).
|
- `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.
|
- `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. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops. #206 `MicroblogHandOffButton` — Open on Micro.blog, only for a PUBLISHED piece (a draft's final URL answers Not Found until the post is published — owner-verified 2026-12-04); mounted beside the Finder pair in both menus.
|
||||||
- `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.
|
- `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.
|
- `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 (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). 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.
|
- `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/Reveal in Finder/Copy Path/Open on Micro.blog (#206, published pieces)/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. #206: the mono-11 micro-label shows the piece's Micro.blog status when it has one (`published <date>` / `draft on Micro.blog`) in origin's place — 178pt of row content cannot carry both — and VoiceOver reads both (`accessibilityText`); origin stays one hover away (the label's tooltip).
|
||||||
- `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.
|
- `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` through the ONE trust gate (`Micropub.rememberedURL`, format-only — ownership is settled upstream: the import boundary drops the key, so only Museion or the writer's own hand writes one); #206 `micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape, read by the shared `parseStamp`) and the row label `micropubStatus` (`published <date>` / `draft on Micro.blog` / 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.
|
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`), `stampFormat` (the frontmatter timestamp shape both stamp writers and the reader share), 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, and the Micro.blog bookkeeping dropped: `micropubKeys` — #206, a foreign file carries no post of this library), update-keys (`updating` — the in-place line-walk, every other line byte-identical; `dropping:` removes named keys' lines — the import and the 404 forget). 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. #207 the one-line `category:` list codec: `categories(in:)` reads the line (bracketed list, a bare scalar = ONE category, empty/absent = none) and `categoryValue(_:)` renders it — both over the unbracketed `categoryList`/`categoryListValue` and the one segment scanner `categorySegments` the publish sheet's field also speaks (ONE quote-aware comma-list parser: commas outside double quotes split, one pair of quotes stripped, `\\` and `\"` escaped on render and unescaped on read, empties dropped, first occurrence wins; newlines/control characters never reach the line-bounded sink).
|
||||||
- `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 `` builder.
|
- `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 and the Micro.blog bookkeeping dropped (#206: an imported `micropub_url` would aim the next send's content replace). 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; a file the disk can't stat refuses as `missing`, never as a folder); `illustrationRef` is the one `` builder. `stampMicropub` / `forgetMicropub` — the frontmatter-only micropub stamps (`micropub_url`, the #206 publish record `micropub_published`, and #207 the `category:` line a sheet edit writes at the send — `[]` renders `category: []`; on a 404 the two micropub lines are REMOVED — `forgetMicropub` throws when that write cannot land, so a failed clear refuses instead of claiming the link is gone), outside the write rail.
|
||||||
- `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).
|
- `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).
|
- `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. `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.
|
||||||
@@ -40,20 +40,21 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
|||||||
- `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).
|
- `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).
|
- `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.
|
- `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 `` 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.
|
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubCategories.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; #207 the piece's `category:` list travels — a create carries `category` ONLY when non-empty, and naming a category Micro.blog doesn't know CREATES it there (no separate create call); 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; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `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) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `` 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; `queryRequest(_:token:)` is the one `GET <endpoint>?q=…` builder (config + the category list). Categories: `blogCategories(token:)` (`q=category`, `MicropubCategories.swift`) = the blog's own category names for the sheet's suggestions — the root `categories` strings, else `microblog-categories`'s `name` fields, trimmed, empties dropped; any failure or non-2xx is `[]` (no suggestions is not an error — the sheet stays silent, and a rejected token surfaces on the send itself). The sheet's Categories field (`MicropubPublishSheet.swift`) is a comma list in the codec's unbracketed form with the system completion menu over `blogCategories` (fetched on open; a failed fetch is silent — a typed new name creates the category at the send); the system REPLACES the whole field text with a completion, so `MicropubCategoryField.completion` IS the merge — a pick ADDS, a half-typed last word is replaced, a present name is never offered; the edit lands at the send via `micropubSend(categories:)` (Publish applies it first and flips the post that send touched — never the sheet's possibly-stale URL); the field syncs from disk over `openPieceCategories()` (the model's read of the open piece — never the scan snapshot) on open and after a forget, settles to the canonical text after a successful send, and after a failed step only its BASELINE re-syncs (the send writes the line before the wire, so a later clear of the field must still count as an edit). 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; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live; #207 `replace` carries `category` ONLY when the piece has the `category:` line — opt-in by key, `[]` is sent and clears the post's categories, no line leaves the blog's); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the Line truncated
|
||||||
- `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.
|
- `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`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — 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; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSend` (#206; was `micropubSendDraft`) = guards → flush → (#207 a non-nil `categories:` edit lands as the piece's `category:` line FIRST — a failed write REFUSES the send with nothing on the wire) → ONE disk read serves the wire fields, the categories, and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update (`stampCategories` + `updateRememberedOrCreate` are its two steps); `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), #207 runs `micropubSend` FIRST when `categories:` is non-nil — the remembered post, or the fresh draft a create returned, is what gets published, and a failed send returns its outcome with NO publish (disk and blog never silently disagree) — then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `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.
|
- `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).
|
- `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`).
|
- `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`).
|
||||||
- `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.
|
- `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.
|
- `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.
|
- `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).
|
- `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). Rides `FileDropTextView` with no route mounted: a file drag landing on a row bounces (no path paste).
|
||||||
- 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).
|
- `FileDropTextView.swift` — the editor text views' drag base (macOS 27.2.1 routing): a live NSTextView registers itself for drag types and receives the drag a window-level SwiftUI destination never sees; URL-bearing drops route through `onFileDrop` (nil = bounce), text-only drops keep the stock drop, everything else bounces — never `super` for URLs (stock NSTextView pastes the dropped file's PATH via `readSelection` on NSFilenamesPboardType). The pasteboard probe is memoized per `changeCount` (`draggingUpdated` fires per mouse-move).
|
||||||
|
- 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). `ProseListTextView` rides `FileDropTextView` with `onFileDrop` → the gate's `routeFileDrop`, so file drags landing on it ingest (never paste the path); `lastIngestNotice` is the refusal text the pins read.
|
||||||
- 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).
|
- 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 · Micro.blog (the app token's home — `MicroblogSettingsPage` in SettingsPagesView.swift: a standing saved-status row / replace / remove over `MicropubTokenStore`); 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.
|
||||||
- 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.
|
- 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 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 (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.
|
||||||
- `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.
|
- `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)
|
## Engine check (gateless launch)
|
||||||
@@ -77,7 +78,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
|||||||
## museion-tools MCP server
|
## museion-tools MCP server
|
||||||
|
|
||||||
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam. #177: both submit tools decode through `ToolPayloads` (below) — the strict entry throws named `CardError`s (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias).
|
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam. #177: both submit tools decode through `ToolPayloads` (below) — the strict entry throws named `CardError`s (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias).
|
||||||
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `appliedText` = the pure nth-occurrence mechanical apply (nil, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
|
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `anchorRange` = the nth-occurrence span (nil = stale, empty quote, or occurrence below 1 — never a wrong span; the lane never gates it); `appliedText` = the mechanical apply over that span (lane-gated, nil on a stale anchor, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
|
||||||
- `LearningDecay.swift` — the pass clock `learnings/pass-counts.json` (lenient read, clamped values); `passesHidden` is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); `dismiss` stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
|
- `LearningDecay.swift` — the pass clock `learnings/pass-counts.json` (lenient read, clamped values); `passesHidden` is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); `dismiss` stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
|
||||||
- `ToolPayloads.swift` — #177: THE tool-payload decoder, one home for the `submit_fix_cards`/`submit_research_notes` wire shapes; the MCP server (strict — required fields throw `CardError`) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in `ToolPayloadsTests` — a shape change fails one suite.
|
- `ToolPayloads.swift` — #177: THE tool-payload decoder, one home for the `submit_fix_cards`/`submit_research_notes` wire shapes; the MCP server (strict — required fields throw `CardError`) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in `ToolPayloadsTests` — a shape change fails one suite.
|
||||||
|
|
||||||
@@ -86,7 +87,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
|||||||
- `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.
|
- `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.
|
- `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).
|
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
|
||||||
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
|
- `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; #204 **Jump** on every non-stale card that still shows an action row (a closed-and-promoted card has none) — leaves reading mode, selects the anchor span in the editor, reveals it, and makes the main window key (the coordinator owns `tv.window`; `NSApp.activate` is a no-op once the palette's click already activated the app)), 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). #200: quit FIRST routes through `WritingLockAppDelegate.applicationShouldTerminate`'s departure gate (`AppGateState.init` registers `PostsModel.active`) — a piece that can't depart blocks quit with one spoken reason; willTerminate's `posts.shutdown()` stays as the belt (conflict-held flush + watcher stop).
|
||||||
|
|
||||||
## Work Guidance
|
## Work Guidance
|
||||||
|
|||||||
@@ -134,6 +134,9 @@ struct ArchivePaneView: View {
|
|||||||
model.stageConversion(post)
|
model.stageConversion(post)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Divider()
|
||||||
|
MicroblogHandOffButton(post: post)
|
||||||
|
FinderHandOffButtons(model: model, post: post)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
//
|
||||||
|
// FileDropTextView.swift
|
||||||
|
// Museion
|
||||||
|
//
|
||||||
|
// #141 (macOS 27.2.1): a drag goes to the DEEPEST destination, and a live
|
||||||
|
// NSTextView registers itself for drag types — so a file drag landing on
|
||||||
|
// an editor text view is delivered to the view, not to the window-level
|
||||||
|
// SwiftUI .dropDestination (the inverse of the 27.0.1 ruling #141 was
|
||||||
|
// verified on). Stock NSTextView handling pastes the dropped file's PATH
|
||||||
|
// (`readSelection` on NSFilenamesPboardType). This base replaces that for
|
||||||
|
// URL-bearing drags and leaves text-only drags to the stock behavior. The
|
||||||
|
// prose editor routes through the gate's one router (`AppGateState.
|
||||||
|
// routeFileDrop`); the outline rows have no route and bounce.
|
||||||
|
//
|
||||||
|
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
class FileDropTextView: NSTextView {
|
||||||
|
/// Where a URL-bearing drop routes. Nil = the view claims nothing
|
||||||
|
/// (outline rows: images don't ingest there, so the drag bounces
|
||||||
|
/// instead of pasting a path).
|
||||||
|
var onFileDrop: (([URL]) -> Bool)?
|
||||||
|
|
||||||
|
/// One classification per pasteboard state — `draggingUpdated` fires on
|
||||||
|
/// every mouse-move and the read is a pasteboard round-trip (a hostile
|
||||||
|
/// 20k-URL drag measured 137 ms per move uncached).
|
||||||
|
private var dropProbe: (changeCount: Int, kind: DropKind)?
|
||||||
|
|
||||||
|
enum DropKind: Equatable {
|
||||||
|
/// File URLs (Finder) or web URLs (browser) — routed, never pasted.
|
||||||
|
case urls([URL])
|
||||||
|
/// Text only (a selection drag, text from another app) — the stock
|
||||||
|
/// NSTextView drop, which inserts text and nothing else.
|
||||||
|
case text
|
||||||
|
/// Raw image data, file promises — anything URL-less and text-less.
|
||||||
|
case none
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The drag's URLs — or nil when it carries none.
|
||||||
|
static func droppedURLs(from pasteboard: NSPasteboard) -> [URL]? {
|
||||||
|
let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: nil) as? [URL] ?? []
|
||||||
|
return urls.isEmpty ? nil : urls
|
||||||
|
}
|
||||||
|
|
||||||
|
static func classify(_ pasteboard: NSPasteboard) -> DropKind {
|
||||||
|
if let urls = droppedURLs(from: pasteboard) {
|
||||||
|
return .urls(urls)
|
||||||
|
}
|
||||||
|
return pasteboard.types?.contains(.string) == true ? .text : .none
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `classify`, memoized on the pasteboard's changeCount.
|
||||||
|
func dropKind(of pasteboard: NSPasteboard) -> DropKind {
|
||||||
|
if let dropProbe, dropProbe.changeCount == pasteboard.changeCount {
|
||||||
|
return dropProbe.kind
|
||||||
|
}
|
||||||
|
let kind = Self.classify(pasteboard)
|
||||||
|
dropProbe = (pasteboard.changeCount, kind)
|
||||||
|
return kind
|
||||||
|
}
|
||||||
|
|
||||||
|
override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation {
|
||||||
|
switch dropKind(of: sender.draggingPasteboard) {
|
||||||
|
case .urls: onFileDrop != nil ? .copy : [] // accept so a refusal stays LOUD
|
||||||
|
case .text: super.draggingEntered(sender)
|
||||||
|
case .none: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func draggingUpdated(_ sender: any NSDraggingInfo) -> NSDragOperation {
|
||||||
|
switch dropKind(of: sender.draggingPasteboard) {
|
||||||
|
case .urls: onFileDrop != nil ? .copy : []
|
||||||
|
case .text: super.draggingUpdated(sender)
|
||||||
|
case .none: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
|
||||||
|
switch dropKind(of: sender.draggingPasteboard) {
|
||||||
|
case let .urls(urls): onFileDrop?(urls) ?? false
|
||||||
|
case .text: super.performDragOperation(sender)
|
||||||
|
case .none: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nothing to conclude — the ingest leaves the scroll stack as a
|
||||||
|
/// keystroke would.
|
||||||
|
override func concludeDragOperation(_: (any NSDraggingInfo)?) {}
|
||||||
|
}
|
||||||
@@ -153,6 +153,20 @@ nonisolated enum FixCardStore {
|
|||||||
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
|
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #204: the anchor's exact span in `text` — the appliedText math WITHOUT
|
||||||
|
/// the edit: the quote's 1-based non-overlapping occurrence as an NSRange
|
||||||
|
/// a jump can select. nil for every case that must never land: a stale
|
||||||
|
/// anchor (quote gone or occurrence short) or an empty quote. The lane
|
||||||
|
/// never gates here — a demonstration card's anchor is still a real
|
||||||
|
/// place in the text; the palette decides what to offer.
|
||||||
|
static func anchorRange(of card: StoredFixCard, in text: String) -> NSRange? {
|
||||||
|
guard card.anchor.occurrence >= 1, !card.anchor.quote.isEmpty else { return nil }
|
||||||
|
return text.ranges(of: card.anchor.quote)
|
||||||
|
.dropFirst(card.anchor.occurrence - 1)
|
||||||
|
.first
|
||||||
|
.map { NSRange($0, in: text) }
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Apply (pure)
|
// MARK: - Apply (pure)
|
||||||
|
|
||||||
/// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit
|
/// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit
|
||||||
@@ -164,12 +178,8 @@ nonisolated enum FixCardStore {
|
|||||||
/// issue and accept degrade to a loud no-match, never a wrong-span
|
/// issue and accept degrade to a loud no-match, never a wrong-span
|
||||||
/// patch. The caller owns the ask and the file write.
|
/// patch. The caller owns the ask and the file write.
|
||||||
static func appliedText(of card: StoredFixCard, in text: String) -> String? {
|
static func appliedText(of card: StoredFixCard, in text: String) -> String? {
|
||||||
guard card.lane == .mechanical,
|
guard card.lane == .mechanical, let range = anchorRange(of: card, in: text) else { return nil }
|
||||||
card.anchor.occurrence >= 1,
|
return (text as NSString).replacingCharacters(in: range, with: card.fix)
|
||||||
!card.anchor.quote.isEmpty,
|
|
||||||
let range = text.ranges(of: card.anchor.quote).dropFirst(card.anchor.occurrence - 1).first
|
|
||||||
else { return nil }
|
|
||||||
return text.replacingCharacters(in: range, with: card.fix)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Submit
|
// MARK: - Submit
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
// Museion
|
// Museion
|
||||||
//
|
//
|
||||||
// #25 (S3.3): the Fix Cards palette becomes the card work surface. Open
|
// #25 (S3.3): the Fix Cards palette becomes the card work surface. Open
|
||||||
// cards lead with their actions — Apply (a blocking ask), Skip, Done —
|
// cards lead with their actions — Apply (a blocking ask), Skip, Done,
|
||||||
// closed cards dim behind them. No apply-all, no batch, nothing applies
|
// Promote (#26), Jump (#204) — closed cards dim behind them. No apply-all, no batch, nothing applies
|
||||||
// without the ask (S3.3). #23's show-only surface kept its bones.
|
// without the ask (S3.3). #23's show-only surface kept its bones.
|
||||||
//
|
//
|
||||||
|
|
||||||
@@ -106,9 +106,10 @@ private struct CardList: View {
|
|||||||
|
|
||||||
/// One card: pattern title, problem + fix body, rank · pass · lane ·
|
/// One card: pattern title, problem + fix body, rank · pass · lane ·
|
||||||
/// emitter mono meta (ADR-0006). A stale anchor reads distinct — orange —
|
/// emitter mono meta (ADR-0006). A stale anchor reads distinct — orange —
|
||||||
/// and never offers Apply. Closed cards dim, record their status in the
|
/// and never offers Apply or Jump (#204). Closed cards dim, record their
|
||||||
/// meta, and offer no actions. The blocking Apply ask is the ROW's own
|
/// status in the meta, and keep only Promote and Jump — a closed card that
|
||||||
/// sheet: one card asks at a time, by construction (S3.3).
|
/// is already promoted keeps neither (its row is gone). The blocking Apply
|
||||||
|
/// ask is the ROW's own sheet: one card asks at a time (S3.3).
|
||||||
private struct CardRow: View {
|
private struct CardRow: View {
|
||||||
let card: FixCardStore.StoredFixCard
|
let card: FixCardStore.StoredFixCard
|
||||||
@Environment(AppGateState.self) private var gate
|
@Environment(AppGateState.self) private var gate
|
||||||
@@ -134,14 +135,22 @@ private struct CardRow: View {
|
|||||||
.font(.system(size: 11, design: DesignTokens.mono))
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
.foregroundStyle(stale ? .orange : DesignTokens.muted)
|
.foregroundStyle(stale ? .orange : DesignTokens.muted)
|
||||||
if open || card.promotedAt == nil {
|
if open || card.promotedAt == nil {
|
||||||
// The actions this card offers (#25 S3.3, #26 S4.1):
|
// The actions this card offers (#25 S3.3, #26 S4.1, #204):
|
||||||
// mechanical + valid → Apply (the blocking ask) and Skip;
|
// Jump on every card whose anchor still resolves (closed cards
|
||||||
// demonstration → Done and Skip (never Apply, ADR-0006);
|
// included — the span is still a real place; stale anchors offer
|
||||||
// stale anchor → Skip only. Promote (its own ask) sits
|
// none — nothing to land on); mechanical + valid → Apply (the
|
||||||
// between the primary action and Skip, and outlives the
|
// blocking ask) and Skip; demonstration → Done and Skip (never
|
||||||
// card — closed cards keep it until promoted (#26: the
|
// Apply, ADR-0006); stale anchor → Skip only. Promote (its own
|
||||||
|
// ask) sits between the primary action and Skip, and outlives
|
||||||
|
// the card — closed cards keep it until promoted (#26: the
|
||||||
// Learning is the durable artifact).
|
// Learning is the durable artifact).
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
|
if !stale {
|
||||||
|
Button("Jump") { gate.posts.revealCard(card) }
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
.controlSize(.small)
|
||||||
|
.help("Select the anchored span in the piece")
|
||||||
|
}
|
||||||
if open, !stale {
|
if open, !stale {
|
||||||
if card.lane == .mechanical {
|
if card.lane == .mechanical {
|
||||||
Button("Apply") { asking = true }
|
Button("Apply") { asking = true }
|
||||||
|
|||||||
@@ -9,8 +9,10 @@
|
|||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
/// One post row per the export: title + origin-only mono-11 meta (the Pass
|
/// One post row per the export: title + a mono-11 meta line — origin, or
|
||||||
/// State rides the uppercase group label above; it stays in the a11y label).
|
/// (#206) the piece's Micro.blog status in its place on a sent piece (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
|
/// #108 (variant B): 2px accent edge bar on the leading side when selected
|
||||||
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
|
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
|
||||||
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
|
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
|
||||||
@@ -55,10 +57,14 @@ struct LibraryPostRow: View {
|
|||||||
// group label above (it stays in the accessibility label).
|
// group label above (it stays in the accessibility label).
|
||||||
// r7: the status micro-label sits INSIDE the row's content
|
// r7: the status micro-label sits INSIDE the row's content
|
||||||
// padding — same x as the title, never flush with the edge.
|
// padding — same x as the title, never flush with the edge.
|
||||||
Text(post.origin.rawValue)
|
// #206: a piece with a Micro.blog status shows THAT here
|
||||||
|
// (origin stays in the accessibility label and one hover
|
||||||
|
// away) — the row's content is 178pt, too narrow for both.
|
||||||
|
Text(post.micropubStatus ?? post.origin.rawValue)
|
||||||
.font(.system(size: 11, design: DesignTokens.mono))
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
.foregroundStyle(DesignTokens.muted)
|
.foregroundStyle(DesignTokens.muted)
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.help(post.origin.rawValue)
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 12)
|
.padding(.horizontal, 12)
|
||||||
.padding(.vertical, 10)
|
.padding(.vertical, 10)
|
||||||
@@ -89,6 +95,16 @@ struct LibraryPostRow: View {
|
|||||||
// help sits on the row — the ✳ span isn't individually hoverable in
|
// help sits on the row — the ✳ span isn't individually hoverable in
|
||||||
// SwiftUI (prototype: `title="outline"` on the star).
|
// SwiftUI (prototype: `title="outline"` on the star).
|
||||||
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
|
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
|
||||||
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
|
.accessibilityLabel(accessibilityText)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// VoiceOver reads every status the row carries — #206's Micro.blog
|
||||||
|
/// status included, since it takes the micro-label's place.
|
||||||
|
private var accessibilityText: String {
|
||||||
|
var parts = [post.title, post.passState.rawValue, "origin \(post.origin.rawValue)"]
|
||||||
|
if let status = post.micropubStatus {
|
||||||
|
parts.append(status)
|
||||||
|
}
|
||||||
|
return parts.joined(separator: ", ")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+371
-81
@@ -6,12 +6,22 @@
|
|||||||
// Two-step publish (G2/G11): create with `post-status: draft`, review,
|
// Two-step publish (G2/G11): create with `post-status: draft`, review,
|
||||||
// then `action=update` flips the draft to published. Bearer app-token
|
// then `action=update` flips the draft to published. Bearer app-token
|
||||||
// auth — no OAuth in v1; the token lives in the Keychain, entered
|
// auth — no OAuth in v1; the token lives in the Keychain, entered
|
||||||
// once. Frontmatter `category:` is permitted but inert (v1 never
|
// once. #207: the piece's `category:` list TRAVELS — a create carries
|
||||||
// sends it — the request carries name + content only).
|
// it when non-empty (naming a category Micro.blog doesn't know
|
||||||
|
// creates it there), a re-send carries it in `replace` only when the
|
||||||
|
// piece has the line (`[]` clears; no line leaves the blog's). The
|
||||||
|
// blog's own list for the sheet's suggestions: MicropubCategories.swift.
|
||||||
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
|
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
|
||||||
// PLACE with the uploaded URLs (position is the writer's) — the
|
// PLACE with the uploaded URLs (position is the writer's) — the
|
||||||
// media surface (parse/upload/config/rewrite) lives in
|
// media surface (parse/upload/config/rewrite) lives in
|
||||||
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
|
// MicropubMedia.swift, the orchestration in micropubSend below.
|
||||||
|
// #206: a piece that remembers its post re-sends as an IN-PLACE
|
||||||
|
// update (action=update + replace name/content — never a second
|
||||||
|
// post; #207 adds `category` when the piece carries the line),
|
||||||
|
// Publish is remembered on the piece (`micropub_published`),
|
||||||
|
// and a 404 forgets the link. Wire facts live-verified 2026-12-04
|
||||||
|
// (microblog.dev/api/posting): `replace` sets name and content;
|
||||||
|
// updates answer 200 with an empty body, 404 when the URL is gone.
|
||||||
//
|
//
|
||||||
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
|
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
|
||||||
// book.micro.blog/micropub): JSON create = type/properties; the
|
// book.micro.blog/micropub): JSON create = type/properties; the
|
||||||
@@ -32,9 +42,17 @@ nonisolated enum Micropub {
|
|||||||
/// header, body url as fallback) — what `publish` targets and
|
/// header, body url as fallback) — what `publish` targets and
|
||||||
/// what the piece remembers.
|
/// what the piece remembers.
|
||||||
case drafted(url: String, preview: String?)
|
case drafted(url: String, preview: String?)
|
||||||
|
/// #206: an in-place update landed — `url` is the post the piece
|
||||||
|
/// already remembered (a draft refreshed, a live post edited).
|
||||||
|
/// No second post, no new URL.
|
||||||
|
case updated(url: String)
|
||||||
case published
|
case published
|
||||||
/// No open saved piece (model guard) — nothing went out.
|
/// No open saved piece (model guard) — nothing went out.
|
||||||
case refused(String)
|
case refused(String)
|
||||||
|
/// #206 (model-level): Micro.blog answered 404 — the post is gone
|
||||||
|
/// there. The piece has forgotten it (both stamps cleared); the
|
||||||
|
/// payload says so. The next send is a fresh draft.
|
||||||
|
case forgotten(String)
|
||||||
case authFailed(String)
|
case authFailed(String)
|
||||||
case requestFailed(status: Int, detail: String)
|
case requestFailed(status: Int, detail: String)
|
||||||
case unreachable(String)
|
case unreachable(String)
|
||||||
@@ -52,12 +70,19 @@ nonisolated enum Micropub {
|
|||||||
|
|
||||||
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
|
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
|
||||||
|
|
||||||
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
|
/// The one JSON POST shape every request rides: the fixed endpoint,
|
||||||
|
/// Bearer token, 30 s, sorted keys.
|
||||||
|
private static func jsonPost(_ object: [String: Any], token: String) -> URLRequest {
|
||||||
var request = URLRequest(url: endpoint)
|
var request = URLRequest(url: endpoint)
|
||||||
request.httpMethod = "POST"
|
request.httpMethod = "POST"
|
||||||
request.timeoutInterval = 30
|
request.timeoutInterval = 30
|
||||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||||
|
request.httpBody = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
static func makeDraftRequest(title: String, body: String, token: String, categories: [String] = []) -> URLRequest {
|
||||||
// h=entry with markdown content and name for the title; the
|
// h=entry with markdown content and name for the title; the
|
||||||
// Title publishes as the entry's name, the body ships verbatim
|
// Title publishes as the entry's name, the body ships verbatim
|
||||||
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
|
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
|
||||||
@@ -65,44 +90,64 @@ nonisolated enum Micropub {
|
|||||||
// the WIRE (position and alt are the writer's; the piece on
|
// the WIRE (position and alt are the writer's; the piece on
|
||||||
// disk never changes). No photo property: it would render
|
// disk never changes). No photo property: it would render
|
||||||
// wherever the theme decides, not where placed (2026-11-01).
|
// wherever the theme decides, not where placed (2026-11-01).
|
||||||
// category: never sent in v1.
|
// #207: the categories travel — naming one Micro.blog doesn't
|
||||||
request.httpBody = try? JSONSerialization.data(withJSONObject: [
|
// know creates it there; no list, no key.
|
||||||
"type": ["h-entry"],
|
var properties: [String: Any] = [
|
||||||
"properties": [
|
"name": [title],
|
||||||
"name": [title],
|
"content": [body],
|
||||||
"content": [body],
|
"post-status": ["draft"],
|
||||||
"post-status": ["draft"],
|
]
|
||||||
] as [String: Any],
|
if !categories.isEmpty {
|
||||||
], options: [.sortedKeys])
|
properties["category"] = categories
|
||||||
return request
|
}
|
||||||
|
return jsonPost(["type": ["h-entry"], "properties": properties], token: token)
|
||||||
}
|
}
|
||||||
|
|
||||||
static func makePublishRequest(url: String, token: String) -> URLRequest {
|
static func makePublishRequest(url: String, token: String) -> URLRequest {
|
||||||
var request = URLRequest(url: endpoint)
|
jsonPost([
|
||||||
request.httpMethod = "POST"
|
|
||||||
request.timeoutInterval = 30
|
|
||||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
||||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
||||||
request.httpBody = try? JSONSerialization.data(withJSONObject: [
|
|
||||||
"action": "update",
|
"action": "update",
|
||||||
"url": url,
|
"url": url,
|
||||||
"replace": ["post-status": ["published"]],
|
"replace": ["post-status": ["published"]],
|
||||||
], options: [.sortedKeys])
|
], token: token)
|
||||||
return request
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: The two steps
|
/// #206: refresh the post the piece remembers — title and content
|
||||||
|
/// replaced IN PLACE over the remembered URL (wire-verified
|
||||||
|
/// 2026-12-04: `replace` sets name and content, JSON-only). Never
|
||||||
|
/// a status flip: a draft stays a draft, a published post stays live.
|
||||||
|
/// #207: `categories` opts the post's categories into `replace` —
|
||||||
|
/// a list (even empty: it clears them) is sent as written; nil
|
||||||
|
/// leaves whatever the post has.
|
||||||
|
static func makeUpdateRequest(url: String, title: String, body: String, token: String, categories: [String]? = nil) -> URLRequest {
|
||||||
|
var replace: [String: Any] = [
|
||||||
|
"name": [title],
|
||||||
|
"content": [body],
|
||||||
|
]
|
||||||
|
if let categories {
|
||||||
|
replace["category"] = categories
|
||||||
|
}
|
||||||
|
return jsonPost([
|
||||||
|
"action": "update",
|
||||||
|
"url": url,
|
||||||
|
"replace": replace,
|
||||||
|
], token: token)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: The steps
|
||||||
|
|
||||||
/// Step 1: send the piece as a draft. The piece's Title is the
|
/// Step 1: send the piece as a draft. The piece's Title is the
|
||||||
/// entry's name; the markdown body is the content; #34's uploaded
|
/// entry's name; the markdown body is the content; #34's uploaded
|
||||||
/// illustrations already rewrote their refs in the body.
|
/// illustrations already rewrote their refs in the body. #207: the
|
||||||
|
/// categories ride as the entry's `category` (non-empty only).
|
||||||
static func sendDraft(
|
static func sendDraft(
|
||||||
title: String,
|
title: String,
|
||||||
body: String,
|
body: String,
|
||||||
token: String,
|
token: String,
|
||||||
|
categories: [String] = [],
|
||||||
transport: Transport = urlSessionTransport,
|
transport: Transport = urlSessionTransport,
|
||||||
) async -> Outcome {
|
) async -> Outcome {
|
||||||
await run(makeDraftRequest(title: title, body: body, token: token), transport: transport, decodeDraftURL: true)
|
let request = makeDraftRequest(title: title, body: body, token: token, categories: categories)
|
||||||
|
return await run(request, transport: transport, decodeDraftURL: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Step 2: publish the draft — flip its post-status. Needs the
|
/// Step 2: publish the draft — flip its post-status. Needs the
|
||||||
@@ -116,6 +161,28 @@ nonisolated enum Micropub {
|
|||||||
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
|
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #206: step 1 again, in place — the piece's current title and
|
||||||
|
/// body replace the remembered post's (a draft refreshed for
|
||||||
|
/// review; a live post edited). Needs the remembered URL. #207:
|
||||||
|
/// `categories` non-nil also replaces the post's categories.
|
||||||
|
static func update(
|
||||||
|
url: String,
|
||||||
|
title: String,
|
||||||
|
body: String,
|
||||||
|
token: String,
|
||||||
|
categories: [String]? = nil,
|
||||||
|
transport: Transport = urlSessionTransport,
|
||||||
|
) async -> Outcome {
|
||||||
|
let request = makeUpdateRequest(url: url, title: title, body: body, token: token, categories: categories)
|
||||||
|
let outcome = await run(request, transport: transport, decodeDraftURL: false)
|
||||||
|
// `run` has one success word for the URL-less steps; the update's
|
||||||
|
// carries the URL it touched.
|
||||||
|
if outcome == .published {
|
||||||
|
return .updated(url: url)
|
||||||
|
}
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
/// One POST + the honest decode: 2xx → drafted/published (drafts
|
/// One POST + the honest decode: 2xx → drafted/published (drafts
|
||||||
/// need a URL — Location header first, body `url` second; the
|
/// need a URL — Location header first, body `url` second; the
|
||||||
/// preview link is display-only, never the publish target; a create
|
/// preview link is display-only, never the publish target; a create
|
||||||
@@ -152,10 +219,12 @@ nonisolated enum Micropub {
|
|||||||
/// the frontmatter block on the next parse and re-parse as BODY
|
/// the frontmatter block on the next parse and re-parse as BODY
|
||||||
/// (arbitrary markdown in the writer's piece, shipped under their
|
/// (arbitrary markdown in the writer's piece, shipped under their
|
||||||
/// token by the next send). Applied at both ends: the decode above
|
/// token by the next send). Applied at both ends: the decode above
|
||||||
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
|
/// and `Post.scan`'s read-back. Format-only by design — ownership is
|
||||||
/// Format-only by design — ponytail: a well-formed foreign URL still
|
/// settled upstream, not here: the import boundary drops the micropub
|
||||||
/// passes (the label shows its full text); host-allowlist when v2's
|
/// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
|
||||||
/// q=config surface names the blog's real domains.
|
/// update a well-formed foreign URL would aim a content replace), so
|
||||||
|
/// only Museion or the writer's own hand writes one. ponytail:
|
||||||
|
/// host-allowlist stays the upgrade if another way in ever appears.
|
||||||
static func trustworthyURL(_ string: String) -> Bool {
|
static func trustworthyURL(_ string: String) -> Bool {
|
||||||
guard !string.isEmpty,
|
guard !string.isEmpty,
|
||||||
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
|
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
|
||||||
@@ -166,15 +235,38 @@ nonisolated enum Micropub {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The remembered post URL read from frontmatter — the ONE read the
|
||||||
|
/// scan and the send share, gated like the decode: a hand-written
|
||||||
|
/// broken value is no memory at all (an imported one never arrives —
|
||||||
|
/// the boundary drops the key).
|
||||||
|
static func rememberedURL(_ matter: [String: String]) -> String? {
|
||||||
|
guard let raw = matter["micropub_url"], trustworthyURL(raw) else { return nil }
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #206: the short date the library row and the publish sheet both
|
||||||
|
/// show (`Dec 4, 2026`) — one format, so the two can't drift.
|
||||||
|
static func shortDate(_ date: Date) -> String {
|
||||||
|
FixCardStore.formatted(date, "MMM d, yyyy")
|
||||||
|
}
|
||||||
|
|
||||||
/// Internal for MicropubMedia's media steps (#34) — the one failure
|
/// Internal for MicropubMedia's media steps (#34) — the one failure
|
||||||
/// decode this client speaks; extensions share it rather than fork it.
|
/// decode this client speaks; extensions share it rather than fork it.
|
||||||
|
/// A 5xx is Micro.blog's side (their nginx front with the app not
|
||||||
|
/// answering behind it, or a rate limit) and arrives as an HTML page,
|
||||||
|
/// never Micropub JSON — so the fallback names the outage instead of
|
||||||
|
/// a bare `HTTP 503` (2026-12-04: a 503 in the sheet while the
|
||||||
|
/// endpoint answered its usual 400 to a tokenless probe minutes later).
|
||||||
static func decodeFailure(status: Int, body: Data) -> Outcome {
|
static func decodeFailure(status: Int, body: Data) -> Outcome {
|
||||||
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
|
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
|
||||||
let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)"
|
let described = (root["error_description"] as? String) ?? (root["error"] as? String)
|
||||||
if status == 401 || status == 403 {
|
if status == 401 || status == 403 {
|
||||||
return .authFailed(detail)
|
return .authFailed(described ?? "HTTP \(status)")
|
||||||
}
|
}
|
||||||
return .requestFailed(status: status, detail: detail)
|
let fallback = (500 ... 599).contains(status)
|
||||||
|
? "unavailable on their side — retry in a few minutes (status.micro.blog)"
|
||||||
|
: "HTTP \(status)"
|
||||||
|
return .requestFailed(status: status, detail: described ?? fallback)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,29 +324,15 @@ nonisolated enum MicropubTokenStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - #33 (S6.1) Micropub draft → publish
|
// MARK: - #33 (S6.1) / #206 Micropub draft → publish
|
||||||
|
|
||||||
extension PostsModel {
|
extension PostsModel {
|
||||||
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
|
/// The OPEN saved library piece as the micropub pair (id, Home) —
|
||||||
/// as a draft (h=entry, name = Title, markdown content, post-status
|
/// the identity guard both publish steps share. brief-28: the open
|
||||||
/// draft — category frontmatter never travels). runPass's guard set
|
/// session must target THIS library's selected piece; the wire and
|
||||||
/// minus the engine gates (no engine involved); flush-first so the
|
/// every stamp below act on the piece actually sent (Home, ID),
|
||||||
/// wire carries the editor's latest. On success the piece remembers
|
/// never the current Home's same-slug file. Nil = nothing to send.
|
||||||
/// the draft URL (`micropub_url` stamp) — a stamp failure never
|
private var openMicropubPiece: (id: String, home: URL)? {
|
||||||
/// 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(
|
|
||||||
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,
|
guard let session,
|
||||||
let id = session.postID,
|
let id = session.postID,
|
||||||
let home = watchedHome,
|
let home = watchedHome,
|
||||||
@@ -263,18 +341,64 @@ extension PostsModel {
|
|||||||
draft == nil,
|
draft == nil,
|
||||||
externalSession == nil,
|
externalSession == nil,
|
||||||
outlineGuardPieceID == nil
|
outlineGuardPieceID == nil
|
||||||
else {
|
else { return nil }
|
||||||
|
return (id, home)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #207: the open piece's categories as they are on DISK — what the
|
||||||
|
/// publish sheet's field syncs to (never the scan snapshot: the list
|
||||||
|
/// can lag the open piece). No open saved piece → none.
|
||||||
|
func openPieceCategories() -> [String] {
|
||||||
|
guard let piece = openMicropubPiece,
|
||||||
|
let file = PostStore.folder(of: piece.id, home: piece.home)?.appendingPathComponent("post.md"),
|
||||||
|
let raw = try? String(contentsOf: file, encoding: .utf8)
|
||||||
|
else { return [] }
|
||||||
|
return PostFrontmatter.categories(in: PostFrontmatter.parse(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
|
||||||
|
/// (name = Title, markdown content). runPass's guard set minus
|
||||||
|
/// the engine gates (no engine involved); flush-first so the wire
|
||||||
|
/// carries the editor's latest. #207: the piece's `category:` list
|
||||||
|
/// travels — a create carries it when non-empty; a re-send carries
|
||||||
|
/// `category` in `replace` only when the piece HAS the line
|
||||||
|
/// (opt-in by key — `[]` clears the post's categories, no line
|
||||||
|
/// leaves the blog's).
|
||||||
|
/// #206: a piece that remembers no post is CREATED as a draft
|
||||||
|
/// (h=entry, post-status draft) and remembers its URL
|
||||||
|
/// (`micropub_url` stamp); a piece that remembers one UPDATES that
|
||||||
|
/// post in place — same URL, no second post — so a draft refreshes
|
||||||
|
/// for review and a published piece edits live. A stamp failure
|
||||||
|
/// never un-sends the draft.
|
||||||
|
/// #207: `categories` (the sheet's edit) — nil = no edit, the
|
||||||
|
/// piece's line is used as written; non-nil = that list is written
|
||||||
|
/// to the piece FIRST (`[]` renders `category: []`), after the
|
||||||
|
/// flush and before the ONE disk read that feeds the wire, so disk
|
||||||
|
/// and blog never disagree. A category write that cannot land
|
||||||
|
/// REFUSES the send — nothing goes out.
|
||||||
|
/// #179: outside the write rail by design — publish is not a library
|
||||||
|
/// verb, and a stamp failure must never un-send the draft.
|
||||||
|
func micropubSend(
|
||||||
|
token: String,
|
||||||
|
categories: [String]? = nil,
|
||||||
|
transport: Micropub.Transport = Micropub.urlSessionTransport,
|
||||||
|
) async -> Micropub.Outcome {
|
||||||
|
guard let piece = openMicropubPiece else {
|
||||||
return .refused("Open a saved post to publish.")
|
return .refused("Open a saved post to publish.")
|
||||||
}
|
}
|
||||||
guard flushOrAbort(id) else {
|
guard flushOrAbort(piece.id) else {
|
||||||
return .refused(lastError ?? "Couldn't save the piece before sending.")
|
return .refused(lastError ?? "Couldn't save the piece before sending.")
|
||||||
}
|
}
|
||||||
// Disk is the truth post-flush — ONE read serves both wire fields:
|
if let refused = stampCategories(categories, piece: piece) {
|
||||||
|
return refused
|
||||||
|
}
|
||||||
|
// Disk is the truth post-flush — ONE read serves the wire fields:
|
||||||
// Title (heading markers stripped — it publishes as the entry's
|
// Title (heading markers stripped — it publishes as the entry's
|
||||||
// name) and the frontmatter-stripped body (the stamp is
|
// name), the frontmatter-stripped body (the stamp is
|
||||||
// bookkeeping, never prose; the body itself is never stripped,
|
// bookkeeping, never prose; the body itself is never stripped,
|
||||||
// GLOSSARY). No scan dependency: the list can lag the open piece.
|
// GLOSSARY), the remembered URL, and the categories. No scan
|
||||||
guard let dir = PostStore.folder(of: id, home: home),
|
// dependency: the list can lag the open piece.
|
||||||
|
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
|
||||||
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
|
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
|
||||||
else {
|
else {
|
||||||
return .refused("Couldn't read the piece before sending.")
|
return .refused("Couldn't read the piece before sending.")
|
||||||
@@ -295,25 +419,152 @@ extension PostsModel {
|
|||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let outcome = await Micropub.sendDraft(
|
return await updateRememberedOrCreate(
|
||||||
title: Post.title(of: raw),
|
raw: raw,
|
||||||
body: wireBody,
|
wireBody: wireBody,
|
||||||
|
piece: piece,
|
||||||
token: token,
|
token: token,
|
||||||
transport: transport,
|
transport: transport,
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #207: the sheet's category edit lands on the piece HERE — after
|
||||||
|
/// the flush, before the ONE read that feeds the wire, so disk and
|
||||||
|
/// blog never disagree. nil is no edit. The refusal when the line
|
||||||
|
/// cannot land: the send stops here and nothing goes out.
|
||||||
|
private func stampCategories(_ categories: [String]?, piece: (id: String, home: URL)) -> Micropub.Outcome? {
|
||||||
|
guard let categories else { return nil }
|
||||||
|
do {
|
||||||
|
try PostStore.stampMicropub(piece.id, home: piece.home, [("category", PostFrontmatter.categoryValue(categories))])
|
||||||
|
} catch {
|
||||||
|
return .refused("Couldn't save this piece's categories — nothing was sent. (\(error.localizedDescription))")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wire step over the disk's text (`raw` — the Title and the
|
||||||
|
/// frontmatter come from it) and the wire body. #206: a piece that
|
||||||
|
/// remembers its post UPDATES it in place (the remembered URL never
|
||||||
|
/// moves, nothing new to stamp; a 404 means the post is gone on
|
||||||
|
/// Micro.blog — the piece forgets it rather than fail forever
|
||||||
|
/// against a dead URL); a piece that remembers none is CREATED as
|
||||||
|
/// a draft and remembers its URL. A stamp failure can't un-send
|
||||||
|
/// the draft; the sheet still holds the URL for this session — the
|
||||||
|
/// piece just loses the memory across a reopen (it would create a
|
||||||
|
/// second draft then). Kept quiet: the same disk accepted the
|
||||||
|
/// flush moments before.
|
||||||
|
/// #207: a create carries the categories when non-empty (never
|
||||||
|
/// `[]`); an update carries `category` only when the piece HAS the
|
||||||
|
/// line — opt-in by key, `[]` clears, no line leaves the blog's.
|
||||||
|
private func updateRememberedOrCreate(
|
||||||
|
raw: String,
|
||||||
|
wireBody: String,
|
||||||
|
piece: (id: String, home: URL),
|
||||||
|
token: String,
|
||||||
|
transport: Micropub.Transport,
|
||||||
|
) async -> Micropub.Outcome {
|
||||||
|
let matter = PostFrontmatter.parse(raw)
|
||||||
|
let title = Post.title(of: raw)
|
||||||
|
if let remembered = Micropub.rememberedURL(matter) {
|
||||||
|
let outcome = await Micropub.update(
|
||||||
|
url: remembered,
|
||||||
|
title: title,
|
||||||
|
body: wireBody,
|
||||||
|
token: token,
|
||||||
|
categories: matter["category"] != nil ? PostFrontmatter.categories(in: matter) : nil,
|
||||||
|
transport: transport,
|
||||||
|
)
|
||||||
|
if case .requestFailed(404, _) = outcome {
|
||||||
|
return micropubPostGone(id: piece.id, home: piece.home)
|
||||||
|
}
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
let outcome = await Micropub.sendDraft(
|
||||||
|
title: title,
|
||||||
|
body: wireBody,
|
||||||
|
token: token,
|
||||||
|
categories: PostFrontmatter.categories(in: matter),
|
||||||
|
transport: transport,
|
||||||
|
)
|
||||||
if case let .drafted(url, _) = outcome {
|
if case let .drafted(url, _) = outcome {
|
||||||
// Remember the draft URL for the publish step. A stamp
|
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
|
||||||
// failure can't un-send the draft; the sheet still holds
|
|
||||||
// the URL for this session — the piece just loses the
|
|
||||||
// memory across a reopen (re-send the draft then). Kept
|
|
||||||
// quiet: lastError's setter stays PostsModel-file-private,
|
|
||||||
// and the same disk accepted the flush moments before.
|
|
||||||
try? PostStore.stampMicropubURL(id: id, url: url, home: home)
|
|
||||||
}
|
}
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
|
|
||||||
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
|
/// Step 2: flip the remembered draft to published. #206: the model
|
||||||
|
/// owns it — the sheet used to call the client directly, so nothing
|
||||||
|
/// remembered a publish. Success is the piece's publish record:
|
||||||
|
/// `micropub_published` stamped now (first publish wins — a later
|
||||||
|
/// in-place update of the live post never moves it) and
|
||||||
|
/// `micropub_url` healed in the same write should the send's stamp
|
||||||
|
/// have failed. A stamp failure never un-publishes. No flush: no
|
||||||
|
/// content travels, and the editor never writes frontmatter. The URL
|
||||||
|
/// is trust-gated HERE — it lands in frontmatter (the heal), and a
|
||||||
|
/// caller's value is external until proven.
|
||||||
|
/// #207: `categories` non-nil = pending edits — the piece is sent
|
||||||
|
/// FIRST (`micropubSend`, the edit landing on disk), then the post
|
||||||
|
/// that send leaves is published: the remembered one, or the fresh
|
||||||
|
/// draft a create returned — never the caller's URL, which the
|
||||||
|
/// sheet may hold stale against the disk. A failed send returns its
|
||||||
|
/// outcome with NO publish — disk and blog never silently disagree.
|
||||||
|
func micropubPublish(
|
||||||
|
url: String,
|
||||||
|
token: String,
|
||||||
|
categories: [String]? = nil,
|
||||||
|
transport: Micropub.Transport = Micropub.urlSessionTransport,
|
||||||
|
) async -> Micropub.Outcome {
|
||||||
|
guard let piece = openMicropubPiece else {
|
||||||
|
return .refused("Open a saved post to publish.")
|
||||||
|
}
|
||||||
|
guard Micropub.trustworthyURL(url) else {
|
||||||
|
return .refused("That post address isn't a clean https URL — nothing was sent or remembered.")
|
||||||
|
}
|
||||||
|
var target = url
|
||||||
|
if let categories {
|
||||||
|
switch await micropubSend(token: token, categories: categories, transport: transport) {
|
||||||
|
case let .updated(touched):
|
||||||
|
target = touched
|
||||||
|
case let .drafted(fresh, _):
|
||||||
|
target = fresh
|
||||||
|
case let other:
|
||||||
|
return other
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let outcome = await Micropub.publish(url: target, token: token, transport: transport)
|
||||||
|
switch outcome {
|
||||||
|
case .published:
|
||||||
|
try? PostStore.stampMicropub(piece.id, home: piece.home, [
|
||||||
|
("micropub_url", target),
|
||||||
|
("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)),
|
||||||
|
])
|
||||||
|
case .requestFailed(404, _):
|
||||||
|
return micropubPostGone(id: piece.id, home: piece.home)
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #206: Micro.blog answered 404 — the post is gone there, so the
|
||||||
|
/// piece is no longer on Micro.blog: it forgets both stamps and the
|
||||||
|
/// writer hears why (the next send is a fresh draft). A forget that
|
||||||
|
/// cannot land refuses instead — never a "cleared" the disk
|
||||||
|
/// contradicts: the link is still on the piece, so the sheet stays
|
||||||
|
/// on it and says what to do by hand.
|
||||||
|
private func micropubPostGone(id: String, home: URL) -> Micropub.Outcome {
|
||||||
|
do {
|
||||||
|
try PostStore.forgetMicropub(id: id, home: home)
|
||||||
|
} catch {
|
||||||
|
return .refused(
|
||||||
|
"Micro.blog no longer has this post — it was deleted there — but its link couldn't be cleared from this piece "
|
||||||
|
+ "(\(error.localizedDescription)). Delete the `micropub_url` line from its frontmatter, then send it as a draft.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return .forgotten("Micro.blog no longer has this post — it was deleted there. Its link is cleared; send it as a draft again.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #34 (S6.2): the illustration rail of `micropubSend`. The
|
||||||
/// FLOOR first (G12): a photo without alt text never ships, and
|
/// FLOOR first (G12): a photo without alt text never ships, and
|
||||||
/// nothing touches the wire until every illustration clears it —
|
/// nothing touches the wire until every illustration clears it —
|
||||||
/// the ONLY gate (the only way an image ships is a parsed body ref,
|
/// the ONLY gate (the only way an image ships is a parsed body ref,
|
||||||
@@ -342,11 +593,6 @@ extension PostsModel {
|
|||||||
// `../` ref or a symlinked asset is out of shape) before the
|
// `../` ref or a symlinked asset is out of shape) before the
|
||||||
// first upload. One payload per FILE: duplicate refs to one
|
// first upload. One payload per FILE: duplicate refs to one
|
||||||
// destination upload once and share the URL.
|
// destination upload once and share the URL.
|
||||||
struct Payload {
|
|
||||||
let destination: String
|
|
||||||
let mimeType: String
|
|
||||||
let data: Data
|
|
||||||
}
|
|
||||||
let root = dir.resolvingSymlinksInPath().path + "/"
|
let root = dir.resolvingSymlinksInPath().path + "/"
|
||||||
var payloads: [Payload] = []
|
var payloads: [Payload] = []
|
||||||
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
|
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
|
||||||
@@ -361,8 +607,36 @@ extension PostsModel {
|
|||||||
}
|
}
|
||||||
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
|
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
|
||||||
}
|
}
|
||||||
// ponytail: a re-send re-uploads (Micro.blog keeps both
|
return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
|
||||||
// copies) — dedup via q=source listing is v2's call.
|
}
|
||||||
|
|
||||||
|
/// One asset about to travel: its ref destination (the rewrite's
|
||||||
|
/// map key), its wire content type, its bytes.
|
||||||
|
private struct Payload {
|
||||||
|
let destination: String
|
||||||
|
let mimeType: String
|
||||||
|
let data: Data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #206: the piece's upload memo answers first — an image whose
|
||||||
|
/// bytes uploaded before rides that URL again (Micro.blog keeps
|
||||||
|
/// every copy, and their listing carries no hash to match against,
|
||||||
|
/// so the memory is local). Only what the memo lacks touches the
|
||||||
|
/// wire: q=config, then one upload per pending payload, each
|
||||||
|
/// remembered as it lands.
|
||||||
|
private func uploadRemembered(
|
||||||
|
_ payloads: [Payload],
|
||||||
|
dir: URL,
|
||||||
|
body: String,
|
||||||
|
token: String,
|
||||||
|
transport: Micropub.Transport,
|
||||||
|
) async -> IllustrationRail {
|
||||||
|
var memo = Micropub.readUploadMemo(in: dir)
|
||||||
|
let remembered = uploadedDestinations(payloads, memo: memo)
|
||||||
|
let pending = payloads.filter { remembered[$0.destination] == nil }
|
||||||
|
guard !pending.isEmpty else {
|
||||||
|
return .ready(Micropub.rewritingIllustrations(body, uploaded: remembered))
|
||||||
|
}
|
||||||
let mediaEndpoint: String
|
let mediaEndpoint: String
|
||||||
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
|
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
|
||||||
case let .url(named):
|
case let .url(named):
|
||||||
@@ -370,8 +644,9 @@ extension PostsModel {
|
|||||||
case let .failed(outcome):
|
case let .failed(outcome):
|
||||||
return .blocked(outcome)
|
return .blocked(outcome)
|
||||||
}
|
}
|
||||||
var uploaded: [String: String] = [:]
|
// The `where` skips a later payload with the same bytes as one
|
||||||
for payload in payloads {
|
// uploaded earlier in this batch.
|
||||||
|
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
|
||||||
let outcome = await Micropub.uploadMedia(
|
let outcome = await Micropub.uploadMedia(
|
||||||
mediaEndpoint: mediaEndpoint,
|
mediaEndpoint: mediaEndpoint,
|
||||||
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
|
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
|
||||||
@@ -382,11 +657,26 @@ extension PostsModel {
|
|||||||
)
|
)
|
||||||
switch outcome {
|
switch outcome {
|
||||||
case let .url(url):
|
case let .url(url):
|
||||||
uploaded[payload.destination] = url
|
// Remembered as it lands: a later failure in the batch
|
||||||
|
// keeps the earlier uploads (a retry never repeats them).
|
||||||
|
memo[Micropub.uploadKey(payload.data)] = url
|
||||||
|
Micropub.writeUploadMemo(memo, in: dir)
|
||||||
case let .failed(failure):
|
case let .failed(failure):
|
||||||
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
|
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
|
// Every payload is memoized now — the earlier uploads and this batch's.
|
||||||
|
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploadedDestinations(payloads, memo: memo)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rewrite's map: each payload's ref destination → its upload URL.
|
||||||
|
private func uploadedDestinations(_ payloads: [Payload], memo: [String: String]) -> [String: String] {
|
||||||
|
var uploaded: [String: String] = [:]
|
||||||
|
for payload in payloads {
|
||||||
|
if let url = memo[Micropub.uploadKey(payload.data)] {
|
||||||
|
uploaded[payload.destination] = url
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return uploaded
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
//
|
||||||
|
// MicropubCategories.swift
|
||||||
|
// Museion
|
||||||
|
//
|
||||||
|
// #207: the blog's own categories — the list the publish sheet
|
||||||
|
// offers as suggestions for the piece's `category:` line. One
|
||||||
|
// query, no writes: naming a category Micro.blog doesn't know
|
||||||
|
// CREATES it when the post is sent (the create/update carry the
|
||||||
|
// list — Micropub.swift and the codec in PostFrontmatter.swift),
|
||||||
|
// so there is no separate create call here.
|
||||||
|
//
|
||||||
|
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
|
||||||
|
// `GET /micropub?q=category` answers the blog's categories as a
|
||||||
|
// root `categories` string array; some answers carry the richer
|
||||||
|
// `microblog-categories` objects (`name` + `url`) instead. A 2xx
|
||||||
|
// with neither is a blog without categories — no suggestions is
|
||||||
|
// not an error, and neither is any failure: the sheet stays silent
|
||||||
|
// (a typed new name still creates the category at the send, and a
|
||||||
|
// rejected token surfaces on the send itself).
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
nonisolated extension Micropub {
|
||||||
|
/// `GET <endpoint>?q=category` — the config query's shape.
|
||||||
|
static func makeCategoryListRequest(token: String) -> URLRequest {
|
||||||
|
queryRequest("category", token: token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The blog's categories for the sheet's suggestions — trimmed,
|
||||||
|
/// empties dropped; `[]` on any failure or non-2xx (there is no
|
||||||
|
/// error to surface — see the header).
|
||||||
|
static func blogCategories(token: String, transport: Transport = urlSessionTransport) async -> [String] {
|
||||||
|
guard let (data, response) = try? await transport(makeCategoryListRequest(token: token)),
|
||||||
|
(200 ..< 300).contains(response.statusCode) else { return [] }
|
||||||
|
return categoryNames(in: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The root `categories` strings, else the `microblog-categories`
|
||||||
|
/// objects' `name` fields.
|
||||||
|
private static func categoryNames(in data: Data) -> [String] {
|
||||||
|
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
|
||||||
|
let names = (root["categories"] as? [String])
|
||||||
|
?? (root["microblog-categories"] as? [[String: Any]])?.compactMap { $0["name"] as? String }
|
||||||
|
?? []
|
||||||
|
return names.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,8 +16,11 @@
|
|||||||
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
|
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
|
||||||
// `GET /micropub?q=config` carries `media-endpoint`;
|
// `GET /micropub?q=config` carries `media-endpoint`;
|
||||||
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
|
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
|
||||||
|
// #206: the upload memo — an image whose bytes uploaded before rides
|
||||||
|
// that URL again (`.museion-uploads.json` in the piece folder).
|
||||||
//
|
//
|
||||||
|
|
||||||
|
import CryptoKit
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
nonisolated extension Micropub {
|
nonisolated extension Micropub {
|
||||||
@@ -105,8 +108,14 @@ nonisolated extension Micropub {
|
|||||||
// MARK: q=config (hop 1)
|
// MARK: q=config (hop 1)
|
||||||
|
|
||||||
static func makeConfigRequest(token: String) -> URLRequest {
|
static func makeConfigRequest(token: String) -> URLRequest {
|
||||||
|
queryRequest("config", token: token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one `GET <endpoint>?q=…` shape (#34's config query, #207's
|
||||||
|
/// category list): the fixed endpoint, Bearer token, 30 s.
|
||||||
|
static func queryRequest(_ q: String, token: String) -> URLRequest {
|
||||||
var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
||||||
components.queryItems = [URLQueryItem(name: "q", value: "config")]
|
components.queryItems = [URLQueryItem(name: "q", value: q)]
|
||||||
var request = URLRequest(url: components.url!)
|
var request = URLRequest(url: components.url!)
|
||||||
request.timeoutInterval = 30
|
request.timeoutInterval = 30
|
||||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||||
@@ -194,6 +203,43 @@ nonisolated extension Micropub {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: #206 — the upload memo (a re-send never re-uploads)
|
||||||
|
|
||||||
|
/// `.museion-uploads.json` in the piece folder — the cursor
|
||||||
|
/// sidecar's posture: Finder-invisible, dies with the folder.
|
||||||
|
static let uploadMemoFile = ".museion-uploads.json"
|
||||||
|
|
||||||
|
/// The memo's key: the asset's exact bytes. Rename the file or
|
||||||
|
/// rewrite the alt and it is still the same upload; change one byte
|
||||||
|
/// and it uploads fresh.
|
||||||
|
static func uploadKey(_ data: Data) -> String {
|
||||||
|
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `uploadKey → uploaded URL`. Disk is external data: a symlinked
|
||||||
|
/// memo never reads (the rail's planted-link posture) and only
|
||||||
|
/// trustworthy URLs come back — a memo URL lands in published
|
||||||
|
/// content. ponytail: an upload deleted on Micro.blog stays memoized
|
||||||
|
/// (a dead image URL) until the sidecar is removed; no liveness probe.
|
||||||
|
static func readUploadMemo(in pieceFolder: URL) -> [String: String] {
|
||||||
|
let url = pieceFolder.appendingPathComponent(uploadMemoFile)
|
||||||
|
guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey]),
|
||||||
|
values.isSymbolicLink != true,
|
||||||
|
let data = try? Data(contentsOf: url)
|
||||||
|
else { return [:] }
|
||||||
|
let memo = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
|
||||||
|
return memo.filter { trustworthyURL($1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Best-effort, like the cursor sidecar: a failed memo write only
|
||||||
|
/// costs a re-upload, never a send.
|
||||||
|
static func writeUploadMemo(_ memo: [String: String], in pieceFolder: URL) {
|
||||||
|
let encoder = JSONEncoder()
|
||||||
|
encoder.outputFormatting = .sortedKeys // a stable file: no churn across sends or syncs
|
||||||
|
guard let data = try? encoder.encode(memo) else { return }
|
||||||
|
try? data.write(to: pieceFolder.appendingPathComponent(uploadMemoFile), options: .atomic)
|
||||||
|
}
|
||||||
|
|
||||||
/// The one illustration-ref pattern both passes share (the parse
|
/// The one illustration-ref pattern both passes share (the parse
|
||||||
/// and the rewrite can never drift). The alt class is single-line
|
/// and the rewrite can never drift). The alt class is single-line
|
||||||
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
|
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
|
||||||
|
|||||||
@@ -7,34 +7,146 @@
|
|||||||
// sheet owns the whole two-step flow over the OPEN piece: Send as
|
// sheet owns the whole two-step flow over the OPEN piece: Send as
|
||||||
// Draft (h=entry, name, markdown content) → review on Micro.blog →
|
// Draft (h=entry, name, markdown content) → review on Micro.blog →
|
||||||
// Publish (the post-status update against the piece's remembered
|
// Publish (the post-status update against the piece's remembered
|
||||||
// draft URL). The app token is entered here ONCE and lives in the
|
// draft URL). The app token is entered here when none is saved and
|
||||||
// Keychain (G11; re-offered only on an auth failure). Refusals show
|
// lives in the Keychain (G11; re-offered only on an auth failure —
|
||||||
|
// Settings → Micro.blog is the standing manager). Refusals show
|
||||||
// inline with the buttons kept (ApplyAskSheet posture).
|
// inline with the buttons kept (ApplyAskSheet posture).
|
||||||
|
// #206: the sheet opens on the piece's publish record. A published
|
||||||
|
// piece says so (and links its live post) and offers Update Live
|
||||||
|
// Post; a draft offers Publish / Update Draft. Both re-sends update
|
||||||
|
// the remembered post IN PLACE — never a second post.
|
||||||
|
// #207: a Categories field — the piece's `category:` line as a
|
||||||
|
// comma list, edited with the system completion menu over the
|
||||||
|
// blog's own categories (`Micropub.blogCategories`, fetched on
|
||||||
|
// open; a failed fetch is silent). The system REPLACES the whole
|
||||||
|
// field text with a completion, so `MicropubCategoryField` (the
|
||||||
|
// enum above the view) carries the merge: a pick ADDS, a
|
||||||
|
// half-typed last word is replaced. The edit lands on disk AT THE
|
||||||
|
// SEND (the model's `categories:`), never before — Cancel/Done
|
||||||
|
// discard it and a refused send puts nothing on the wire; the field
|
||||||
|
// syncs from disk on open and after a forget, settles to the
|
||||||
|
// canonical text after a successful send, and after a failed step
|
||||||
|
// only its baseline re-syncs (the send writes the line before the
|
||||||
|
// wire — a later clear must still count as an edit).
|
||||||
//
|
//
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
|
/// #207: the publish sheet's Categories field — its pure rules over
|
||||||
|
/// the one-line category codec (`PostFrontmatter.categoryList` /
|
||||||
|
/// `categoryListValue`: the ONE quote-aware comma-list parser — the
|
||||||
|
/// field holds exactly the bracket-inner text). The system completion
|
||||||
|
/// menu REPLACES the whole field text with a completion, so a
|
||||||
|
/// completion IS the merge: a pick ADDS, a half-typed last word is
|
||||||
|
/// replaced, a present name is never offered.
|
||||||
|
nonisolated enum MicropubCategoryField {
|
||||||
|
/// The word being typed — the LAST comma segment (a comma inside
|
||||||
|
/// double quotes never splits), trimmed, one pair of quotes off
|
||||||
|
/// (the codec's own step: the field reads `Tech, "Tech, general"`
|
||||||
|
/// after that pick, and the word is the name). SwiftUI exposes no
|
||||||
|
/// caret, so the end of the text is the only place a writer can be
|
||||||
|
/// typing. "" when the text is empty or ends with a comma.
|
||||||
|
static func partial(_ text: String) -> String {
|
||||||
|
// The codec's own segment scanner splits (ONE quote-aware walk);
|
||||||
|
// its `categoryList` trims, unquotes and unescapes the segment.
|
||||||
|
PostFrontmatter.categoryList(PostFrontmatter.categorySegments(text).last ?? "").first ?? ""
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last thing typed is itself a known category — nothing is
|
||||||
|
/// half-typed.
|
||||||
|
static func finished(_ text: String, blog: [String]) -> Bool {
|
||||||
|
let word = partial(text)
|
||||||
|
return !word.isEmpty && blog.contains { same($0, word) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menu over the blog's categories, blog order kept: ALL of
|
||||||
|
/// them when nothing or a finished name is typed, else the names
|
||||||
|
/// starting with the half-typed word (case-insensitive); a name
|
||||||
|
/// already in the field is never offered.
|
||||||
|
static func suggestions(text: String, blog: [String]) -> [String] {
|
||||||
|
let word = partial(text)
|
||||||
|
let present = Set(PostFrontmatter.categoryList(text).map { $0.lowercased() })
|
||||||
|
let all = word.isEmpty || finished(text, blog: blog)
|
||||||
|
return blog.filter { name in
|
||||||
|
!present.contains(name.lowercased()) && (all || name.lowercased().hasPrefix(word.lowercased()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the WHOLE field becomes when `name` is picked: a
|
||||||
|
/// half-typed last word makes room (the pick extends it, and the
|
||||||
|
/// word is not itself a category), then `name` is appended unless
|
||||||
|
/// present — never a duplicate.
|
||||||
|
static func completion(text: String, picking name: String, blog: [String]) -> String {
|
||||||
|
var names = PostFrontmatter.categoryList(text)
|
||||||
|
let word = partial(text)
|
||||||
|
let halfTyped = !word.isEmpty && !finished(text, blog: blog) && same(names.last ?? "", word)
|
||||||
|
if halfTyped, !same(word, name), name.lowercased().hasPrefix(word.lowercased()) {
|
||||||
|
names.removeLast()
|
||||||
|
}
|
||||||
|
if !names.contains(where: { same($0, name) }) {
|
||||||
|
names.append(name)
|
||||||
|
}
|
||||||
|
return PostFrontmatter.categoryListValue(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sheet's edit for the model: nil when the field's list IS the
|
||||||
|
/// settled one — LISTS, so a trailing comma is not an edit, and
|
||||||
|
/// equal empties stay nil (a piece without a line never gains an
|
||||||
|
/// empty key); else the field's list (`[]` = cleared — the model
|
||||||
|
/// writes `category: []`).
|
||||||
|
static func pendingCategories(field: String, settled: String) -> [String]? {
|
||||||
|
let list = PostFrontmatter.categoryList(field)
|
||||||
|
return list == PostFrontmatter.categoryList(settled) ? nil : list
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ponytail: case-insensitive on purpose — the writer's spelling stays
|
||||||
|
/// in the field, the menu just never re-offers a name that's there in
|
||||||
|
/// any case; the codec's own dedup stays exact (it records what was
|
||||||
|
/// written, it never rewrites a spelling).
|
||||||
|
private static func same(_ a: String, _ b: String) -> Bool {
|
||||||
|
a.caseInsensitiveCompare(b) == .orderedSame
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
|
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
|
||||||
struct MicropubPublishSheet: View {
|
struct MicropubPublishSheet: View {
|
||||||
let posts: PostsModel
|
let posts: PostsModel
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
private enum Phase: Equatable {
|
private enum Phase: Equatable {
|
||||||
|
/// Never sent — nothing on Micro.blog yet.
|
||||||
case idle
|
case idle
|
||||||
case drafting
|
case drafting
|
||||||
|
/// A draft is on Micro.blog, not published (fresh or remembered).
|
||||||
case drafted
|
case drafted
|
||||||
|
case updating
|
||||||
|
case updated
|
||||||
case publishing
|
case publishing
|
||||||
|
/// The publish record — this session's Publish, or the piece's stamp.
|
||||||
case published
|
case published
|
||||||
}
|
}
|
||||||
|
|
||||||
@State private var phase: Phase = .idle
|
@State private var phase: Phase = .idle
|
||||||
/// The draft URL this sheet knows: fresh from a send, or the piece's
|
/// The post URL this sheet knows: fresh from a send, or the piece's
|
||||||
/// remembered `micropub_url` (a draft sent in an earlier session).
|
/// remembered `micropub_url` (sent in an earlier session) — a draft's
|
||||||
@State private var draftURL: String?
|
/// until it is published, the live post's after.
|
||||||
|
@State private var postURL: String?
|
||||||
|
/// #206: when the piece was published — its stamp, or this session's
|
||||||
|
/// Publish. Nil while it is a draft.
|
||||||
|
@State private var publishedAt: Date?
|
||||||
@State private var previewURL: String?
|
@State private var previewURL: String?
|
||||||
@State private var refusal: String?
|
@State private var refusal: String?
|
||||||
@State private var tokenField = ""
|
@State private var tokenField = ""
|
||||||
@State private var reentry = false
|
@State private var reentry = false
|
||||||
|
/// #207: the Categories field as typed, the text it rests on (the
|
||||||
|
/// disk read on open, or a successful send's canonical form — the
|
||||||
|
/// pending-edit baseline), and the blog's categories the menu offers.
|
||||||
|
@State private var categoryField = ""
|
||||||
|
@State private var settledCategoryField = ""
|
||||||
|
@State private var blogCategories: [String] = []
|
||||||
|
/// Whether the blog's categories were ever fetched in this sheet
|
||||||
|
/// (a blog with none is not re-asked after every send).
|
||||||
|
@State private var suggestionsLoaded = false
|
||||||
|
|
||||||
/// Token entry shows when none is saved — or again after an auth
|
/// Token entry shows when none is saved — or again after an auth
|
||||||
/// failure (the entered-once token can be replaced, never a dead end).
|
/// failure (the entered-once token can be replaced, never a dead end).
|
||||||
@@ -42,16 +154,47 @@ struct MicropubPublishSheet: View {
|
|||||||
reentry || MicropubTokenStore.read() == nil
|
reentry || MicropubTokenStore.read() == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var busy: Bool {
|
||||||
|
phase == .drafting || phase == .updating || phase == .publishing
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #207: the field's edit for the send — nil when nothing changed.
|
||||||
|
private var pendingCategories: [String]? {
|
||||||
|
MicropubCategoryField.pendingCategories(field: categoryField, settled: settledCategoryField)
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
VStack(alignment: .leading, spacing: 12) {
|
||||||
Text("Publish to Micro.blog?")
|
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
Text(pieceTitle)
|
Text(pieceTitle)
|
||||||
.font(.callout.weight(.semibold))
|
.font(.callout.weight(.semibold))
|
||||||
.lineLimit(2)
|
.lineLimit(2)
|
||||||
Text("Museion sends it as a draft first — nothing goes out until you publish.")
|
if phase == .idle {
|
||||||
.font(.callout)
|
Text("Museion sends it as a draft first — nothing goes out until you publish.")
|
||||||
.foregroundStyle(DesignTokens.muted)
|
.font(.callout)
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #207: the Categories field, in every phase — a send is possible in all of them.
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("Categories")
|
||||||
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
TextField("Tech, Notes", text: $categoryField)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.font(.system(size: 12, design: DesignTokens.mono))
|
||||||
|
.disabled(busy)
|
||||||
|
.accessibilityLabel("Categories")
|
||||||
|
.textInputSuggestions {
|
||||||
|
ForEach(MicropubCategoryField.suggestions(text: categoryField, blog: blogCategories), id: \.self) { name in
|
||||||
|
Text(name).textInputCompletion(MicropubCategoryField.completion(text: categoryField, picking: name, blog: blogCategories))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text("Comma-separated. A name Micro.blog doesn't know is created when the post is sent.")
|
||||||
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
}
|
||||||
|
|
||||||
if showsTokenField {
|
if showsTokenField {
|
||||||
SecureField("App token", text: $tokenField)
|
SecureField("App token", text: $tokenField)
|
||||||
@@ -60,20 +203,26 @@ struct MicropubPublishSheet: View {
|
|||||||
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
|
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
|
||||||
.font(.system(size: 11, design: DesignTokens.mono))
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
.foregroundStyle(DesignTokens.muted)
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
} else {
|
||||||
|
// A stored token is in use — the field's absence alone
|
||||||
|
// never said which token a send carries.
|
||||||
|
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
|
||||||
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
}
|
}
|
||||||
|
|
||||||
if phase == .drafting || phase == .publishing {
|
if busy {
|
||||||
ProgressView()
|
ProgressView()
|
||||||
}
|
}
|
||||||
|
|
||||||
if let url = statusURL {
|
if let label = statusLabel {
|
||||||
// The draft lives on Micro.blog — the preview link goes
|
// A published piece's link is the post itself; a draft's
|
||||||
// there for review; once published it's the post itself.
|
// is its review page.
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
Text(phase == .published ? "Published" : "Draft on Micro.blog")
|
Text(label)
|
||||||
.font(.system(size: 11, design: DesignTokens.mono))
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
.foregroundStyle(DesignTokens.muted)
|
.foregroundStyle(DesignTokens.muted)
|
||||||
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) {
|
if let link = statusLink {
|
||||||
Link(destination: link) {
|
Link(destination: link) {
|
||||||
Text(link.absoluteString)
|
Text(link.absoluteString)
|
||||||
.font(.system(size: 11, design: DesignTokens.mono))
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
@@ -90,24 +239,25 @@ struct MicropubPublishSheet: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
if phase == .published {
|
if publishedAt != nil {
|
||||||
|
// The piece is out: the only send left edits the live
|
||||||
|
// post, immediately — the label says so. A stamp with no
|
||||||
|
// remembered link (a hand-added key) has no post to
|
||||||
|
// update: that send is a fresh draft, and says so.
|
||||||
|
Button(postURL == nil ? "Send as Draft" : "Update Live Post") { send() }
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
.disabled(busy)
|
||||||
Button("Done") { dismiss() }
|
Button("Done") { dismiss() }
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
} else {
|
} else {
|
||||||
Button("Publish") { publish() }
|
Button("Publish") { publish() }
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
.disabled(draftURL == nil || phase == .drafting || phase == .publishing)
|
.disabled(postURL == nil || busy)
|
||||||
if draftURL != nil {
|
// The piece changed since the draft — a re-send
|
||||||
// The piece changed since the draft — a fresh send
|
// updates that same draft (never a second post).
|
||||||
// replaces it (and the remembered URL).
|
Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
|
||||||
Button("Send Again") { sendDraft() }
|
.buttonStyle(.bordered)
|
||||||
.buttonStyle(.bordered)
|
.disabled(busy)
|
||||||
.disabled(phase == .drafting || phase == .publishing)
|
|
||||||
} else {
|
|
||||||
Button("Send as Draft") { sendDraft() }
|
|
||||||
.buttonStyle(.bordered)
|
|
||||||
.disabled(phase == .drafting || phase == .publishing)
|
|
||||||
}
|
|
||||||
Button("Cancel") { dismiss() }
|
Button("Cancel") { dismiss() }
|
||||||
.buttonStyle(.bordered)
|
.buttonStyle(.bordered)
|
||||||
}
|
}
|
||||||
@@ -117,17 +267,20 @@ struct MicropubPublishSheet: View {
|
|||||||
.padding(16)
|
.padding(16)
|
||||||
.frame(width: 340, alignment: .leading)
|
.frame(width: 340, alignment: .leading)
|
||||||
.onAppear {
|
.onAppear {
|
||||||
// A draft sent in an earlier session is still publishable:
|
// A piece sent in an earlier session still has its record:
|
||||||
// the piece remembers its URL.
|
// the remembered URL, and (#206) its publish stamp.
|
||||||
if draftURL == nil, let id = posts.session?.postID {
|
guard postURL == nil, let id = posts.session?.postID,
|
||||||
if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL {
|
let post = posts.posts.first(where: { $0.id == id })
|
||||||
draftURL = remembered
|
else { return }
|
||||||
}
|
postURL = post.micropubURL
|
||||||
}
|
publishedAt = post.micropubPublished
|
||||||
|
phase = settledPhase
|
||||||
|
syncFieldFromDisk()
|
||||||
|
loadSuggestions()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Steps
|
// MARK: Status
|
||||||
|
|
||||||
/// The open piece's Title (the sheet is only reachable with a piece
|
/// The open piece's Title (the sheet is only reachable with a piece
|
||||||
/// open; the id is the honest fallback).
|
/// open; the id is the honest fallback).
|
||||||
@@ -135,10 +288,49 @@ struct MicropubPublishSheet: View {
|
|||||||
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
|
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
|
||||||
}
|
}
|
||||||
|
|
||||||
private var statusURL: String? {
|
private var statusLabel: String? {
|
||||||
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil
|
switch phase {
|
||||||
|
case .idle:
|
||||||
|
nil
|
||||||
|
case .drafting:
|
||||||
|
"Sending draft…"
|
||||||
|
case .drafted:
|
||||||
|
"Draft on Micro.blog — not published yet"
|
||||||
|
case .updating:
|
||||||
|
publishedAt == nil ? "Updating draft…" : "Updating live post…"
|
||||||
|
case .updated:
|
||||||
|
publishedAt.map { "Updated live — published \(Micropub.shortDate($0))" } ?? "Draft updated — not published yet"
|
||||||
|
case .publishing:
|
||||||
|
"Publishing…"
|
||||||
|
case .published:
|
||||||
|
publishedAt.map { "Published \(Micropub.shortDate($0))" }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A published piece links its live post; a draft links the review
|
||||||
|
/// page — only the send that created it carries one, so a draft
|
||||||
|
/// remembered from an earlier session shows no (dead) link.
|
||||||
|
private var statusLink: URL? {
|
||||||
|
if publishedAt != nil {
|
||||||
|
return postURL.flatMap { URL(string: $0) }
|
||||||
|
}
|
||||||
|
return previewURL.flatMap { URL(string: $0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the sheet rests on the piece's record: published, draft,
|
||||||
|
/// or never sent.
|
||||||
|
private var settledPhase: Phase {
|
||||||
|
if publishedAt != nil {
|
||||||
|
return .published
|
||||||
|
}
|
||||||
|
if postURL != nil {
|
||||||
|
return .drafted
|
||||||
|
}
|
||||||
|
return .idle
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Steps
|
||||||
|
|
||||||
/// Resolve the token: a freshly entered one is saved ONCE (rotation
|
/// Resolve the token: a freshly entered one is saved ONCE (rotation
|
||||||
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
|
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
|
||||||
/// a silent send.
|
/// a silent send.
|
||||||
@@ -153,29 +345,48 @@ struct MicropubPublishSheet: View {
|
|||||||
return saved
|
return saved
|
||||||
}
|
}
|
||||||
|
|
||||||
private func sendDraft() {
|
/// A failed step: the message shows inline with the buttons kept, and
|
||||||
|
/// the sheet rests on the piece's record (a rejected token re-opens
|
||||||
|
/// entry — the entered-once token may be wrong). #207: the category
|
||||||
|
/// baseline follows the disk (the field keeps the text as typed).
|
||||||
|
private func fail(_ message: String, tokenRejected: Bool = false) {
|
||||||
|
if tokenRejected {
|
||||||
|
reentry = true
|
||||||
|
}
|
||||||
|
refusal = message
|
||||||
|
phase = settledPhase
|
||||||
|
syncSettledFromDisk()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Step 1 — the model decides create-vs-update by the piece's
|
||||||
|
/// remembered URL: a first send creates the draft, every later one
|
||||||
|
/// updates that post in place.
|
||||||
|
private func send() {
|
||||||
guard let token = resolveToken() else {
|
guard let token = resolveToken() else {
|
||||||
refusal = "Paste your Micro.blog app token first."
|
refusal = "Paste your Micro.blog app token first."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
refusal = nil
|
refusal = nil
|
||||||
phase = .drafting
|
phase = postURL == nil ? .drafting : .updating
|
||||||
Task {
|
Task {
|
||||||
switch await posts.micropubSendDraft(token: token) {
|
switch await posts.micropubSend(token: token, categories: pendingCategories) {
|
||||||
case let .drafted(url, preview):
|
case let .drafted(url, preview):
|
||||||
draftURL = url
|
postURL = url
|
||||||
previewURL = preview
|
previewURL = preview
|
||||||
phase = .drafted
|
phase = .drafted
|
||||||
|
sendLanded()
|
||||||
|
case let .updated(url):
|
||||||
|
postURL = url
|
||||||
|
phase = .updated
|
||||||
|
sendLanded()
|
||||||
case let .authFailed(detail):
|
case let .authFailed(detail):
|
||||||
reentry = true // the entered-once token may be wrong
|
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
|
||||||
refusal = "Micro.blog rejected the token: \(detail)"
|
|
||||||
phase = draftURL == nil ? .idle : .drafted
|
|
||||||
case let .refused(reason), let .unreachable(reason):
|
case let .refused(reason), let .unreachable(reason):
|
||||||
refusal = reason
|
fail(reason)
|
||||||
phase = draftURL == nil ? .idle : .drafted
|
|
||||||
case let .requestFailed(status, detail):
|
case let .requestFailed(status, detail):
|
||||||
refusal = "Micro.blog said \(status): \(detail)"
|
fail("Micro.blog said \(status): \(detail)")
|
||||||
phase = draftURL == nil ? .idle : .drafted
|
case let .forgotten(reason):
|
||||||
|
forgot(reason)
|
||||||
case .published:
|
case .published:
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -183,29 +394,98 @@ struct MicropubPublishSheet: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func publish() {
|
private func publish() {
|
||||||
guard let url = draftURL, let token = resolveToken() else {
|
guard let url = postURL, let token = resolveToken() else {
|
||||||
refusal = "Paste your Micro.blog app token first."
|
refusal = "Paste your Micro.blog app token first."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
refusal = nil
|
refusal = nil
|
||||||
phase = .publishing
|
phase = .publishing
|
||||||
Task {
|
Task {
|
||||||
switch await Micropub.publish(url: url, token: token) {
|
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories) {
|
||||||
case .published:
|
case .published:
|
||||||
|
publishedAt = Date()
|
||||||
phase = .published
|
phase = .published
|
||||||
|
settle()
|
||||||
case let .authFailed(detail):
|
case let .authFailed(detail):
|
||||||
reentry = true
|
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
|
||||||
refusal = "Micro.blog rejected the token: \(detail)"
|
|
||||||
phase = .drafted
|
|
||||||
case let .refused(reason), let .unreachable(reason):
|
case let .refused(reason), let .unreachable(reason):
|
||||||
refusal = reason
|
fail(reason)
|
||||||
phase = .drafted
|
|
||||||
case let .requestFailed(status, detail):
|
case let .requestFailed(status, detail):
|
||||||
refusal = "Micro.blog said \(status): \(detail)"
|
fail("Micro.blog said \(status): \(detail)")
|
||||||
phase = .drafted
|
case let .forgotten(reason):
|
||||||
case .drafted:
|
forgot(reason)
|
||||||
|
case .drafted, .updated:
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #206: Micro.blog lost the post and the piece forgot it — the
|
||||||
|
/// sheet is back on a never-sent piece (a fresh draft is one click
|
||||||
|
/// away).
|
||||||
|
private func forgot(_ reason: String) {
|
||||||
|
refusal = reason
|
||||||
|
postURL = nil
|
||||||
|
publishedAt = nil
|
||||||
|
previewURL = nil
|
||||||
|
phase = .idle
|
||||||
|
// #207: the forget clears only the micropub keys — a category
|
||||||
|
// line the failed send already wrote stays on the piece, so the
|
||||||
|
// field re-syncs to it (no false pending state).
|
||||||
|
syncFieldFromDisk()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Categories (#207)
|
||||||
|
|
||||||
|
/// The piece's `category:` line as it is on DISK (the model's read —
|
||||||
|
/// never the scan snapshot), in the codec's unbracketed form. No
|
||||||
|
/// open saved piece, or an unreadable file → "".
|
||||||
|
private var diskCategoryText: String {
|
||||||
|
PostFrontmatter.categoryListValue(posts.openPieceCategories())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The field AND its baseline take the disk's line (on open, after a
|
||||||
|
/// forget).
|
||||||
|
private func syncFieldFromDisk() {
|
||||||
|
categoryField = diskCategoryText
|
||||||
|
settledCategoryField = categoryField
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only the BASELINE follows the disk (a failed step). The send
|
||||||
|
/// writes the category line BEFORE the wire, so a refusal or a
|
||||||
|
/// failed publish may leave the edit on the piece; the pending test
|
||||||
|
/// must compare against what the piece really holds — a later clear
|
||||||
|
/// of the field has to count as an edit. The field keeps the text as
|
||||||
|
/// typed.
|
||||||
|
private func syncSettledFromDisk() {
|
||||||
|
settledCategoryField = diskCategoryText
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The blog's categories for the menu, over the Keychain's token.
|
||||||
|
/// A failure is silent — no suggestions is a normal state (the
|
||||||
|
/// field still works: a typed new name creates the category).
|
||||||
|
private func loadSuggestions() {
|
||||||
|
guard let token = MicropubTokenStore.read() else { return }
|
||||||
|
Task {
|
||||||
|
blogCategories = await Micropub.blogCategories(token: token)
|
||||||
|
suggestionsLoaded = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A send landed: the writer sees the canonical text, and the
|
||||||
|
/// edit is no longer pending. (A REFUSED send keeps the text as typed.)
|
||||||
|
private func settle() {
|
||||||
|
categoryField = PostFrontmatter.categoryListValue(PostFrontmatter.categoryList(categoryField))
|
||||||
|
settledCategoryField = categoryField
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A successful send: the field settles, and a token first entered
|
||||||
|
/// in this sheet gets its suggestions now — once. A blog WITH no
|
||||||
|
/// categories is not asked again after every send.
|
||||||
|
private func sendLanded() {
|
||||||
|
settle()
|
||||||
|
if !suggestionsLoaded {
|
||||||
|
loadSuggestions()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -16,11 +16,9 @@ import SwiftUI
|
|||||||
@MainActor
|
@MainActor
|
||||||
@Observable
|
@Observable
|
||||||
final class AppGateState {
|
final class AppGateState {
|
||||||
/// #141: the live prose text view — the window-level drop destination
|
/// #141: the live prose text view — the window-level SwiftUI destination
|
||||||
/// (the ONLY destination that ever fires; nested editor-level SwiftUI
|
/// (drops landing OUTSIDE the editor) reaches it through this handle;
|
||||||
/// targets are never consulted, and AppKit views registered for file
|
/// routing lives in `routeFileDrop`.
|
||||||
/// drags are starved by it — field-verified 2026-11-02) routes image
|
|
||||||
/// drops to the editor through this handle.
|
|
||||||
let proseDrop = ProseDropBridge()
|
let proseDrop = ProseDropBridge()
|
||||||
let gateModel = EngineGateModel()
|
let gateModel = EngineGateModel()
|
||||||
let provisioning = ProvisioningModel()
|
let provisioning = ProvisioningModel()
|
||||||
@@ -118,6 +116,23 @@ final class AppGateState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #91 + #141 — the ONE file-drop router. Two surfaces reach it, never
|
||||||
|
/// both for one drag (27.2 routing: the editor's text view when the
|
||||||
|
/// pointer is over it, the window-level SwiftUI destination elsewhere):
|
||||||
|
/// a PURE-markdown set opens as the guest; anything else goes to the
|
||||||
|
/// open piece's prose ingest, which refuses loudly (drafts, mixed
|
||||||
|
/// md+image sets, non-publishable or non-file URLs).
|
||||||
|
/// #162: no new buffers while a Cold Turkey block holds.
|
||||||
|
func routeFileDrop(_ urls: [URL]) -> Bool {
|
||||||
|
guard !writingLock.isLocked else { return false }
|
||||||
|
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
|
||||||
|
posts.openExternal(url)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
guard let textView = proseDrop.textView else { return false }
|
||||||
|
return textView.ingestDrop(urls)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
|
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
|
||||||
|
|||||||
@@ -127,8 +127,11 @@ struct OutlineRowTextView: NSViewRepresentable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The row NSTextView: structural key interception.
|
/// The row NSTextView: structural key interception. `FileDropTextView`
|
||||||
final class RowTextView: NSTextView {
|
/// base (27.2 routing): a file drag landing on a row bounces instead of
|
||||||
|
/// pasting the path — images don't ingest into outlines (#141); text
|
||||||
|
/// drags keep the stock drop.
|
||||||
|
final class RowTextView: FileDropTextView {
|
||||||
weak var bridge: OutlineRowTextView.Coordinator?
|
weak var bridge: OutlineRowTextView.Coordinator?
|
||||||
|
|
||||||
override func keyDown(with event: NSEvent) {
|
override func keyDown(with event: NSEvent) {
|
||||||
|
|||||||
@@ -47,9 +47,10 @@ struct PostEditorView: View {
|
|||||||
/// #68: reading is a transient act of inspection — no persistence; a
|
/// #68: reading is a transient act of inspection — no persistence; a
|
||||||
/// fresh open always lands in editing.
|
/// fresh open always lands in editing.
|
||||||
@State private var reading = false
|
@State private var reading = false
|
||||||
/// Flip-back caret (#68): source location + a token so repeated flips to
|
/// Flip-back caret (#68) and #204 jump span: a zero-length range is a
|
||||||
/// the same location re-apply. Consumed by ProseTextView's coordinator.
|
/// bare caret landing, a non-zero range selects the anchor; the token
|
||||||
@State private var flipBackCaret: (location: Int, token: Int)?
|
/// re-applies repeats. Consumed by ProseTextView's coordinator.
|
||||||
|
@State private var flipBackCaret: FixCardRevealRequest?
|
||||||
@State private var flipToken = 0
|
@State private var flipToken = 0
|
||||||
/// Reading scroll state (#68 mapping): entry caret + live top block.
|
/// Reading scroll state (#68 mapping): entry caret + live top block.
|
||||||
@State private var readingState = ReadingStateBox()
|
@State private var readingState = ReadingStateBox()
|
||||||
@@ -108,6 +109,22 @@ struct PostEditorView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// #204: a Fix Card jump (the palette's Jump) lands here — the model's
|
||||||
|
// reveal request rides the SAME caret rail as the reading flip-back,
|
||||||
|
// through the ONE token counter (two counters could collide and a
|
||||||
|
// jump would silently never land): the span selected, revealed, and
|
||||||
|
// the main window made key so the writer can type where the card
|
||||||
|
// pointed (the coordinator does that — it owns tv.window). A jump
|
||||||
|
// while READING leaves reading first — plain `reading = false`, not
|
||||||
|
// exitReading (which would stamp its own zero-length hint over the
|
||||||
|
// jump); the remounted coordinator applies the jump after the load.
|
||||||
|
// Outline pieces have no prose surface — the request is dropped.
|
||||||
|
.onChange(of: gate.posts.revealRequest) { _, request in
|
||||||
|
guard let request, !outline else { return }
|
||||||
|
flipToken += 1
|
||||||
|
flipBackCaret = FixCardRevealRequest(range: request.range, token: flipToken)
|
||||||
|
reading = false
|
||||||
|
}
|
||||||
.onAppear {
|
.onAppear {
|
||||||
if draftMirror.isEmpty {
|
if draftMirror.isEmpty {
|
||||||
draftMirror = draftText ?? ""
|
draftMirror = draftText ?? ""
|
||||||
@@ -182,6 +199,7 @@ struct PostEditorView: View {
|
|||||||
focused: gate.isFocused,
|
focused: gate.isFocused,
|
||||||
caretHint: flipBackCaret,
|
caretHint: flipBackCaret,
|
||||||
dropBridge: gate.proseDrop,
|
dropBridge: gate.proseDrop,
|
||||||
|
routeDrop: { gate.routeFileDrop($0) },
|
||||||
// #162: the Cold Turkey word feed.
|
// #162: the Cold Turkey word feed.
|
||||||
onTextChange: { gate.writingLock.feed(text: $0) },
|
onTextChange: { gate.writingLock.feed(text: $0) },
|
||||||
)
|
)
|
||||||
@@ -196,6 +214,7 @@ struct PostEditorView: View {
|
|||||||
},
|
},
|
||||||
caretHint: flipBackCaret,
|
caretHint: flipBackCaret,
|
||||||
dropBridge: gate.proseDrop,
|
dropBridge: gate.proseDrop,
|
||||||
|
routeDrop: { gate.routeFileDrop($0) },
|
||||||
// #162: the Cold Turkey word feed.
|
// #162: the Cold Turkey word feed.
|
||||||
onTextChange: { gate.writingLock.feed(text: $0) },
|
onTextChange: { gate.writingLock.feed(text: $0) },
|
||||||
)
|
)
|
||||||
@@ -218,7 +237,7 @@ struct PostEditorView: View {
|
|||||||
flipToken += 1
|
flipToken += 1
|
||||||
// Toggle-back maps the reading scroll back (top visible block);
|
// Toggle-back maps the reading scroll back (top visible block);
|
||||||
// click-to-edit lands at the clicked paragraph (survives always).
|
// click-to-edit lands at the clicked paragraph (survives always).
|
||||||
flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken)
|
flipBackCaret = FixCardRevealRequest(range: NSRange(location: caret ?? readingState.topSourceLocation ?? 0, length: 0), token: flipToken)
|
||||||
reading = false
|
reading = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,8 +357,8 @@ private struct SaveStateDot: View {
|
|||||||
|
|
||||||
// MARK: - TextKit2 surface (the lifted spike pane)
|
// MARK: - TextKit2 surface (the lifted spike pane)
|
||||||
|
|
||||||
/// #141: the SwiftUI drop target's handle down to the live prose text
|
/// #141: the window-level SwiftUI destination's handle down to the live
|
||||||
/// view (weak — dies with the editor surface).
|
/// prose text view (weak — dies with the editor surface).
|
||||||
@MainActor
|
@MainActor
|
||||||
final class ProseDropBridge {
|
final class ProseDropBridge {
|
||||||
weak var textView: ProseListTextView?
|
weak var textView: ProseListTextView?
|
||||||
@@ -348,8 +367,9 @@ final class ProseDropBridge {
|
|||||||
/// NSTextView in a scroll view; attributes are presentation-only over a plain
|
/// NSTextView in a scroll view; attributes are presentation-only over a plain
|
||||||
/// store. Session mode: edits → session.edit (debounce), cursor → session,
|
/// store. Session mode: edits → session.edit (debounce), cursor → session,
|
||||||
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
|
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
|
||||||
/// #71: `caretHint` (location + token) lands the caret after a flip back
|
/// #71/#204: `caretHint` (range + token) lands a bare caret after a flip
|
||||||
/// from reading — applied once per token, after any generation load.
|
/// back from reading or SELECTS a card's anchor span after a Jump — applied
|
||||||
|
/// once per token, after any generation load.
|
||||||
struct ProseTextView: NSViewRepresentable {
|
struct ProseTextView: NSViewRepresentable {
|
||||||
var session: EditorSession?
|
var session: EditorSession?
|
||||||
var draft: String?
|
var draft: String?
|
||||||
@@ -361,22 +381,24 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
var spellChecking = false
|
var spellChecking = false
|
||||||
/// #21: focus mode — the text ground joins the workspace background.
|
/// #21: focus mode — the text ground joins the workspace background.
|
||||||
var focused = false
|
var focused = false
|
||||||
var caretHint: (location: Int, token: Int)?
|
var caretHint: FixCardRevealRequest?
|
||||||
/// #141: the piece folder dropped images ingest into — saved posts
|
/// #141: the piece folder dropped images ingest into — saved posts
|
||||||
/// only (drafts have no folder until first save; the external guest
|
/// only (drafts have no folder until first save; the external guest
|
||||||
/// isn't a piece). Nil = image drags refuse loudly.
|
/// isn't a piece). Nil = image drags refuse loudly.
|
||||||
var ingestFolder: URL?
|
var ingestFolder: URL?
|
||||||
/// #141: the drop bridge — the WINDOW-level SwiftUI drop target
|
/// #141: the window-level SwiftUI destination's handle to the live
|
||||||
/// reaches this text view through it (app-scoped, passed down from
|
/// view (drops landing OUTSIDE the editor); the gate's router for drops
|
||||||
/// the gate at both call sites — never optional).
|
/// landing ON it — both handed down from the gate at both call sites.
|
||||||
var dropBridge: ProseDropBridge
|
var dropBridge: ProseDropBridge
|
||||||
|
var routeDrop: ([URL]) -> Bool
|
||||||
|
|
||||||
init(
|
init(
|
||||||
session: EditorSession,
|
session: EditorSession,
|
||||||
spellChecking: Bool = false,
|
spellChecking: Bool = false,
|
||||||
focused: Bool = false,
|
focused: Bool = false,
|
||||||
caretHint: (location: Int, token: Int)? = nil,
|
caretHint: FixCardRevealRequest? = nil,
|
||||||
dropBridge: ProseDropBridge,
|
dropBridge: ProseDropBridge,
|
||||||
|
routeDrop: @escaping ([URL]) -> Bool,
|
||||||
onTextChange: ((String) -> Void)? = nil,
|
onTextChange: ((String) -> Void)? = nil,
|
||||||
) {
|
) {
|
||||||
self.session = session
|
self.session = session
|
||||||
@@ -386,6 +408,7 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
self.onTextChange = onTextChange
|
self.onTextChange = onTextChange
|
||||||
ingestFolder = session.postID != nil ? session.folderURL : nil
|
ingestFolder = session.postID != nil ? session.folderURL : nil
|
||||||
self.dropBridge = dropBridge
|
self.dropBridge = dropBridge
|
||||||
|
self.routeDrop = routeDrop
|
||||||
}
|
}
|
||||||
|
|
||||||
init(
|
init(
|
||||||
@@ -393,8 +416,9 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
spellChecking: Bool = false,
|
spellChecking: Bool = false,
|
||||||
focused: Bool = false,
|
focused: Bool = false,
|
||||||
onEdit: @escaping (String) -> Void,
|
onEdit: @escaping (String) -> Void,
|
||||||
caretHint: (location: Int, token: Int)? = nil,
|
caretHint: FixCardRevealRequest? = nil,
|
||||||
dropBridge: ProseDropBridge,
|
dropBridge: ProseDropBridge,
|
||||||
|
routeDrop: @escaping ([URL]) -> Bool,
|
||||||
onTextChange: ((String) -> Void)? = nil,
|
onTextChange: ((String) -> Void)? = nil,
|
||||||
) {
|
) {
|
||||||
self.draft = draft
|
self.draft = draft
|
||||||
@@ -404,6 +428,7 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
self.caretHint = caretHint
|
self.caretHint = caretHint
|
||||||
self.onTextChange = onTextChange
|
self.onTextChange = onTextChange
|
||||||
self.dropBridge = dropBridge
|
self.dropBridge = dropBridge
|
||||||
|
self.routeDrop = routeDrop
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cursor state snapshot from the live view (#66).
|
/// Cursor state snapshot from the live view (#66).
|
||||||
@@ -421,16 +446,30 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
/// location 0 then rests inside the invisible 9pt blank fragment ABOVE
|
/// location 0 then rests inside the invisible 9pt blank fragment ABOVE
|
||||||
/// the title, rendering as a detached terracotta stroke at the canvas
|
/// the title, rendering as a detached terracotta stroke at the canvas
|
||||||
/// top. Programmatic landings (cursor restore, reading flip-back) hop
|
/// top. Programmatic landings (cursor restore, reading flip-back) hop
|
||||||
/// over leading blanks to the first content line; interactive
|
/// over leading blanks to the first content line — zero-length landings
|
||||||
/// placements (click, drag, typing) never route through here.
|
/// only, a #204 span never hops (`landingSpan`); interactive placements
|
||||||
|
/// (click, drag, typing) never route through here.
|
||||||
static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int {
|
static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int {
|
||||||
max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
|
max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where a caret-hint lands, clamped to the text: a zero-length range
|
||||||
|
/// (#71 flip-back) is a bare caret and hops past leading blanks; a
|
||||||
|
/// non-zero range (#204 jump) SELECTS the anchor exactly where it
|
||||||
|
/// resolved — a quote that IS the leading blanks selects those blanks,
|
||||||
|
/// never the title (the load restore gates its hop the same way).
|
||||||
|
static func landingSpan(for hint: FixCardRevealRequest, in text: String) -> NSRange {
|
||||||
|
let length = (text as NSString).length
|
||||||
|
let start = hint.range.length == 0 ? caretPastLeadingBlanks(max(0, hint.range.location), in: text) : max(0, hint.range.location)
|
||||||
|
let loc = min(start, length)
|
||||||
|
return NSRange(location: loc, length: min(max(0, hint.range.length), length - loc))
|
||||||
|
}
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSScrollView {
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
|
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
|
||||||
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
|
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
|
||||||
dropBridge.textView = tv // #141: the SwiftUI drop target's handle
|
dropBridge.textView = tv // #141: the window destination's handle
|
||||||
|
tv.onFileDrop = routeDrop // #141: the view's own drag handlers route here
|
||||||
tv.isRichText = false // plain source of truth; attributes are presentation
|
tv.isRichText = false // plain source of truth; attributes are presentation
|
||||||
tv.allowsUndo = true
|
tv.allowsUndo = true
|
||||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
@@ -485,6 +524,7 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
tv.isContinuousSpellCheckingEnabled = spellChecking
|
tv.isContinuousSpellCheckingEnabled = spellChecking
|
||||||
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
|
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
|
||||||
dropBridge.textView = tv // #141: idempotent re-point
|
dropBridge.textView = tv // #141: idempotent re-point
|
||||||
|
tv.onFileDrop = routeDrop // #141: idempotent re-point
|
||||||
// #21: the ground follows focus in/out without a remount.
|
// #21: the ground follows focus in/out without a remount.
|
||||||
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
|
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
|
||||||
tv.backgroundColor = ground
|
tv.backgroundColor = ground
|
||||||
@@ -532,25 +572,9 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
|
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
|
||||||
tv.refreshFolds() // #115: re-key folds over the swapped content
|
tv.refreshFolds() // #115: re-key folds over the swapped content
|
||||||
}
|
}
|
||||||
// #71: flip-back caret — apply once per token, after any load above.
|
// #71 flip-back caret / #204 jump span — apply once per token, after any load above.
|
||||||
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
|
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
|
||||||
context.coordinator.appliedCaretToken = hint.token
|
context.coordinator.applyCaretHint(hint, tv: tv, session: session)
|
||||||
let length = (tv.string as NSString).length
|
|
||||||
// #ui-r1: same leading-blank hop as the load restore — a reading
|
|
||||||
// flip-back must never park the caret above the first content line.
|
|
||||||
let loc = min(Self.caretPastLeadingBlanks(max(0, hint.location), in: tv.string), length)
|
|
||||||
tv.setSelectedRange(NSRange(location: loc, length: 0))
|
|
||||||
// ponytail: same layout race as the cursor-restore scroll above —
|
|
||||||
// this was the click-to-edit "always lands at top" defect: the sync
|
|
||||||
// scrollRangeToVisible fired before the target region was laid out.
|
|
||||||
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
|
|
||||||
DispatchQueue.main.async { [weak tv] in
|
|
||||||
tv?.scrollRangeToVisible(NSRange(location: loc, length: 0))
|
|
||||||
tv?.window?.makeFirstResponder(tv)
|
|
||||||
}
|
|
||||||
if let session {
|
|
||||||
session.cursorUpdate(ProseTextView.cursorState(of: tv))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -576,6 +600,33 @@ struct ProseTextView: NSViewRepresentable {
|
|||||||
onTextChange = representable.onTextChange
|
onTextChange = representable.onTextChange
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The caret rail's landing (#71 flip-back, #204 jump). Called by the
|
||||||
|
/// representable once per token.
|
||||||
|
func applyCaretHint(_ hint: FixCardRevealRequest, tv: NSTextView, session: EditorSession?) {
|
||||||
|
appliedCaretToken = hint.token
|
||||||
|
let landing = ProseTextView.landingSpan(for: hint, in: tv.string)
|
||||||
|
tv.setSelectedRange(landing)
|
||||||
|
// ponytail: same layout race as the cursor-restore scroll — this was
|
||||||
|
// the click-to-edit "always lands at top" defect: the sync
|
||||||
|
// scrollRangeToVisible fired before the target region was laid out.
|
||||||
|
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
|
||||||
|
DispatchQueue.main.async { [weak tv] in
|
||||||
|
guard let tv else { return }
|
||||||
|
// #204: a jump (span > 0) comes from the palette window, which
|
||||||
|
// holds key after the click — make the main window key or the
|
||||||
|
// first responder never sees keystrokes. The #71 flip-back
|
||||||
|
// (span 0) is already in the key window; untouched.
|
||||||
|
if landing.length > 0 {
|
||||||
|
tv.window?.makeKeyAndOrderFront(nil)
|
||||||
|
}
|
||||||
|
tv.scrollRangeToVisible(landing)
|
||||||
|
tv.window?.makeFirstResponder(tv)
|
||||||
|
// Recorded AFTER the scroll: the sidecar's scrollOffset must be
|
||||||
|
// the landed one, or a reopen restores an off-screen selection.
|
||||||
|
session?.cursorUpdate(ProseTextView.cursorState(of: tv))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
func textDidChange(_ notification: Notification) {
|
||||||
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
||||||
let sel = tv.selectedRange()
|
let sel = tv.selectedRange()
|
||||||
|
|||||||
+168
-13
@@ -12,6 +12,10 @@
|
|||||||
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
|
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
|
||||||
// of scope (#180); their dismiss stamp rides the generic update posture
|
// of scope (#180); their dismiss stamp rides the generic update posture
|
||||||
// without redesigning its shape.
|
// without redesigning its shape.
|
||||||
|
// #207: the one-line `category:` list — read (`categories(in:)`) and
|
||||||
|
// render (`categoryValue(_:)`) over the unbracketed pair the publish
|
||||||
|
// sheet's field also speaks (`categoryList`/`categoryListValue`): ONE
|
||||||
|
// parser serves the piece, the sheet, and the wire.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
@@ -24,7 +28,9 @@ import Foundation
|
|||||||
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
|
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
|
||||||
/// normalization on save/advance, convert. Replaces any existing block.
|
/// normalization on save/advance, convert. Replaces any existing block.
|
||||||
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
|
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
|
||||||
/// with our three owned keys winning in place (importFile, #95).
|
/// with our three owned keys winning in place (importFile, #95), and
|
||||||
|
/// Museion's Micro.blog bookkeeping dropped (#206 — a foreign file
|
||||||
|
/// carries no post of THIS library).
|
||||||
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
|
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
|
||||||
/// every other line byte-identical (editor save, pass advance, stats
|
/// every other line byte-identical (editor save, pass advance, stats
|
||||||
/// capture, micropub URL, learnings dismiss).
|
/// capture, micropub URL, learnings dismiss).
|
||||||
@@ -33,6 +39,19 @@ import Foundation
|
|||||||
/// `origin`) are ONE rule shared by every posture: absent owned keys
|
/// `origin`) are ONE rule shared by every posture: absent owned keys
|
||||||
/// insert before the closing `---` in that order.
|
/// insert before the closing `---` in that order.
|
||||||
nonisolated enum PostFrontmatter {
|
nonisolated enum PostFrontmatter {
|
||||||
|
/// The frontmatter timestamp shape (`stats_captured`, #31;
|
||||||
|
/// `micropub_published`, #206) — local time, lexically sortable. The
|
||||||
|
/// one home for the format: both stamp writers and the reader share it.
|
||||||
|
static let stampFormat = "yyyy-MM-dd'T'HH:mm:ss"
|
||||||
|
|
||||||
|
/// Museion's Micro.blog bookkeeping — written only by the app (or the
|
||||||
|
/// writer's own hand, the legacy migration), never trusted from
|
||||||
|
/// outside: the import boundary DROPS these keys and the 404 forget
|
||||||
|
/// removes them. #206: an imported `micropub_url` passes the format
|
||||||
|
/// gate and would steer the next send's content replace — under the
|
||||||
|
/// writer's token — onto whatever post it names.
|
||||||
|
static let micropubKeys: Set<String> = ["micropub_url", "micropub_published"]
|
||||||
|
|
||||||
/// The leniently-decoded identity triple — one home for the `?? default`
|
/// The leniently-decoded identity triple — one home for the `?? default`
|
||||||
/// reads scan, the write paths, and the eligibility predicates share
|
/// reads scan, the write paths, and the eligibility predicates share
|
||||||
/// (the extraction the #31 capture's ponytail note deferred until this
|
/// (the extraction the #31 capture's ponytail note deferred until this
|
||||||
@@ -108,6 +127,126 @@ nonisolated enum PostFrontmatter {
|
|||||||
return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft
|
return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Category list (#207)
|
||||||
|
|
||||||
|
/// #207: the quote-aware comma-list parse the `category:` line and
|
||||||
|
/// the publish sheet's category FIELD share — ONE parser (the
|
||||||
|
/// field holds exactly the bracket-inner text). Splits on the
|
||||||
|
/// commas OUTSIDE double quotes, trims each item, strips ONE pair
|
||||||
|
/// of surrounding double quotes and unescapes `\\` and `\"`;
|
||||||
|
/// empties drop and the first occurrence of a name wins. Creation
|
||||||
|
/// is implicit on Micro.blog: naming a category that doesn't exist
|
||||||
|
/// creates it when the post is sent.
|
||||||
|
static func categoryList(_ inner: String) -> [String] {
|
||||||
|
var names: [String] = []
|
||||||
|
var seen: Set<String> = []
|
||||||
|
for item in categorySegments(inner) {
|
||||||
|
let trimmed = item.trimmingCharacters(in: .whitespaces)
|
||||||
|
var name = trimmed
|
||||||
|
// A quoted item carries its whitespace and its escapes
|
||||||
|
// (`\\` and `\"`) verbatim; a bare item is taken as written.
|
||||||
|
if trimmed.hasPrefix("\""), trimmed.hasSuffix("\""), trimmed.count >= 2 {
|
||||||
|
name = categoryUnescaped(String(trimmed.dropFirst().dropLast()))
|
||||||
|
}
|
||||||
|
guard !name.isEmpty, seen.insert(name).inserted else { continue }
|
||||||
|
names.append(name)
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `categoryListValue`'s escape, undone: `\\` is a backslash, `\"` a
|
||||||
|
/// quote. Any other escaped character keeps its backslash (a
|
||||||
|
/// hand-typed `\n` stays the two characters it is), and a trailing
|
||||||
|
/// lone backslash stays.
|
||||||
|
private static func categoryUnescaped(_ text: String) -> String {
|
||||||
|
var out = ""
|
||||||
|
var escaped = false
|
||||||
|
for char in text {
|
||||||
|
if escaped {
|
||||||
|
if char != "\\", char != "\"" {
|
||||||
|
out.append("\\")
|
||||||
|
}
|
||||||
|
out.append(char)
|
||||||
|
escaped = false
|
||||||
|
} else if char == "\\" {
|
||||||
|
escaped = true
|
||||||
|
} else {
|
||||||
|
out.append(char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if escaped {
|
||||||
|
out.append("\\")
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unbracketed render `categoryList` reads back — a name
|
||||||
|
/// holding `,` `[` `]` `"` or `\` rides double-quoted with its
|
||||||
|
/// backslashes and quotes escaped. Newlines and control characters
|
||||||
|
/// strip from every name first (the frontmatter sink is
|
||||||
|
/// line-bounded) and names left empty drop.
|
||||||
|
static func categoryListValue(_ names: [String]) -> String {
|
||||||
|
names.compactMap { name -> String? in
|
||||||
|
let cleaned = String(name.trimmingCharacters(in: .whitespaces).unicodeScalars.filter {
|
||||||
|
!CharacterSet.newlines.contains($0) && !CharacterSet.controlCharacters.contains($0)
|
||||||
|
})
|
||||||
|
guard !cleaned.isEmpty else { return nil }
|
||||||
|
guard cleaned.contains(where: { ",[]\"\\".contains($0) }) else { return cleaned }
|
||||||
|
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
|
||||||
|
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
|
||||||
|
}.joined(separator: ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list items, split on the commas outside double quotes (an
|
||||||
|
/// escaped quote inside a quoted item never toggles the quote
|
||||||
|
/// state — `["say \"hi\", Notes]` is two items).
|
||||||
|
/// The ONE segment scanner behind `categoryList` and the publish
|
||||||
|
/// sheet's `partial` — the raw (untrimmed, still-quoted) items.
|
||||||
|
static func categorySegments(_ text: String) -> [String] {
|
||||||
|
var items: [String] = []
|
||||||
|
var current = ""
|
||||||
|
var quoted = false
|
||||||
|
var escaped = false
|
||||||
|
for char in text {
|
||||||
|
if escaped {
|
||||||
|
current.append(char)
|
||||||
|
escaped = false
|
||||||
|
} else if char == "\\" {
|
||||||
|
current.append(char)
|
||||||
|
escaped = true
|
||||||
|
} else if char == "\"" {
|
||||||
|
current.append(char)
|
||||||
|
quoted.toggle()
|
||||||
|
} else if char == ",", !quoted {
|
||||||
|
items.append(current)
|
||||||
|
current = ""
|
||||||
|
} else {
|
||||||
|
current.append(char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items.append(current)
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #207: the piece's categories from its `category:` line — ONE
|
||||||
|
/// line by construction (the read is line-bounded, #33), so a
|
||||||
|
/// value can never carry a newline. Shapes: `[Tech, Notes]` (the
|
||||||
|
/// bracketed list, read through `categoryList`), a bare scalar
|
||||||
|
/// (`Essays` — YAML's plain string) = ONE category, and empty /
|
||||||
|
/// absent = none.
|
||||||
|
static func categories(in matter: [String: String]) -> [String] {
|
||||||
|
guard let raw = matter["category"]?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else { return [] }
|
||||||
|
let listShaped = raw.hasPrefix("[") && raw.hasSuffix("]") && raw.count >= 2
|
||||||
|
return listShaped ? categoryList(String(raw.dropFirst().dropLast())) : [raw]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #207: the one-line `category:` value `categories(in:)` reads
|
||||||
|
/// back — the bracketed `categoryListValue`. `[]` is the empty
|
||||||
|
/// list, the value a re-send's clear carries.
|
||||||
|
static func categoryValue(_ names: [String]) -> String {
|
||||||
|
"[" + categoryListValue(names) + "]"
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Write postures
|
// MARK: - Write postures
|
||||||
|
|
||||||
/// The known-key table: Museion's three owned keys in stamp order —
|
/// The known-key table: Museion's three owned keys in stamp order —
|
||||||
@@ -139,8 +278,9 @@ nonisolated enum PostFrontmatter {
|
|||||||
/// order), preserve every other line verbatim (leading hand-edit lines
|
/// order), preserve every other line verbatim (leading hand-edit lines
|
||||||
/// above the opening `---` included, #27 review), keep the block's
|
/// above the opening `---` included, #27 review), keep the block's
|
||||||
/// trailing newline. No block at all → prepend a fresh one with the
|
/// trailing newline. No block at all → prepend a fresh one with the
|
||||||
/// pairs.
|
/// pairs. `dropping` removes those keys' lines outright, first (#206:
|
||||||
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
|
/// the import boundary and the 404 forget).
|
||||||
|
static func updating(text: String, with pairs: [(key: String, value: String)], dropping: Set<String> = []) -> String {
|
||||||
let (block, body) = split(text)
|
let (block, body) = split(text)
|
||||||
guard !block.isEmpty else {
|
guard !block.isEmpty else {
|
||||||
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
|
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
|
||||||
@@ -159,17 +299,15 @@ nonisolated enum PostFrontmatter {
|
|||||||
// the lenient flat reader never claimed nested support (posture
|
// the lenient flat reader never claimed nested support (posture
|
||||||
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
|
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
|
||||||
// if nested frontmatter ever matters.
|
// if nested frontmatter ever matters.
|
||||||
|
if !dropping.isEmpty {
|
||||||
|
lines.removeAll { key(ofLine: $0).map(dropping.contains) == true }
|
||||||
|
}
|
||||||
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
|
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
|
||||||
var seen = Set<String>()
|
var seen = Set<String>()
|
||||||
for (index, line) in lines.enumerated() {
|
for (index, line) in lines.enumerated() {
|
||||||
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
|
guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
|
||||||
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
lines[index] = "\(key): \(value)"
|
||||||
guard !trimmed.isEmpty, trimmed != "---" else { continue }
|
seen.insert(key)
|
||||||
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)" }
|
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 {
|
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
|
||||||
@@ -181,13 +319,30 @@ nonisolated enum PostFrontmatter {
|
|||||||
/// Posture 2 — merge-import: external frontmatter rides verbatim;
|
/// Posture 2 — merge-import: external frontmatter rides verbatim;
|
||||||
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
|
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
|
||||||
/// (#95: our three keys win — external `type: outline` still imports
|
/// (#95: our three keys win — external `type: outline` still imports
|
||||||
/// as post). The update posture over the known-key table.
|
/// as post), and Museion's Micro.blog bookkeeping is dropped (#206: a
|
||||||
|
/// foreign file carries no post of this library — its `micropub_url`
|
||||||
|
/// would otherwise aim the next send's content replace). The update
|
||||||
|
/// posture over the known-key table.
|
||||||
///
|
///
|
||||||
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
|
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
|
||||||
/// hand-edit lines above the opening `---` now survive import (the old
|
/// hand-edit lines above the opening `---` now survive import (the old
|
||||||
/// split-first shape silently dropped them) — lossless through every
|
/// split-first shape silently dropped them) — lossless through every
|
||||||
/// posture is the ticket's contract.
|
/// posture is the ticket's contract.
|
||||||
static func mergingImport(text: String, origin: Post.Origin) -> String {
|
static func mergingImport(text: String, origin: Post.Origin) -> String {
|
||||||
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
|
updating(
|
||||||
|
text: text,
|
||||||
|
with: ownedKeys(type: .post, passState: .firstDraft, origin: origin),
|
||||||
|
dropping: micropubKeys,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A block line's key — the update posture's ONE key read (so the
|
||||||
|
/// drop and the walk can never disagree about a line): leading and
|
||||||
|
/// trailing whitespace trimmed, a trailing `\r` included (CRLF
|
||||||
|
/// files). Nil for the fences and blank lines.
|
||||||
|
private static func key(ofLine line: String) -> String? {
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty, trimmed != "---" else { return nil }
|
||||||
|
return String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+38
-22
@@ -28,10 +28,18 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
var project: String
|
var project: String
|
||||||
/// True when the piece lives under archive/ (#107).
|
/// True when the piece lives under archive/ (#107).
|
||||||
var isArchived: Bool
|
var isArchived: Bool
|
||||||
/// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter
|
/// #33 (S6.1): the remembered Micro.blog post URL (frontmatter
|
||||||
/// `micropub_url`) — set when a draft was sent, the target the
|
/// `micropub_url`) — set when a draft was sent; the target the
|
||||||
/// publish step updates. Inert to everything else.
|
/// publish step updates and a re-send replaces in place (#206), and
|
||||||
|
/// half of the row's status. Inert to everything else.
|
||||||
var micropubURL: String?
|
var micropubURL: String?
|
||||||
|
/// #206: when Publish succeeded — frontmatter `micropub_published`,
|
||||||
|
/// the `stats_captured` stamp shape (local time). The Museion-side
|
||||||
|
/// publish record: the library answers "is this piece out, and
|
||||||
|
/// since when" from disk, never from a live query. Nil = never
|
||||||
|
/// published from here (a piece published before this stamp read
|
||||||
|
/// as a draft until its next Publish).
|
||||||
|
var micropubPublished: Date?
|
||||||
/// #32 (S5.2): the captured first-draft stats — present ONLY when
|
/// #32 (S5.2): the captured first-draft stats — present ONLY when
|
||||||
/// `captureFirstDraftStats` stamped the piece at a pass invocation
|
/// `captureFirstDraftStats` stamped the piece at a pass invocation
|
||||||
/// (writer origin, First Draft, post type, decided there against the
|
/// (writer origin, First Draft, post type, decided there against the
|
||||||
@@ -41,6 +49,15 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
/// keys, and non-writer or outline pieces never render them.
|
/// keys, and non-writer or outline pieces never render them.
|
||||||
var firstDraftStats: FirstDraftStats?
|
var firstDraftStats: FirstDraftStats?
|
||||||
|
|
||||||
|
/// #206: the row's Micro.blog status — nil when the piece was never
|
||||||
|
/// sent; a remembered URL alone is a draft; the publish stamp wins.
|
||||||
|
var micropubStatus: String? {
|
||||||
|
if let micropubPublished {
|
||||||
|
return "published \(Micropub.shortDate(micropubPublished))"
|
||||||
|
}
|
||||||
|
return micropubURL == nil ? nil : "draft on Micro.blog"
|
||||||
|
}
|
||||||
|
|
||||||
/// New pieces land here when no project is selected (#107).
|
/// New pieces land here when no project is selected (#107).
|
||||||
static let defaultProject = "posts"
|
static let defaultProject = "posts"
|
||||||
|
|
||||||
@@ -58,7 +75,7 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
/// reads "steady" in the verdict (finish-audit #32).
|
/// reads "steady" in the verdict (finish-audit #32).
|
||||||
init?(frontmatter: [String: String]) {
|
init?(frontmatter: [String: String]) {
|
||||||
guard
|
guard
|
||||||
let captured = frontmatter["stats_captured"].flatMap(Self.parseCaptured),
|
let captured = frontmatter["stats_captured"].flatMap(Post.parseStamp),
|
||||||
let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
|
let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
|
||||||
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
|
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
|
||||||
let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite),
|
let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite),
|
||||||
@@ -73,15 +90,6 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The symmetric read of the capture stamp (`FixCardStore.formatted`,
|
|
||||||
/// local time) — per-access formatter, the repo's no-static convention.
|
|
||||||
private static func parseCaptured(_ stamp: String) -> Date? {
|
|
||||||
let formatter = DateFormatter()
|
|
||||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
|
|
||||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
|
||||||
return formatter.date(from: stamp)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Frontmatter is external data (hand-edits, imports): reject the
|
/// Frontmatter is external data (hand-edits, imports): reject the
|
||||||
/// non-finite doubles Swift's `Double(String)` happily parses.
|
/// non-finite doubles Swift's `Double(String)` happily parses.
|
||||||
private static func finite(_ raw: String) -> Double? {
|
private static func finite(_ raw: String) -> Double? {
|
||||||
@@ -189,15 +197,12 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
type: stamp.type,
|
type: stamp.type,
|
||||||
project: project,
|
project: project,
|
||||||
isArchived: isArchived,
|
isArchived: isArchived,
|
||||||
// #33: the remembered Micro.blog draft URL —
|
// #33: the remembered Micro.blog URL — one flat key
|
||||||
// one flat key, read leniently like the rest.
|
// through the ONE trust gate (an import drops the key,
|
||||||
// #33 audit: imported frontmatter rides
|
// #206, so a hostile value never pre-arms the publish
|
||||||
// verbatim, so the read-back gates on the same
|
// sheet); #206: the publish stamp beside it.
|
||||||
// format guard the decode applies — a hostile
|
micropubURL: Micropub.rememberedURL(frontmatter),
|
||||||
// value never pre-arms the publish sheet.
|
micropubPublished: frontmatter["micropub_published"].flatMap(parseStamp),
|
||||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
|
||||||
Micropub.trustworthyURL($0) ? $0 : nil
|
|
||||||
},
|
|
||||||
// #32/#180 read-back gate: the named immutable pair
|
// #32/#180 read-back gate: the named immutable pair
|
||||||
// (origin writer, type post) — NOT pass_state, which
|
// (origin writer, type post) — NOT pass_state, which
|
||||||
// legitimately advances after the capture. `stats_*`
|
// legitimately advances after the capture. `stats_*`
|
||||||
@@ -210,6 +215,17 @@ nonisolated struct Post: Identifiable, Equatable {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The frontmatter timestamp reader — `yyyy-MM-dd'T'HH:mm:ss`, local
|
||||||
|
/// time (`FixCardStore.formatted`'s writer side); nil on anything
|
||||||
|
/// else. The symmetric read of the #31 capture stamp and the #206
|
||||||
|
/// publish stamp. Per-access formatter, the repo's no-static convention.
|
||||||
|
private static func parseStamp(_ stamp: String) -> Date? {
|
||||||
|
let formatter = DateFormatter()
|
||||||
|
formatter.dateFormat = PostFrontmatter.stampFormat
|
||||||
|
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||||
|
return formatter.date(from: stamp)
|
||||||
|
}
|
||||||
|
|
||||||
/// The Post's Title: first non-empty line after any frontmatter block,
|
/// The Post's Title: first non-empty line after any frontmatter block,
|
||||||
/// `#` heading markers stripped; `untitled` when nothing readable remains.
|
/// `#` heading markers stripped; `untitled` when nothing readable remains.
|
||||||
static func title(of text: String) -> String {
|
static func title(of text: String) -> String {
|
||||||
|
|||||||
+37
-13
@@ -166,7 +166,9 @@ nonisolated enum PostStore {
|
|||||||
/// #22/#94/#95: import one external markdown file as a Post — copy, never
|
/// #22/#94/#95: import one external markdown file as a Post — copy, never
|
||||||
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
|
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
|
||||||
/// verbatim with `type: post`, `pass_state: First Draft` and
|
/// verbatim with `type: post`, `pass_state: First Draft` and
|
||||||
/// `origin: <chosen>` set / overwritten (our three keys win); id = Title
|
/// `origin: <chosen>` set / overwritten (our three keys win) and the
|
||||||
|
/// Micro.blog bookkeeping dropped (#206 — a foreign file carries no
|
||||||
|
/// post of this library); id = Title
|
||||||
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
|
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
|
||||||
/// no mtime preservation (#96).
|
/// no mtime preservation (#96).
|
||||||
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
|
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
|
||||||
@@ -663,7 +665,7 @@ nonisolated extension PostStore {
|
|||||||
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
|
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
|
||||||
let stats = DraftStats.compute(body: body)
|
let stats = DraftStats.compute(body: body)
|
||||||
let stamped = PostFrontmatter.updating(text: text, with: [
|
let stamped = PostFrontmatter.updating(text: text, with: [
|
||||||
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
|
("stats_captured", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)), // lexically sortable
|
||||||
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
|
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
|
||||||
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
|
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
|
||||||
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
|
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
|
||||||
@@ -675,22 +677,36 @@ nonisolated extension PostStore {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: #33 (S6.1) — the remembered Micro.blog draft URL
|
// MARK: #33 (S6.1) / #206 — the remembered Micro.blog post
|
||||||
|
|
||||||
/// Stamp `micropub_url` in place on a successful draft send — the
|
/// Stamp micropub keys in place (`micropub_url`, the publish record
|
||||||
/// publish step's target (a frontmatter-only change: the body and
|
/// `micropub_published`, and #207 the `category:` line) — a
|
||||||
|
/// frontmatter-only change: the body and
|
||||||
/// every other key stay byte-identical, so the open session's
|
/// every other key stay byte-identical, so the open session's
|
||||||
/// readBody-based echo check never fires). A vanished piece throws
|
/// readBody-based echo check never fires, and every later editor
|
||||||
/// (write-never-resurrects, `writeNew` is the only creator).
|
/// save re-reads the block (the stamps survive it). A vanished piece
|
||||||
static func stampMicropubURL(id: String, url: String, home: URL) throws {
|
/// throws (write-never-resurrects, `writeNew` is the only creator).
|
||||||
|
/// `dropping` removes those keys' lines outright (the forget).
|
||||||
|
static func stampMicropub(_ id: String, home: URL, _ pairs: [(key: String, value: String)], dropping: Set<String> = []) throws {
|
||||||
guard let dir = folder(of: id, home: home) else {
|
guard let dir = folder(of: id, home: home) else {
|
||||||
throw CocoaError(.fileReadNoSuchFile)
|
throw CocoaError(.fileReadNoSuchFile)
|
||||||
}
|
}
|
||||||
let file = dir.appendingPathComponent("post.md")
|
let file = dir.appendingPathComponent("post.md")
|
||||||
let raw = try String(contentsOf: file, encoding: .utf8)
|
let raw = try String(contentsOf: file, encoding: .utf8)
|
||||||
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
|
try PostFrontmatter.updating(text: raw, with: pairs, dropping: dropping)
|
||||||
.write(to: file, atomically: true, encoding: .utf8)
|
.write(to: file, atomically: true, encoding: .utf8)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #206: the piece forgets Micro.blog — both keys' lines removed
|
||||||
|
/// through the update posture's drop (no empty key left behind; an
|
||||||
|
/// absent key scans as no memory, and the next send inserts the line
|
||||||
|
/// fresh). Called when Micro.blog answers 404: the post is gone
|
||||||
|
/// there, so the piece is no longer on Micro.blog. Throws when the
|
||||||
|
/// write cannot land — the caller must not then claim the link is
|
||||||
|
/// gone.
|
||||||
|
static func forgetMicropub(id: String, home: URL) throws {
|
||||||
|
try stampMicropub(id, home: home, [], dropping: PostFrontmatter.micropubKeys)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Cursor-state sidecar (#66)
|
// MARK: Cursor-state sidecar (#66)
|
||||||
@@ -756,6 +772,12 @@ struct IngestError: LocalizedError {
|
|||||||
IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
|
IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A file the drag named but the disk can no longer stat — moved or
|
||||||
|
/// deleted between drag and drop (or a URL that never was a file).
|
||||||
|
static func missing(_ name: String) -> IngestError {
|
||||||
|
IngestError(message: "“\(name.prefix(40))” couldn’t be read — it may have moved since the drag began.")
|
||||||
|
}
|
||||||
|
|
||||||
/// assets/ exists as a symlink or a file — never write through it
|
/// assets/ exists as a symlink or a file — never write through it
|
||||||
/// (research/promote posture: the #34 rail would refuse the send).
|
/// (research/promote posture: the #34 rail would refuse the send).
|
||||||
static func hostileAssets() -> IngestError {
|
static func hostileAssets() -> IngestError {
|
||||||
@@ -790,10 +812,12 @@ nonisolated extension PostStore {
|
|||||||
// AS a link (finish-audit 2026-11-02), and the #34 rail then
|
// AS a link (finish-audit 2026-11-02), and the #34 rail then
|
||||||
// refuses the whole send — nothing enters assets/ that can't ship.
|
// refuses the whole send — nothing enters assets/ that can't ship.
|
||||||
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||||
guard source.isFileURL, let values,
|
guard source.isFileURL, let values else { throw IngestError.missing(name) }
|
||||||
values.isDirectory != true, values.isSymbolicLink != true
|
if values.isSymbolicLink == true {
|
||||||
else {
|
throw IngestError.isLink(name)
|
||||||
throw values?.isSymbolicLink == true ? IngestError.isLink(name) : IngestError.isFolder(name)
|
}
|
||||||
|
if values.isDirectory == true {
|
||||||
|
throw IngestError.isFolder(name)
|
||||||
}
|
}
|
||||||
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
|
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
|
||||||
if FileManager.default.fileExists(atPath: assets.path) {
|
if FileManager.default.fileExists(atPath: assets.path) {
|
||||||
|
|||||||
@@ -218,6 +218,9 @@ struct PostsLibraryColumn: View {
|
|||||||
Button("Move to Archive") {
|
Button("Move to Archive") {
|
||||||
model.archivePost(post)
|
model.archivePost(post)
|
||||||
}
|
}
|
||||||
|
Divider()
|
||||||
|
MicroblogHandOffButton(post: post)
|
||||||
|
FinderHandOffButtons(model: model, post: post)
|
||||||
Button("Move to Trash", role: .destructive) {
|
Button("Move to Trash", role: .destructive) {
|
||||||
model.trash(post)
|
model.trash(post)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,6 +140,12 @@ final class PostsModel {
|
|||||||
/// submitted; nil session (draft/guest/nothing) shows none.
|
/// submitted; nil session (draft/guest/nothing) shows none.
|
||||||
/// #146: setter internal — the split-out domain extensions set it.
|
/// #146: setter internal — the split-out domain extensions set it.
|
||||||
var openPieceCards: [FixCardStore.StoredFixCard] = []
|
var openPieceCards: [FixCardStore.StoredFixCard] = []
|
||||||
|
/// #204: one jump-to-the-anchor request from the Fix Cards palette —
|
||||||
|
/// the anchor's span in the LIVE session text plus a token that
|
||||||
|
/// advances per jump (the editor column applies once per token, the
|
||||||
|
/// #71 flip-back caret pattern). Set by `revealCard`; never written
|
||||||
|
/// to disk — a jump is a view act.
|
||||||
|
var revealRequest: FixCardRevealRequest?
|
||||||
/// Last failed-op message surfaced in the editor (nil = clean).
|
/// Last failed-op message surfaced in the editor (nil = clean).
|
||||||
/// #146: setter internal — the split-out domain extensions set it.
|
/// #146: setter internal — the split-out domain extensions set it.
|
||||||
var lastError: String?
|
var lastError: String?
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
//
|
//
|
||||||
// #146: the fix-card extensions of PostsModel — stored-card surfacing
|
// #146: the fix-card extensions of PostsModel — stored-card surfacing
|
||||||
// (#23), apply/skip/done (#25, S3.2/S3.3), and promote (#26, S4.1) —
|
// (#23), apply/skip/done (#25, S3.2/S3.3), and promote (#26, S4.1) —
|
||||||
// moved from PostsModel.swift (file-length ceiling), code unchanged.
|
// moved from PostsModel.swift (file-length ceiling), code unchanged;
|
||||||
|
// #204: the jump-to-the-anchor reveal (`revealCard`, `FixCardRevealRequest`).
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
@@ -133,6 +134,31 @@ extension PostsModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: Jump to the anchor (#204)
|
||||||
|
|
||||||
|
/// #204: one jump-to-the-anchor request — the anchor's span in the live
|
||||||
|
/// session text plus a token that advances per jump so the editor column
|
||||||
|
/// (which applies once per token) re-fires on a repeated jump. Ephemeral
|
||||||
|
/// view state: nothing here ever reaches disk.
|
||||||
|
struct FixCardRevealRequest: Equatable {
|
||||||
|
var range: NSRange
|
||||||
|
var token: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
extension PostsModel {
|
||||||
|
/// #204: jump to a card's anchor — the palette's Jump. Resolves the
|
||||||
|
/// anchor against the LIVE session text (a dirty buffer still lands
|
||||||
|
/// where the writer sees it) and stamps one reveal request; the editor
|
||||||
|
/// column observes it and selects + reveals the span. A stale anchor
|
||||||
|
/// (quote gone, occurrence short) stamps nothing — the previous
|
||||||
|
/// request stands. Touches no text, no card, no disk: a jump is a view
|
||||||
|
/// act, the writer's hands stay on the wheel.
|
||||||
|
func revealCard(_ card: FixCardStore.StoredFixCard) {
|
||||||
|
guard let session, let range = FixCardStore.anchorRange(of: card, in: session.text) else { return }
|
||||||
|
revealRequest = FixCardRevealRequest(range: range, token: (revealRequest?.token ?? 0) + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: Fix Card promote (#26, S4.1/S4.3)
|
// MARK: Fix Card promote (#26, S4.1/S4.3)
|
||||||
|
|
||||||
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
|
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
|
||||||
|
|||||||
@@ -8,6 +8,9 @@
|
|||||||
// card refresh, Micropub. The bare `session.postID == id` comparison is
|
// card refresh, Micropub. The bare `session.postID == id` comparison is
|
||||||
// retired: two libraries can hold the same slug, and the id alone matched
|
// retired: two libraries can hold the same slug, and the id alone matched
|
||||||
// a session retained from another library (the repoint finding's seam).
|
// a session retained from another library (the repoint finding's seam).
|
||||||
|
// #205: also the piece's on-disk path (`fileURL(for:)`) — the same
|
||||||
|
// (Home, ID) identity resolved to post.md for the row menus' Finder
|
||||||
|
// hand-off; nil when the piece is gone.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
@@ -22,4 +25,17 @@ extension PostsModel {
|
|||||||
guard let session, let home = watchedHome else { return false }
|
guard let session, let home = watchedHome else { return false }
|
||||||
return session.targets(postID: id, home: home)
|
return session.targets(postID: id, home: home)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #205: the piece's `post.md` on disk — the row menus' Reveal in
|
||||||
|
/// Finder / Copy Path target. The same (Home, ID) identity resolved to
|
||||||
|
/// a path: `watchedHome` is the Home half, `PostStore.folder(of:)` the
|
||||||
|
/// ONE id→folder resolver (never the scan snapshot — the folder is
|
||||||
|
/// what Finder opens). A pure read — nothing written, no strip. Nil
|
||||||
|
/// when the piece is gone, so the menu entries no-op instead of
|
||||||
|
/// revealing a stale path.
|
||||||
|
func fileURL(for post: Post) -> URL? {
|
||||||
|
guard let home = watchedHome,
|
||||||
|
let dir = PostStore.folder(of: post.id, home: home) else { return nil }
|
||||||
|
return dir.appendingPathComponent("post.md")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -71,7 +71,7 @@ final class ProseChromeView: NSView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final class ProseListTextView: NSTextView {
|
final class ProseListTextView: FileDropTextView {
|
||||||
/// A fold: the marker line's buffer position + its text (the re-key
|
/// A fold: the marker line's buffer position + its text (the re-key
|
||||||
/// identity when an edit above shifts offsets) + the hidden scope
|
/// identity when an edit above shifts offsets) + the hidden scope
|
||||||
/// (shift-maintained by the #142 cheap path; the full pass re-derives
|
/// (shift-maintained by the #142 cheap path; the full pass re-derives
|
||||||
@@ -338,8 +338,10 @@ final class ProseListTextView: NSTextView {
|
|||||||
return firstRect(forCharacterRange: NSRange(location: charIndex, length: 1), actualRange: nil).midY
|
return firstRect(forCharacterRange: NSRange(location: charIndex, length: 1), actualRange: nil).midY
|
||||||
}
|
}
|
||||||
|
|
||||||
/// #141's SwiftUI entry — the window `.dropDestination`'s perform
|
/// #141's ingest entry — `AppGateState.routeFileDrop` routes here
|
||||||
/// routes here after markdown forwarding is ruled out upstream.
|
/// from whichever surface took the drag (the text view's own drag
|
||||||
|
/// handlers over the editor, the window `.dropDestination` elsewhere)
|
||||||
|
/// after markdown forwarding is ruled out upstream.
|
||||||
/// The drop point is read from the live pointer (NSEvent.mouseLocation
|
/// The drop point is read from the live pointer (NSEvent.mouseLocation
|
||||||
/// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02).
|
/// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02).
|
||||||
/// Gates: saved piece, every file publishable (#34's mimeType set) —
|
/// Gates: saved piece, every file publishable (#34's mimeType set) —
|
||||||
@@ -354,8 +356,10 @@ final class ProseListTextView: NSTextView {
|
|||||||
}
|
}
|
||||||
// The publish-able set IS #34's mimeType gate — nothing the rail
|
// The publish-able set IS #34's mimeType gate — nothing the rail
|
||||||
// can't ship ever enters assets/. A mixed md+image set refuses
|
// can't ship ever enters assets/. A mixed md+image set refuses
|
||||||
// here too (only pure-markdown sets are forwarded upstream).
|
// here too (only pure-markdown sets are forwarded upstream), and
|
||||||
guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
|
// so does a web URL (a browser image drag): the extension may
|
||||||
|
// look publishable, but nothing is on disk to copy.
|
||||||
|
guard urls.allSatisfy({ $0.isFileURL && Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
|
||||||
showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.")
|
showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -416,7 +420,12 @@ final class ProseListTextView: NSTextView {
|
|||||||
private var ingestNotice: NSTextField?
|
private var ingestNotice: NSTextField?
|
||||||
private var ingestNoticeHide: DispatchWorkItem?
|
private var ingestNoticeHide: DispatchWorkItem?
|
||||||
|
|
||||||
|
/// The last refusal text — the observable the pins read (the strip
|
||||||
|
/// itself is private chrome).
|
||||||
|
private(set) var lastIngestNotice: String?
|
||||||
|
|
||||||
private func showIngestNotice(_ text: String) {
|
private func showIngestNotice(_ text: String) {
|
||||||
|
lastIngestNotice = text
|
||||||
let strip: NSTextField
|
let strip: NSTextField
|
||||||
if let ingestNotice {
|
if let ingestNotice {
|
||||||
strip = ingestNotice
|
strip = ingestNotice
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# 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.
@@ -6,7 +6,9 @@
|
|||||||
// in-memory SettingsModel — one page per LLM surface (provider select,
|
// in-memory SettingsModel — one page per LLM surface (provider select,
|
||||||
// registry combobox with first-class free text, per-provider effort menu)
|
// registry combobox with first-class free text, per-provider effort menu)
|
||||||
// and the Provider Keys page (endpoint, z.ai key-type toggle swapping the
|
// and the Provider Keys page (endpoint, z.ai key-type toggle swapping the
|
||||||
// endpoint family, masked key + reveal). Visual contract: #130 prototype
|
// endpoint family, masked key + reveal). The Micro.blog page is the app
|
||||||
|
// token's home (saved status, replace, remove over the publish sheet's own
|
||||||
|
// Keychain slot). Visual contract: #130 prototype
|
||||||
// variant C, with variant B's current-model headline folded in.
|
// variant C, with variant B's current-model headline folded in.
|
||||||
//
|
//
|
||||||
|
|
||||||
@@ -340,6 +342,83 @@ private struct TestConnectionResult: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Micro.blog page: the app token's home — saved status, replace,
|
||||||
|
/// remove. Writes the SAME Keychain slot the publish sheet reads
|
||||||
|
/// (`MicropubTokenStore`), so a token saved here is the one a send
|
||||||
|
/// carries; the sheet's own field stays the first-run path and its
|
||||||
|
/// 401/403 re-entry. `saved` is read back from the Keychain after every
|
||||||
|
/// write, never assumed — a locked keychain fails the save and the
|
||||||
|
/// status line says so.
|
||||||
|
struct MicroblogSettingsPage: View {
|
||||||
|
@State private var tokenField = ""
|
||||||
|
@State private var saved = MicropubTokenStore.read() != nil
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("Micro.blog")
|
||||||
|
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||||
|
Text("Where the Micro.blog app token lives.")
|
||||||
|
.font(.system(size: 12))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
form
|
||||||
|
.padding(.top, 12)
|
||||||
|
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 24)
|
||||||
|
.padding(.top, 17)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var trimmedToken: String {
|
||||||
|
tokenField.trimmingCharacters(in: .whitespaces)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var form: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
SettingsFieldLabel("App Token")
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
SecureField("App token", text: $tokenField)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.font(.system(size: 12, design: DesignTokens.mono))
|
||||||
|
Button("Save") {
|
||||||
|
let token = trimmedToken
|
||||||
|
MicropubTokenStore.save(token)
|
||||||
|
tokenField = ""
|
||||||
|
saved = MicropubTokenStore.read() == token
|
||||||
|
}
|
||||||
|
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
|
||||||
|
.disabled(trimmedToken.isEmpty)
|
||||||
|
if saved {
|
||||||
|
Button("Remove") {
|
||||||
|
MicropubTokenStore.delete()
|
||||||
|
saved = MicropubTokenStore.read() != nil
|
||||||
|
}
|
||||||
|
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The standing state, in the Settings verdict idiom (Provider
|
||||||
|
// Keys' "✓ works"). The intro line is a description — a state
|
||||||
|
// swap there never read as a status.
|
||||||
|
status
|
||||||
|
Text("From micro.blog → Account → App Tokens. Stored in your Keychain — the publish sheet sends with this token.")
|
||||||
|
.font(.system(size: 11.5))
|
||||||
|
.foregroundStyle(DesignTokens.muted)
|
||||||
|
.padding(.top, 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live: Save and Remove read the Keychain back, so this line is
|
||||||
|
/// both the confirmation that a write landed and the standing
|
||||||
|
/// answer to "is a token stored?".
|
||||||
|
private var status: some View {
|
||||||
|
Text(saved ? "✓ Token saved in your Keychain" : "No token saved — publishing will ask for one")
|
||||||
|
.font(.system(size: 11, design: DesignTokens.mono))
|
||||||
|
.foregroundStyle(saved ? DesignTokens.accent : DesignTokens.muted)
|
||||||
|
.padding(.top, 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The z.ai key-type toggle (prototype `.seg`): a two-segment capsule, the
|
/// The z.ai key-type toggle (prototype `.seg`): a two-segment capsule, the
|
||||||
/// selected segment filled with the foreground ink. Toggling swaps the
|
/// selected segment filled with the foreground ink. Toggling swaps the
|
||||||
/// endpoint family (the model guards a custom endpoint).
|
/// endpoint family (the model guards a custom endpoint).
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
|
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
|
||||||
// #135 (Profiles S2): reworked to the #130 prototype's variant C verdict —
|
// #135 (Profiles S2): reworked to the #130 prototype's variant C verdict —
|
||||||
// a Settings sidebar + detail column (System Settings shape): destinations
|
// a Settings sidebar + detail column (System Settings shape): destinations
|
||||||
// Content · Pass 1 · Pass 2 · Chat · Provider Keys. Content keeps the #17
|
// Content · Pass 1 · Pass 2 · Chat · Provider Keys · Micro.blog. Content
|
||||||
// Home control unchanged; the surface and keys pages live in
|
// keeps the #17 Home control unchanged; the surface, keys, and Micro.blog
|
||||||
// SettingsPagesView.swift.
|
// pages live in SettingsPagesView.swift.
|
||||||
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
|
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
|
||||||
// CLI/.env rail) and hydrates from the profiles at pane open.
|
// CLI/.env rail) and hydrates from the profiles at pane open.
|
||||||
//
|
//
|
||||||
@@ -109,6 +109,8 @@ struct SettingsPaneView: View {
|
|||||||
SurfaceSettingsPage(model: model, surface: .chat)
|
SurfaceSettingsPage(model: model, surface: .chat)
|
||||||
case .keys:
|
case .keys:
|
||||||
ProviderKeysPage(model: model)
|
ProviderKeysPage(model: model)
|
||||||
|
case .microblog:
|
||||||
|
MicroblogSettingsPage()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
@@ -116,13 +118,15 @@ struct SettingsPaneView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The sidebar's destinations (#135): the #17 Content control, one page per
|
/// The sidebar's destinations (#135): the #17 Content control, one page per
|
||||||
/// LLM surface (Sessions rides Chat — #126), and the provider keys.
|
/// LLM surface (Sessions rides Chat — #126), the provider keys, and the
|
||||||
|
/// Micro.blog app token (the one Keychain credential, ADR-0014).
|
||||||
enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
|
enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
|
||||||
case content
|
case content
|
||||||
case pass1
|
case pass1
|
||||||
case pass2
|
case pass2
|
||||||
case chat
|
case chat
|
||||||
case keys
|
case keys
|
||||||
|
case microblog
|
||||||
|
|
||||||
var id: String {
|
var id: String {
|
||||||
rawValue
|
rawValue
|
||||||
@@ -135,6 +139,7 @@ enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
|
|||||||
case .pass2: "Pass 2"
|
case .pass2: "Pass 2"
|
||||||
case .chat: "Chat"
|
case .chat: "Chat"
|
||||||
case .keys: "Provider Keys"
|
case .keys: "Provider Keys"
|
||||||
|
case .microblog: "Micro.blog"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,11 @@
|
|||||||
//
|
//
|
||||||
// #193: the shared workspace chrome, moved from WorkspaceView.swift
|
// #193: the shared workspace chrome, moved from WorkspaceView.swift
|
||||||
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
|
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
|
||||||
// PaneHeader; every pane reuses them, code unchanged.
|
// PaneHeader; every pane reuses them, code unchanged. #205 adds
|
||||||
|
// FinderHandOffButtons, #206 MicroblogHandOffButton (both born here).
|
||||||
//
|
//
|
||||||
|
|
||||||
|
import AppKit
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
|
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
|
||||||
@@ -94,3 +96,43 @@ struct PaneHeader<Trailing: View>: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #205: the row menus' Finder hand-off — Reveal in Finder + Copy Path,
|
||||||
|
/// one fragment for every surface that lists pieces (the library column,
|
||||||
|
/// the Archive pane). Both act on `model.fileURL(for:)` — the resolved
|
||||||
|
/// `post.md`; a nil URL (the piece is gone) no-ops.
|
||||||
|
struct FinderHandOffButtons: View {
|
||||||
|
let model: PostsModel
|
||||||
|
let post: Post
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button("Reveal in Finder") {
|
||||||
|
if let url = model.fileURL(for: post) {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([url])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Button("Copy Path") {
|
||||||
|
if let url = model.fileURL(for: post) {
|
||||||
|
NSPasteboard.general.clearContents()
|
||||||
|
NSPasteboard.general.setString(url.path, forType: .string)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #206: the row menus' Micro.blog hand-off — Open on Micro.blog, for a
|
||||||
|
/// piece that is published (a draft's final URL does not exist yet on
|
||||||
|
/// their side, so a draft shows no entry; neither does a never-sent
|
||||||
|
/// piece). The URL is the piece's remembered `micropub_url`, already
|
||||||
|
/// trust-gated at the scan.
|
||||||
|
struct MicroblogHandOffButton: View {
|
||||||
|
let post: Post
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
if post.micropubPublished != nil, let url = post.micropubURL.flatMap({ URL(string: $0) }) {
|
||||||
|
Button("Open on Micro.blog") {
|
||||||
|
NSWorkspace.shared.open(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,27 +56,14 @@ struct WorkspaceView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// #91: drag a markdown file onto the window — same guest slot as
|
// #91/#141: drops landing OUTSIDE the editor (over the editor the
|
||||||
// File ▸ Open… Non-markdown drops are refused.
|
// text view takes the drag itself — FileDropTextView); one router.
|
||||||
.dropDestination(for: URL.self) { urls, _ in
|
.dropDestination(for: URL.self) { urls, _ in
|
||||||
// #162: no new buffers while a Cold Turkey block holds —
|
let landed = gate.routeFileDrop(urls)
|
||||||
// the open Piece is the one being counted.
|
if landed {
|
||||||
guard !gate.writingLock.isLocked else { return false }
|
|
||||||
// #141: the window destination is the only one that ever
|
|
||||||
// fires (field-verified 2026-11-02 — nested editor-level
|
|
||||||
// SwiftUI targets are never consulted, and AppKit views
|
|
||||||
// registered for file drags are starved by it).
|
|
||||||
// PURE-markdown sets keep #91's open-as-guest; a mixed
|
|
||||||
// md+image set falls through and ingestDrop refuses it
|
|
||||||
// loudly (images must not vanish silently behind the md).
|
|
||||||
// Nil text view: bounce.
|
|
||||||
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
|
|
||||||
gate.posts.openExternal(url)
|
|
||||||
selection = .posts
|
selection = .posts
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
guard let textView = gate.proseDrop.textView else { return false }
|
return landed
|
||||||
return textView.ingestDrop(urls)
|
|
||||||
}
|
}
|
||||||
// #21: left-edge hover slides rail+library back in as an overlay.
|
// #21: left-edge hover slides rail+library back in as an overlay.
|
||||||
// Library only while the window width allows it (#17 verdict stands:
|
// Library only while the window width allows it (#17 verdict stands:
|
||||||
|
|||||||
@@ -39,12 +39,12 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
|
|||||||
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
|
- `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.
|
- `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).
|
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
|
||||||
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
|
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses); #207 `MicropubCategoryTests` — categories travel (a create carries the list when non-empty; a re-send opt-in by key, `[]` clears), the codec list incl. the unbracketed primitives, apply-at-send with the failed-write refusal, the blog's `q=category` list, publish-applies-first (a failed update never publishes — the request count is pinned; the flip targets the post the send touched, never a stale caller URL), the sanitized name on disk and wire, the model's `openPieceCategories()` read, the import keeps a category line, + the sheet field's pure rules (pending edit, picks-add completion, the menu). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared; `plantedPiece` (a saved `# Titled` piece with planted frontmatter) lives in `MicropubTests.swift` beside the other shared helpers. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
|
||||||
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
|
- `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.
|
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does).
|
||||||
- `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), 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).
|
||||||
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
|
- `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.
|
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import, image ingest + the 27.2 drag-routing seam (`DragInfoStub`, the suite's NSDraggingInfo mock: a Finder-shaped drag routes through the text view and never pastes the path; text-only drags keep the stock drop; outline rows bounce; the probe follows `changeCount`; web URLs and vanished files refuse with the right notice) + the one router's pins (guest, Cold Turkey refusal, ingest hand-off, mixed refusal).
|
||||||
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
|
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
|
||||||
- `ProseListTests`, `ProseRekeyTests` — prose list model + fold rendering, fold rekey pipeline.
|
- `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`, `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).
|
||||||
|
|||||||
@@ -14,6 +14,16 @@
|
|||||||
// card closes applied), skip and done flip only the status, and the stale
|
// card closes applied), skip and done flip only the status, and the stale
|
||||||
// anchor selects and changes no text while the card flags itself stale.
|
// anchor selects and changes no text while the card flags itself stale.
|
||||||
//
|
//
|
||||||
|
// #204 — Scenario: the card points, the editor lands
|
||||||
|
// From issue #204: a Fix Card should let the writer jump to the relevant
|
||||||
|
// paragraph — the palette's Jump hands the editor the anchor's exact span.
|
||||||
|
// Given an open piece carrying a fix card whose anchor is valid,
|
||||||
|
// when the writer clicks Jump on that card,
|
||||||
|
// then the model stamps one reveal request carrying the anchor's NSRange
|
||||||
|
// resolved against the LIVE session text (a dirty buffer still lands),
|
||||||
|
// the request's token advances so repeated jumps re-fire, nothing is
|
||||||
|
// written (not text, not the card), and a stale anchor stamps nothing.
|
||||||
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
@testable import Museion
|
@testable import Museion
|
||||||
@@ -284,7 +294,103 @@ struct FixCardApplyTests {
|
|||||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
|
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Promote (#26, S4.1)
|
// MARK: Jump to the anchor (#204)
|
||||||
|
|
||||||
|
/// #204: the pure anchor-span math — the appliedText occurrence rule
|
||||||
|
/// (1-based, non-overlapping) answered as a range, with every
|
||||||
|
/// must-never-land case nil.
|
||||||
|
@Test func `anchorRange resolves the nth occurrence and nils every unlandable case`() throws {
|
||||||
|
let piece = try makePiece()
|
||||||
|
let written = try FixCardStore.submit(
|
||||||
|
piecePath: piece.path,
|
||||||
|
cards: [
|
||||||
|
card(quote: "anchor sentence"),
|
||||||
|
card(quote: "anchor sentence", occurrence: 2),
|
||||||
|
card(quote: "vanished quote", occurrence: 1),
|
||||||
|
card(quote: "anchor sentence", lane: .demonstration),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
// submit refuses an empty quote and occurrence 0 at the trust
|
||||||
|
// boundary — the unlandable-input cases are pinned through the
|
||||||
|
// stored shape directly.
|
||||||
|
let emptyQuote = FixCardStore.StoredFixCard(
|
||||||
|
id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p",
|
||||||
|
diagnosticQuestion: "", fix: "", anchor: .init(quote: "", occurrence: 1),
|
||||||
|
lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil,
|
||||||
|
)
|
||||||
|
let zeroOccurrence = FixCardStore.StoredFixCard(
|
||||||
|
id: UUID(), submittedAt: Date(), rank: nil, pattern: "p", problem: "p",
|
||||||
|
diagnosticQuestion: "", fix: "", anchor: .init(quote: "anchor", occurrence: 0),
|
||||||
|
lane: .mechanical, emitter: .lint, provenance: nil, status: .open, anchorStatus: .stale, promotedAt: nil,
|
||||||
|
)
|
||||||
|
let text = "The anchor sentence. And the anchor sentence again."
|
||||||
|
|
||||||
|
let first = try #require(FixCardStore.anchorRange(of: written[0].card, in: text))
|
||||||
|
#expect((text as NSString).substring(with: first) == "anchor sentence")
|
||||||
|
#expect(first.location == 4) // 1-based, the FIRST match
|
||||||
|
let second = try #require(FixCardStore.anchorRange(of: written[1].card, in: text))
|
||||||
|
#expect(second.location == 29) // occurrence 2 — not the first
|
||||||
|
#expect(FixCardStore.anchorRange(of: written[2].card, in: text) == nil) // stale
|
||||||
|
// A demonstration card's anchor is still a real place in the text.
|
||||||
|
#expect(FixCardStore.anchorRange(of: written[3].card, in: text) != nil)
|
||||||
|
#expect(FixCardStore.anchorRange(of: emptyQuote, in: text) == nil)
|
||||||
|
#expect(FixCardStore.anchorRange(of: zeroOccurrence, in: text) == nil)
|
||||||
|
// The range is UTF-16 (NSTextView's unit), not Characters — a grapheme
|
||||||
|
// before the anchor is 2 units here; a Character-counted location would say 6.
|
||||||
|
let wide = FixCardStore.anchorRange(of: written[0].card, in: "✍️ The anchor sentence.")
|
||||||
|
#expect(wide?.location == 7)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #204: a jump selects the anchor exactly where it resolved; only a bare
|
||||||
|
/// caret (the #71 flip-back) hops past leading blanks — a quote that IS
|
||||||
|
/// the leading blanks must select those blanks, never the title. Both
|
||||||
|
/// shapes clamp to the text.
|
||||||
|
@Test @MainActor func `landingSpan hops only a bare caret and clamps both shapes to the text`() {
|
||||||
|
let text = "\n\n\nTitle line."
|
||||||
|
let jump = FixCardRevealRequest(range: NSRange(location: 0, length: 3), token: 1)
|
||||||
|
#expect(ProseTextView.landingSpan(for: jump, in: text) == NSRange(location: 0, length: 3)) // the blank run itself
|
||||||
|
let caret = FixCardRevealRequest(range: NSRange(location: 0, length: 0), token: 2)
|
||||||
|
#expect(ProseTextView.landingSpan(for: caret, in: text) == NSRange(location: 3, length: 0)) // hops to the title
|
||||||
|
let over = FixCardRevealRequest(range: NSRange(location: 10, length: 50), token: 3)
|
||||||
|
#expect(ProseTextView.landingSpan(for: over, in: text) == NSRange(location: 10, length: 4)) // clamped
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #204: the model stamps ONE reveal request per jump — the range
|
||||||
|
/// resolved against the LIVE session text (dirty buffer included), the
|
||||||
|
/// token advancing so a repeated jump re-fires; a stale anchor stamps
|
||||||
|
/// nothing. No write of any kind.
|
||||||
|
@Test @MainActor func `revealCard stamps a reveal request against the live text and writes nothing`() 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))
|
||||||
|
let written = try FixCardStore.submit(
|
||||||
|
piecePath: folder.path,
|
||||||
|
cards: [card(quote: "anchor sentence"), card(quote: "vanished quote")],
|
||||||
|
)
|
||||||
|
model.select(post.id)
|
||||||
|
let session = try #require(model.session)
|
||||||
|
// The writer typed since the last flush — the jump must resolve
|
||||||
|
// against the buffer, not disk (the range would otherwise drift).
|
||||||
|
session.edit("# Carded\n\nIntro line.\nThe anchor sentence.\n")
|
||||||
|
let before = try Data(contentsOf: folder.appendingPathComponent("post.md"))
|
||||||
|
|
||||||
|
model.revealCard(written[0].card)
|
||||||
|
|
||||||
|
let request = try #require(model.revealRequest)
|
||||||
|
#expect(request.range.location == (session.text as NSString).range(of: "anchor sentence").location)
|
||||||
|
#expect(request.range.length == ("anchor sentence" as NSString).length) // UTF-16 units — what NSTextView selects
|
||||||
|
let token = request.token
|
||||||
|
#expect(try Data(contentsOf: folder.appendingPathComponent("post.md")) == before) // no write
|
||||||
|
#expect(try FixCardStore.scan(pieceURL: folder).allSatisfy { $0.status == .open }) // card untouched
|
||||||
|
|
||||||
|
// A repeated jump re-fires (the editor applies once per token).
|
||||||
|
model.revealCard(written[0].card)
|
||||||
|
#expect(model.revealRequest?.token == token + 1)
|
||||||
|
|
||||||
|
// A stale anchor stamps nothing — the previous request stands.
|
||||||
|
model.revealCard(written[1].card)
|
||||||
|
#expect(model.revealRequest?.token == token + 1)
|
||||||
|
}
|
||||||
|
|
||||||
/// Scenario: the mentor remembers — promoting through the model writes
|
/// Scenario: the mentor remembers — promoting through the model writes
|
||||||
/// the Learning under the open piece's Home, refreshes the palette's
|
/// the Learning under the open piece's Home, refreshes the palette's
|
||||||
|
|||||||
@@ -25,6 +25,66 @@ import Foundation
|
|||||||
@testable import Museion
|
@testable import Museion
|
||||||
import Testing
|
import Testing
|
||||||
|
|
||||||
|
/// The smallest NSDraggingInfo the drag overrides read: only the
|
||||||
|
/// pasteboard matters (the stock text drop also wants a destination view,
|
||||||
|
/// which the hosted text view supplies itself).
|
||||||
|
@MainActor
|
||||||
|
final class DragInfoStub: NSObject, NSDraggingInfo {
|
||||||
|
let draggingPasteboard: NSPasteboard
|
||||||
|
init(_ pb: NSPasteboard) {
|
||||||
|
draggingPasteboard = pb
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingDestinationWindow: NSWindow? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingSourceOperationMask: NSDragOperation {
|
||||||
|
[.copy]
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingLocation: NSPoint {
|
||||||
|
.zero
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggedImageLocation: NSPoint {
|
||||||
|
.zero
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggedImage: NSImage? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingSource: Any? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingSequenceNumber: Int {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
func slideDraggedImage(to _: NSPoint) {}
|
||||||
|
override func namesOfPromisedFilesDropped(atDestination _: URL) -> [String]? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var draggingFormation: NSDraggingFormation = .none
|
||||||
|
var animatesToDestination = false
|
||||||
|
var numberOfValidItemsForDrop = 0
|
||||||
|
func enumerateDraggingItems(
|
||||||
|
options _: NSDraggingItemEnumerationOptions,
|
||||||
|
for _: NSView?,
|
||||||
|
classes _: [AnyClass],
|
||||||
|
searchOptions _: [NSPasteboard.ReadingOptionKey: Any],
|
||||||
|
using _: @escaping (NSDraggingItem, Int, UnsafeMutablePointer<ObjCBool>) -> Void,
|
||||||
|
) {}
|
||||||
|
var springLoadingHighlight: NSSpringLoadingHighlight {
|
||||||
|
.none
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetSpringLoading() {}
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
struct ImageIngestTests {
|
struct ImageIngestTests {
|
||||||
/// Throwaway Home + a saved post standing in for the open editor
|
/// Throwaway Home + a saved post standing in for the open editor
|
||||||
@@ -96,9 +156,10 @@ struct ImageIngestTests {
|
|||||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - #141 drag-layer entry (ingestDrop — the SwiftUI drop
|
// MARK: - #141 drag-layer entry (ingestDrop — whichever surface took
|
||||||
|
|
||||||
// target's perform lands on the text view)
|
// the drag routes here: the text view's own handlers over the editor,
|
||||||
|
// the window SwiftUI destination elsewhere)
|
||||||
|
|
||||||
@Test func `ingestDrop copies lands the ref and selects alt`() throws {
|
@Test func `ingestDrop copies lands the ref and selects alt`() throws {
|
||||||
let (_, folder) = try ingestHome()
|
let (_, folder) = try ingestHome()
|
||||||
@@ -129,6 +190,189 @@ struct ImageIngestTests {
|
|||||||
#expect(try !draft.ingestDrop([imageSource("x.png")]))
|
#expect(try !draft.ingestDrop([imageSource("x.png")]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - 27.2 drag routing (a drag goes to the deepest destination:
|
||||||
|
|
||||||
|
// FileDropTextView owns drops that land on the editor — stock NSTextView
|
||||||
|
// handling would paste the file PATH)
|
||||||
|
|
||||||
|
/// A Finder-shaped drag pasteboard: `public.file-url` plus the legacy
|
||||||
|
/// filenames type NSTextView registers for.
|
||||||
|
private func finderDragPasteboard(_ urls: [URL]) -> NSPasteboard {
|
||||||
|
let filenames = NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")
|
||||||
|
let pb = NSPasteboard(name: .drag)
|
||||||
|
pb.declareTypes([.fileURL, filenames], owner: nil)
|
||||||
|
pb.setString(urls[0].absoluteString, forType: .fileURL)
|
||||||
|
pb.setPropertyList(urls.map(\.path), forType: filenames)
|
||||||
|
return pb
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A live text view in a window (the stock text drop inserts only into
|
||||||
|
/// a hosted view). Caller orders the window out.
|
||||||
|
private func hostedView() -> (tv: ProseListTextView, win: NSWindow) {
|
||||||
|
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false)
|
||||||
|
let tv = ProseListTextView()
|
||||||
|
tv.string = "Body.\n"
|
||||||
|
win.contentView?.addSubview(tv)
|
||||||
|
win.makeFirstResponder(tv)
|
||||||
|
return (tv, win)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A temp markdown file standing in for a dragged guest.
|
||||||
|
private func markdownSource() throws -> URL {
|
||||||
|
let md = FileManager.default.temporaryDirectory.appendingPathComponent("imageingest-\(UUID().uuidString).md")
|
||||||
|
try "# Guest\n".write(to: md, atomically: true, encoding: .utf8)
|
||||||
|
return md
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a file drag landing on the text view routes, never pastes the path`() throws {
|
||||||
|
let (_, folder) = try ingestHome()
|
||||||
|
let (tv, win) = hostedView()
|
||||||
|
defer { win.orderOut(nil) }
|
||||||
|
tv.ingestFolder = folder
|
||||||
|
tv.onFileDrop = { [weak tv] in tv?.ingestDrop($0) ?? false } // the gate's router in miniature
|
||||||
|
let source = try imageSource("sketch.png")
|
||||||
|
let drag = DragInfoStub(finderDragPasteboard([source]))
|
||||||
|
|
||||||
|
#expect(tv.draggingEntered(drag) == .copy)
|
||||||
|
#expect(tv.draggingUpdated(drag) == .copy)
|
||||||
|
#expect(tv.performDragOperation(drag))
|
||||||
|
#expect(tv.string.contains(""))
|
||||||
|
#expect(!tv.string.contains(source.path), "the stock path paste survived")
|
||||||
|
|
||||||
|
// Unrouted (no handler mounted): a Finder drag claims nothing and
|
||||||
|
// pastes nothing.
|
||||||
|
let (bare, bareWin) = hostedView()
|
||||||
|
defer { bareWin.orderOut(nil) }
|
||||||
|
let bareDrag = DragInfoStub(finderDragPasteboard([source]))
|
||||||
|
#expect(bare.draggingEntered(bareDrag) == [])
|
||||||
|
#expect(!bare.performDragOperation(bareDrag))
|
||||||
|
#expect(bare.string == "Body.\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a text-only drag keeps the stock drop and never reaches the router`() {
|
||||||
|
let (tv, win) = hostedView()
|
||||||
|
defer { win.orderOut(nil) }
|
||||||
|
var routed: [URL]?
|
||||||
|
tv.onFileDrop = { routed = $0; return true }
|
||||||
|
let pb = NSPasteboard(name: .drag)
|
||||||
|
pb.declareTypes([.string], owner: nil)
|
||||||
|
pb.setString("dropped text", forType: .string)
|
||||||
|
|
||||||
|
#expect(FileDropTextView.classify(pb) == .text)
|
||||||
|
#expect(tv.draggingEntered(DragInfoStub(pb)) == .copy)
|
||||||
|
#expect(tv.performDragOperation(DragInfoStub(pb)))
|
||||||
|
#expect(tv.string.contains("dropped text"))
|
||||||
|
#expect(routed == nil)
|
||||||
|
|
||||||
|
// URL-less AND text-less (raw image data from Photos/Preview): bounces.
|
||||||
|
let png = NSPasteboard(name: .drag)
|
||||||
|
png.declareTypes([.png], owner: nil)
|
||||||
|
#expect(tv.draggingEntered(DragInfoStub(png)) == [])
|
||||||
|
#expect(!tv.performDragOperation(DragInfoStub(png)))
|
||||||
|
#expect(tv.string.contains("dropped text"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the drag probe follows the pasteboard contents, not its memory`() throws {
|
||||||
|
let (tv, win) = hostedView()
|
||||||
|
defer { win.orderOut(nil) }
|
||||||
|
let source = try imageSource("sketch.png")
|
||||||
|
let pb = finderDragPasteboard([source])
|
||||||
|
#expect(tv.dropKind(of: pb) == .urls([source]))
|
||||||
|
// Same pasteboard object, new contents (changeCount moved): follows.
|
||||||
|
pb.declareTypes([.string], owner: nil)
|
||||||
|
pb.setString("now text", forType: .string)
|
||||||
|
#expect(tv.dropKind(of: pb) == .text)
|
||||||
|
pb.clearContents()
|
||||||
|
#expect(tv.dropKind(of: pb) == .none)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the outline rows bounce a file drag instead of pasting the path`() throws {
|
||||||
|
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false)
|
||||||
|
defer { win.orderOut(nil) }
|
||||||
|
let row = RowTextView()
|
||||||
|
row.string = "- item"
|
||||||
|
win.contentView?.addSubview(row)
|
||||||
|
let drag = try DragInfoStub(finderDragPasteboard([imageSource("sketch.png")]))
|
||||||
|
|
||||||
|
#expect(row.draggingEntered(drag) == [])
|
||||||
|
#expect(!row.performDragOperation(drag))
|
||||||
|
#expect(row.string == "- item")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a web URL refuses loudly with the type notice and plants nothing`() throws {
|
||||||
|
// A browser image drag reaches the router as an https URL — the
|
||||||
|
// extension looks publishable, but nothing is on disk to copy. The
|
||||||
|
// sink would refuse it too; only the isFileURL gate names the type.
|
||||||
|
let (_, folder) = try ingestHome()
|
||||||
|
let tv = ProseListTextView()
|
||||||
|
tv.string = "Body.\n"
|
||||||
|
tv.ingestFolder = folder
|
||||||
|
let web = try #require(URL(string: "https://example.com/cat.jpg"))
|
||||||
|
#expect(!tv.ingestDrop([web]))
|
||||||
|
#expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true, "notice: \(tv.lastIngestNotice ?? "nil")")
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a file that vanished after the drag refuses as missing, not as a folder`() throws {
|
||||||
|
let (_, folder) = try ingestHome()
|
||||||
|
let tv = ProseListTextView()
|
||||||
|
tv.string = "Body.\n"
|
||||||
|
tv.ingestFolder = folder
|
||||||
|
let gone = try imageSource("ghost.png")
|
||||||
|
try FileManager.default.removeItem(at: gone)
|
||||||
|
#expect(!tv.ingestDrop([gone]))
|
||||||
|
let notice = try #require(tv.lastIngestNotice)
|
||||||
|
#expect(notice.contains("couldn’t be read"), "notice: \(notice)")
|
||||||
|
#expect(!notice.contains("folder"), "notice: \(notice)")
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - The one router (AppGateState.routeFileDrop)
|
||||||
|
|
||||||
|
@Test func `the router opens a pure-markdown set as the guest`() throws {
|
||||||
|
let gate = AppGateState()
|
||||||
|
let md = try markdownSource()
|
||||||
|
defer { try? FileManager.default.removeItem(at: md) }
|
||||||
|
#expect(gate.routeFileDrop([md]))
|
||||||
|
#expect(gate.posts.externalSession != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the router refuses everything while a Cold Turkey block holds`() throws {
|
||||||
|
let gate = AppGateState()
|
||||||
|
gate.posts.newPost()
|
||||||
|
gate.posts.draft?.text = "seed words here"
|
||||||
|
gate.startWritingLock(goal: .words(2))
|
||||||
|
defer {
|
||||||
|
gate.writingLock.feed(text: "seed words here plus two more")
|
||||||
|
gate.writingLock.tick()
|
||||||
|
}
|
||||||
|
let md = try markdownSource()
|
||||||
|
defer { try? FileManager.default.removeItem(at: md) }
|
||||||
|
#expect(gate.writingLock.isLocked)
|
||||||
|
#expect(!gate.routeFileDrop([md]))
|
||||||
|
#expect(gate.posts.externalSession == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the router hands non-markdown to the open piece's ingest`() throws {
|
||||||
|
let gate = AppGateState()
|
||||||
|
let (_, folder) = try ingestHome()
|
||||||
|
let source = try imageSource("sketch.png")
|
||||||
|
// No editor mounted: bounce.
|
||||||
|
#expect(!gate.routeFileDrop([source]))
|
||||||
|
let tv = ProseListTextView()
|
||||||
|
tv.string = "Body.\n"
|
||||||
|
tv.ingestFolder = folder
|
||||||
|
gate.proseDrop.textView = tv
|
||||||
|
#expect(gate.routeFileDrop([source]))
|
||||||
|
#expect(tv.string.contains(""))
|
||||||
|
// A mixed md+image set reaches the ingest's loud refusal, never the guest.
|
||||||
|
let md = try markdownSource()
|
||||||
|
defer { try? FileManager.default.removeItem(at: md) }
|
||||||
|
#expect(try !gate.routeFileDrop([imageSource("second.png"), md]))
|
||||||
|
#expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true)
|
||||||
|
#expect(gate.posts.externalSession == nil)
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - #141 finish-audit pins
|
// MARK: - #141 finish-audit pins
|
||||||
|
|
||||||
@Test func `a dropped symlink refuses with nothing planted`() throws {
|
@Test func `a dropped symlink refuses with nothing planted`() throws {
|
||||||
@@ -149,8 +393,8 @@ struct ImageIngestTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test func `a mixed image and markdown set refuses loudly`() throws {
|
@Test func `a mixed image and markdown set refuses loudly`() throws {
|
||||||
// The window destination forwards only PURE-markdown sets (#91);
|
// The router forwards only PURE-markdown sets (#91); a mixed set
|
||||||
// a mixed set must reach this refusal, not vanish behind the md.
|
// must reach this refusal, not vanish behind the md.
|
||||||
let (_, folder) = try ingestHome()
|
let (_, folder) = try ingestHome()
|
||||||
let tv = ProseListTextView()
|
let tv = ProseListTextView()
|
||||||
tv.string = "Body.\n"
|
tv.string = "Body.\n"
|
||||||
|
|||||||
@@ -0,0 +1,547 @@
|
|||||||
|
//
|
||||||
|
// MicropubCategoryTests.swift
|
||||||
|
// MuseionTests
|
||||||
|
//
|
||||||
|
// #207: Micro.blog categories travel. Scenario:
|
||||||
|
//
|
||||||
|
// Given a saved Post whose frontmatter carries a one-line
|
||||||
|
// `category:` list (`[Tech, Notes]`, a bare scalar `Essays`, or
|
||||||
|
// empty — the codec is line-bounded)
|
||||||
|
// When the writer sends it to Micro.blog, re-sends it over the
|
||||||
|
// remembered post, or publishes with a category edit made in the
|
||||||
|
// sheet
|
||||||
|
// Then a CREATE carries `properties.category` (only when the list
|
||||||
|
// is non-empty — naming a category that doesn't exist CREATES it on
|
||||||
|
// Micro.blog, no separate call); a RE-SEND carries `category` in
|
||||||
|
// `replace` ONLY when the piece has the line (opt-in by key — `[]`
|
||||||
|
// is sent and clears the post's categories; no line → `replace`
|
||||||
|
// names exactly name + content, the blog keeps whatever it has); a
|
||||||
|
// sheet edit (`categories:` non-nil) lands on disk AT THE SEND —
|
||||||
|
// flush → category line → ONE disk read feeds the wire — and a
|
||||||
|
// failed category write REFUSES the send with nothing on the wire;
|
||||||
|
// Publish with pending edits runs the update FIRST and never
|
||||||
|
// publishes after a failed update (disk and blog never silently
|
||||||
|
// disagree); the blog's own categories list through `q=category`
|
||||||
|
// (no suggestions is not an error). Import keeps an imported
|
||||||
|
// `category:` key (external keys ride verbatim). The sheet's
|
||||||
|
// Categories FIELD is a comma list in the codec's unbracketed form
|
||||||
|
// over the blog's categories (the system completion menu REPLACES
|
||||||
|
// the whole field text, so a completion IS the merge): its pure
|
||||||
|
// rules — the pending-edit test, picks add / a half-typed word is
|
||||||
|
// replaced, the menu — are pinned here; the view itself is not.
|
||||||
|
//
|
||||||
|
// Pins: S1 categories travel on create · S2 re-send replaces,
|
||||||
|
// opt-in by key (builders + model) · S3 the codec (read + render,
|
||||||
|
// round-trip incl. backslashes) · S4 the edit lands at the send
|
||||||
|
// (sanitized, readable through the model; + the refusal, + the
|
||||||
|
// import keeps the line) · S5 the blog's categories · S6 publish
|
||||||
|
// applies pending edits first and targets the post the send
|
||||||
|
// touched · S7 the field's pending-edit rule · S8 picks add (the
|
||||||
|
// whole-text completion) + the menu.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
@testable import Museion
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite("MicropubCategoryTests")
|
||||||
|
struct MicropubCategoryTests {
|
||||||
|
/// A saved piece opened in the model, with `frontmatter` planted
|
||||||
|
/// after the owned keys (before the session loads it); returns its id.
|
||||||
|
@MainActor private func openPiece(_ model: PostsModel, _ home: URL, frontmatter: String = "") throws -> String {
|
||||||
|
let id = try plantedPiece(home, frontmatter: frontmatter)
|
||||||
|
model.select(id)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A recorded create's `properties` — a short log fails the pin's
|
||||||
|
/// own requirement instead of trapping (#206: `request(_:)`, never a subscript).
|
||||||
|
private nonisolated func createProperties(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
|
||||||
|
let request = try #require(log.request(index))
|
||||||
|
return try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A recorded update's `replace`.
|
||||||
|
private nonisolated func updateReplace(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
|
||||||
|
let request = try #require(log.request(index))
|
||||||
|
return try #require(micropubJSON(request)["replace"] as? [String: Any])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The writer's blog categories the S8 pins pick against (blog
|
||||||
|
/// order is the wire's).
|
||||||
|
private static let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"]
|
||||||
|
|
||||||
|
// MARK: S3 — the codec reads and renders the one-line list (pure)
|
||||||
|
|
||||||
|
@Test func `category read is the list the bare scalar or empty`() {
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": "[Tech, Notes]"]) == ["Tech", "Notes"])
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": "[\"Tech, general\", Notes]"]) == ["Tech, general", "Notes"])
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": "Essays"]) == ["Essays"])
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": "[ Tech , Notes,, Tech ]"]) == ["Tech", "Notes"])
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": ""]) == [])
|
||||||
|
#expect(PostFrontmatter.categories(in: ["category": "[]"]) == [])
|
||||||
|
#expect(PostFrontmatter.categories(in: [:]) == [])
|
||||||
|
// A hand-quoted scalar is one category (parse strips the quotes).
|
||||||
|
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \"Tech, general\"\n---\n")) == ["Tech, general"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `category value renders one line that round-trips through parse`() {
|
||||||
|
let value = PostFrontmatter.categoryValue(["Tech", "Tech, general", "say \"hi\""])
|
||||||
|
#expect(!value.contains("\n")) // the frontmatter sink is line-bounded
|
||||||
|
let matter = PostFrontmatter.parse("---\ncategory: \(value)\n---\n")
|
||||||
|
#expect(PostFrontmatter.categories(in: matter) == ["Tech", "Tech, general", "say \"hi\""])
|
||||||
|
|
||||||
|
// Backslashes escape too — a name ending in one, or holding `\"`,
|
||||||
|
// reads back as itself (never one junk name swallowing the next).
|
||||||
|
let slashed = ["a\\", "x\\\"y", "Notes"]
|
||||||
|
let slashedValue = PostFrontmatter.categoryValue(slashed)
|
||||||
|
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \(slashedValue)\n---\n")) == slashed)
|
||||||
|
|
||||||
|
// Line/control characters strip before the sink; empties drop.
|
||||||
|
#expect(PostFrontmatter.categoryValue(["a\nb", "", " "]) == "[ab]")
|
||||||
|
#expect(PostFrontmatter.categoryValue([]) == "[]")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `category list primitives are the unbracketed parse and render`() {
|
||||||
|
#expect(PostFrontmatter.categoryList("Tech, No") == ["Tech", "No"])
|
||||||
|
#expect(PostFrontmatter.categoryListValue(["Tech", "Tech, general"]) == "Tech, \"Tech, general\"")
|
||||||
|
let names = ["Tech", "Tech, general", "say \"hi\""]
|
||||||
|
#expect(PostFrontmatter.categoryList(PostFrontmatter.categoryListValue(names)) == names)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S2 — the wire contract (pure builders)
|
||||||
|
|
||||||
|
@Test func `draft request carries category only when the list is non-empty`() throws {
|
||||||
|
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
|
||||||
|
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||||
|
#expect(props["category"] as? [String] == ["Tech", "Notes"])
|
||||||
|
#expect(props["name"] as? [String] == ["T"])
|
||||||
|
#expect(props["content"] as? [String] == ["B"])
|
||||||
|
#expect(props["post-status"] as? [String] == ["draft"])
|
||||||
|
|
||||||
|
// No categories → no key at all (a create never carries an empty list).
|
||||||
|
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
|
||||||
|
#expect(bare["category"] == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `update request carries category in replace only when a list is given`() throws {
|
||||||
|
let url = "https://example.micro.blog/hello.html"
|
||||||
|
let listedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
|
||||||
|
let listed = try #require(micropubJSON(listedRequest)["replace"] as? [String: Any])
|
||||||
|
#expect(listed["category"] as? [String] == ["Tech", "Notes"])
|
||||||
|
#expect(listed["name"] as? [String] == ["T"])
|
||||||
|
#expect(listed["content"] as? [String] == ["B"])
|
||||||
|
|
||||||
|
// An empty list IS sent — it clears the post's categories.
|
||||||
|
let clearedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: [])
|
||||||
|
let cleared = try #require(micropubJSON(clearedRequest)["replace"] as? [String: Any])
|
||||||
|
#expect(cleared["category"] as? [String] == [])
|
||||||
|
|
||||||
|
// nil → the opt-out: replace names exactly name + content, the
|
||||||
|
// bytes the #206 request carried (JSONSerialization escapes `/`).
|
||||||
|
let kept = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok")
|
||||||
|
let replace = try #require(micropubJSON(kept)["replace"] as? [String: Any])
|
||||||
|
#expect(Set(replace.keys) == ["name", "content"])
|
||||||
|
let expected = #"{"action":"update","replace":{"content":["B"],"name":["T"]},"url":"https:\/\/example.micro.blog\/hello.html"}"#
|
||||||
|
#expect(kept.httpBody == Data(expected.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S1 — categories travel (create)
|
||||||
|
|
||||||
|
@Test @MainActor func `create carries the piece's category list and no key when there is none`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/categorized"], log: log)
|
||||||
|
|
||||||
|
_ = try openPiece(model, home, frontmatter: "category: [Tech, Notes]\n")
|
||||||
|
let listed = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
#expect(listed == .drafted(url: "https://example.micro.blog/categorized", preview: nil))
|
||||||
|
let props = try createProperties(log, 0)
|
||||||
|
#expect(props["category"] as? [String] == ["Tech", "Notes"])
|
||||||
|
#expect(props["name"] as? [String] == ["Titled"])
|
||||||
|
#expect(props["content"] as? [String] == ["# Titled\n\nBody."])
|
||||||
|
#expect(props["post-status"] as? [String] == ["draft"])
|
||||||
|
|
||||||
|
// No line at all → no key; an empty line → no key either.
|
||||||
|
_ = try openPiece(model, home)
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
let bare = try createProperties(log, 1)
|
||||||
|
#expect(bare["category"] == nil)
|
||||||
|
_ = try openPiece(model, home, frontmatter: "category:\n")
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
let emptyLine = try createProperties(log, 2)
|
||||||
|
#expect(emptyLine["category"] == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S2 — a re-send replaces, opt-in by key (the model)
|
||||||
|
|
||||||
|
@Test @MainActor func `a re-send carries the line's list in replace and clears on an empty list`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let url = "https://example.micro.blog/live"
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let transport = micropubCanned(200, log: log)
|
||||||
|
|
||||||
|
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech, Notes]\n")
|
||||||
|
let listed = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
#expect(listed == .updated(url: url))
|
||||||
|
let replace = try updateReplace(log, 0)
|
||||||
|
#expect(replace["category"] as? [String] == ["Tech", "Notes"])
|
||||||
|
#expect(replace["name"] as? [String] == ["Titled"])
|
||||||
|
|
||||||
|
// An empty list IS sent — it clears the post's categories.
|
||||||
|
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: []\n")
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
let cleared = try updateReplace(log, 1)
|
||||||
|
#expect(cleared["category"] as? [String] == [])
|
||||||
|
|
||||||
|
// No line → replace names exactly name + content: the blog keeps whatever it has.
|
||||||
|
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||||
|
let kept = try updateReplace(log, 2)
|
||||||
|
#expect(Set(kept.keys) == ["name", "content"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S4 — the edit lands at the send
|
||||||
|
|
||||||
|
@Test @MainActor func `a category edit lands on the piece before the wire`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let id = try openPiece(model, home) // no category line yet
|
||||||
|
let before = try PostFrontmatter.split(readPost(home, id)).body
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/edited"], log: log)
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: transport)
|
||||||
|
|
||||||
|
#expect(outcome == .drafted(url: "https://example.micro.blog/edited", preview: nil))
|
||||||
|
let after = try readPost(home, id)
|
||||||
|
// The line is a line of the block (inserted before the closing
|
||||||
|
// `---` — the send's own `micropub_url` stamp lands after it);
|
||||||
|
// the body is byte-identical.
|
||||||
|
#expect(PostFrontmatter.split(after).block.contains("\ncategory: [Essays]\n"))
|
||||||
|
#expect(PostFrontmatter.split(after).body == before)
|
||||||
|
let props = try createProperties(log, 0)
|
||||||
|
#expect(props["category"] as? [String] == ["Essays"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `clearing as an empty list writes category empty and sends it in replace`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let url = "https://example.micro.blog/live"
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech]\n")
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", categories: [], transport: micropubCanned(200, log: log))
|
||||||
|
|
||||||
|
#expect(outcome == .updated(url: url))
|
||||||
|
let disk = try readPost(home, id)
|
||||||
|
#expect(disk.contains("category: []\n"))
|
||||||
|
let replace = try updateReplace(log, 0)
|
||||||
|
#expect(replace["category"] as? [String] == [])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a refused send with a category edit writes nothing`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never opened
|
||||||
|
let before = try readPost(home, post.id)
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
|
||||||
|
|
||||||
|
guard case .refused = outcome else {
|
||||||
|
Issue.record("expected refused, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(log.requests.isEmpty)
|
||||||
|
let after = try readPost(home, post.id)
|
||||||
|
#expect(after == before) // the edit never reached the disk
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a category write that cannot land refuses the send with nothing on the wire`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let id = try openPiece(model, home)
|
||||||
|
// The piece folder goes read-only: the category line cannot land
|
||||||
|
// (the #206 stamp-failure injection).
|
||||||
|
let dir = try #require(PostStore.folder(of: id, home: home))
|
||||||
|
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||||
|
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
|
||||||
|
|
||||||
|
guard case let .refused(reason) = outcome else {
|
||||||
|
Issue.record("expected refused, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(reason.hasPrefix("Couldn't save this piece's categories — nothing was sent."))
|
||||||
|
#expect(log.requests.isEmpty)
|
||||||
|
let disk = try readPost(home, id)
|
||||||
|
#expect(!disk.contains("category:"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a category name is sanitized before it lands on the piece and the wire`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let id = try openPiece(model, home)
|
||||||
|
|
||||||
|
_ = await model.micropubSend(
|
||||||
|
token: "tok",
|
||||||
|
categories: ["a\nb", " "],
|
||||||
|
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/clean"], log: log),
|
||||||
|
)
|
||||||
|
|
||||||
|
// The newline never reaches the line-bounded sink and the blank
|
||||||
|
// name drops; the wire's names come from that sanitized disk line.
|
||||||
|
#expect(try PostFrontmatter.parse(readPost(home, id))["category"] == "[ab]")
|
||||||
|
#expect(try createProperties(log, 0)["category"] as? [String] == ["ab"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `the sheet's disk read is the open piece's category line`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
#expect(model.openPieceCategories() == []) // nothing open
|
||||||
|
|
||||||
|
_ = try openPiece(model, home)
|
||||||
|
#expect(model.openPieceCategories() == []) // no line yet
|
||||||
|
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
_ = await model.micropubSend(
|
||||||
|
token: "tok",
|
||||||
|
categories: ["Essays"],
|
||||||
|
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: log),
|
||||||
|
)
|
||||||
|
#expect(model.openPieceCategories() == ["Essays"]) // read from disk, never a snapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `an imported category line rides through import`() throws {
|
||||||
|
let home = try storeHome()
|
||||||
|
// A foreign file carries its own classification — only Museion's
|
||||||
|
// bookkeeping drops at the boundary (#206); the category line is
|
||||||
|
// the writer's, so it stays (#207).
|
||||||
|
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("categorized-\(UUID().uuidString).md")
|
||||||
|
try "---\ncategory: [Tech]\nmicropub_url: https://example.micro.blog/x\n---\n\n# Outside\n\nBody.\n"
|
||||||
|
.write(to: ext, atomically: true, encoding: .utf8)
|
||||||
|
defer { try? FileManager.default.removeItem(at: ext) }
|
||||||
|
|
||||||
|
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
|
||||||
|
|
||||||
|
let matter = try PostFrontmatter.parse(readPost(home, post.id))
|
||||||
|
#expect(PostFrontmatter.categories(in: matter) == ["Tech"])
|
||||||
|
#expect(matter["micropub_url"] == nil) // the bookkeeping still drops
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S5 — the blog's own categories (q=category)
|
||||||
|
|
||||||
|
@Test func `blog categories ride a get to q=category with the bearer token and come from the categories array`() async throws {
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let body = #"{"categories": ["Travel", " Photos ", ""], "microblog-categories": [{"name": "Ignored"}]}"#
|
||||||
|
let listed = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: body, log: log))
|
||||||
|
|
||||||
|
#expect(listed == ["Travel", "Photos"])
|
||||||
|
let request = try #require(log.request(0))
|
||||||
|
let target = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
||||||
|
#expect(target?.queryItems == [URLQueryItem(name: "q", value: "category")])
|
||||||
|
#expect(request.httpMethod == "GET")
|
||||||
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
||||||
|
#expect(request.httpBody == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `blog categories fall back to the detailed list and a bare 2xx is no suggestions`() async {
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let detailed = #"{"microblog-categories": [{"name": "Travel"}, {"name": " "}, {"url": "https://micro.blog/c/x", "name": "Photos"}]}"#
|
||||||
|
let fallback = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: detailed, log: log))
|
||||||
|
#expect(fallback == ["Travel", "Photos"])
|
||||||
|
|
||||||
|
let bare = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: "{}", log: log))
|
||||||
|
#expect(bare == [])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a 401 and a transport throw are no suggestions never an error`() async {
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let deniedBody = #"{"error":"forbidden","error_description":"token not authorized"}"#
|
||||||
|
let denied = await Micropub.blogCategories(token: "tok", transport: micropubCanned(401, body: deniedBody, log: log))
|
||||||
|
#expect(denied == []) // a rejected token surfaces on the send itself
|
||||||
|
|
||||||
|
let dead: Micropub.Transport = { _ in throw URLError(.notConnectedToInternet) }
|
||||||
|
let unreachable = await Micropub.blogCategories(token: "tok", transport: dead)
|
||||||
|
#expect(unreachable == [])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S6 — publish applies pending edits first
|
||||||
|
|
||||||
|
@Test @MainActor func `publish with a category edit updates first then flips the status`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let url = "https://example.micro.blog/drafted"
|
||||||
|
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let transport = micropubCanned(200, log: log)
|
||||||
|
|
||||||
|
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: transport)
|
||||||
|
|
||||||
|
#expect(outcome == .published)
|
||||||
|
// TWO requests, in order: the update carrying the edit, THEN the post-status publish.
|
||||||
|
#expect(log.requests.count == 2)
|
||||||
|
let replace = try updateReplace(log, 0)
|
||||||
|
#expect(replace["category"] as? [String] == ["Essays"])
|
||||||
|
let publish = try #require(log.request(1))
|
||||||
|
let flip = try #require(micropubJSON(publish)["replace"] as? [String: Any])
|
||||||
|
#expect(flip["post-status"] as? [String] == ["published"])
|
||||||
|
#expect(flip["category"] == nil)
|
||||||
|
let disk = try readPost(home, id)
|
||||||
|
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a failed update half never publishes`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let url = "https://example.micro.blog/gone"
|
||||||
|
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
|
||||||
|
// Micro.blog answers 404 to the update: the post is gone there.
|
||||||
|
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: micropubCanned(404, log: log))
|
||||||
|
|
||||||
|
// The update's own outcome (#206: the piece forgot the dead link).
|
||||||
|
guard case .forgotten = outcome else {
|
||||||
|
Issue.record("expected forgotten, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// ONE request — the update half; the publish never went out (the
|
||||||
|
// count says so: a publish that leaked would still answer 404).
|
||||||
|
#expect(log.requests.count == 1)
|
||||||
|
let only = try #require(log.request(0))
|
||||||
|
let replace = try #require(micropubJSON(only)["replace"] as? [String: Any])
|
||||||
|
#expect(replace["category"] as? [String] == ["Essays"])
|
||||||
|
#expect(replace["post-status"] == nil)
|
||||||
|
let forgotten = try #require(Post.scan(home: home).first)
|
||||||
|
#expect(forgotten.micropubURL == nil)
|
||||||
|
// The edit stayed on the piece: the next send (a fresh draft) carries it.
|
||||||
|
let disk = try readPost(home, id)
|
||||||
|
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish targets the post the send updated never the caller's stale url`() async throws {
|
||||||
|
// The sheet's URL comes from the scan at open; the piece on disk
|
||||||
|
// remembers another (edited by hand meanwhile). The edit and the
|
||||||
|
// status flip must land on the SAME post — the one the send touched.
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let id = try openPiece(model, home, frontmatter: "micropub_url: https://example.micro.blog/live\n")
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
|
||||||
|
let outcome = await model.micropubPublish(
|
||||||
|
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: micropubCanned(200, log: log),
|
||||||
|
)
|
||||||
|
|
||||||
|
#expect(outcome == .published)
|
||||||
|
let flip = try #require(log.request(1))
|
||||||
|
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/live")
|
||||||
|
// And the stamp never overwrites the real memory with the stale address.
|
||||||
|
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/live")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish follows a fresh draft when the send had to create one`() async throws {
|
||||||
|
// No remembered post on disk (an earlier stamp failed), so the send
|
||||||
|
// creates a draft; the publish flips THAT post, and the piece remembers it.
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let id = try openPiece(model, home)
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/fresh"], log: log)
|
||||||
|
|
||||||
|
let outcome = await model.micropubPublish(
|
||||||
|
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: transport,
|
||||||
|
)
|
||||||
|
|
||||||
|
#expect(outcome == .published)
|
||||||
|
let flip = try #require(log.request(1))
|
||||||
|
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/fresh")
|
||||||
|
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/fresh")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S7 — the sheet field's pending-edit rule (pure)
|
||||||
|
|
||||||
|
@Test func `a category edit is pending only when the field's list differs from the settled one`() {
|
||||||
|
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes", settled: "Tech, Notes") == nil)
|
||||||
|
// A trailing comma is not an edit.
|
||||||
|
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes,", settled: "Tech, Notes") == nil)
|
||||||
|
// Clearing a piece that had a line sends `category: []`.
|
||||||
|
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "Tech") == [])
|
||||||
|
#expect(MicropubCategoryField.pendingCategories(field: "Tech", settled: "") == ["Tech"])
|
||||||
|
// A piece without a line never gains an empty key.
|
||||||
|
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "") == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: S8 — picks add (the whole-text completion IS the merge) + the menu (pure)
|
||||||
|
|
||||||
|
@Test func `the partial word is the last comma segment with its quotes off`() {
|
||||||
|
#expect(MicropubCategoryField.partial("Tech, ") == "")
|
||||||
|
// A quoted comma is not a separator — the segment is the one name.
|
||||||
|
#expect(MicropubCategoryField.partial("Tech, \"Tech, general\"") == "Tech, general")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the menu lists the whole blog for an empty field in blog order`() {
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "", blog: Self.blog)
|
||||||
|
== ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the menu narrows to the case-insensitive prefix of the half-typed word`() {
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "te", blog: Self.blog) == ["Tech", "Tech, general"])
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "Tech, Te", blog: Self.blog) == ["Tech, general"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the menu offers everything else once the last word is a finished category`() {
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "Tech", blog: Self.blog)
|
||||||
|
== ["Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the menu never offers a name already in the field`() {
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "notes, swift", blog: Self.blog)
|
||||||
|
== ["Tech", "Essays", "Fieldwork", "Tech, general", "SwiftUI"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `the menu stays open after a pick of a comma-containing name`() {
|
||||||
|
// The field reads `Tech, "Tech, general"` — the quoted last word is the finished name, so everything else is offered.
|
||||||
|
#expect(MicropubCategoryField.suggestions(text: "Tech, \"Tech, general\"", blog: Self.blog)
|
||||||
|
== ["Notes", "Essays", "Fieldwork", "Swift", "SwiftUI"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick into an empty field is the name`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "", picking: "Tech", blog: Self.blog) == "Tech")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick adds after a finished name`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick adds after a quoted name and keeps its quotes`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech, \"Tech, general\"", picking: "Notes", blog: Self.blog)
|
||||||
|
== "Tech, \"Tech, general\", Notes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `any number of picks keep adding`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Essays", blog: Self.blog) == "Tech, Notes, Essays")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick replaces the half-typed word`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Te", picking: "Tech", blog: Self.blog) == "Tech")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick replaces the half-typed word after a comma`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech, No", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a finished name stays when the pick only extends it`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Tech, general", blog: Self.blog) == "Tech, \"Tech, general\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick replaces a half-typed shared prefix`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Sw", picking: "SwiftUI", blog: Self.blog) == "SwiftUI")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a pick never adds a present name twice`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a half-typed duplicate of an earlier name collapses to it`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "Notes, No", picking: "Notes", blog: Self.blog) == "Notes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `a custom name stays when a known one is picked`() {
|
||||||
|
#expect(MicropubCategoryField.completion(text: "MyNewCat", picking: "Notes", blog: Self.blog) == "MyNewCat, Notes")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ struct MicropubModelTests {
|
|||||||
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
|
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(
|
let outcome = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
|
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
|
||||||
)
|
)
|
||||||
@@ -42,7 +42,7 @@ struct MicropubModelTests {
|
|||||||
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
|
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
|
||||||
let (model, _) = try makeModelHome()
|
let (model, _) = try makeModelHome()
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(
|
let outcome = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(201, body: "{}", log: log),
|
transport: micropubCanned(201, body: "{}", log: log),
|
||||||
)
|
)
|
||||||
@@ -57,7 +57,7 @@ struct MicropubModelTests {
|
|||||||
let (model, _) = try makeModelHome()
|
let (model, _) = try makeModelHome()
|
||||||
model.newPost() // staged draft — no folder, no session
|
model.newPost() // staged draft — no folder, no session
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(
|
let outcome = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(201, body: "{}", log: log),
|
transport: micropubCanned(201, body: "{}", log: log),
|
||||||
)
|
)
|
||||||
@@ -76,7 +76,7 @@ struct MicropubModelTests {
|
|||||||
model.select(post.id)
|
model.select(post.id)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(
|
let outcome = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(201, body: "{}", log: log),
|
transport: micropubCanned(201, body: "{}", log: log),
|
||||||
)
|
)
|
||||||
@@ -88,26 +88,21 @@ struct MicropubModelTests {
|
|||||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test @MainActor func `frontmatter category never travels`() async throws {
|
@Test @MainActor func `frontmatter category travels`() async throws {
|
||||||
let (model, home) = try makeModelHome()
|
let (model, home) = try makeModelHome()
|
||||||
let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
|
// The writer's own category frontmatter — #207: a bare scalar
|
||||||
model.select(post.id)
|
// is ONE category, and it rides the create as `category`.
|
||||||
// The writer's own category frontmatter — permitted, inert.
|
try model.select(plantedPiece(home, frontmatter: "category: Essays\n"))
|
||||||
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
|
||||||
let raw = try String(contentsOf: fileURL, encoding: .utf8)
|
|
||||||
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\ncategory: Essays\n")
|
|
||||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
_ = await model.micropubSendDraft(
|
_ = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
|
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
|
||||||
)
|
)
|
||||||
|
|
||||||
let request = try #require(log.requests.first)
|
let request = try #require(log.requests.first)
|
||||||
let wire = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? ""
|
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||||
#expect(!wire.lowercased().contains("category"))
|
#expect(props["category"] as? [String] == ["Essays"])
|
||||||
#expect(!wire.contains("Essays"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test @MainActor func `a failed draft stamps nothing`() async throws {
|
@Test @MainActor func `a failed draft stamps nothing`() async throws {
|
||||||
@@ -116,7 +111,7 @@ struct MicropubModelTests {
|
|||||||
model.select(post.id)
|
model.select(post.id)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
_ = await model.micropubSendDraft(
|
_ = await model.micropubSend(
|
||||||
token: "tok",
|
token: "tok",
|
||||||
transport: micropubCanned(500, body: "{}", log: log),
|
transport: micropubCanned(500, body: "{}", log: log),
|
||||||
)
|
)
|
||||||
@@ -124,28 +119,11 @@ struct MicropubModelTests {
|
|||||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@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)
|
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
|
||||||
_ = await model.micropubSendDraft(
|
|
||||||
token: "tok",
|
|
||||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
|
|
||||||
)
|
|
||||||
_ = await model.micropubSendDraft(
|
|
||||||
token: "tok",
|
|
||||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
|
|
||||||
)
|
|
||||||
|
|
||||||
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second")
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: #34 (S6.2) — illustrations travel with it
|
// MARK: #34 (S6.2) — illustrations travel with it
|
||||||
|
|
||||||
/// Plants a PNG beside the piece; returns the piece's post.md URL.
|
/// 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 {
|
/// Shared with `MicropubStatusTests` (shared-helper convention).
|
||||||
|
@MainActor func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
|
||||||
let post = try PostStore.writeNew(body: body, home: home)
|
let post = try PostStore.writeNew(body: body, home: home)
|
||||||
model.select(post.id)
|
model.select(post.id)
|
||||||
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||||
@@ -162,20 +140,21 @@ struct MicropubModelTests {
|
|||||||
)
|
)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
||||||
// The three hops, in order: q=config → upload → create.
|
// The three hops, in order: q=config → upload → create.
|
||||||
#expect(log.requests.count == 3)
|
#expect(log.requests.count == 3)
|
||||||
let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
let config = URLComponents(url: log.request(0)?.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
||||||
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
|
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
|
||||||
#expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media")
|
#expect(log.request(1)?.url?.absoluteString == "https://micro.blog/micropub/media")
|
||||||
#expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
|
#expect(log.request(1)?.httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
|
||||||
// The create: the ref REWRITTEN in place with its uploaded URL
|
// The create: the ref REWRITTEN in place with its uploaded URL
|
||||||
// — exactly where the writer placed it (2026-11-01: the photo
|
// — exactly where the writer placed it (2026-11-01: the photo
|
||||||
// PROPERTY rendered at the bottom, position lost), alt in the
|
// PROPERTY rendered at the bottom, position lost), alt in the
|
||||||
// markdown, NO photo property keys.
|
// markdown, NO photo property keys.
|
||||||
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
|
let create = try #require(log.request(2))
|
||||||
|
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
|
||||||
let expected = "# Inked\n\nProse before.\n\n\n\nProse after."
|
let expected = "# Inked\n\nProse before.\n\n\n\nProse after."
|
||||||
#expect(props["content"] as? [String] == [expected])
|
#expect(props["content"] as? [String] == [expected])
|
||||||
#expect(props["photo"] == nil)
|
#expect(props["photo"] == nil)
|
||||||
@@ -197,7 +176,7 @@ struct MicropubModelTests {
|
|||||||
)
|
)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
guard case let .refused(reason) = outcome else {
|
guard case let .refused(reason) = outcome else {
|
||||||
Issue.record("expected refused, got \(outcome)")
|
Issue.record("expected refused, got \(outcome)")
|
||||||
@@ -228,7 +207,7 @@ struct MicropubModelTests {
|
|||||||
)
|
)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
guard case let .refused(reason) = outcome else {
|
guard case let .refused(reason) = outcome else {
|
||||||
Issue.record("expected refused, got \(outcome)")
|
Issue.record("expected refused, got \(outcome)")
|
||||||
@@ -246,13 +225,14 @@ struct MicropubModelTests {
|
|||||||
)
|
)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
||||||
// config + ONE upload + create — the FILE uploads once, not once per ref.
|
// config + ONE upload + create — the FILE uploads once, not once per ref.
|
||||||
#expect(log.requests.count == 3)
|
#expect(log.requests.count == 3)
|
||||||
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
|
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
|
||||||
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
|
let create = try #require(log.request(2))
|
||||||
|
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
|
||||||
let content = try #require((props["content"] as? [String])?.first)
|
let content = try #require((props["content"] as? [String])?.first)
|
||||||
// Both refs share the one uploaded URL.
|
// Both refs share the one uploaded URL.
|
||||||
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
|
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
|
||||||
@@ -266,7 +246,7 @@ struct MicropubModelTests {
|
|||||||
) // path.png planted, ghost.png never
|
) // path.png planted, ghost.png never
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
guard case .refused = outcome else {
|
guard case .refused = outcome else {
|
||||||
Issue.record("expected refused, got \(outcome)")
|
Issue.record("expected refused, got \(outcome)")
|
||||||
@@ -281,10 +261,10 @@ struct MicropubModelTests {
|
|||||||
model.select(post.id)
|
model.select(post.id)
|
||||||
|
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
// The #33 path unchanged: no config round-trip, straight to the create.
|
// The #33 path unchanged: no config round-trip, straight to the create.
|
||||||
#expect(log.requests.count == 1)
|
#expect(log.requests.count == 1)
|
||||||
#expect(log.requests[0].url == Micropub.endpoint)
|
#expect(log.request(0)?.url == Micropub.endpoint)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
//
|
||||||
|
// MicropubStatusTests.swift
|
||||||
|
// MuseionTests
|
||||||
|
//
|
||||||
|
// #206: the Micro.blog publish record. Scenario:
|
||||||
|
//
|
||||||
|
// Given a saved Post the writer sent to Micro.blog (the piece
|
||||||
|
// remembers its post URL)
|
||||||
|
// When the writer publishes it, sends it again, or Micro.blog has
|
||||||
|
// lost the post
|
||||||
|
// Then the piece remembers the publish (frontmatter
|
||||||
|
// `micropub_published`, healing a link the send could not stamp)
|
||||||
|
// and the library row can say
|
||||||
|
// "published <date>"; a re-send UPDATES the remembered post in
|
||||||
|
// place — same URL, no second post, no second upload for an
|
||||||
|
// unchanged image — and leaves the publish date alone; a 404 (the
|
||||||
|
// post deleted on Micro.blog) clears the link so the piece can go
|
||||||
|
// out as a fresh draft. Nothing is stamped on any failure, and a forget that
|
||||||
|
// cannot land says so — never a "cleared" the disk contradicts.
|
||||||
|
//
|
||||||
|
// Wire facts (microblog.dev/api/posting, 2026-12-04):
|
||||||
|
// `action=update` with `replace` sets name and content; updates
|
||||||
|
// answer 200 with an empty body and 404 when `url` is not on the
|
||||||
|
// blog. The media listing carries no content hash, so upload dedup
|
||||||
|
// is a local memo keyed by the asset's bytes.
|
||||||
|
//
|
||||||
|
// A file from outside brings none of this: the import boundary drops
|
||||||
|
// Museion's micropub keys, so a foreign `micropub_url` can never aim
|
||||||
|
// a send at one of the writer's posts.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
@testable import Museion
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite("MicropubStatusTests")
|
||||||
|
struct MicropubStatusTests {
|
||||||
|
/// A fresh piece with extra frontmatter lines planted after the
|
||||||
|
/// owned keys; returns its id.
|
||||||
|
private func piece(_ home: URL, frontmatter: String = "") throws -> String {
|
||||||
|
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
|
||||||
|
if !frontmatter.isEmpty {
|
||||||
|
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
||||||
|
let raw = try String(contentsOf: fileURL, encoding: .utf8)
|
||||||
|
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
|
||||||
|
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||||
|
}
|
||||||
|
return post.id
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: The record on disk
|
||||||
|
|
||||||
|
@Test func `row status reads nil draft or published from the frontmatter`() throws {
|
||||||
|
let home = try storeHome()
|
||||||
|
defer { try? FileManager.default.removeItem(at: home) }
|
||||||
|
let live = try piece(
|
||||||
|
home,
|
||||||
|
frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2026-12-04T15:02:00\n",
|
||||||
|
)
|
||||||
|
let draft = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/draft\n")
|
||||||
|
let untouched = try piece(home)
|
||||||
|
// A stamp that isn't the stamp shape never reads as a publish.
|
||||||
|
let broken = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/broken\nmicropub_published: yesterday\n")
|
||||||
|
|
||||||
|
let posts = Post.scan(home: home)
|
||||||
|
#expect(posts.first { $0.id == live }?.micropubStatus == "published Dec 4, 2026")
|
||||||
|
#expect(posts.first { $0.id == draft }?.micropubStatus == "draft on Micro.blog")
|
||||||
|
#expect(posts.first { $0.id == untouched }?.micropubStatus == nil)
|
||||||
|
#expect(posts.first { $0.id == broken }?.micropubStatus == "draft on Micro.blog")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func `an imported piece brings no micro.blog memory`() throws {
|
||||||
|
let home = try storeHome()
|
||||||
|
defer { try? FileManager.default.removeItem(at: home) }
|
||||||
|
let source = home.appendingPathComponent("guest.md")
|
||||||
|
try """
|
||||||
|
---
|
||||||
|
title: Guest
|
||||||
|
micropub_url: https://example.micro.blog/someone-elses-live-post
|
||||||
|
micropub_published: 2026-01-01T00:00:00
|
||||||
|
---
|
||||||
|
# Guest
|
||||||
|
|
||||||
|
Body.
|
||||||
|
""".write(to: source, atomically: true, encoding: .utf8)
|
||||||
|
|
||||||
|
// A foreign file's remembered URL would aim the next send's
|
||||||
|
// content replace at whatever post it names, under the writer's
|
||||||
|
// token — so Museion's bookkeeping is ours to set, never theirs
|
||||||
|
// to carry in (the way a foreign `origin` loses).
|
||||||
|
let post = try PostStore.importFile(at: source, origin: .writer, home: home)
|
||||||
|
|
||||||
|
let scanned = try #require(Post.scan(home: home).first { $0.id == post.id })
|
||||||
|
#expect(scanned.micropubURL == nil)
|
||||||
|
#expect(scanned.micropubPublished == nil)
|
||||||
|
#expect(scanned.micropubStatus == nil)
|
||||||
|
let matter = try PostFrontmatter.parse(readPost(home, post.id))
|
||||||
|
#expect(matter["title"] == "Guest") // every other external key still rides verbatim
|
||||||
|
#expect(matter["micropub_url"] == nil) // the line is gone, not merely emptied
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish remembers the date on the piece`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Stamped\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/stamped"
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
#expect(Post.scan(home: home).first?.micropubPublished == nil) // a draft is not a publish
|
||||||
|
|
||||||
|
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
#expect(outcome == .published)
|
||||||
|
let scanned = try #require(Post.scan(home: home).first)
|
||||||
|
let published = try #require(scanned.micropubPublished)
|
||||||
|
#expect(abs(published.timeIntervalSinceNow) < 60) // stamped now, local time
|
||||||
|
#expect(scanned.micropubURL == url)
|
||||||
|
#expect(scanned.micropubStatus?.hasPrefix("published ") == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish remembers a post whose send could not stamp it`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Unstamped\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/unstamped"
|
||||||
|
|
||||||
|
// The send lands, but its stamp cannot: the piece folder is
|
||||||
|
// read-only for the moment (the sheet still holds the URL for
|
||||||
|
// this session; the piece remembers nothing on disk).
|
||||||
|
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||||
|
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||||
|
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||||
|
let sent = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
#expect(sent == .drafted(url: url, preview: nil))
|
||||||
|
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
|
||||||
|
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||||
|
|
||||||
|
// Publish writes the record AND heals the link the send couldn't.
|
||||||
|
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
let scanned = try #require(Post.scan(home: home).first)
|
||||||
|
#expect(scanned.micropubURL == url)
|
||||||
|
#expect(scanned.micropubPublished != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a failed publish stamps nothing`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Refused\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
|
||||||
|
let outcome = await model.micropubPublish(
|
||||||
|
url: "https://example.micro.blog/refused",
|
||||||
|
token: "tok",
|
||||||
|
transport: micropubCanned(500, log: MicropubRequestLog()),
|
||||||
|
)
|
||||||
|
|
||||||
|
guard case let .requestFailed(status, _) = outcome else {
|
||||||
|
Issue.record("expected requestFailed, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(status == 500)
|
||||||
|
#expect(Post.scan(home: home).first?.micropubPublished == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish refuses a post address that is not a clean url`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Injected\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
|
||||||
|
// A newline in the address would close the frontmatter block on
|
||||||
|
// the heal write — so nothing travels and nothing is remembered.
|
||||||
|
let outcome = await model.micropubPublish(
|
||||||
|
url: "https://example.micro.blog/live\nmicropub_published: 2020-01-01T00:00:00",
|
||||||
|
token: "tok",
|
||||||
|
transport: micropubCanned(200, log: log),
|
||||||
|
)
|
||||||
|
|
||||||
|
guard case .refused = outcome else {
|
||||||
|
Issue.record("expected refused, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(log.requests.isEmpty)
|
||||||
|
let scanned = try #require(Post.scan(home: home).first)
|
||||||
|
#expect(scanned.micropubURL == nil)
|
||||||
|
#expect(scanned.micropubPublished == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: A re-send updates the remembered post in place
|
||||||
|
|
||||||
|
@Test func `update request is the in-place replace against the remembered url`() {
|
||||||
|
let request = Micropub.makeUpdateRequest(
|
||||||
|
url: "https://example.micro.blog/hello.html",
|
||||||
|
title: "The Title",
|
||||||
|
body: "The body.",
|
||||||
|
token: "tok",
|
||||||
|
)
|
||||||
|
|
||||||
|
#expect(request.url == Micropub.endpoint)
|
||||||
|
#expect(request.httpMethod == "POST")
|
||||||
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
||||||
|
let root = micropubJSON(request)
|
||||||
|
#expect(root["action"] as? String == "update")
|
||||||
|
#expect(root["url"] as? String == "https://example.micro.blog/hello.html")
|
||||||
|
let replace = root["replace"] as? [String: Any]
|
||||||
|
#expect(replace?["name"] as? [String] == ["The Title"])
|
||||||
|
#expect(replace?["content"] as? [String] == ["The body."])
|
||||||
|
// Never a status flip — a draft stays a draft, a live post stays live.
|
||||||
|
#expect(replace?["post-status"] == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a re-send updates the remembered post and never creates a second`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Again\n\nFirst body.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/again"
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
model.session?.edit("# Again\n\nSecond body.")
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
|
||||||
|
|
||||||
|
#expect(outcome == .updated(url: url))
|
||||||
|
let request = try #require(log.requests.first)
|
||||||
|
let root = micropubJSON(request)
|
||||||
|
#expect(root["action"] as? String == "update") // the create's `type`/`properties` never ride
|
||||||
|
#expect(root["type"] == nil)
|
||||||
|
#expect(root["url"] as? String == url)
|
||||||
|
let replace = try #require(root["replace"] as? [String: Any])
|
||||||
|
#expect(replace["content"] as? [String] == ["# Again\n\nSecond body."])
|
||||||
|
#expect(Post.scan(home: home).first?.micropubURL == url) // the remembered URL never moves
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a live update leaves the publish date alone`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let live = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2025-01-15T08:00:00\n")
|
||||||
|
model.select(live)
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
#expect(outcome == .updated(url: "https://example.micro.blog/live"))
|
||||||
|
#expect(Post.scan(home: home).first?.micropubStatus == "published Jan 15, 2025")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: A re-send never re-uploads an unchanged image
|
||||||
|
|
||||||
|
/// An illustrated piece, opened in the model; returns its folder
|
||||||
|
/// (`MicropubModelTests` owns the planting — shared-helper convention).
|
||||||
|
@MainActor private func illustratedPiece(_ model: PostsModel, _ home: URL) throws -> URL {
|
||||||
|
try MicropubModelTests()
|
||||||
|
.plantIllustratedPiece(model, home, body: "# Inked\n\n\n\nProse.")
|
||||||
|
.deletingLastPathComponent()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `an unchanged illustration rides its earlier upload`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
_ = try illustratedPiece(model, home)
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // config + upload + create
|
||||||
|
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
|
// ONE request — the in-place update. No q=config, no upload.
|
||||||
|
#expect(outcome == .updated(url: "https://example.micro.blog/inked"))
|
||||||
|
#expect(log.requests.count == 1)
|
||||||
|
let resent = try #require(log.request(0))
|
||||||
|
let replace = try #require(micropubJSON(resent)["replace"] as? [String: Any])
|
||||||
|
#expect((replace["content"] as? [String])?.first?.contains("") == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a changed illustration uploads again`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let dir = try illustratedPiece(model, home)
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
// The writer replaces the image — same name, new bytes.
|
||||||
|
let fresh = micropubPNG() + Data([0x7F])
|
||||||
|
try fresh.write(to: dir.appendingPathComponent("assets/path.png"))
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
|
// config → upload → update, and the upload carries the NEW bytes.
|
||||||
|
#expect(log.requests.count == 3)
|
||||||
|
#expect(log.request(1)?.httpBody?.firstRange(of: fresh) != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `an untrustworthy memo url never rides the wire`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let dir = try illustratedPiece(model, home)
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
// The sidecar is disk, so external data: a planted http URL is
|
||||||
|
// no memory at all.
|
||||||
|
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
|
||||||
|
var memo = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: memoURL))
|
||||||
|
let key = try #require(memo.keys.first)
|
||||||
|
memo[key] = "http://evil.example/swap.png"
|
||||||
|
try JSONEncoder().encode(memo).write(to: memoURL, options: .atomic)
|
||||||
|
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
|
#expect(log.requests.count == 3) // re-uploaded rather than trusted
|
||||||
|
let last = try #require(log.request(2))
|
||||||
|
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
|
||||||
|
let content = try #require((replace["content"] as? [String])?.first)
|
||||||
|
#expect(!content.contains("evil.example"))
|
||||||
|
#expect(content.contains("https://micro.blog/uploads/2026/ink.png"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a symlinked upload memo is no memory at all`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let dir = try illustratedPiece(model, home)
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // the real memo lands
|
||||||
|
|
||||||
|
// Planted: the sidecar becomes a link to a memo OUTSIDE the piece
|
||||||
|
// that names this image's bytes with an attacker-chosen URL.
|
||||||
|
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
|
||||||
|
try FileManager.default.removeItem(at: memoURL)
|
||||||
|
let outside = home.appendingPathComponent("planted-memo.json")
|
||||||
|
let planted = [Micropub.uploadKey(micropubPNG()): "https://micro.blog/uploads/2026/planted.png"]
|
||||||
|
try JSONEncoder().encode(planted).write(to: outside, options: .atomic)
|
||||||
|
try FileManager.default.createSymbolicLink(at: memoURL, withDestinationURL: outside)
|
||||||
|
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||||
|
|
||||||
|
#expect(log.requests.count == 3) // config → a fresh upload → the update
|
||||||
|
let last = try #require(log.request(2))
|
||||||
|
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
|
||||||
|
let content = try #require((replace["content"] as? [String])?.first)
|
||||||
|
#expect(!content.contains("planted.png"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: A post Micro.blog lost
|
||||||
|
|
||||||
|
@Test @MainActor func `a post micro.blog lost is forgotten named and sendable again`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Gone\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/gone"
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
// The writer deleted the draft on Micro.blog; the next send hears 404.
|
||||||
|
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
guard case let .forgotten(reason) = outcome else {
|
||||||
|
Issue.record("expected forgotten, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(reason.contains("deleted"))
|
||||||
|
let forgotten = try #require(Post.scan(home: home).first)
|
||||||
|
#expect(forgotten.micropubURL == nil) // no dead link left on the piece
|
||||||
|
#expect(forgotten.micropubStatus == nil)
|
||||||
|
|
||||||
|
// Recovery: with nothing remembered, the next send is a fresh draft.
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: log))
|
||||||
|
let created = try #require(log.request(0))
|
||||||
|
#expect(micropubJSON(created)["action"] == nil) // a create, not an update
|
||||||
|
#expect(Post.scan(home: home).first?.micropubURL == url)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a lost live post takes the publish record with it`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Vanish\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/vanish"
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||||
|
#expect(Post.scan(home: home).first?.micropubPublished != nil) // the record exists
|
||||||
|
|
||||||
|
// The post is deleted on Micro.blog; the next word there is 404.
|
||||||
|
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
guard case .forgotten = outcome else {
|
||||||
|
Issue.record("expected forgotten, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||||
|
#expect(Post.scan(home: home).first?.micropubPublished == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `publish refuses a piece that is not the open one`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
_ = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never selected
|
||||||
|
|
||||||
|
let log = MicropubRequestLog()
|
||||||
|
let outcome = await model.micropubPublish(
|
||||||
|
url: "https://example.micro.blog/unopened",
|
||||||
|
token: "tok",
|
||||||
|
transport: micropubCanned(200, log: log),
|
||||||
|
)
|
||||||
|
|
||||||
|
guard case .refused = outcome else {
|
||||||
|
Issue.record("expected refused, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(log.requests.isEmpty) // nothing went out
|
||||||
|
#expect(Post.scan(home: home).first?.micropubPublished == nil) // and nothing was remembered for it
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `a forget that cannot write says so instead of claiming the link is cleared`() async throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Stuck\n\nBody.", home: home)
|
||||||
|
model.select(post.id)
|
||||||
|
let url = "https://example.micro.blog/stuck"
|
||||||
|
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
// The piece folder goes read-only: the forget cannot land.
|
||||||
|
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||||
|
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||||
|
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||||
|
|
||||||
|
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||||
|
|
||||||
|
guard case let .refused(reason) = outcome else {
|
||||||
|
Issue.record("expected refused, got \(outcome)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(reason.contains("couldn't be cleared"))
|
||||||
|
#expect(Post.scan(home: home).first?.micropubURL == url) // still on the piece — and said to be
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,8 +10,9 @@
|
|||||||
// confirms publish
|
// confirms publish
|
||||||
// Then Micro.blog receives an h=entry create (markdown content, name,
|
// Then Micro.blog receives an h=entry create (markdown content, name,
|
||||||
// post-status=draft) followed by an update flipping post-status to
|
// post-status=draft) followed by an update flipping post-status to
|
||||||
// published — the piece's frontmatter `category:` never travels, and
|
// published; #207: the piece's `category:` list rides the create (its
|
||||||
// the draft URL is remembered on the piece.
|
// own pins: MicropubCategoryTests) — and the draft URL is remembered
|
||||||
|
// on the piece.
|
||||||
//
|
//
|
||||||
// Wire facts live-verified against microblog.dev/api/posting and
|
// Wire facts live-verified against microblog.dev/api/posting and
|
||||||
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
|
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
|
||||||
@@ -43,6 +44,18 @@ final class MicropubRequestLog: @unchecked Sendable {
|
|||||||
defer { lock.unlock() }
|
defer { lock.unlock() }
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The request at `index`, nil when fewer traveled. Read recorded
|
||||||
|
/// requests through here, never `requests[index]`: an out-of-range
|
||||||
|
/// subscript TRAPS, one trap kills the hosted runner, and every
|
||||||
|
/// queued test reports `Crash:` beside it (#206 flip cycle). A nil
|
||||||
|
/// here fails the pin's OWN expectation — `#require` it when the
|
||||||
|
/// value feeds a non-optional parameter.
|
||||||
|
func request(_ index: Int) -> URLRequest? {
|
||||||
|
lock.lock()
|
||||||
|
defer { lock.unlock() }
|
||||||
|
return index < items.count ? items[index] : nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
|
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
|
||||||
@@ -73,6 +86,19 @@ nonisolated func micropubJSON(_ request: URLRequest) -> [String: Any] {
|
|||||||
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
|
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A saved `# Titled` piece carrying `frontmatter` planted after the
|
||||||
|
/// owned keys (a `category:` or `micropub_url:` line) — its id. The
|
||||||
|
/// anchor is `origin: writer`, the last key `writeNew` stamps.
|
||||||
|
nonisolated func plantedPiece(_ home: URL, frontmatter: String = "") throws -> String {
|
||||||
|
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
|
||||||
|
guard !frontmatter.isEmpty else { return post.id }
|
||||||
|
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
||||||
|
try String(contentsOf: fileURL, encoding: .utf8)
|
||||||
|
.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
|
||||||
|
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||||
|
return post.id
|
||||||
|
}
|
||||||
|
|
||||||
@Suite("MicropubTests")
|
@Suite("MicropubTests")
|
||||||
struct MicropubTests {
|
struct MicropubTests {
|
||||||
// MARK: Request shapes (the wire contract)
|
// MARK: Request shapes (the wire contract)
|
||||||
@@ -214,6 +240,25 @@ struct MicropubTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func `a 5xx names micro.blog's outage not a bare status`() {
|
||||||
|
// Their errors arrive as HTML pages, so the JSON decode finds
|
||||||
|
// nothing — a 503 over that body names their side; a 4xx keeps
|
||||||
|
// the bare status; a described 5xx keeps the description.
|
||||||
|
let html = Data("<html><body>503 Service Unavailable</body></html>".utf8)
|
||||||
|
let outage = Micropub.decodeFailure(status: 503, body: html)
|
||||||
|
guard case let .requestFailed(status, detail) = outage else {
|
||||||
|
Issue.record("expected requestFailed, got \(outage)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(status == 503)
|
||||||
|
#expect(detail.contains("their side"))
|
||||||
|
|
||||||
|
let bare = Micropub.decodeFailure(status: 422, body: html)
|
||||||
|
#expect(bare == .requestFailed(status: 422, detail: "HTTP 422"))
|
||||||
|
let described = Micropub.decodeFailure(status: 502, body: Data(#"{"error_description":"upstream timeout"}"#.utf8))
|
||||||
|
#expect(described == .requestFailed(status: 502, detail: "upstream timeout"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test func `publish outcome is published on 2xx`() async {
|
@Test func `publish outcome is published on 2xx`() async {
|
||||||
let log = MicropubRequestLog()
|
let log = MicropubRequestLog()
|
||||||
let outcome = await Micropub.publish(
|
let outcome = await Micropub.publish(
|
||||||
@@ -247,7 +292,7 @@ struct MicropubTests {
|
|||||||
|
|
||||||
// MARK: The stamp + scan (the remembered draft URL)
|
// MARK: The stamp + scan (the remembered draft URL)
|
||||||
|
|
||||||
@Test func `stampMicropubURL stamps in place and scan reads it back`() throws {
|
@Test func `stampMicropub stamps in place and scan reads it back`() throws {
|
||||||
let home = FileManager.default.temporaryDirectory
|
let home = FileManager.default.temporaryDirectory
|
||||||
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
||||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||||
@@ -273,7 +318,7 @@ struct MicropubTests {
|
|||||||
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
|
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
|
||||||
let before = try String(contentsOf: fileURL, encoding: .utf8)
|
let before = try String(contentsOf: fileURL, encoding: .utf8)
|
||||||
|
|
||||||
try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home)
|
try PostStore.stampMicropub(post.id, home: home, [("micropub_url", "https://example.micro.blog/hello.html")])
|
||||||
|
|
||||||
let after = try String(contentsOf: fileURL, encoding: .utf8)
|
let after = try String(contentsOf: fileURL, encoding: .utf8)
|
||||||
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
|
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
|
||||||
@@ -286,11 +331,11 @@ struct MicropubTests {
|
|||||||
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
|
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func `stampMicropubURL throws on a vanished piece`() throws {
|
@Test func `stampMicropub throws on a vanished piece`() throws {
|
||||||
let home = FileManager.default.temporaryDirectory
|
let home = FileManager.default.temporaryDirectory
|
||||||
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
||||||
#expect(throws: (any Error).self) {
|
#expect(throws: (any Error).self) {
|
||||||
try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home)
|
try PostStore.stampMicropub("ghost", home: home, [("micropub_url", "https://x.example/")])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
// #179: the write-rail pins — one seam pairs every library store write
|
// #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
|
// with exactly one rescan and owns the error strip; the model owns the
|
||||||
// Home (no method takes one).
|
// Home (no method takes one).
|
||||||
|
// #205: the row menus' Reveal in Finder / Copy Path target — the piece's
|
||||||
|
// post.md resolved on disk; a vanished piece answers nil.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
@@ -68,6 +70,37 @@ func makeModelHome() throws -> (PostsModel, URL) {
|
|||||||
#expect(model.lastError == nil)
|
#expect(model.lastError == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `reveal and copy path resolve the post file on disk`() throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Find Me\n", project: "essays", home: home)
|
||||||
|
|
||||||
|
let url = model.fileURL(for: post)
|
||||||
|
|
||||||
|
let expected = home.appendingPathComponent("projects/essays/\(post.id)/post.md")
|
||||||
|
#expect(url == expected)
|
||||||
|
#expect(FileManager.default.fileExists(atPath: url?.path ?? ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `reveal and copy path answer nil for a vanished piece`() throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Ghost\n", home: home)
|
||||||
|
try PostStore.trash(post, home: home)
|
||||||
|
|
||||||
|
#expect(model.fileURL(for: post) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func `reveal and copy path resolve an archived piece off the archive root`() throws {
|
||||||
|
let (model, home) = try makeModelHome()
|
||||||
|
let post = try PostStore.writeNew(body: "# Shelved\n", project: "essays", home: home)
|
||||||
|
try PostStore.archive(post, home: home)
|
||||||
|
|
||||||
|
let url = model.fileURL(for: post)
|
||||||
|
|
||||||
|
let expected = home.appendingPathComponent("archive/essays/\(post.id)/post.md")
|
||||||
|
#expect(url == expected)
|
||||||
|
#expect(FileManager.default.fileExists(atPath: url?.path ?? ""))
|
||||||
|
}
|
||||||
|
|
||||||
@Test @MainActor func `new project draft lands in the named project`() throws {
|
@Test @MainActor func `new project draft lands in the named project`() throws {
|
||||||
let (model, home) = try makeModelHome()
|
let (model, home) = try makeModelHome()
|
||||||
try PostStore.createProject(named: "essays", home: home)
|
try PostStore.createProject(named: "essays", home: home)
|
||||||
|
|||||||
@@ -322,7 +322,7 @@ extension ProseFoldRekeyTests {
|
|||||||
debounce: .seconds(3600),
|
debounce: .seconds(3600),
|
||||||
)
|
)
|
||||||
let coordinator = ProseTextView.Coordinator(
|
let coordinator = ProseTextView.Coordinator(
|
||||||
representable: ProseTextView(session: session, dropBridge: ProseDropBridge()),
|
representable: ProseTextView(session: session, dropBridge: ProseDropBridge(), routeDrop: { _ in false }),
|
||||||
)
|
)
|
||||||
textView.delegate = coordinator // production wiring (PostEditorView)
|
textView.delegate = coordinator // production wiring (PostEditorView)
|
||||||
textView.setSelectedRange(NSRange(location: 0, length: 0))
|
textView.setSelectedRange(NSRange(location: 0, length: 0))
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of
|
|||||||
|
|
||||||
### Publish path (M6)
|
### Publish path (M6)
|
||||||
|
|
||||||
- **S6.1 — Draft then publish.** As the writer, I send a post to Micro.blog as a draft first, then publish. *AC:* `POST /micropub` with `h=entry`, markdown `content`, `name` for the title, `post-status=draft` → publish; Bearer app-token auth — token in Keychain, entered once; no OAuth in v1; frontmatter `category:` is permitted but inert in v1 (never sent) — v2 fetches existing categories and allows creating new.
|
- **S6.1 — Draft then publish.** As the writer, I send a post to Micro.blog as a draft first, then publish. *AC:* `POST /micropub` with `h=entry`, markdown `content`, `name` for the title, `post-status=draft` → publish; Bearer app-token auth — token in Keychain, entered once; no OAuth in v1; frontmatter `category:` travels since #207 — the publish sheet's Categories field offers the blog's existing categories (fetched), and a name Micro.blog doesn't know is created when the post is sent.
|
||||||
- **S6.2 — Illustrations travel with it.** As the writer, illustrations upload and attach with alt text. *AC:* `q=config` → media-endpoint → multipart PNG upload → `202` + `Location` URL → attached as `photo` with `mp-photo-alt`; publish never sends a photo without alt text — the only floor, style judgment stays with the author.
|
- **S6.2 — Illustrations travel with it.** As the writer, illustrations upload and attach with alt text. *AC:* `q=config` → media-endpoint → multipart PNG upload → `202` + `Location` URL → attached as `photo` with `mp-photo-alt`; publish never sends a photo without alt text — the only floor, style judgment stays with the author.
|
||||||
|
|
||||||
### Research & library-light (M5)
|
### Research & library-light (M5)
|
||||||
|
|||||||
@@ -1,40 +1,158 @@
|
|||||||
# Museion
|
# Museion
|
||||||
|
|
||||||
The Agentic Writing Environment (AWE): where scholars, texts, and AI minds work under a single roof — named for the Mouseion of Alexandria, the one place in history where they already did.
|
**The Agentic Writing Environment** — a native macOS app where your text, your library, and a resident AI mentor work under one roof. Named for the Mouseion of Alexandria, the one place in history where they already did.
|
||||||
|
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
|
|
||||||
An Obsidian-and-Copilot-class tool for long-form AI-assisted writing, with Ulysses/Scrivener depth and Paper elegance. Native macOS, built in SwiftUI.
|
Museion is built for long-form writers who want to get *better*, not ghostwritten. The mentor critiques, demonstrates, and remembers your recurring weaknesses — and nothing ships without your hand on it. Everything you write is plain markdown in a folder you own.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
### Writing
|
||||||
|
|
||||||
|
- **Native prose editor** (TextKit 2) with styled markdown source — headings scale, syntax dims, the plain file stays the truth. Autosaves about a second after you stop typing; `⌘S` saves now. The dot in the toolbar tells the truth: changed, saved, or failed.
|
||||||
|
- **Reading mode** (`⌘R`) renders the piece for reading. Click anywhere to drop back into editing at that spot.
|
||||||
|
- **Focus mode** (`⌥⌘F`) recesses the library, the mentor, and the toolbar; they return on edge hover.
|
||||||
|
- **Cold Turkey** — a writing lock inside focus mode. Set a goal (net new words, or minutes) and Museion goes into a fullscreen kiosk until you meet it. Quitting asks once. Nothing persists.
|
||||||
|
- **Drop an image** into prose: it is copied into the piece's `assets/` and a markdown reference lands at the drop point with the alt text selected.
|
||||||
|
- **Lists** — `Tab` / `⇧Tab` indents and outdents, `⌥↑` / `⌥↓` moves the item with its subtree. Nested lists fold behind a gutter chevron.
|
||||||
|
- **External files** — `⌘O` opens any `.md` file in place as a guest (never converted, never moved). `⇧⌘O` imports `.md` files as posts (copies; the originals stay put).
|
||||||
|
- An edit from outside (Finder, iCloud, another editor) raises a **Reload / Keep Local** alert — never a silent overwrite. Cursor and scroll position come back on reopen.
|
||||||
|
|
||||||
|
### Outlines
|
||||||
|
|
||||||
|
Outline pieces are plain nested bullets with LogSeq-style keys: `⌘↑` / `⌘↓` fold, `Enter` splits at the caret, double-click a bullet to zoom into its branch with breadcrumbs back out. Drag blocks to reorder or nest. **Convert to Post…** turns an outline into prose — verbatim bullets, or a headings ladder. One-way in v1.
|
||||||
|
|
||||||
|
### Library
|
||||||
|
|
||||||
|
- Pieces live under **projects** and fold into an **archive**. The library column groups by project and Pass State, with collapse toggles and counts.
|
||||||
|
- **Search** across titles and bodies (frontmatter excluded), title matches first.
|
||||||
|
- Rename (retitles and moves the folder), move to project, archive, restore, trash — all from the row's menu. A folder move flushes pending edits first; a failed write aborts the move with nothing relocated.
|
||||||
|
- The library mirrors the folder live: a recursive file watcher picks up Finder edits, new pieces, and deletes.
|
||||||
|
|
||||||
|
### The Mentor
|
||||||
|
|
||||||
|
- The mentor is a resident **[Hermes](https://hermes-agent.nousresearch.com/docs)** engine you install yourself, spawned as a child process over ACP under three isolated profiles — `museion` for Chat and Sessions, `museion-pass1` and `museion-pass2` for the passes. Model, provider, and reasoning effort are set per surface in Settings and written through Hermes' own config rail. z.ai, Anthropic, OpenAI, and Nous Portal are wired up; **Test Connection** says in plain words what is wrong.
|
||||||
|
- **Passes** — Pass 1 critiques structure, argument, and flow (paragraph level and up); Pass 2 works at sentence level and below. Each pass streams live and ends in a verdict plus **Fix Cards**.
|
||||||
|
- **Fix Cards** are a first-class surface, never toasts. A mechanical card offers **Apply** behind a sheet showing the exact edit (anchored quote → replacement) — one card at a time, there is no apply-all. A demonstration card shows one annotated example on your own text and closes Done or Skip. A stale anchor (the text moved) flags the card instead of editing.
|
||||||
|
- **Deslop lint** runs natively in Swift at every pass invocation — banned-vocabulary tiers and em-dash density land as cards before the engine even sees the piece. Override the tables with `<Home>/deslop-lint.json`.
|
||||||
|
- **Learnings** — promote a card into a per-writer, per-content-type memory of your recurring weaknesses. Plain markdown files in the Home; every later pass consults them. Dismiss a Learning and it fades, resurfacing after 10 completed passes (doubling on each re-dismiss).
|
||||||
|
- **Sessions** — freeform conversations: new, resume, fork, compact, Stop. **New Post** turns a reply into a piece (stamped `origin: ai`, never stats-eligible). A Brainstorm is a session with an opener.
|
||||||
|
- **Blind Read** — an advisory A/B judgment of the current text against the pass-start snapshot, by a fresh session that never saw the history. Records nothing; you stay the judge.
|
||||||
|
- **Research notes** — mid-pass findings arrive as candidate cards with provenance. Keep lands a note in the piece's `research/`; Reject vanishes.
|
||||||
|
- **Drill offers** — two-minute craft drills riding the finding that motivates them. Declined drills vanish; drill output never touches the draft.
|
||||||
|
- The methodology ships as markdown skills seeded into the profiles (the Serif stack, deslop, pass and session personas, demonstrator doctrine, craft canon, the VOICE payload). Your own skills are never overwritten.
|
||||||
|
|
||||||
|
### Measuring progress
|
||||||
|
|
||||||
|
Running a pass on an unaided first draft captures four style metrics — burstiness, type-token ratio, sentence variation, trigram repetition — before the mentor sees the text. The **Trends** pane charts them across captures with an honest *improving / steady / slipping* verdict per metric.
|
||||||
|
|
||||||
|
### Publishing
|
||||||
|
|
||||||
|
**[Micro.blog](https://micro.blog) via Micropub:** Publish ▸ **Send as Draft** ▸ review on Micro.blog ▸ **Publish**. The app token lives in your login keychain. Illustrations upload first and ride inline where you placed them; a picture without alt text never ships. The piece on disk never changes. The library row shows where each piece stands — `draft on Micro.blog` or `published <date>` — and its menu opens the live post. Sending again updates the same post in place (never a second post) and reuses images that haven't changed.
|
||||||
|
|
||||||
|
### Rails
|
||||||
|
|
||||||
|
- Hardened runtime on; sandbox off (the app spawns your `hermes` binary).
|
||||||
|
- Daily backup of the three Hermes profiles, last seven kept — Help ▸ Open Backup Folder.
|
||||||
|
- Quit, navigation, and Home changes all pass one departure gate: an unanswered conflict or a failed save blocks the move. Edits are never dropped.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- macOS 26.5+ — developed against the latest Xcode (26.x) and Swift (6.3.x); no backward compatibility
|
- **macOS 27 or later** (Apple Silicon).
|
||||||
- [SwiftFormat](https://github.com/nicklockwood/SwiftFormat) and [SwiftLint](https://github.com/realm/SwiftLint) for linting (`brew install swiftformat swiftlint`)
|
- **Hermes engine** — needed for Passes and Sessions. The editor, library, outlines, and publishing work without it. Install with `curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash` ([installation guide](https://hermes-agent.nousresearch.com/docs)).
|
||||||
|
- A provider API key for the model the mentor should run on (Settings ▸ Provider Keys).
|
||||||
|
- A [Micro.blog](https://micro.blog) account — only if you publish.
|
||||||
|
|
||||||
## Getting started
|
### Fonts
|
||||||
|
|
||||||
```bash
|
Museion's typography is set in Matthew Butterick's typefaces. They are commercial, so the app does not ship them — install them yourself (open each `.otf` in Font Book):
|
||||||
git clone https://git.babylondreams.de/AlexKucera/museion.git
|
|
||||||
cd museion
|
|
||||||
|
|
||||||
open Museion.xcodeproj # develop in Xcode
|
- **[Valkyrie OT](https://practicaltypography.com/valkyrie.html)**, the B cut — body text, document titles, the mentor's prose.
|
||||||
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build # build
|
- **[Concourse OT](https://practicaltypography.com/concourse.html)** — headings and your side of the conversation.
|
||||||
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test # test (unit + UI)
|
- **[Ubuntu Mono Nerd Font](https://www.nerdfonts.com/font-downloads)** — code and syntax dimming (free).
|
||||||
swiftformat . && swiftlint . # lint
|
|
||||||
```
|
|
||||||
|
|
||||||
Full Xcode project at the repo root — `open Museion.xcodeproj` and run.
|
Without them Museion still works: the editor falls back to the system font (SF Pro), Reading mode to Georgia. The spacing is calibrated on the real faces, so install them for the intended look.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download `Museion-<version>.dmg` from [Releases](https://git.babylondreams.de/AlexKucera/museion/releases), open it, drag Museion to **Applications**.
|
||||||
|
|
||||||
|
The app is signed with a Developer ID and notarized with Apple, so it opens like any other app.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
1. **First launch** picks your **Museion Home** — the folder everything lives in. Fresh installs get `iCloud Drive/Museion` when iCloud Drive is on, otherwise `~/Documents/Museion`. Settings ▸ Content shows the path; repoint any time (Museion never moves files).
|
||||||
|
2. **Install Hermes** (one-liner above). Museion finds it on the next launch, creates the three profiles, and seeds the writing skills — nothing else to set up. The rail pill and the Mentor header show engine state; the status card carries **Re-check**.
|
||||||
|
3. **Add a provider key** under Settings ▸ Provider Keys and hit **Test Connection**.
|
||||||
|
4. **Write.** `⌘N` for a new post, `⇧⌘N` for an outline. The first line is the title.
|
||||||
|
5. **Run a Pass** from the Mentor pane. Read the verdict, work the Fix Cards one at a time, promote the patterns worth remembering into Learnings.
|
||||||
|
6. **Publish** when the piece is yours.
|
||||||
|
|
||||||
|
## Support Museion
|
||||||
|
|
||||||
|
Museion is free and open source. It is one of a suite of apps I build and publish, and together they are my only income.
|
||||||
|
|
||||||
|
Every feature above took hours to build. Those hours have to come from somewhere. If Museion has become part of how you write, a coffee at **[buymeacoffee.com/babylondreams](https://buymeacoffee.com/babylondreams)** keeps them coming, for this app and the rest of the suite.
|
||||||
|
|
||||||
|
Thank you for writing with it.
|
||||||
|
|
||||||
|
## Keyboard shortcuts
|
||||||
|
|
||||||
|
| Action | Keys |
|
||||||
|
| --- | --- |
|
||||||
|
| New Post · New Outline · New Project… | `⌘N` · `⇧⌘N` · `⌥⌘N` |
|
||||||
|
| Open a file as a guest · Import files | `⌘O` · `⇧⌘O` |
|
||||||
|
| Save | `⌘S` |
|
||||||
|
| Toggle Reading Mode | `⌘R` |
|
||||||
|
| Toggle Focus Mode | `⌥⌘F` |
|
||||||
|
| Start Cold Turkey… | View menu (inside focus mode) |
|
||||||
|
| Check Spelling While Typing | Edit menu (off by default) |
|
||||||
|
| Prose list: indent · outdent · move item | `Tab` · `⇧Tab` · `⌥↑` `⌥↓` |
|
||||||
|
| Outline: fold · move subtree · select blocks · split | `⌘↑` `⌘↓` · `⌥↑` `⌥↓` · `⇧↑` `⇧↓` · `Enter` |
|
||||||
|
| Composer: send · newline | `Return` · `⇧Return` |
|
||||||
|
|
||||||
## Your Museion Home
|
## Your Museion Home
|
||||||
|
|
||||||
Everything you write lives in one folder — the **Museion Home** — as plain markdown you can reach from anywhere.
|
Everything you write lives in one folder — the **Museion Home** — as plain markdown you can reach from anywhere.
|
||||||
|
|
||||||
|
```
|
||||||
|
<Home>/
|
||||||
|
projects/<project>/<piece-id>/post.md one piece, one folder
|
||||||
|
assets/ illustrations (drop an image)
|
||||||
|
research/ kept research notes
|
||||||
|
cards/ the piece's fix cards
|
||||||
|
passes/ pass-start snapshots
|
||||||
|
archive/<project>/<piece-id>/post.md finished work, Finder-visible
|
||||||
|
learnings/<content-type>/… promoted patterns, one markdown file each
|
||||||
|
deslop-lint.json optional lint-table override
|
||||||
|
```
|
||||||
|
|
||||||
- **Default for new Homes: `iCloud Drive/Museion`** — `~/Library/Mobile Documents/com~apple~CloudDocs/Museion`, resolved dynamically. When iCloud Drive is unavailable at first run, Museion silently falls back to `~/Documents/Museion` — no dialog; the Settings Home field shows the resolved path. An existing `~/Documents/Museion` Home is never silently moved — it stays your Home until you migrate it yourself (#169).
|
- **Default for new Homes: `iCloud Drive/Museion`** — `~/Library/Mobile Documents/com~apple~CloudDocs/Museion`, resolved dynamically. When iCloud Drive is unavailable at first run, Museion silently falls back to `~/Documents/Museion` — no dialog; the Settings Home field shows the resolved path. An existing `~/Documents/Museion` Home is never silently moved — it stays your Home until you migrate it yourself (#169).
|
||||||
- **Migrating an existing Home:** Museion is repoint-only — it never moves content. Move the `Museion` folder in Finder (e.g. `~/Documents/Museion` → `iCloud Drive/Museion`), then repoint via **Settings ▸ Content ▸ Museion Home ▸ Choose…** (Museion/SettingsPaneView.swift:199).
|
- **Migrating an existing Home:** Museion is repoint-only — it never moves content. Move the `Museion` folder in Finder (e.g. `~/Documents/Museion` → `iCloud Drive/Museion`), then repoint via **Settings ▸ Content ▸ Museion Home ▸ Choose…**.
|
||||||
- **Avoid eviction stalls:** right-click the `Museion` folder in Finder and choose **Keep Downloaded**. Pinning keeps files local, so opening a piece never waits on a download (#168).
|
- **Avoid eviction stalls:** right-click the `Museion` folder in Finder and choose **Keep Downloaded**. Pinning keeps files local, so opening a piece never waits on a download (#168).
|
||||||
- **iCloud quirks are substrate, not bugs:** editing the same file on two devices yields numbered duplicate siblings — iCloud keeps both, it never merges. An evicted file keeps its real name and size, but its first read blocks while the data downloads (#168).
|
- **iCloud quirks are substrate, not bugs:** editing the same file on two devices yields numbered duplicate siblings — iCloud keeps both, it never merges. An evicted file keeps its real name and size, but its first read blocks while the data downloads (#168).
|
||||||
- **Companions:** Textastic-class editors open and edit pieces in place on iPhone/iPad via the Files app / document picker; iCloud.com and iCloud for Windows reach the Home too (#168, #169).
|
- **Companions:** Textastic-class editors open and edit pieces in place on iPhone/iPad via the Files app / document picker; iCloud.com and iCloud for Windows reach the Home too (#168, #169).
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
SwiftUI, Swift 6 (language mode 6, default MainActor isolation), macOS 27+, latest Xcode only — no backward compatibility, no pinned toolchains.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.babylondreams.de/AlexKucera/museion.git
|
||||||
|
cd museion
|
||||||
|
|
||||||
|
open Museion.xcodeproj # develop in Xcode
|
||||||
|
./scripts/build-and-run.sh # build + launch (⌘R equivalent)
|
||||||
|
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' build
|
||||||
|
./scripts/full-test.sh start && ./scripts/full-test.sh status # full unit suite (verify rail)
|
||||||
|
swiftformat . && swiftlint . # lint (brew install swiftformat swiftlint)
|
||||||
|
./scripts/deploy.sh # Release build → /Applications
|
||||||
|
./scripts/release.sh # Developer ID-signed, notarized DMG → dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
`AGENTS.md` is the binding work contract for agents and humans alike; `GLOSSARY.md` pins the vocabulary; decisions live in `docs/adr/`; one session log per task in `docs/devlog/`.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
GPL-3.0-or-later — see [LICENSE](LICENSE).
|
GPL-3.0-or-later — see [LICENSE](LICENSE). The bundled reading renderer (apex) and its libyaml are MIT; see [Museion/Resources/THIRD-PARTY-NOTICES.md](Museion/Resources/THIRD-PARTY-NOTICES.md).
|
||||||
@@ -14,6 +14,7 @@ Owned by the root AGENTS.md contract.
|
|||||||
- ADR format follows the domain-modeling skill's `ADR-FORMAT.md`: short title + 1–3 sentences; optional Considered Options / Consequences only when they earn their place.
|
- ADR format follows the domain-modeling skill's `ADR-FORMAT.md`: short title + 1–3 sentences; optional Considered Options / Consequences only when they earn their place.
|
||||||
- `docs/agents/` holds the engineering-skills config (issue tracker, triage labels, domain-docs consumer rules) written by `setup-matt-pocock-skills` — edit directly, no child doc needed.
|
- `docs/agents/` holds the engineering-skills config (issue tracker, triage labels, domain-docs consumer rules) written by `setup-matt-pocock-skills` — edit directly, no child doc needed.
|
||||||
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7, #11, #123, and #58 verification artifacts); card shape follows GLOSSARY.md (lane and emitter fields included), anchors follow ADR-0006.
|
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7, #11, #123, and #58 verification artifacts); card shape follows GLOSSARY.md (lane and emitter fields included), anchors follow ADR-0006.
|
||||||
|
- `docs/releases/<version>.md` holds the release notes, one file per released version, written for humans: highlights, the milestones it closes, install, known limits. It distills that version's `CHANGELOG.md` section (which stays the entry-by-entry record with issue numbers); the Gitea release body is pasted from it.
|
||||||
|
|
||||||
## Work Guidance
|
## Work Guidance
|
||||||
|
|
||||||
@@ -31,3 +32,4 @@ Owned by the root AGENTS.md contract.
|
|||||||
| `agents/` | Agent-skills config — issue-tracker, triage-label, domain conventions (written by `/setup-matt-pocock-skills`) |
|
| `agents/` | Agent-skills config — issue-tracker, triage-label, domain conventions (written by `/setup-matt-pocock-skills`) |
|
||||||
| `brainstorming-output/` | Transient brainstorming session records — working artifacts, not durable decisions; durable outcomes flow into PRD/ADRs |
|
| `brainstorming-output/` | Transient brainstorming session records — working artifacts, not durable decisions; durable outcomes flow into PRD/ADRs |
|
||||||
| `research/` | Verified research artifacts (provider/API factsheets) feeding ADRs — source-cited and probe-dated, not decisions |
|
| `research/` | Verified research artifacts (provider/API factsheets) feeding ADRs — source-cited and probe-dated, not decisions |
|
||||||
|
| `releases/` | Release notes per version — human-readable distillation of the CHANGELOG section; the Gitea release body |
|
||||||
@@ -9,7 +9,7 @@ Reading mode renders markdown through apex (MIT, unified dialect) as an HTML fra
|
|||||||
|
|
||||||
## Consequences
|
## Consequences
|
||||||
|
|
||||||
- **Bundling:** the prebuilt apex binary ships in app resources, signed + notarized. No source build in CI, no user install gate — a renderer must not grow a gate.
|
- **Bundling:** the prebuilt apex binary (arm64 slice) and a vendored libyaml ship in app resources, Developer ID–signed at commit time (apex with the hardened runtime), apex's rpaths replaced by the single `@executable_path/../Resources`, which resolves in the bundle and in the checkout alike; Xcode copies and seals both as resources untouched. The vendored copy lives in `Resources/libyaml.bundle/` ON PURPOSE: Xcode's synced-folder classifier sniffs Mach-O content and silently adds any bare dylib (extension or not) to the app's link phase; a `.bundle` folder is an opaque resource. apex's release build links libyaml through CI/Homebrew rpaths, so alone it only ever ran on developer machines — reading mode silently fell back to source for everyone else (surfaced by the 0.1.0 notarization, which also rejects an unsigned Mach-O in Resources). Re-sign both when the Developer ID certificate rotates (`codesign -f -s "<identity>" --options runtime --timestamp Resources/apex`; `codesign -f -s "<identity>" --timestamp Resources/libyaml.bundle/libyaml-0.2.dylib`). No source build in CI, no user install gate — a renderer must not grow a gate. Licenses: `Resources/THIRD-PARTY-NOTICES.md`.
|
||||||
- **One WKWebView, reloaded in place.** Remounting per document (`.id(sel)`) was the dominant switch cost — hundreds of ms of web-process respawn; `loadHTMLString` on a retained view feels instant.
|
- **One WKWebView, reloaded in place.** Remounting per document (`.id(sel)`) was the dominant switch cost — hundreds of ms of web-process respawn; `loadHTMLString` on a retained view feels instant.
|
||||||
- **`--no-mixed-lists` is required**, not tuning: apex's default merges an ordered list following a bullet list into one `<ul>`, killing `1. 1. 1.` auto-renumbering.
|
- **`--no-mixed-lists` is required**, not tuning: apex's default merges an ordered list following a bullet list into one `<ul>`, killing `1. 1. 1.` auto-renumbering.
|
||||||
- **Early handoff:** stdout EOF is conversion done; apex's ~65 ms teardown is reaped async via `terminationHandler` (the error path still waits for exit status).
|
- **Early handoff:** stdout EOF is conversion done; apex's ~65 ms teardown is reaped async via `terminationHandler` (the error path still waits for exit status).
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# Release 0.1.0 — version bump, README rewrite, release notes, DMG packaging
|
||||||
|
|
||||||
|
> **Date:** 2026-12-01
|
||||||
|
> **Type:** milestone
|
||||||
|
> **Reference:** tag `v0.1.0` at `d470615` (local; push + Gitea release pending Alexander's go)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Cut the first release: bump to 0.1.0 with a git tag, a DMG shareable on Gitea, a human-readable
|
||||||
|
release-notes document (CHANGELOG.md is too dense for a release page), and a README with a real
|
||||||
|
feature list and usage instructions now that the codebase is stable.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- `Museion.xcodeproj/project.pbxproj`: `MARKETING_VERSION` 1.0 → 0.1.0 on all three targets (six
|
||||||
|
configs). `CURRENT_PROJECT_VERSION` stays 1. Verified in a real Release archive: Info.plist reads
|
||||||
|
`0.1.0` / `1`, `LSMinimumSystemVersion` 27.0, binary arm64 only.
|
||||||
|
- `CHANGELOG.md`: `## [0.1.0] - 2026-12-01` heading over the former Unreleased entries, empty
|
||||||
|
`[Unreleased]` above, pointer to the release notes.
|
||||||
|
- `README.md`: rewritten. Intro → features (Writing, Outlines, Library, The Mentor, Measuring
|
||||||
|
progress, Publishing, Rails) → requirements → install → quick start → shortcut table → the
|
||||||
|
Museion Home (kept, plus a folder-layout block) → development commands → license. Every feature
|
||||||
|
line grounded in `MuseionApp.swift` (menus/shortcuts), `Museion/AGENTS.md`, and CHANGELOG entries;
|
||||||
|
nothing from the PRD's ambitions.
|
||||||
|
- `docs/releases/0.1.0.md`: the distilled notes — what's in it, the milestones closed (M0–M6 plus
|
||||||
|
the post-v1 extensions), install, known limits, numbers. This is the Gitea release body.
|
||||||
|
- `scripts/release.sh`: archive → `-exportArchive` with `method: developer-id` → UDZO DMG
|
||||||
|
(`diskutil image create from`) → `notarytool --wait` → `stapler staple` → `spctl` assessment.
|
||||||
|
Preflight refuses before any build when no `Developer ID Application` identity is in the
|
||||||
|
keychain. `NOTARIZE=0` skips notarize+staple. Output `dist/Museion-<MARKETING_VERSION>.dmg`
|
||||||
|
(version read from build settings, not from the pbxproj text). `.gitignore` gains `dist/`.
|
||||||
|
- DOX: root `AGENTS.md` commands block + scripts index row + Stack line (macOS 27+, see gotchas);
|
||||||
|
`docs/AGENTS.md` Local Contract for `docs/releases/<version>.md` + Child DOX Index row.
|
||||||
|
- Three commits (`docs(readme)`, `build(release)`, `chore(release)`) and annotated tag `v0.1.0` on
|
||||||
|
the last.
|
||||||
|
- **Signing prerequisites (Alexander, this Mac):** Developer ID Application identity created through
|
||||||
|
developer.apple.com + a Keychain Access CSR (Xcode's Manage Certificates refuses even for the
|
||||||
|
Account Holder); `notarytool store-credentials museion-notary` registered by Alexander.
|
||||||
|
- **`scripts/release.sh` hardened by the real runs:** capture `codesign -dvv` before grepping
|
||||||
|
(pipefail + `grep -q` SIGPIPEs codesign → false "not Developer ID signed"); read notarytool's
|
||||||
|
status FIELD (`--wait` exits 0 on Invalid; JSON goes to stdout only — no output-path option);
|
||||||
|
sign the DMG before submitting (Gatekeeper's `spctl -t open` on the image needs it); retry the
|
||||||
|
staple 6× (ticket can lag "Accepted"); two shipped-layout proofs before notarizing — apex must
|
||||||
|
run from the export and the app must not link libyaml.
|
||||||
|
- **Reading renderer made self-contained (`Museion/Resources/`):** `apex` → 1.1.58 (the
|
||||||
|
bundle had 1.1.17; the official universal release tarball, `.sha256` verified), arm64 slice,
|
||||||
|
rpaths replaced by the single `@executable_path/../Resources/libyaml.bundle`, Developer ID–signed
|
||||||
|
with `--options runtime`; `libyaml.bundle/libyaml-0.2.dylib` (0.2.5 from Homebrew's Cellar, install
|
||||||
|
name `@rpath/libyaml-0.2.dylib`) beside it, same identity; `THIRD-PARTY-NOTICES.md` (both MIT
|
||||||
|
texts fetched from the source repos). `--no-mixed-lists` still exists in 1.1.58 (ADR-0011's
|
||||||
|
requirement). ADR-0011's Bundling consequence rewritten; `Museion/AGENTS.md`
|
||||||
|
reading-mode line; README license pointer; CHANGELOG `**reading:**` entry.
|
||||||
|
- Final DMG: `dist/Museion-0.1.0.dmg` 3.0 MB — notarization **Accepted**, staple valid, `spctl`:
|
||||||
|
DMG and the app inside both `accepted, source=Notarized Developer ID`; apex runs from the mounted
|
||||||
|
DMG with the bundled libyaml.
|
||||||
|
- Verification: `scripts/full-test.sh` at the tagged commit — 717 executed / 717 passed / 0 failed;
|
||||||
|
`shellcheck scripts/release.sh` clean; `bash -n` clean; preflight refusal exercised; archive step
|
||||||
|
ran (38 s); DMG step proven on the dev-signed archive app (3.3 MB UDZO, mounts, signature
|
||||||
|
verifies inside).
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| No wayfinder map — direct session | The skill's own test: no fog, one session. The only real decision (signing) was a question for Alexander, not a ticket. |
|
||||||
|
| `v0.1.0` tag with the `v` | The convention Gitea release pages expect; annotated so it carries a message. |
|
||||||
|
| Tag AFTER the docs commits | The tagged tree must contain the README and release notes it describes. |
|
||||||
|
| DMG, no zip | Same effort with `diskutil image create`; DMG is what Mac users expect. |
|
||||||
|
| `docs/releases/<version>.md` over a root `RELEASE_NOTES.md` | Scales per release, lives under the docs contract, reviewable in the commit; the Gitea release body is pasted from it. |
|
||||||
|
| `archive` + `-exportArchive` (method `developer-id`) over a plain Release build with `CODE_SIGN_IDENTITY` overrides | The Xcode-sanctioned distribution path — identical to Organizer's export, so a GUI fallback matches. Preflight guarantees no portal-side surprise from `-allowProvisioningUpdates`. |
|
||||||
|
| arm64 only | `MACOSX_DEPLOYMENT_TARGET = 27.0`; macOS 27 does not run on Intel, so a universal binary is dead weight. |
|
||||||
|
| Developer ID + notarization | Alexander has a Developer ID (not yet on this Mac). Without notarization Gatekeeper still blocks on Sequoia+ regardless of the signing cert, so Developer ID alone buys nothing for the downloader. |
|
||||||
|
| `diskutil image create from` over `hdiutil create` | hdiutil create is deprecated on macOS 27 (warning on every run); the replacement produced an identical UDZO image. |
|
||||||
|
| Stale README "macOS 26.5+" → 27+ | pbxproj `MACOSX_DEPLOYMENT_TARGET = 27.0` on all six configs and `Museion/AGENTS.md` already said 27.0; the root Stack line was corrected to match. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| `codesign -dv` prints no `Authority=` lines — the script's Developer-ID check would have false-failed on the real run | Authority chain needs `-dvv` | `codesign -dvv` in both the check and the diagnostic echo |
|
||||||
|
| `hdiutil create` warns "deprecated. Please use 'diskutil image create…'" on macOS 27 | Apple moved image creation under diskutil | `diskutil image create from --format UDZO --volumeName … <stage> <dmg>`; kept `hdiutil detach` for the busy-volume guard (not deprecated) |
|
||||||
|
| `security find-identity -v -p codesigning` showed only `Apple Development` despite Alexander having a Developer ID | A Developer ID private key exists only on the Mac that generated the CSR; the portal copy is useless without it | Preflight names the Xcode path (Settings ▸ Accounts ▸ Manage Certificates ▸ + ▸ Developer ID Application) or a `.p12` import from the other Mac |
|
||||||
|
| `git log --oneline` hid the merge commit `3bb1782` and read as if HEAD were `cac66f6` | This machine's log config suppresses merges in short logs | Trust `git status --branch` and `git show -s` for ancestry; the snapshot's "ahead 2" was the merge + one chore commit |
|
||||||
|
| AGENTS.md session-log window was one log stale (11-23 missing) | The 11-23 write-log did not refresh the window | Window rebuilt from INDEX's 10 newest rows |
|
||||||
|
| Xcode ▸ Manage Certificates ▸ + ▸ Developer ID Application: "This operation can only be performed by the Account Holder" — for the Account Holder | Xcode caches the team role as Admin on Xcode 27.2 / macOS 27.2 (documented by others on the same combo) | Website route: Keychain Access ▸ Certificate Assistant CSR → developer.apple.com ▸ Certificates ▸ + → download `.cer` → `security import` (not `open`, which strands an "Add Certificates" dialog). Script header + refusal message point there now |
|
||||||
|
| First notarization: `notarytool --wait` passed, `stapler` failed "Record not found" | Submission was **Invalid**, not slow: `--wait` exits 0 on Invalid, so `set -e` walked on | Script reads the status field from `--output-format json` (stdout only) and prints Apple's log on anything but Accepted |
|
||||||
|
| Apple's log: `Contents/Resources/apex` "does not have the hardened runtime enabled" | Xcode never signs Mach-Os in Resources — the bundled apex was ad-hoc linker-signed | Sign apex at commit time with Developer ID + `--options runtime`; Xcode copies and seals it as a resource |
|
||||||
|
| Deeper: the bundled apex could never run on a clean Mac | apex's release build links `@rpath/libyaml-0.2.dylib` with rpaths for its CI runner, `/usr/local/lib`, `/opt/homebrew/lib`; macOS ships no libyaml → reading mode silently fell back to source for every non-Homebrew user since #76 | Vendor `libyaml.bundle/libyaml-0.2.dylib` beside apex, same team signature (library validation), one rpath that resolves in bundle AND checkout; proved by removing the dylib ("Library not loaded") and restoring it |
|
||||||
|
| `Museion/Resources/libyaml-0.2.dylib` → `ld: library 'yaml-0' not found`; and `otool -L Museion` showed `@rpath/libyaml-0.2.dylib` with nothing in Frameworks | Xcode's synced-folder classifier treats a dylib in the folder as the APP's link target — would have shipped an app that can't launch | Extension-less still linked (Xcode sniffs Mach-O content); a `.bundle` folder is an opaque resource → `libyaml.bundle/`. `release.sh` now refuses if the app links libyaml and runs apex from the export |
|
||||||
|
| `spctl -a -t open … Museion-0.1.0.dmg` → "rejected, source=no usable signature" after a successful notarize+staple | The DMG itself was unsigned; the image-level assessment needs a signature for the ticket to ride | `codesign --timestamp --sign "$SIGNER" "$DMG"` before submitting |
|
||||||
|
| `lipo … -out` → usage dump | The flag is `-output` | `lipo in -thin arm64 -output out` |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion.xcodeproj/project.pbxproj` | `MARKETING_VERSION = 0.1.0` ×6 |
|
||||||
|
| `CHANGELOG.md` | `[0.1.0] - 2026-12-01` heading + notes pointer |
|
||||||
|
| `README.md` | Full rewrite: features, requirements, install, quick start, shortcuts, Home layout, development |
|
||||||
|
| `docs/releases/0.1.0.md` | New — distilled release notes (Gitea release body) |
|
||||||
|
| `scripts/release.sh` | New — Developer ID export → notarized DMG |
|
||||||
|
| `.gitignore` | `dist/` |
|
||||||
|
| `AGENTS.md` | Stack line → macOS 27+; commands block `release.sh`; scripts index row; session-log window |
|
||||||
|
| `docs/AGENTS.md` | `docs/releases/<version>.md` contract + index row |
|
||||||
|
| `Museion/Resources/apex` | 1.1.58 (was 1.1.17): arm64 slice, single rpath → `libyaml.bundle`, Developer ID + hardened runtime (committed signed) |
|
||||||
|
| `Museion/Resources/libyaml.bundle/libyaml-0.2.dylib` | New — vendored libyaml 0.2.5, install name `@rpath/libyaml-0.2.dylib`, Developer ID–signed |
|
||||||
|
| `Museion/Resources/THIRD-PARTY-NOTICES.md` | New — apex + libyaml MIT notices (ships in the bundle) |
|
||||||
|
| `docs/adr/0011-apex-html-reading-pipeline.md` | Bundling consequence rewritten (vendoring, signing, `.bundle` rationale, re-sign on cert rotation) |
|
||||||
|
| `Museion/AGENTS.md` | Reading-mode line: bundled apex facts + `.bundle` rule |
|
||||||
|
| `README.md` | License section points at the third-party notices |
|
||||||
|
| `CHANGELOG.md` | `**reading:**` entry under 0.1.0 Fixed |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Authorization to commit the reading-renderer fix (`fix(reading): …`), the `release.sh`
|
||||||
|
hardening (`fix(release): …`), and this log — then move the still-local tag:
|
||||||
|
`git tag -f v0.1.0 <release commit>` so the tagged tree is the one the DMG was built from.
|
||||||
|
- [ ] Only on explicit go: `git push origin main v0.1.0`, then the Gitea release with
|
||||||
|
`dist/Museion-0.1.0.dmg` attached and `docs/releases/0.1.0.md` as the body.
|
||||||
|
- [ ] When the Developer ID certificate rotates: re-sign both bundled binaries (ADR-0011 has the
|
||||||
|
one-liners), otherwise notarization fails on the stale team signature.
|
||||||
|
- [ ] apex upgrades: same recipe (download the universal release tarball, verify `.sha256`, lipo,
|
||||||
|
rpaths, sign) — ADR-0011. Ask upstream for a statically linked build so the dylib dance
|
||||||
|
disappears.
|
||||||
|
- [ ] Pre-existing, not touched: Release build emits `Text +` deprecation warnings in
|
||||||
|
`TrendsPaneView.swift:389–391`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Image drop pastes the file path on macOS 27.2 — the editor's text views now own drops that land on them (#141 follow-up)
|
||||||
|
|
||||||
|
> **Date:** 2026-12-03
|
||||||
|
> **Type:** generic
|
||||||
|
> **Reference:** follow-up to #141 (unticketed fix; dogfood on macOS 27.2.1)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Alexander dropped a Finder screenshot onto a saved post and got the file PATH pasted as plain text — no `assets/` copy, no `` ref. #141 shipped exactly this feature (field-verified 2026-11-02 on macOS 27.0.1). Find out why it broke and restore it with ONE path that targets the current OS (his ruling: "adjust for the latest OS. no two paths"). Closed with a finish-audit (three fresh-context reviewers; findings and dispositions below).
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **Diagnosis from evidence, not theory.** The unified log of the release build showed the drag pasteboard read as `public.file-url` only; the user's post on disk held three `` refs and no `assets/` (so `ingestImage` had never run). `softwareupdate --history` dated the OS jump: 27.0.1 → 27.2.1 on 2026-11-16, two weeks after #141's verification. Then ONE instrumented Debug build (temporary `Logger(subsystem: "com.babylondreams.Museion", category: "dropprobe")` lines in the SwiftUI closure + `NSDraggingDestination`/`readSelection`/`paste` overrides on the text view, read through `log stream`/`log show --level notice`) and one human drag settled it:
|
||||||
|
- `textview draggingEntered → copy` … `performDragOperation BEGIN` → `readSelection type=NSFilenamesPboardType → true` → `performDragOperation → true`
|
||||||
|
- NO `swiftui destination fired`, NO `ingestDrop entry`.
|
||||||
|
- lldb on the live app (`expr -l Swift -- let $ws = NSApp.windows …`) showed the `ProseListTextView` registered for ~19 drag types (NSFilenames, Apple URL, TIFF, PNG, RTF, RTFD, file-promise …) — NSTextView registers itself once live; a bare `NSTextView(frame:)` probe reads `[]`, even inside a window.
|
||||||
|
- `FileDropTextView.swift` (NEW) — the editor text views' drag base: `onFileDrop: (([URL]) -> Bool)?`; `DropKind` (`urls` / `text` / `none`) classified from the pasteboard (`readObjects(forClasses: [NSURL.self])`, else the string type), memoized per `changeCount`; the `NSDraggingDestination` overrides route URL-bearing drags (never `super` — the stock path paste lives there), hand text-only drags to the stock drop, bounce the rest. `ProseListTextView` and the outliner's `RowTextView` ride it (rows mount no route → bounce).
|
||||||
|
- `MuseionApp.swift` — `AppGateState.routeFileDrop(_:)`: the ONE file-drop router (Cold Turkey guard → pure-markdown set → `posts.openExternal` → else `proseDrop.textView?.ingestDrop`). `proseDrop` is documented as the window destination's handle.
|
||||||
|
- `ProseListTextView.swift` — `lastIngestNotice` test seam (the refusal text the pins read); `ingestDrop`'s publishable gate requires `isFileURL` (a browser image drag refuses with the type strip instead of reaching the sink).
|
||||||
|
- `PostStore.swift` — `IngestError.missing(_:)`: a file the disk can't stat refuses as missing ("couldn't be read"), never as a folder; the sink's guards are three flat checks (missing / link / folder).
|
||||||
|
- `PostEditorView.swift` — `ProseTextView` gains a non-optional `routeDrop: @escaping ([URL]) -> Bool` beside `dropBridge`; `makeNSView`/`updateNSView` set `tv.onFileDrop = routeDrop`. Both `PostEditorView` call sites pass `{ gate.routeFileDrop($0) }`; `ProseRekeyTests`' direct construction passes `{ _ in false }`.
|
||||||
|
- `WorkspaceView.swift` — the window `.dropDestination` is four lines: `let landed = gate.routeFileDrop(urls); if landed { selection = .posts }; return landed`. The hop now fires on every landed drop, not only markdown — unreachable for images today (the editor mounts only on Posts).
|
||||||
|
- `MuseionTests/ImageIngestTests.swift` — `DragInfoStub`, the suite's `NSDraggingInfo` mock (pasteboard-only; the stock text drop inserts only into a hosted view). +9 pins: a Finder-shaped drag routes through the view and never pastes the path (and an unrouted view claims nothing); a text-only drag keeps the stock drop and never reaches the router (raw PNG data bounces); the probe follows the pasteboard contents; the outline rows bounce a file drag; a web URL refuses with the type notice; a vanished file refuses as missing; and the router's own pins (pure-markdown → guest, Cold Turkey refusal, ingest hand-off + mixed refusal).
|
||||||
|
- DOX: `Museion/AGENTS.md` (WorkspaceView, editor-core, OutlineRowTextView + the new FileDropTextView bullet, PostStore), `MuseionTests/AGENTS.md` (suite map), root `AGENTS.md` (learning: 27.2 drag routing is an OS-version claim), `CHANGELOG.md` `[Unreleased]` Fixed entry.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Target 27.2.1 only — no dual-surface compat for 27.0.1 | Alexander's ruling mid-session ("adjust for the latest OS. no two paths"); the repo already targets what the maintainer runs. The 27.0.1 "window destination starves everything" contract is deleted from the docs, not carried. |
|
||||||
|
| The view under the pointer owns the drop; ONE router behind both surfaces | AppKit delivers a drag to exactly one destination. Over the editor that is the text view (deepest, self-registered); elsewhere it is the window SwiftUI destination. Both call `routeFileDrop`, so the md→guest / image→ingest decision exists once and can never drift between surfaces. |
|
||||||
|
| Override the `NSDraggingDestination` methods without `super` for URL-bearing drags | The paste is the stock implementation (`performDragOperation` → `readSelection(NSFilenamesPboardType)`); accepting the drag and then refraining from pasting is not an option — the paste happens inside super. |
|
||||||
|
| Text-only drags keep the stock drop (`case .text: super…`) | Finish-audit (security + general): a blanket `[]` for URL-less drags had killed in-editor selection moves and text drops from other apps — a regression the fix itself introduced. The path paste needs file URLs, which never reach super. |
|
||||||
|
| One `FileDropTextView` base for the prose editor AND the outline rows | Finish-audit (general): `RowTextView` had the identical 27.2 exposure and the CHANGELOG claimed outlines refuse. One implementation, two subclasses, zero duplication; rows mount no route → bounce. |
|
||||||
|
| Accept every URL-bearing drag in `draggingEntered` (`copy`), refuse in `performDragOperation` | `.none` at entry bounces silently; #141's contract is a LOUD refusal (the rust strip). Web URLs ride the same gate. URL-less, text-less drags (raw image data) bounce — nothing to route. |
|
||||||
|
| Memoize the probe per `pasteboard.changeCount` | Finish-audit (security, measured): `draggingUpdated` fires per mouse-move and `readObjects` is a pasteboard round-trip — 5k URLs → 38 ms, 20k → 137 ms per move. Two lines make hover O(1). |
|
||||||
|
| Pasteboard-shaped seams replaced by a real `NSDraggingInfo` mock | Finish-audit (general): the first pins called seams that did not exist before the fix, so no code path in them could ever have pasted the path — green with or without the fix. `DragInfoStub` drives the real overrides; the mock is ~17 lines (the one trap: `namesOfPromisedFilesDropped(atDestination:)` sits on an NSObject informal protocol and needs `override`; the class must be `@MainActor`). |
|
||||||
|
| `lastIngestNotice` as the refusal observable | The web-URL pin was green with the `isFileURL` clause deleted (the sink refuses too; only the strip TEXT differs). One `private(set) var` set in `showIngestNotice` makes the message assertable. |
|
||||||
|
| No explicit `registerForDraggedTypes` call | The live view is already registered by AppKit (lldb-verified) and receives the drag; registering again changes nothing on 27.2.1. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| Dropped image → file path pasted, no ingest | macOS 27.2 routes a drag to the deepest destination; a live NSTextView self-registers for drag types and matches Finder via `NSFilenamesPboardType`; the window-level SwiftUI `.dropDestination` never fired — the inverse of the 27.0.1 ruling #141 was built on | Text views own the drop (overrides, no super for URLs) → one router |
|
||||||
|
| A bare `NSTextView(frame:)` probe reported `registeredDraggedTypes == []` and suggested NSTextView could never receive the drag | Registration happens lazily once the view is live in a real window/hosting; the standalone probe is the wrong instrument | Read the LIVE view over lldb (`$`-prefixed bindings persist across `-o` commands) |
|
||||||
|
| `log stream` caught nothing while `log show --last 5m` did | The stream attaches asynchronously; the app launched into the gap | Use `log show` for anything within the last minutes; keep the stream for live watching |
|
||||||
|
| Interpolated values read back as `<private>` | os_log redacts non-public interpolations by default | `privacy: .public` on every value you need to read |
|
||||||
|
| First fixed build failed: `Consecutive statements on a line must be separated by ';'` | `a != nil, b != nil ? x : y` — a condition list inside a ternary does not parse | `guard … else { return [] }; return .copy` (swiftformat later folded the switches into expressions) |
|
||||||
|
| `xcodebuild test` failed to compile `ProseRekeyTests.swift:325` | A third `ProseTextView(…)` call site in the tests dir (my grep covered `Museion/` only) | Pass `routeDrop:` there; grep `dropBridge:` repo-wide next time |
|
||||||
|
| swiftformat turned `ingestDrop`'s `///` block into `//` | A blank line had slipped between the doc block and the function (docComments rule) | Re-attach the `///` block directly above the function |
|
||||||
|
| `open -n` launched the instrumented build once more after a failed compile | The launch command ran unconditionally after `build exit=65` | Gate every launch on the build exit code |
|
||||||
|
| Audit flip: the Cold Turkey pin stayed green with its guard flipped | I batched two guards on ONE path — the md-branch flip (`if false`) sent the lock pin's markdown input down the ingest branch before the missing lock guard mattered | Flip same-path guards one at a time: restored, flipped the lock guard alone → the pin reddened by name (1 failed / 19 passed) |
|
||||||
|
| Audit pin failed on the apostrophe | The message landed as `couldn't` (straight) while the test asserted `couldn’t` — the house voice is the curly one | Fix the message, not the pin |
|
||||||
|
| swiftlint `line_length` (180) on the mock's `enumerateDraggingItems` signature | swiftformat does not wrap that parameter list | Wrap the signature by hand |
|
||||||
|
|
||||||
|
## Finish audit (three reviewers, one fanout)
|
||||||
|
|
||||||
|
Accepted and fixed: the text-drag regression (security S6 + general G4/G5 converged); the web-URL pin's non-discrimination + the vanished-file "is a folder" message (S2 + G6); zero router pins (G3 + S4); the outline rows' identical exposure (G9); the per-mouse-move pasteboard read (S1, measured); stale `ProseDropBridge` doc and a test comment (G1, G2); the retold 27.2 story trimmed to pointers (ponytail P1); devlog/INDEX suite count (G10); "27.2" vs "27.2.1" precision (G11); the widened `selection = .posts` hop documented (G7 — unreachable for images today).
|
||||||
|
Deferred (visible, not dropped): magic-byte sniffing and a size cap in `ingestImage` (S3 — the pre-existing #34 extension-only posture; the drop is an explicit user action on a file the user chose; add if the posture is ever tightened); the non-atomic multi-image loop (pre-existing #141 `ponytail:` ceiling — a `[good, symlink]` drop orphans the good copy).
|
||||||
|
Recorded as checked, no change: lock gate order (S4), pasteboard spoofing — `..` segments never reach `assets/` through the slug (S5), `draggingExited` left to stock (G8).
|
||||||
|
Coherence: the general reviewer verified zero old-contract phrases outside the retained #141 history devlog, all three `ProseTextView(` call sites, the 723→729 count, `readObjects(forClasses: [NSURL.self])` behavior on Finder/browser/text pasteboards (empirical probe), override signatures against the SDK, and no retain cycle (`proseDrop.textView` weak; `onFileDrop` captures the app-lifetime gate). No overlap between the two surfaces was flagged as duplication after the base-class hoist — each drag still reaches exactly one.
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/FileDropTextView.swift` | NEW — the drag base: `onFileDrop`, `DropKind`, `droppedURLs(from:)`, `classify`, per-`changeCount` memo, the four overrides |
|
||||||
|
| `Museion/MuseionApp.swift` | `AppGateState.routeFileDrop` (the one router); `proseDrop` doc rewritten |
|
||||||
|
| `Museion/ProseListTextView.swift` | rides `FileDropTextView`; `lastIngestNotice` seam; `isFileURL` in the ingest gate |
|
||||||
|
| `Museion/OutlineRowTextView.swift` | `RowTextView` rides `FileDropTextView` (no route → bounce) |
|
||||||
|
| `Museion/PostStore.swift` | `IngestError.missing`; flat sink guards |
|
||||||
|
| `Museion/PostEditorView.swift` | `ProseTextView.routeDrop` param + `tv.onFileDrop` wiring in make/update; both call sites; bridge doc |
|
||||||
|
| `Museion/WorkspaceView.swift` | Window destination reduced to the router + `selection = .posts` |
|
||||||
|
| `MuseionTests/ImageIngestTests.swift` | `DragInfoStub` + 9 pins (drag overrides, probe, rows, refusals, router) |
|
||||||
|
| `MuseionTests/ProseRekeyTests.swift` | `routeDrop:` at the direct `ProseTextView` construction |
|
||||||
|
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md`, `CHANGELOG.md`, `docs/devlog/INDEX.md` | DOX pass + learning + `[Unreleased]` Fixed entry |
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Full rail **729/729** (720 + 9 pins), xcresult-authoritative counts; swiftformat 0/153; swiftlint 0 violations. Re-run at finish-up on the exact committed bytes (run `20261203T153446Z`, pid 5687): 729/729 again.
|
||||||
|
- Flip cycle: 8 guards flipped in one batched edit (all independent paths) → exactly those 8 pins failed by name, 13 pre-existing green; the Cold Turkey pin flipped alone → 1 failed / 19 green. Restores byte-compared against `cp` backups (the tree is uncommitted — `git checkout` would have eaten the session).
|
||||||
|
- One real Finder drag on 27.2.1 (Debug build): `assets/…png` landed, `` at the drop point.
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Ticket + commit left to Alexander (forge writes are his call); the CHANGELOG entry is marked "unticketed fix" until then.
|
||||||
|
- [ ] The three pasted-path lines from the probe drag (15:49) may still sit in `ep-1-why-i-built…`/post.md — the real drag on the fixed build landed cleanly at line 43; the earlier paste is the author's to delete.
|
||||||
|
- [ ] Deferred audit items: magic-byte sniff + size cap in `ingestImage` (pre-existing #34 posture); pre-flight all sources before the first copy (non-atomic multi-drop, pre-existing #141 ceiling).
|
||||||
|
- [ ] Browser image drags (https URL) refuse loudly but don't ingest — downloading into assets/ would be new scope.
|
||||||
|
- [ ] Raw image-data drags (Photos/Preview) bounce silently — nothing to route.
|
||||||
|
- [ ] Re-dogfood the drop after the next macOS point release: drag routing is an OS-version claim.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# Fix Cards: Jump to the anchor (#204)
|
||||||
|
|
||||||
|
> **Date:** 2026-12-03
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/204 — "Fix Cards should allow jumping to the relevant paragraph."
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Give the Fix Cards palette a **Jump** action: clicking it on a card lands the writer on the span the card points at — the anchor quote (1-based occurrence) selected in the prose editor, scrolled into view, the main window made key so typing can start at once. The ticket body was empty; four grilling answers settled the shape (borderless Jump in the action row; select the full span + scroll; activate the main window; stale anchors offer none, closed cards keep it).
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- `FixCardStore.anchorRange(of:in:)` — the nth-occurrence math `appliedText` already used, answered as the `NSRange` a jump selects (nil for stale / empty quote / occurrence below 1; the lane never gates it — a demonstration card's anchor is still a real place). `appliedText` now routes through it (one math, −3 lines).
|
||||||
|
- `PostsModel.revealCard(_:)` + `FixCardRevealRequest {range, token}` + the stored `revealRequest` — resolves the span against the LIVE `session.text` (a dirty buffer still lands) and stamps a request whose token advances per jump so repeats re-fire. Writes nothing.
|
||||||
|
- The editor column feeds the request into the existing #71 caret rail: `PostEditorView.caretHint` widened from `(location, token)` to `FixCardRevealRequest?` (a zero-length range = bare caret, non-zero = select the span); one shared `flipToken` counter; a jump leaves reading mode first (`reading = false`, not `exitReading`, which stamps its own zero-length hint). The Coordinator's `applyCaretHint` selects, scrolls (runloop hop, the #71 layout race), and makes the main window key on jumps only.
|
||||||
|
- `ProseTextView.landingSpan(for:in:)` — the landing math as a pure static: a bare caret hops past leading blanks, a span never does; both clamp to the text.
|
||||||
|
- `FixCardsPalette`: a borderless **Jump** button in every non-stale card's action row (open and closed alike).
|
||||||
|
- Pins in `FixCardApplyTests` (`// MARK: Jump to the anchor (#204)`): `anchorRange` occurrence math incl. a UTF-16 emoji fixture; `revealCard` stamps against the live text, re-fires, stale stamps nothing, no write; `landingSpan` hop gate + clamps.
|
||||||
|
- DOX: `Museion/AGENTS.md` (store, model, palette bullets), `MuseionTests/AGENTS.md`, `GLOSSARY.md` gains **Jump** beside Apply; file headers updated.
|
||||||
|
|
||||||
|
**Verification (finish-up step 1, run bare):** `./scripts/full-test.sh` exit 0 — **732 executed / 732 passed / 0 failed** (the rail's log shows `SwiftCompile` lines for every edited file); `swiftformat . --lint` exit 0 (0/153); `swiftlint .` exit 0 (0 violations / 142 files). Every new pin flip-verified with the guard off and the tree restored byte-exact: emoji UTF-16 (Character-count rewrite → location 6 ≠ 7), dirty-buffer location (snapshot text → 14 ≠ 26), token advance (constant token → 0 ≠ 1), landingSpan hop (always-hop → `{3,3}` ≠ `{0,3}`). Two review rounds: an implement-close general review (REQUEST_CHANGES → 2 should-fix + nits fixed) and a three-reviewer finish-audit (ponytail / security / general, all APPROVE after fixes).
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Ride the #71 caret rail (`caretHint`) instead of a second reveal path | One landing mechanism, one layout-race fix, one `appliedCaretToken`. The token counter stays SHARED — two independent counters could collide and a jump would silently never apply |
|
||||||
|
| `FixCardRevealRequest` doubles as the hint type | SwiftLint `large_tuple` rejects a 3-member tuple; the request already IS `(range, token)`, the exact shape the hint needs |
|
||||||
|
| Resolve the span against the live `session.text`, not disk | The card's quote is validated on disk but the writer may have typed since; a disk range would drift under a dirty buffer (pinned: buffer location 26 vs snapshot 14) |
|
||||||
|
| Jump visibility follows the DISK `anchorStatus` | A card valid on disk whose quote the dirty buffer removed still shows Jump and `revealCard` stamps nothing — a documented silent degrade. Folding a live check into `stale` would also hide Apply: a behavior change outside #204, left for a ruling |
|
||||||
|
| Closed non-stale cards keep Jump; a closed AND promoted card has none | The span is still a real place after the card closes. The action row's pre-existing `open \|\| promotedAt == nil` gate hides the whole row for a fully resolved card — kept for the smallest diff; docs say so plainly |
|
||||||
|
| Window keying in the Coordinator (`tv.window?.makeKeyAndOrderFront`), not `NSApp.activate` | `NSApp.activate(ignoringOtherApps:)` is a no-op once the app is active — the palette's click already activated it — and deprecated since macOS 14. The Coordinator owns `tv.window`; gated on a positive span so the #71 flip-back path is untouched |
|
||||||
|
| `reading = false` directly in the handler | `exitReading(caret:)` bumps the token and stamps its own zero-length hint — it would overwrite the jump |
|
||||||
|
| Hoist the landing math into `landingSpan` | The Coordinator method needs an NSTextView; the repo pins pure statics (`caretPastLeadingBlanks` precedent). +3 lines bought a pin that caught the hop bug |
|
||||||
|
| No view-layer pins | Repo convention: pure seams pinned, SwiftUI views dogfooded. The three view-layer deltas are named under Open Items |
|
||||||
|
| No `Closes #204` in the commit | House precedent is the maintainer closes after dogfood; the commit references the ticket only |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| First review: a Jump while the editor was in READING mode did nothing | `reading == true` mounts `ReadingSurface` (no `ProseTextView`); the next `exitReading` would overwrite the hint | `reading = false` in the `.onChange` handler — the remounted Coordinator applies the jump after the generation load; main-queue FIFO puts the jump's scroll after the restore scroll |
|
||||||
|
| First review: "type immediately" failed — main window stayed behind the palette | `NSApp.activate` cannot re-key within an already-active app; `makeFirstResponder` on a non-key window routes no keystrokes | `makeKeyAndOrderFront` on `tv.window` inside the Coordinator's existing async hop, jumps only |
|
||||||
|
| `updateNSView` hit SwiftLint's 50-line `function_body_length` | swiftformat expanded the one-line `if span > 0 { … }` into four brace-lines | Extracted the caret-hint block into `Coordinator.applyCaretHint(_:tv:session:)` |
|
||||||
|
| Audit: a quote that IS the document's leading blanks selected the title | The #ui-r1 leading-blank hop ran for non-zero spans too (the load restore gates its hop on zero length) | `landingSpan` hops only a bare caret; pinned with `"\n\n\nTitle line."` |
|
||||||
|
| Audit: jump → ⌘S → reopen restored an off-screen selection | `cursorUpdate` ran before the async `scrollRangeToVisible`, recording the pre-jump `scrollOffset` | The record moved into the async hop, after the scroll |
|
||||||
|
| Test literal compared UTF-16 length with `.count` | `NSRange.length` is UTF-16 units, `String.count` is graphemes — equal for ASCII only | `("…" as NSString).length` + an emoji fixture (location 7 UTF-16 vs 6 Characters) |
|
||||||
|
| My first UTF-16 probe was useless (7 / 7) | Python `len(str)` counts code points — neither UTF-16 units nor graphemes | Compute Swift test literals with a `swift` probe, not Python |
|
||||||
|
| First flip-run read green-ish (18 s, the target test absent from the output) | Bare `xcodebuild` after a seconds-old edit can serve a stale binary (#197) | `touch` the file, count `SwiftCompile` lines in the run log, then trust the result — the re-run failed exactly the target expect |
|
||||||
|
| Two patch anchors missed (once on tab count, once on an indentation-only blank line) | swiftformat/indentation drift between read and patch | Assert-anchored replaces fired BEFORE any write both times; located regions by stripped markers |
|
||||||
|
| Audit nit: `appliedText` and `anchorRange` were near-copies | The span math existed twice and must change together | `appliedText` = lane gate + `anchorRange` + `replacingCharacters` |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/FixCardStore.swift` | `anchorRange(of:in:)`; `appliedText` routes through it |
|
||||||
|
| `Museion/PostsModel.swift` | stored `revealRequest: FixCardRevealRequest?` |
|
||||||
|
| `Museion/PostsModelCards.swift` | `FixCardRevealRequest`, `revealCard(_:)`; header names #204 |
|
||||||
|
| `Museion/PostEditorView.swift` | `caretHint` → `FixCardRevealRequest?`; the #204 `.onChange` observer; `ProseTextView.landingSpan`; `Coordinator.applyCaretHint` (select, scroll, key on jumps, record after scroll); docs |
|
||||||
|
| `Museion/FixCardsWindow.swift` | borderless **Jump** on non-stale cards; CardRow doc + header |
|
||||||
|
| `MuseionTests/FixCardApplyTests.swift` | three #204 pins |
|
||||||
|
| `Museion/AGENTS.md` | store / model / palette bullets carry #204 |
|
||||||
|
| `MuseionTests/AGENTS.md` | `FixCardApplyTests` row names the #204 pins |
|
||||||
|
| `GLOSSARY.md` | **Jump** entry beside Apply |
|
||||||
|
| `CHANGELOG.md` | `[Unreleased]` → Added |
|
||||||
|
| `docs/devlog/INDEX.md`, `AGENTS.md` | this log's row + the rolling window |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Dogfood on the real app: Jump from reading mode; Jump on a card whose quote sits at the very top of a piece; Jump → ⌘S → reopen lands on the span.
|
||||||
|
- [ ] Close #204 (maintainer).
|
||||||
|
- [ ] Ruling wanted: should a disk-valid / buffer-stale card hide Jump? A live check folded into `stale` would also hide Apply — decide both together.
|
||||||
|
- [ ] Optional: restructure the action-row gate so a closed + promoted card keeps Jump.
|
||||||
|
- [ ] Unpinned view-layer deltas (no render harness): the `reading = false` handler, `makeKeyAndOrderFront` on jump, `cursorUpdate` after the scroll.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# #205 — Reveal in Finder + Copy Path on piece rows
|
||||||
|
|
||||||
|
> **Date:** 2026-12-03
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/205 — "Add Reveal in Finder and Copy Path to sidebar"
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Give every piece row a Finder hand-off: **Reveal in Finder** opens the piece's `post.md` selected, **Copy Path** puts its absolute path on the clipboard. The ticket was a title only — no body, no comments. The owner resolved the fog in one clarifying round: both the library column's row menu AND the Archive pane's row menu; the `post.md` FILE path (not the folder); Archive entries appended after its existing Move Back / Rename / Convert.
|
||||||
|
|
||||||
|
Scenario (the slice's north star): given a piece whose folder exists under the watched Home, right-click → Reveal / Copy Path → Finder opens with `post.md` selected / the absolute `post.md` path lands on the pasteboard — and a vanished piece (folder gone) does nothing, silently.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- `Museion/PostsModelIdentity.swift` — `PostsModel.fileURL(for:) -> URL?`: the piece's `post.md` resolved through the ONE id→folder resolver `PostStore.folder(of:home:)` against the model-owned `watchedHome`. Pure read; nil when the folder is gone. Header names the second resident.
|
||||||
|
- `Museion/WorkspaceChrome.swift` — `FinderHandOffButtons: View` (Reveal → `NSWorkspace.shared.activateFileViewerSelecting`, Copy Path → `NSPasteboard.general` `clearContents` + `setString(url.path)`), each behind `if let url = model.fileURL(for:)`. `import AppKit` added; header updated.
|
||||||
|
- `Museion/PostsLibraryColumn.swift` + `Museion/ArchivePaneView.swift` — two lines each inside the existing `.contextMenu`: `Divider()` + `FinderHandOffButtons(model:post:)`. Library: between Move to Archive and the destructive Trash. Archive: appended after Convert.
|
||||||
|
- `MuseionTests/PostsModelTests.swift` — three pins: projects/ resolve → exact URL + file exists; archive/ resolve → exact URL + file exists; vanished-after-trash → nil. Header lines added.
|
||||||
|
- `Museion/AGENTS.md` — five bullets: WorkspaceChrome (the new struct), PostsLibraryColumn (the fragment's placement), PostsModel extensions list (names `PostsModelIdentity.swift`), LibraryPostRow (menu count + callers-attach attribution), PostsModelWrites (reverted to its original text after the read moved out).
|
||||||
|
- Reviews: implement close (standards + spec, two rounds) and finish-audit (general + security + ponytail). Findings below.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| The seam is a model read, not a view helper | The SwiftUI menu body is untested by repo convention; `fileURL(for:)` is the observable the pins can reach. Resolves against `watchedHome` (the model owns the Home — no public method takes one, #179). |
|
||||||
|
| `fileURL` lives in `PostsModelIdentity.swift`, not `PostsModelWrites.swift` | First landed in the writes file; the standards review flagged a read parked under `// MARK: Projects` in the write-rail file. The identity file's charter is "(Home, ID) questions route through here" — a path IS that identity resolved. Not the write rail: nothing written, no strip. |
|
||||||
|
| One `FinderHandOffButtons` struct shared by both menus | First version pasted the two Buttons + AppKit closures into both menus verbatim (Duplicated Code). Extracted to the shared-chrome file. A `finderButtons(model:post:)` View-extension wrapper was tried and DELETED — a Middle Man: same-length call, module-wide extension for two callers. |
|
||||||
|
| `post.md` path, POSIX `url.path` | Owner decision. Finder's own Copy Path yields the POSIX path; `url.absoluteString` would be a one-line swap if a `file://` form is ever wanted. |
|
||||||
|
| nil when the piece is gone → both entries no-op | The scenario's third line. Never reveal a stale path; the next rescan drops the row. |
|
||||||
|
| Three pins, not one | Each guards a distinct discriminator: projects/ resolve, archive/ resolve (D1 makes Archive half the feature — the general reviewer caught the gap), vanished → nil. The flip cycle proved the vanished and archive pins redden independently of the resolve pin. |
|
||||||
|
| `clearContents()` before `setString` | Drops every declaration from the previous pasteboard owner — no stale file-URL or RTF flavor survives beside the new string (security review confirmed). |
|
||||||
|
| Declined: rename `fileURL` → `postMDURL`/`documentURL` | Sibling of the resolver `folder(of:)`; the doc comment states the target. Reviewer judgement call, declined. |
|
||||||
|
| Declined: folder-present-but-`post.md`-deleted edge | `folder(of:)` answers the directory; the file check is Finder's. Outside the scenario's "folder gone"; self-heals on rescan. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| `-only-testing` on the new pins printed `** TEST SUCCEEDED **` but the bundle said `executed: 0` | Backticked free-function names match zero Swift Testing tests under a name filter — the vacuous-green trap (#31/#134). Suite-name filters don't run free functions either (MuseionTests/AGENTS.md). | Stopped hand-rolling; the sanctioned rail `./scripts/full-test.sh start` + `status` is the only scoped-or-full verdict, counts from `xcresulttool` only. |
|
||||||
|
| Two mis-patches in a row on `WorkspaceChrome.swift`'s tail (a collapsed newline in `PaneHeader.body`, then the new struct nested four levels deep inside `PaneHeader`) | The patch tool kept the leading tabs of my `old_string`; the end-of-file anchor had no trailing context to pin the column | After the second failure, rewrote the tail via a scripted read/replace/write instead of a third patch; verified 4 top-level structs, 0 extensions, balanced braces. Rule: two failed patches in one region → rewrite the enclosing region, don't patch a third time. |
|
||||||
|
| Formatter flagged `ArchivePaneView.swift` closing brace (indent) — twice, same line | My inserted `.contextMenu` entries were right; the closing brace one tab off | `swiftformat` on the file; it touched only that brace (+14/−0 → pure additions). |
|
||||||
|
| Standards review: 4 LOW findings on the first shape | Duplicated menu pair; read in the write-rail file; tautological `#expect(lastError == nil)`; test header missing #205 | All fixed; second-round review confirmed all four hold. |
|
||||||
|
| Finish-audit fanout: 2 of 3 reviewer children died on HTTP 429 | Provider rate limit — three children plus the parent stream over the budget; both died before any tool call (transcripts held only the brief echo) | Solo, staggered re-dispatch after ~3 min cool-down; both completed. Nothing reported on a dead child. |
|
||||||
|
| Post-fix lint flagged two files for trailing newline | The kernel's `write_file` after `read_file()["text"]` dropped the EOF newline in my own fix batch | `swiftformat` on the two files. Exactly why the audit skill says re-lint after fixes. The verify rail was re-run on the final bytes afterwards. |
|
||||||
|
| RED proof: stashing the impl produced a compile error, not a test failure | The method didn't exist pre-fix — the pins can't build without the seam | That IS the honest red. The discriminating flip came later: bypassing the resolver (build `projects/<project>/<id>/post.md` without consulting disk) reddened exactly the vanished + archive pins (`733/735`), resolve pin green. |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/PostsModelIdentity.swift` | `fileURL(for:)` — the row menus' post.md resolver; header names #205 |
|
||||||
|
| `Museion/WorkspaceChrome.swift` | `FinderHandOffButtons` struct + `import AppKit`; header updated |
|
||||||
|
| `Museion/PostsLibraryColumn.swift` | `Divider()` + the fragment between Move to Archive and Trash |
|
||||||
|
| `Museion/ArchivePaneView.swift` | `Divider()` + the fragment appended after Convert |
|
||||||
|
| `MuseionTests/PostsModelTests.swift` | three pins (projects/ resolve, archive/ resolve, vanished → nil) + header |
|
||||||
|
| `Museion/AGENTS.md` | five bullets (Chrome, LibraryColumn, PostsModel extensions, LibraryPostRow, Writes reverted) |
|
||||||
|
| `docs/devlog/20261203-issue205-reveal-in-finder-copy-path_log.md` | this log |
|
||||||
|
| `docs/devlog/INDEX.md`, `AGENTS.md` | log registration (row + 10-row window) |
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Final tree (run `20261203T171228Z`, postdates the last edit): `./scripts/full-test.sh` **735 executed / 735 passed / 0 failed** (734 baseline + 1 new pin… the three pins replaced the original two, net +1); `swiftformat --lint` exit 0, 0/5 files; `swiftlint lint` exit 0, 0 findings; `xcodebuild build` green. Flip: resolver bypass → `733/735`, exactly the vanished + archive pins red with their designed assertions.
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] `DESIGN.md:188` row-menu enumeration ("Rename / Convert / Move / Trash") has been stale since #108 — pre-existing, outside the DOX chain, not this diff. Lands with the next DESIGN.md sweep.
|
||||||
|
- [ ] Unpinned by convention: the SwiftUI menu bodies (labels, placement, `activateFileViewerSelecting`, pasteboard contents). Two review rounds were their only gate. Hand-test: right-click a piece in the library or Archive pane.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Release 0.1.1 — the apex refresh becomes step one
|
||||||
|
|
||||||
|
> **Date:** 2026-12-03
|
||||||
|
> **Type:** milestone
|
||||||
|
> **Reference:** tag `v0.1.1` → `4a056f9`; [docs/releases/0.1.1.md](../releases/0.1.1.md)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Cut 0.1.1, a bug-fix release carrying the one fix that sat under `[Unreleased]` since 0.1.0 (the external-watch normalizer, PR #203), and land the release skill that ran it.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **Pre-flight.** Local `main` == forge at `2d5073e` (the #203 merge; Alexander pulled it mid-session). Developer ID identity present, `tea` default login present. `[Unreleased]` held exactly one entry — the fix that defines this release.
|
||||||
|
- **apex 1.1.58 → 1.1.59 (step 1).** GitHub `releases/latest` = v1.1.59 (published 2026-12-01, the day after the 0.1.0 cut). Universal tarball `.sha256` verified (`e75cd828…`), `lipo -thin arm64`, the three CI/Homebrew rpaths deleted, `@executable_path/../Resources/libyaml.bundle` added, Developer ID–signed `--options runtime --timestamp`. Proven in a scratch `Resources/libyaml.bundle/` layout before the copy: `--version` = 1.1.59, `--no-mixed-lists` renders `- a` + `1. one` as `<ul>` then `<ol>`. 1.1.59 still links libyaml dynamically — the vendored dylib and the ADR-0011 recipe stay as they were. `THIRD-PARTY-NOTICES.md` bumped.
|
||||||
|
- **Bump.** `MARKETING_VERSION` 0.1.0 → 0.1.1 on all six target×configuration pairs; `CURRENT_PROJECT_VERSION` stays 1. Read back from `-showBuildSettings`: one unique value, `0.1.1`.
|
||||||
|
- **Changelog.** `## [0.1.1] - 2026-12-03` over the external-watch entry, fresh empty `[Unreleased]` above, pointer to the notes, a `### Changed` → `- **reading:**` line for the apex refresh.
|
||||||
|
- **Release notes.** `docs/releases/0.1.1.md` — bug-fix-sized: the false #67 conflict in plain language, the apex refresh, known limits pointing at 0.1.0's, install (replaces 0.1.1 in place), numbers (720 at the tag).
|
||||||
|
- **README.** Unchanged — `<version>` placeholder, "macOS 27 or later" matches the 6× `MACOSX_DEPLOYMENT_TARGET = 27.0`, license pointer already covers apex + libyaml.
|
||||||
|
- **Rail.** 720 executed / 720 passed / 0 failed. Freshness proven, not assumed: run dir `_build/full-test/20261203T064608Z-Museion/` at 07:46:32 > last tree edit 07:45:51; `CpResource …/Resources/apex` at 07:46:10; the built test host's apex reports 1.1.59; 59 `SwiftCompile` lines. `swiftformat` 0/152, `swiftlint` 0/0/141, `shellcheck scripts/release.sh` clean.
|
||||||
|
- **Slices + tag.** `bba4688 build(release)` (skill + its DOX row + notes) · `570abb3 fix(reading)` (apex binary + notices) · `4a056f9 chore(release)` (bump + changelog heading). Working tree byte-identical to HEAD's tree at tag time (`git diff HEAD` empty). `git tag -a v0.1.1` on `4a056f9`.
|
||||||
|
- **DMG.** `release.sh`: archive → Developer ID export → UDZO DMG → signed → notarized → stapled. Four proofs: from the mounted image `Contents/Resources/apex --version` = 1.1.59 and `CFBundleShortVersionString` = 0.1.1, shipped apex carries exactly the one rpath, the app does not link libyaml, `stapler validate` OK, `spctl` → `accepted, source=Notarized Developer ID`. **sha256 `e7add45a9a577b36fa39864f1acfdfa9db72448311ffa459031a33344dd9d76b`**, 3,164,194 bytes.
|
||||||
|
- **Skill updated (mid-session, on Alexander's steer).** Step 1 went from "compare `--version`, upgrade if stale" to an **unconditional refresh with the full recipe inline** — the exact commands that until now lived only in the 0.1.0 devlog. Homebrew is a labeled fallback. Quick Reference line and three Pitfalls added; skill `version: 0.1.1`.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| GitHub `releases/latest` is the apex source of record; Homebrew is fallback only | Live-checked during the cut: the Homebrew formula and the installed binary were both **1.1.58** while GitHub had 1.1.59. A `brew upgrade apex` printing "already up-to-date" would have shipped the stale renderer with a clean conscience |
|
||||||
|
| Step 1 is unconditional, not a comparison | The old wording read as optional and was skipped by habit — Alexander's steer. A bundled binary is stale by definition between releases |
|
||||||
|
| Scratch-layout proof BEFORE the copy into `Resources/` | A binary that fails `--no-mixed-lists` in `$TMPDIR` has touched nothing; the same failure in-tree costs a rail run |
|
||||||
|
| The apex bump is its own `fix(reading)` slice | Same shape as 0.1.0's `fd806e9`; the binary and its notices travel together, separate from the version bump |
|
||||||
|
| CHANGELOG `### Changed` entry for apex even though it's a patch bump | Common Changelog: anything a user can observe (renderer version) is recorded. 0.1.0 did the same for 1.1.17→1.1.58 |
|
||||||
|
| Homebrew variant's rpath loop tolerates absent paths (`2>/dev/null \|\| true`) | The Homebrew build carries `$(brew --prefix)/lib` instead of the CI paths; `install_name_tool -delete_rpath` fails on a path the binary lacks. The Done-check (exactly ONE rpath left) is the real gate |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| `git log --oneline` showed `3197b92` as tip while `rev-parse HEAD` said `2d5073e` — looked like a corrupted state | `rtk` (terminal-output wrapper on PATH) mangles `git log` porcelain output; it dropped the merge commit and flattened the first-parent line | Trusted plumbing (`cat-file -p`, `rev-parse`, `describe`) and the forge (`ls-remote`), all of which agreed: `2d5073e` is a real merge, parents `3197b92` + `07da076`, tree `93dcb24`. Prefer plumbing when a wrapper is in the path |
|
||||||
|
| My first `origin/main` check printed `3197b92`, then minutes later everything said `2d5073e` | Alexander pulled the PR mid-session (reflog: `pull: Fast-forward`); my earlier read was correct at the time | Confirmed via `git ls-remote origin refs/heads/main` = forge truth before any write |
|
||||||
|
| The release skill itself was uncommitted (untracked `SKILL.md` + unstaged `AGENTS.md` row) at the start of a release that requires a clean tree | The skill was authored in the 0.1.0 session but never committed | Folded into `build(release)` — it is release tooling; Alexander approved |
|
||||||
|
| `find -newer rel.json` missed the extracted tarball files | Both were written in the same second | `tar tzf` for the layout, `find -name apex` for the binary |
|
||||||
|
| `full-test.sh status` prints no run directory | The script keeps it in `${FT_BASE_DIR:-$ROOT/_build/full-test}/<utc-id>-<scheme>/` | Read `BASE` from the script; the run dir's mtime + the log's `CpResource` line are the freshness proof |
|
||||||
|
| `tea releases create` printed nothing on success | Normal — silent exit 0 | The `tea api` read-back is the proof; it showed release id 28, `draft: false`, one asset at the local byte size |
|
||||||
|
| First read-back script died on `KeyError: 'tag'` | Gitea's release JSON spells it `tag_name` (GitHub-shaped assumptions) | Read `tag_name`; recorded in the skill's Quick Reference |
|
||||||
|
| `python3 -c 'import yaml'` → `ModuleNotFoundError` reading the tea token | PyYAML isn't on the system python | `grep -E '^\s*token:'` + `sed` — no new dependency for a one-line read |
|
||||||
|
| `security add-generic-password … -w <value>` → "passwords don't match", nothing stored (read-back 0 chars) | Without a tty, `security` prompts for a retype | `</dev/null` on the add; always read the length back before relying on it |
|
||||||
|
| Micro.blog `q=config` shows three microblogs, none `microblog-default` | A post without `mp-destination` would be ambiguous | Sent `mp-destination: https://AlexKucera.micro.blog/` explicitly; `Location` host confirms it took |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `.agents/skills/release/SKILL.md` | New (committed this release): step 1 = unconditional apex refresh with the full recipe inline (GitHub canonical, Homebrew fallback); step 11 = Micro.blog announcement as a draft (Keychain token service, `mp-destination` mandatory, read-back); Quick Reference lines; eight Pitfalls; `version: 0.2.0` |
|
||||||
|
| `AGENTS.md` | `.agents/skills/` Child DOX Index row (now mentions the Micro.blog draft); session-log window refreshed to the 10 newest INDEX rows (picks up the 11-30 log the #203 merge indexed but didn't window) |
|
||||||
|
| `docs/releases/0.1.1.md` | New — human-readable notes, the Gitea release body |
|
||||||
|
| `CHANGELOG.md` | `[0.1.1] - 2026-12-03` heading, fresh `[Unreleased]`, notes pointer, `### Changed` apex entry |
|
||||||
|
| `Museion.xcodeproj/project.pbxproj` | `MARKETING_VERSION = 0.1.1` ×6 |
|
||||||
|
| `Museion/Resources/apex` | 1.1.58 → 1.1.59, arm64 slice, one rpath, Developer ID + hardened runtime (1,019,232 → 1,019,312 bytes) |
|
||||||
|
| `Museion/Resources/THIRD-PARTY-NOTICES.md` | `## apex 1.1.59`, `v1.1.59` prose |
|
||||||
|
| `docs/devlog/20261203-release-011-apex-refresh-is-step-one_log.md` | This log |
|
||||||
|
| `docs/devlog/INDEX.md` | Row inserted at top |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [x] Go given 2026-12-03. `git push origin main v0.1.1` → forge `main` = `4a056f9`, annotated tag derefs to it.
|
||||||
|
- [x] Gitea release id 28 created (`draft: false`, one asset 3,164,194 bytes, body ends `[Generated by AI]`). Token-authenticated download hashes to `e7add45a…` — byte-identical to local — and `stapler validate` passes on the downloaded file.
|
||||||
|
- [x] Micro.blog announcement posted as a **draft** (on Alexander's request, mid-run): `POST /micropub` → `202`, `Location` `https://alexanderkucera.com/2026/12/03/museion.html`, preview `https://micro.blog/account/posts/239/preview/6088556`. Read back `q=source` → `post-status: draft`, 1118 chars, both links present. Awaiting Alexander's publish.
|
||||||
|
- [ ] Alexander: review + publish the Micro.blog draft from the preview link.
|
||||||
|
- [ ] **Rotate the Micro.blog App Token** — it was pasted into chat, so it lives in this transcript. After rotating, re-store: `security add-generic-password -U -a micro.blog -s com.babylondreams.Museion.release-announce -w '<new>' </dev/null`.
|
||||||
|
- [ ] Ask upstream (ApexMarkdown/apex) for a statically linked macOS build — would retire the rpath/codesign dylib dance and the `.bundle`; carried from the 0.1.0 log, still open
|
||||||
|
- [ ] `rtk` mangling `git log` is a recurring hazard on this machine — already has a skill (`rtk-terminal-output`); consider making the release skill's step 7 use `git log --format` via plumbing or `--no-color` if it bites again
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Release 0.1.2 — the macOS 27.2 image-drop fix ships
|
||||||
|
|
||||||
|
> **Date:** 2026-12-03
|
||||||
|
> **Type:** milestone
|
||||||
|
> **Reference:** Gitea release id 29 (tag v0.1.2); follow-up to #141 (unticketed fix, same-day)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Ship the macOS 27.2 image-drop fix (this morning's `fix(editor)` work, finish-audited) as **0.1.2** — the first cut under the release skill's new patch-for-a-bug-fix rule — through the full runbook: apex check, bump, changelog heading, notes, rail, sliced commits, annotated tag, notarized DMG, then on Alexander's go: push, forge release, Micro.blog draft, Buy Me a Coffee draft.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **apex check (step 1):** GitHub `releases/latest` is still **v1.1.59** — identical to the bundled binary (published 2026-12-01). The shipped layout re-proven without any upgrade: exactly one rpath (`@executable_path/../Resources/libyaml.bundle`), `flags=0x10000(runtime)` + Developer ID authority, `--version` 1.1.59, and the load-bearing `--no-mixed-lists` check emits `<ul>` then `<ol>`. No `THIRD-PARTY-NOTICES.md` bump, no `### Changed` line. (The skill's "appears in `--help`" phrasing reads 0 because the help spells the flag `--[no-]mixed-lists`; the functional check is the evidence.)
|
||||||
|
- **Bump (step 2, first run of the new rule):** `MARKETING_VERSION` 0.1.1 → 0.1.2 in all 6 pbxproj occurrences; build-settings read-back prints 0.1.2. Bug-fix cut → patch, per the rule committed this morning (`1b0c23a`).
|
||||||
|
- **Changelog heading (step 3):** the former `[Unreleased]` Fixed entry moved under `## [0.1.2] - 2026-12-03` with the pointer line to the notes; a fresh empty `[Unreleased]` sits above.
|
||||||
|
- **Notes (step 4):** `docs/releases/0.1.2.md` in the 0.1.1 shape — the fix told for a reader who never saw the ticket, the two deliberate refusals, install copy, suite numbers. **README (step 5):** no change — it carries no version-specific copy; "macOS 27 or later" matches `MACOSX_DEPLOYMENT_TARGET = 27.0`.
|
||||||
|
- **Rail (step 6):** run `20261203T154235Z` (pid 41682) — **729/729**; swiftformat `--lint` 0/153; swiftlint 0. Freshness pinned on the test host's `Info.plist` reading **0.1.2** (zero `SwiftCompile` lines is expected — no Swift source changed).
|
||||||
|
- **Slices + tag (step 7):** `build(release)` (notes) · `chore(release)` (bump + changelog heading) · annotated tag `v0.1.2` on the DMG tree `c959b67`. The `chore(release)` body wrapped at 74–77 columns past a 72 check — amended (tree byte-unchanged, verified) and the still-local tag force-moved onto the amended commit per the runbook.
|
||||||
|
- **DMG (step 8):** `dist/Museion-0.1.2.dmg` — 3,167,265 bytes, **sha256 `2d0942ea1b5c01675feccc817424786f551b4ff4e1cc7aa8f60d016c54001913`**; mounted image: app `0.1.2`, apex `1.1.59`; `stapler validate` clean; `spctl` → `accepted, source=Notarized Developer ID`.
|
||||||
|
- **On go (step 10):** `git push origin main v0.1.2` (remote main `d183d735` — Alexander's own `chore: ignore .hermes directory` rode between the tag and the push; the tag stayed on `c959b67`); `tea releases create` → release **id 29**, `draft: false`, one asset at the local byte size, body ends with the `[Generated by AI]` marker; token-authenticated download sha256-identical to the local DMG.
|
||||||
|
- **Micro.blog (step 11):** draft posted to the main blog via `mp-destination` + `mp-channel: default` → 202, `Location: https://alexanderkucera.com/2026/12/03/164803.html`; read-back `q=source` → `post-status: draft`, download/release/notarized lines intact. **preview** `https://micro.blog/account/posts/239/preview/6088880`, **edit** `https://micro.blog/account/posts/239/edit/6088880`.
|
||||||
|
- **Buy Me a Coffee (step 12):** `bmc.js` `create`/`draft`/`public` → `RESULT.mode: "draft"`, **editUrl** `https://www.buymeacoffee.com/posts/5336222/edit`; task space finished.
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| The apex `--help` grep for `no-mixed-lists` printed 0 | The help spells the flag `--[no-]mixed-lists` | The functional check (`printf … \| apex --no-mixed-lists` → `<ul>` then `<ol>`) is the evidence; expect the literal grep to miss |
|
||||||
|
| The `chore(release)` body wrapped at 74–77 columns | Drafted wider than the 72 rule | Amended the message (tree verified unchanged), force-moved the still-local tag — after a push this would have been a new version |
|
||||||
|
| `status` reported done ~60 s after `start`, looking like a stale summary read | Warm incremental build + no Swift changes: the suite is that fast on this tree | Freshness pinned on the run-dir pid (41682) and the test host's `Info.plist` version (0.1.2), not on elapsed time |
|
||||||
|
| A `.hermes -> .agents` symlink appeared at the repo root mid-session | Hermes runtime artifact | Left untracked; Alexander committed `chore: ignore .hermes directory` (`d183d735`) which rode the release push |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion.xcodeproj/project.pbxproj` | `MARKETING_VERSION` 0.1.1 → 0.1.2 (6 occurrences) |
|
||||||
|
| `CHANGELOG.md` | `## [0.1.2] - 2026-12-03` heading + notes pointer; fresh `[Unreleased]` |
|
||||||
|
| `docs/releases/0.1.2.md` | NEW — human-readable notes |
|
||||||
|
| `.agents/skills/release/SKILL.md` | (Alexander, `1b0c23a`) patch-for-a-bug-fix bump rule |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Release live: https://git.babylondreams.de/AlexKucera/museion/releases/tag/v0.1.2 — DMG sha256 `2d0942ea…`, asset byte-identical on download.
|
||||||
|
- [ ] Both announcements sit as DRAFTS in Alexander's queues (Micro.blog preview link, BMC edit link) — he publishes; rotation of the Micro.blog announce token recommended if it ever pastes into a transcript.
|
||||||
|
- [ ] `/Applications/Museion.app` (0.1.1) should be replaced by the 0.1.2 DMG locally.
|
||||||
|
- [ ] Next session: nothing pending from this release.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Micro.blog: the publish is remembered and shown (#206)
|
||||||
|
|
||||||
|
> **Date:** 2026-12-04
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [#206 — Display Micro.blog published status](https://git.babylondreams.de/AlexKucera/museion/issues/206) ("Right now it is unclear when a post was published.")
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Make the library say where each piece stands on Micro.blog. The publish sheet flipped a draft live and remembered nothing, so nothing on disk ever said a piece was out — the row could not show it, and sending a piece again created a second post.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- Grilling first (13 questions, every one owner-answered in session). The agreed design, built as one cohesive slice: a local publish record, the row label, the in-place re-send, the upload memo, a model-owned Publish, 404 recovery, the sheet's three open-states, the row-menu item.
|
||||||
|
- `PostLibrary.swift` — `Post.micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape) and the pure row label `micropubStatus` (`published <MMM d, yyyy>` / `draft on Micro.blog` / nil). `parseStamp` now serves both stamps; `Micropub.rememberedURL` moved to the client as the one trust-gate read.
|
||||||
|
- `Micropub.swift` — `Outcome.updated(url:)` and `.forgotten(String)`; `jsonPost` (the one JSON request builder); `makeUpdateRequest` + `Micropub.update` (`action=update` + `replace` name/content against the remembered URL — never a status flip, so Micro.blog-side categories stay untouched); `micropubSend` (was `micropubSendDraft`: no remembered URL → create + stamp `micropub_url`; a remembered one → the in-place update; a 404 → the piece forgets); `micropubPublish` (model-owned now: trust-gates its URL, flips the status, stamps the publish record, and heals `micropub_url` in the same write should the send's stamp have failed); `micropubPostGone` (a clear that cannot land refuses with the by-hand instruction); the illustration rail split into `uploadIllustrations` (floor + pre-flight) and `uploadRemembered` (memo-aware upload).
|
||||||
|
- `MicropubMedia.swift` — the upload memo: `.museion-uploads.json` in the piece folder maps `sha256(bytes)` → uploaded URL. Read back through the trust gate; a symlinked memo never reads; written as each upload lands.
|
||||||
|
- `PostFrontmatter.swift` — `stampFormat` (the one home for the stamp shape); `micropubKeys`; `updating(dropping:)` removes named keys' lines; `mergingImport` drops the micropub keys.
|
||||||
|
- `PostStore.swift` — `stampMicropub(_:home:_:dropping:)` (was `stampMicropubURL`); `forgetMicropub` throws, and removes both lines rather than emptying them.
|
||||||
|
- UI — `LibraryPostRow`: the mono-11 micro-label shows the status in origin's place on a sent piece (VoiceOver reads both; origin stays in the tooltip). `WorkspaceChrome`: `MicroblogHandOffButton` (Open on Micro.blog, published pieces only) mounted in the library and Archive menus. `MicropubPublishSheet` rewritten around the piece's record: Send as Draft → Publish / Update Draft / Update Live Post (status line + the live link).
|
||||||
|
- Tests — new `MicropubStatusTests` (17 pins); `MicropubTests`/`MicropubModelTests` follow the renames; the old "re-drafting overwrites the url" pin is retired (its premise is void under the in-place design); `MicropubRequestLog.request(_:)` replaces 11 index-after-count subscripts (4 new, 7 pre-existing).
|
||||||
|
- Owner sign-off in session: origin hidden on sent rows; drafts get no link and no menu item (he tested it — a draft's URL answers "Not Found" until published); the stamp is Museion's publish-click time in local time. His one legacy published post was hand-stamped from the blog's feed (`micropub_published: 2026-12-04T14:08:11` — one frontmatter line, +40 bytes, nothing sent to Micro.blog).
|
||||||
|
- Reviews — two-axis during the build (standards + spec: 0 hard violations, 7 of 8 judgement calls fixed, 1 rejected), then finish-audit (ponytail + security + general; see Decisions).
|
||||||
|
- DOX: `CHANGELOG.md` `[Unreleased]`, the README publishing paragraph, root `AGENTS.md` (three learnings), `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`.
|
||||||
|
|
||||||
|
**Verification (finish-up gates, each decided by its own exit code):** `swiftformat --lint .` — 0/154 files require formatting, exit 0. `swiftlint lint --strict --quiet` — 0 violations, exit 0. `./scripts/full-test.sh` — **752 executed / 752 passed / 0 failed** (run dir `_build/full-test/20261204T163814Z-Museion`; 736 at session start → +17 new pins, −1 retired).
|
||||||
|
|
||||||
|
**Flip cycle:** six assert-anchored batches on the uncommitted tree (pristine copies + `cmp` on restore, byte-exact every time). All 17 new pins were watched fail — each on its own guard, nothing else red except where predicted: update branch, publish stamp, publish identity guard, row label (10 red — the update branch's flip also reddens the three pins whose third request becomes a create); memo lookup + both 404 sites (4); memo trust gate + the honest-forget catch (2); the link heal (1); import drop + publish URL gate + memo symlink guard (3); stamp-on-failure + the update request's literal + the bytes-keyed memo (4 — the literal's flip also reddens the re-send pin that asserts the same `action`).
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| The publish is a local frontmatter stamp (`micropub_published`, local time), not a live query | The ticket asks what the writer published from here. A live status query needs a token on every list render and still cannot say "from this machine". Owner-approved, including that the date is Museion's publish-click time. |
|
||||||
|
| The row's micro-label shows the status in origin's place on a sent piece | 178pt of row content cannot hold both. Origin stays in the accessibility label and the tooltip. Owner-approved. |
|
||||||
|
| A re-send updates the remembered post in place (`action=update` + `replace` name/content) | Before: a second post every time. `replace` names only those two properties, so categories and everything else set on Micro.blog survive (the owner's explicit worry). |
|
||||||
|
| Publish stays a status flip and becomes model-owned | No content travels on publish. The sheet used to call the client directly, which is exactly why nothing was ever remembered. |
|
||||||
|
| An unchanged image rides its earlier upload via a per-piece memo keyed by `sha256(bytes)` | Micro.blog's media listing carries no content hash to match against, so the memory has to be local. Ceilings are ponytail comments: no liveness probe (a deleted upload stays memoized), memo URLs pass the format gate only (blogs use custom domains). |
|
||||||
|
| A 404 means the post is gone there: the piece forgets both keys, and a clear that cannot land refuses | Before: the piece failed forever against a dead URL. Emptying the keys left a dangling `micropub_published:` line — the lines are removed instead. A swallowed write must not be reported as "cleared". |
|
||||||
|
| Drafts show no link and no Open on Micro.blog item | Owner-verified: a draft's final URL answers "Not Found" until the post is published. |
|
||||||
|
| No typed status enum | Two consumers (row, sheet) of a computed label. Rejected as speculative by the standards review. |
|
||||||
|
| **The import boundary drops `micropub_url` and `micropub_published`** | Finish-audit security finding. An imported `micropub_url` passes the format gate, and since the in-place update it would aim a content replace — under the writer's token — at any post on their blog; a crafted guest post would open the sheet reading "Published" with one **Update Live Post** button. These keys are Museion's bookkeeping, so they are treated like `origin`: ours to set, never a foreign file's to carry in. One codec parameter (`updating(dropping:)`) serves the import and the forget. Side effect: re-importing one's own exported piece loses the link (next send = a new draft); moving the library is a Home repoint, not an import. |
|
||||||
|
| `micropubPublish` trust-gates its URL before anything travels | Security and general reviewers converged. Every current caller passes a gated value, but the URL lands in frontmatter on the heal, and the repo's rule is to gate at the sink. |
|
||||||
|
| Pins read recorded requests through `MicropubRequestLog.request(_:)` | An out-of-range subscript traps the hosted runner (first Gotcha). A nil from the accessor fails the pin's own expectation. |
|
||||||
|
| Ponytail cuts accepted | `statusHome()` duplicated the shared `storeHome()`; `illustratedPiece` duplicated `plantIllustratedPiece` line for line; `Micropub.update`'s empty-URL guard was unreachable (its only caller passes the trust gate's output). |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| A flip run reported 9 failures with no assertion text anywhere | The test host had trapped: `log.requests[2]` after a failed `#expect(log.requests.count == 3)`. An out-of-range subscript kills the hosted runner, and every queued test reports `Crash:` beside it (the crash report: `Array._checkSubscript` under `Runner._applyScopingTraits`). A real regression of the memo gate would have turned one red pin into nine | `MicropubRequestLog.request(_:)` at all 11 sites, `#require` where the value feeds a non-optional parameter. Read `summary.json` `testFailures` for a shared `Crash:` signature before reading a red count as a verdict. |
|
||||||
|
| `micropubStatus` compiled in the app but read "no member" from a fresh test file | Spelling drift between targets (`microblogStatus` in the test), not a stale binary | Grep the exact name across app AND tests before hunting binaries. |
|
||||||
|
| The patch tool re-indented `ArchivePaneView`'s closing braces | A replaced region that starts on a closing-brace run is re-indented to the anchor's scope | Restored from HEAD by a scripted splice; recorded as the code-editing skill's rule 9. |
|
||||||
|
| A scripted flip's anchor missed twice (count 0) | I typed the `do`/`try`/`catch` lines one tab short of the file | The assert fired before anything flipped. Anchors are now written from `repr()` of the real bytes. |
|
||||||
|
| swiftformat reflowed the multi-line `updating(...)` call after the edits | A formatter pass between edit and flip | Read anchors back after formatting; file-mutating tools run before the suite, never after. |
|
||||||
|
| The terminal's grep wrapper returned 0 matches for a parenthesised pattern that exists in the file | The wrapper's regex dialect | `search_files` for source reads; the terminal only for build logs. |
|
||||||
|
| The xcresult summary's `passedTests` reads total + 1 on green runs | Pre-existing rail quirk | Counts come from the rail's own line, never from the summary's passed figure. |
|
||||||
|
| "Update Live Post" on a stamp with no remembered link would have created a second post (audit) | The sheet branched on the stamp alone | The button reads "Send as Draft" when nothing is remembered — there is no post to update. |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/Micropub.swift` | Update request + client step; `micropubSend` (create-or-update, 404 forget), model-owned `micropubPublish` with the URL gate, `micropubPostGone`, the memo-aware upload rail, `rememberedURL`, `shortDate` |
|
||||||
|
| `Museion/MicropubMedia.swift` | The upload memo: key, trust-gated read, symlink refusal, atomic write |
|
||||||
|
| `Museion/MicropubPublishSheet.swift` | Opens on the piece's record; the three open-states; honest button labels |
|
||||||
|
| `Museion/PostLibrary.swift` | `micropubPublished`, `micropubStatus`, the shared `parseStamp` |
|
||||||
|
| `Museion/PostFrontmatter.swift` | `stampFormat`, `micropubKeys`, `updating(dropping:)`, import drops the micropub keys |
|
||||||
|
| `Museion/PostStore.swift` | `stampMicropub(dropping:)`, `forgetMicropub` throws and removes the lines |
|
||||||
|
| `Museion/LibraryPostRow.swift` | Status in the micro-label, composite accessibility label, origin tooltip |
|
||||||
|
| `Museion/WorkspaceChrome.swift` | `MicroblogHandOffButton` |
|
||||||
|
| `Museion/PostsLibraryColumn.swift`, `Museion/ArchivePaneView.swift` | Mount the menu item |
|
||||||
|
| `MuseionTests/MicropubStatusTests.swift` | New — 17 pins: the record, the heal, the import drop, the URL gate, the in-place re-send, the memo, the 404 forget |
|
||||||
|
| `MuseionTests/MicropubTests.swift` | `MicropubRequestLog.request(_:)`; renames |
|
||||||
|
| `MuseionTests/MicropubModelTests.swift` | Renames; safe request reads; `plantIllustratedPiece` shared |
|
||||||
|
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass: contracts, suite map, three learnings |
|
||||||
|
| `CHANGELOG.md`, `README.md` | The feature, the import rule, the by-hand legacy key |
|
||||||
|
| `docs/devlog/` | This log; `INDEX.md` row; the `AGENTS.md` window |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Owner to confirm the audit default: Import drops a file's Micro.blog memory (re-importing one's own exported piece loses the link; the next send creates a new draft).
|
||||||
|
- [ ] Ticket candidate: the `preview` URL from Micro.blog feeds a `Link` without the URL gate — the same posture at HEAD, outside this diff.
|
||||||
|
- [ ] Ticket candidate: Convert to Post rebuilds the frontmatter block and drops every foreign key, the micropub memory included (#114 posture; reachable only for a sent outline).
|
||||||
|
- [ ] Named ceiling, no action: a TLS-intercepting proxy answering 404 would clear a live post's record.
|
||||||
|
- [ ] Pieces published before this build read as drafts until Publish is clicked once (or the key is added by hand — one was).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Micro.blog categories travel with the piece (#207)
|
||||||
|
|
||||||
|
> **Date:** 2026-12-04
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [#207 — Allow setting and creating Micro.blog categories](https://git.babylondreams.de/AlexKucera/museion/issues/207) (a title-only ticket — the spec was grilled in session: eight decisions, D1–D8)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
A piece could carry no Micro.blog categories: the send left the post unclassified and the writer had to file it on the web. Make the piece's categories part of the piece — set and created from the publish sheet — and let them travel with every send.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- Grilling first (two rounds, every question owner-answered in session) → eight decisions (D1–D8, below). A throwaway prototype of three controls (`prototypes/MicropubCategoriesPrototype.swift`, kept beside the other prototypes) settled the control live: the owner ruled variant B while clicking it.
|
||||||
|
- `PostFrontmatter.swift` — the one-line `category:` list codec: `categorySegments` (the ONE quote-aware comma-list scanner), `categoryList` / `categoryListValue` (the unbracketed read and render), `categories(in:)` / `categoryValue` (the bracketed frontmatter forms). Line-bounded: newlines and control characters strip before the sink; names holding `, [ ] " \` ride quoted with backslashes and quotes escaped; empties drop; the first occurrence wins (a `Set`).
|
||||||
|
- `MicropubCategories.swift` (new) — `GET /micropub?q=category`: `makeCategoryListRequest`, `blogCategories(token:transport:) async -> [String]` (the root `categories` strings, else the `microblog-categories` objects' `name` fields; trimmed; any failure or non-2xx is `[]`).
|
||||||
|
- `Micropub.swift` — the wire: `makeDraftRequest(title:body:token:categories:)` carries `category` only when non-empty; `makeUpdateRequest(…, categories: [String]? = nil)` — nil is the #206 body byte for byte, `[]` is sent and clears; `sendDraft(categories:)`, `update(categories:)`. The model: `micropubSend(token:categories:…)` lands a pending edit as the piece's line FIRST (a failed write refuses with nothing on the wire), then one disk read feeds the wire; `updateRememberedOrCreate` (opt-in by key); `stampCategories`; `micropubPublish(url:token:categories:…)` runs the send first and flips the post that send touched; `openPieceCategories()` (the sheet's read of the open piece, never the scan snapshot).
|
||||||
|
- `MicropubMedia.swift` — `queryRequest(_:token:)` is the one `GET <endpoint>?q=…` builder (config and the category list).
|
||||||
|
- `PostStore.swift` — doc only: `stampMicropub` now also stamps the `category:` line (`[]` renders `category: []`); on a 404 the micropub lines still go.
|
||||||
|
- `MicropubPublishSheet.swift` — the **Categories** field: a comma list in the codec's unbracketed form with the system completion menu over the blog's categories (fetched when the sheet opens; a failed fetch is silent). The pure rules live in `MicropubCategoryField`: `pendingCategories` (the pending-edit test), `partial`, `finished`, `suggestions`, `completion`. The view: syncs from disk on open and after a forget, settles to the canonical text after a successful send, and after a failed step only its BASELINE re-syncs (`syncSettledFromDisk`).
|
||||||
|
- Tests — new `MicropubCategoryTests` (39 pins, S1–S8: create, re-send opt-in, the codec, apply-at-send + the refusal + the import, the blog list, publish-applies-first + the publish target, the field's pending rule, picks-add + the menu). `MicropubModelTests`: the old "frontmatter category never travels" pin flipped to `frontmatter category travels`. `MicropubTests`: header; the shared `plantedPiece` helper (a saved `# Titled` piece with planted frontmatter).
|
||||||
|
- Reviews — two-axis during the build (standards + spec: one real defect and six judgement calls fixed), then finish-audit (ponytail + security + general; see Decisions and Gotchas).
|
||||||
|
- DOX: `CHANGELOG.md` `[Unreleased]`, `PRD.md` S6.1, root `AGENTS.md` (learnings), `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `GLOSSARY.md` (Category).
|
||||||
|
|
||||||
|
**Verification (finish-up gates, each decided by its own exit code):** `swiftformat . --lint` — 0/157 files require formatting, exit 0. `swiftlint . --strict` — 0 violations in 146 files, exit 0. `./scripts/full-test.sh` — **791 executed / 791 passed / 0 failed** (run dir `_build/full-test/20261205T070414Z-Museion`; 752 at session start → +39 new pins, one existing pin flipped).
|
||||||
|
|
||||||
|
**Flip cycle:** eight batches on the uncommitted tree (pristine copies + `cmp` on restore, byte-exact every time). Before the reviewer fanout: A the codec (split, dedupe, bare scalar, quoting, control-char strip) · B create/opt-in/stamp/blog list (six guards) · C update builder/publish/create-eager · D–F the sheet field (partial, dup, half-typed, pending; present/finished/prefix/never-append; the two-mechanism empty-field pin) · G the three guards the earlier batches had masked. After the audit fixes: H (backslash escape, touched target, fresh target, sanitize strip, disk read, bare scalar). **39 of 40 pins were watched fail on their own guard**, nothing else red except where predicted. The hold-out is `a refused send with a category edit writes nothing` — an ordering pin whose guard also supplies the data the write would need, so no flip can redden it.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Creation is implicit on Micro.blog — no separate create call or UI (D1) | Naming a category Micro.blog does not know in the create/update creates it there. A second step would be a second click for the same outcome. |
|
||||||
|
| The control is variant B: a comma-separated field plus the native completion menu (`textInputSuggestions` / `textInputCompletion`, macOS 15+) (D2) | Three controls were prototyped live. A visible chip row does not scale to the owner's many categories; an NSTokenField fights the completion system. The owner ruled B while clicking it. |
|
||||||
|
| A pick ADDS; a half-typed last word is replaced; a present name is never offered again | The system REPLACES the whole field text with a completion — so the completion IS the merge. A prototype finding; owner-ruled. |
|
||||||
|
| `finished` means the last word equals a known blog category; the field compares case-insensitively, the codec exactly | SwiftUI exposes no caret, so the end of the text is the only place a writer can be typing. Case-insensitivity keeps the menu from re-offering `notes` when `Notes` is present; the codec's de-duplication stays exact — ponytail-noted. |
|
||||||
|
| `partial` strips one pair of surrounding quotes | A just-picked comma-containing name (`"Tech, general"`) must read as finished, or the menu narrows to nothing. |
|
||||||
|
| One line, `category: [Tech, Notes]`; a bare scalar is one; `[]` is an explicit empty; the codec is line-bounded | The frontmatter sink is line-bounded (#33). Names with commas, brackets, quotes or backslashes ride quoted — the audit closed the backslash gap. |
|
||||||
|
| Re-sends are opt-in by key (D5) | A piece WITH the line replaces the post's categories with exactly its list (`[]` clears); a piece without one leaves whatever the blog has — the #206 posture survives for every piece that never got a line. |
|
||||||
|
| The edit lands at the send: guards → flush → category write → ONE disk read → wire; a failed write refuses (D6) | Never a half-state: the wire's names always come from the line on disk. Cancel/Done discard the edit; an unrelated later refusal may leave the line on the piece — documented, and the sheet re-baselines from disk. |
|
||||||
|
| Publish with a pending edit runs the update first, then flips the post that send touched (D7) | A failed update returns its outcome with NO publish — disk and blog never disagree. The audit made the target the touched post: the sheet's URL can be stale against the disk, and flipping it would also have stamped the stale address over the real memory. |
|
||||||
|
| After any failed step only the pending BASELINE re-syncs from disk; the field keeps its text | The send writes before the wire, so a later clear of the field must still count as an edit (the first review's stale-baseline defect). |
|
||||||
|
| Import keeps an imported `category:` line (D8) | It is the writer's classification, not Museion's bookkeeping — only the micropub keys drop. The writer sees the list in the field before any send. |
|
||||||
|
| `blogCategories` returns `[String]`; `[]` on any failure | Finish-audit ponytail: the `.failed` payload had no consumer. The sheet is silent by decision; a rejected token surfaces on the send itself. |
|
||||||
|
| `[String]?` carries nil = no edit versus `[]` = clear; `stampMicropub` keeps its name | Two states with different wire meanings, documented on the parameter; a named enum was deferred. No drive-by rename. |
|
||||||
|
| De-duplication through a `Set` | Finish-audit security: a hostile 600 KB imported `category:` line cost 16 s on the main actor — at sheet open and on every keystroke. |
|
||||||
|
| The test plant is one shared helper (`plantedPiece`) | Finish-audit ponytail: four copies of the `origin: writer` anchor would have to change together. The two pre-existing copies outside this diff stay until touched. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| After a failed publish-with-edit, a later CLEAR of the field read as "no edit" and was silently dropped | The pending baseline was captured at sheet open; the failed send had already written the line | `fail()` → `syncSettledFromDisk()` (baseline only; the typed text stays). Found by the first review, pinned by the clearing pins. |
|
||||||
|
| A name ending in a backslash, or holding `\"`, re-parsed as ONE junk name and swallowed the next | The renderer escaped only `"`, while the scanner honored every `\` as an escape | Escape `\` before `"`; unescape both; a backslash triggers quoting. Audit — security and general converged, probe-confirmed; pinned by the round-trip. |
|
||||||
|
| `micropubPublish` flipped the CALLER's URL, not the post the update touched | `case .updated: break` discarded the URL the send returned | `target = touched`. Audit — two angles; two pins (the stale-URL case and the fresh-draft case). |
|
||||||
|
| Three guards were unproven after their first flip batch | Two flips in one batch reddened the same pins for a different reason: the splitter switched off hid the dedupe; never-append hid the `finished` oracle and the prefix rule | An isolated closing batch per masked guard. A guard is proven only when it is the SOLE explanation of a red pin. |
|
||||||
|
| Two of the listed flip edits did not compile (`filter { true }`; `if let x = x ?? []`) | Closure argument lists cannot be implicitly ignored; a conditional binding needs an Optional | Compile-equivalent forms: `{ _ in true }`, `as [String]?`. |
|
||||||
|
| The TUI shell wedged mid-session (every command timed out, `echo` included) and `execute_code` was blocked in delegation-triggered turns | — | The rail and the flip runs were delegated to children with their own terminals; one child's shell wedged too and fell back to detached subprocesses from its `execute_code` kernel. `read_file` / `search_files` never failed. |
|
||||||
|
| `swift-test-results.py` died with `NameError: sys` | The skill script never imported `sys` | The one-line import was added to the skill. |
|
||||||
|
| The xcresult summary's device-level `passedTests` reads total + 1 | The dynamic-parameter statistic (pre-existing) | The top-level `totalTestCount` and the rail's own line are authoritative. |
|
||||||
|
| A stub proves less than a flip | The sheet pins' first red came against a constant stub — that only proves a pin reads the function, not that each rule discriminates | The field's interaction pins were proven guard by guard in batches D–G. |
|
||||||
|
| A child's first attempt to read the suite log undercounted by one (50 rows for 51 tests) | An xcodebuild progress line split one status line | Bundle counts, never log-line tallies. |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/PostFrontmatter.swift` | The one-line `category:` codec: `categorySegments`, `categoryList`, `categoryListValue`, `categories(in:)`, `categoryValue`, the unescape helper |
|
||||||
|
| `Museion/MicropubCategories.swift` | New — `GET /micropub?q=category`, `blogCategories(token:)` |
|
||||||
|
| `Museion/Micropub.swift` | Category on the create/update builders; `micropubSend(categories:)`, `micropubPublish(categories:)`, `openPieceCategories()`, `stampCategories`, `updateRememberedOrCreate` |
|
||||||
|
| `Museion/MicropubMedia.swift` | `queryRequest(_:token:)` — the one `GET ?q=` builder |
|
||||||
|
| `Museion/MicropubPublishSheet.swift` | The Categories field (`MicropubCategoryField` + the view wiring) |
|
||||||
|
| `Museion/PostStore.swift` | Doc: `stampMicropub` stamps the `category:` line |
|
||||||
|
| `MuseionTests/MicropubCategoryTests.swift` | New — 39 pins, S1–S8 |
|
||||||
|
| `MuseionTests/MicropubModelTests.swift` | The "category travels" pin flipped; rides `plantedPiece` |
|
||||||
|
| `MuseionTests/MicropubTests.swift` | Header; the shared `plantedPiece` helper |
|
||||||
|
| `prototypes/MicropubCategoriesPrototype.swift` | New — the throwaway three-control prototype (`--selftest`, `PROTO_MANY=1`) |
|
||||||
|
| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass: contracts, suite map, learnings |
|
||||||
|
| `CHANGELOG.md`, `PRD.md`, `GLOSSARY.md` | The feature; S6.1; the Category term |
|
||||||
|
| `docs/devlog/` | This log; `INDEX.md` row; the `AGENTS.md` window |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Owner to try the live completion menu in the app — hosted tests cannot exercise the SwiftUI wiring: open a saved post → Publish → Categories.
|
||||||
|
- [ ] Ticket candidate: a pick rewrites the field from its end (SwiftUI exposes no caret) — a visible-chips v2 if caret-mid-text bites.
|
||||||
|
- [ ] Ticket candidate: Convert to Post rebuilds the frontmatter block and drops every foreign key, a piece's `category:` line included (#114 posture; the same class as the #206 note).
|
||||||
|
- [ ] Unverified wire fact: the `microblog-categories` fallback shape is cited from Micro.blog's docs, never observed on the wire.
|
||||||
|
- [ ] Named ceilings, no action: blog-side duplicate names in the suggestions (`ForEach(id: \.self)`); an imported empty `category:` line makes later re-sends clear the blog's categories (opt-in by key).
|
||||||
|
- [ ] The two pre-existing plant copies in `MicropubStatusTests` / `MicropubTests` can ride `plantedPiece` when next touched.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Micro.blog: honest 5xx wording + a Settings page for the app token
|
||||||
|
|
||||||
|
> **Date:** 2026-12-04
|
||||||
|
> **Type:** generic
|
||||||
|
> **Reference:** unticketed — owner report in session ("publishing returns error 503; there is no place in settings to save the auth token")
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Two things the owner hit while publishing to Micro.blog. First, the publish sheet showed `Micro.blog said 503: HTTP 503` — find out whether the 503 was Museion's or Micro.blog's, and make the message say so. Second, the Micro.blog app token had no home in Settings: it was entered once in the publish sheet, the field came back only after a 401/403, and a saved token could not be replaced or removed anywhere in the app.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **Diagnosis first, no code.** Probed `https://micro.blog/micropub` tokenless at 14:01 CET: 25/25 POSTs → `400 Invalid request` (text/html — their no-token answer), homepage 200, media endpoint 400, an app-like User-Agent 400. The request shape matched the current `microblog.dev/api/posting` docs (JSON create with `post-status: draft`; `update`/`replace` is JSON-only, which is what `Micropub.swift` sends). Their documented error vocabulary is 400 (bad request) and 401/403 (auth) — a 503 is their nginx front with the app behind it not answering, or a rate limit. Their news feed logs the same pattern repeatedly (Nov 25 "traffic spikes or attacks", Nov 30 "blog publishing stuck", 2025-04-26 "sorry for the 503s"). The bare `HTTP 503` in the sheet was `decodeFailure` falling through: the body was an HTML page, so the JSON decode found no `error_description`.
|
||||||
|
- `Micropub.decodeFailure(status:body:)` — the ONE failure decode every step shares (create, publish, q=config, media upload) — answers `unavailable on their side — retry in a few minutes (status.micro.blog)` for a 5xx that carries no JSON description. A described 5xx keeps its description; a 4xx keeps the bare `HTTP n`; 401/403 → `authFailed` unchanged. The sheet needed no change — it already renders `Micro.blog said <status>: <detail>`.
|
||||||
|
- `SettingsPage.microblog` (label **Micro.blog**, last in the sidebar after Provider Keys) + `MicroblogSettingsPage` in `SettingsPagesView.swift`: a status line (stored / not saved), a `SecureField` + **Save** (replaces the stored token), a **Remove** button while one is stored. It writes the same `MicropubTokenStore` slot the publish sheet reads, so the sheet picks the token up unchanged.
|
||||||
|
- `saved` is read back from the Keychain after every write: `save` is void (the `SecItemAdd` result is ignored), so a locked keychain would otherwise flip the status to "stored" falsely. On Save the read-back is compared with the token just written — an older token surviving a failed replace must not read as success.
|
||||||
|
- Pin in `MicropubTests`: `a 5xx names micro.blog's outage not a bare status` — 503 over an HTML body → the their-side wording; 422 over the same body → `HTTP 422`; 502 with `error_description` → the description.
|
||||||
|
- DOX: `Museion/AGENTS.md` (the Micropub bullet carries the 5xx contract and the token's two entry points; the Settings bullet names the page), the sheet's and both Settings files' headers, `CHANGELOG.md` `[Unreleased]` (Added + Fixed).
|
||||||
|
|
||||||
|
**Verification:** `./scripts/full-test.sh` — **736 executed / 736 passed / 0 failed** (run dir `_build/full-test/20261204T131024Z-Museion`; was 735, exactly +1). The filtered `MicropubTests` run 14/14 with `SwiftCompile` lines for every edited source. The new pin flip-verified: guard off (`status < 0`) → 14 executed / 13 passed / 1 failed, the one red being that pin with `detail → "HTTP 503"`; tree restored byte-exact (sha256 `21e9f101…` before and after). `swiftformat .` 0/153 formatted, `swiftlint .` exit 0.
|
||||||
|
|
||||||
|
**Follow-up, same session (owner: "there should be an indication on if the token was saved / is currently saved").** The owner was on the 14:59 build, so they had the page — the status was there, but as a muted intro-line text swap, which reads as description, not status. And the publish sheet showed nothing at all when a stored token was in use (the field just wasn't there).
|
||||||
|
|
||||||
|
- `MicroblogSettingsPage`: the intro is static again ("Where the Micro.blog app token lives."), and the status moved under the field row as its own row in the Settings verdict idiom — `✓ Token saved in your Keychain` in accent mono 11, `No token saved — publishing will ask for one` muted. Live: Save and Remove already read the Keychain back into `saved`.
|
||||||
|
- `MicropubPublishSheet`: when the field is hidden because a token is stored, the sheet says `Sends with the app token in your Keychain — Settings → Micro.blog manages it.`
|
||||||
|
- Verification: rail again on the settled tree — **736 / 736 / 0** (run dir `20261204T140402Z-Museion`). The two files were compiled by the standalone build that preceded the rail (`SwiftCompile` 2 lines each in its log; the rail's own build found them up to date — 0 lines, legitimately), so the artifact was checked instead: the dylib (15:04:07) postdates every source and carries all four new strings. `swiftformat --lint` 0/2, `swiftlint` 0. No new pin — both are view-only over the already-pinned store.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| The 5xx wording lives in `decodeFailure`, not the sheet's `.requestFailed` branch | One decode serves create, publish, q=config, and media upload; every one of them surfaces through the same refusal line. Patching the sheet would have left the three other callers saying `HTTP 503`. |
|
||||||
|
| A JSON description on a 5xx still wins over the outage wording | Never hide a real server explanation behind the generic line. Their documented errors are 400-shaped JSON; a 5xx from the app itself might still carry one. |
|
||||||
|
| No retry, no `Retry-After` parsing | The user asked for honest wording. A 503 from an overloaded service is best retried by a human a few minutes later; automatic retries on a publish path can double-post. Add when a real outage pattern justifies it. |
|
||||||
|
| The page goes into `SettingsPagesView.swift`, not a new file | This repo disables `file_length`/`type_body_length` ("deliberately large cohesive units"); the surface pages and Provider Keys already live there. |
|
||||||
|
| Sidebar position: last, after Provider Keys | Enum declaration order is sidebar order. Credentials cluster at the end: provider keys (`.env`), then the one Keychain credential. |
|
||||||
|
| `saved` is read back from the Keychain, compared with the written token on Save | `MicropubTokenStore.save` ignores the `SecItemAdd` status. A void write plus an assumed `saved = true` would lie on a locked keychain; comparing against the new token also catches a failed replace that leaves the old one in place. |
|
||||||
|
| Capture `trimmedToken` into a local before clearing the field | `trimmedToken` is computed over `tokenField`. Clearing first made the read-back compare against `""` — always false. Caught before the first build. |
|
||||||
|
| No "Test token" button on the page | The publish sheet's Send as Draft is the test, and a draft creates nothing public. A read-only `q=config` probe is a fine follow-up if the owner wants it. |
|
||||||
|
| No view-layer pin | Repo convention: pure seams pinned, SwiftUI dogfooded. The page's logic is three calls into the store the `token store round-trips` pin already covers. |
|
||||||
|
| The owner's Keychain token was confirmed present but never read | Credential rule. A read-only `q=config` with it was offered and not run; the tokenless probe was enough to rule out a hard outage. |
|
||||||
|
| Unticketed, generic log | The owner asked for both fixes directly in session; no Gitea issue exists. The CHANGELOG carries the entry. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| My first test patch called `outcomeDetail(outage)`, a helper that does not exist | Wrote the pin from a mental shape instead of the suite's | Read the landed region before building; replaced with the suite's `guard case let .requestFailed` shape |
|
||||||
|
| The patch tool's diffs around closing-brace runs read ambiguously (the `}` lines seemed added/re-indented) | Repeated `}` lines let the diff algorithm pair them unpredictably; the display is not the file | Read the landed regions and counted braces (open == close in every touched file) instead of trusting the diff |
|
||||||
|
| The rail log showed 0 `SwiftCompile` lines for four of the edited sources on first grep | The earlier filtered run had compiled them (2 lines each in its log); the rail recompiled only the sheet, whose header comment changed after that build | Verified the artifact instead: the dylib postdates every source and carries all five distinctive strings |
|
||||||
|
| `cut -c` on Swift source with em-dashes → `Illegal byte sequence` | macOS `cut` is not UTF-8-aware under the default locale | `read_file` for the region |
|
||||||
|
| A tokenless POST answers **400** `Invalid request` (text/html), not 401 | Micro.blog's no-token answer is not REST-shaped | Useful probe signature for "is the endpoint up": 400 means healthy, 503 means theirs |
|
||||||
|
| `MicropubPublishSheet` header said the token is "entered here ONCE" | True until this session | Header now names both entry points; the sheet's own logic is untouched |
|
||||||
|
| Owner follow-up: "there should be an indication" although the page had a status text | The status sat in the intro slot — a muted 12pt subtitle swapping text — which reads as description, not state; the sheet showed nothing when a stored token was in use | A dedicated status row under the field in the Settings verdict idiom (`✓ …` accent / muted); the sheet names the stored token it sends with |
|
||||||
|
| The first status-row patch nested `private var status` inside `form`'s body | The fuzzy patch matcher re-indents a replaced region that starts on a closing-brace run to the anchor's scope (the code-editing skill's rule 7) | Repaired by a programmatic splice of the whole struct between two unique doc-comment markers; verified column-0 struct line, brace balance, then swiftformat/swiftlint/build |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `Museion/Micropub.swift` | `decodeFailure`: 5xx → their-side wording (JSON description wins); doc comment |
|
||||||
|
| `Museion/SettingsPaneView.swift` | `SettingsPage.microblog` + label + detail switch; header |
|
||||||
|
| `Museion/SettingsPagesView.swift` | `MicroblogSettingsPage` (status row / Save / Remove, Keychain read-back); header |
|
||||||
|
| `Museion/MicropubPublishSheet.swift` | header comment (names the Settings manager); names the stored token a send carries when the field is hidden |
|
||||||
|
| `MuseionTests/MicropubTests.swift` | +1 pin (5xx wording; 4xx and described-5xx contrasts) |
|
||||||
|
| `Museion/AGENTS.md` | Micropub bullet (5xx contract, token entry points); Settings bullet (the page) |
|
||||||
|
| `CHANGELOG.md` | `[Unreleased]` → Added (the page), Fixed (the wording) |
|
||||||
|
| `docs/devlog/INDEX.md`, `AGENTS.md` | this log's row + the rolling window |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Retry the publish that 503'd — the endpoint was healthy at 14:01 CET; if it 503s again, run a read-only `q=config` with the saved token (owner's go needed) to tell an account-specific 503 from a blip.
|
||||||
|
- [ ] Dogfood Settings → Micro.blog: the `✓ Token saved in your Keychain` row shows on open; Save replaces it (Remove appears); Remove flips it to `No token saved` and the publish sheet offers its field again; the sheet shows `Sends with the app token in your Keychain…` while one is stored.
|
||||||
|
- [ ] Optional: a **Test token** button (read-only `q=config`) on the page.
|
||||||
|
- [ ] Optional: `Retry-After`-aware outage wording; automatic retry on 503 for the draft send (mind double-posting).
|
||||||
|
- [ ] Pre-existing, untouched: the sheet's `showsTokenField` reads the Keychain on every body evaluation; a `.onAppear`-seeded state would read once.
|
||||||
|
- [ ] Commit (maintainer) — nothing was committed, pushed, or commented on the forge.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
+10
-1
@@ -5,6 +5,15 @@ Complete history of session logs in this directory, newest first. One-line summa
|
|||||||
<!-- write-log: full-index -->
|
<!-- write-log: full-index -->
|
||||||
| Date | Type | File | Summary |
|
| Date | Type | File | Summary |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
| 2026-12-04 | issue | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md) | Micro.blog categories travel with the piece; comma field with native completion; publish targets the post the send touched (rail 791/791) |
|
||||||
|
| 2026-12-04 | issue | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) | Micro.blog publish is remembered and shown: row status, in-place re-send, upload memo, 404 forget; Import drops micropub keys (rail 752/752) |
|
||||||
|
| 2026-12-04 | generic | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) | Micro.blog publish: a 5xx names their outage instead of `HTTP 503`, and the app token gains a Settings page (rail 736/736) |
|
||||||
|
| 2026-12-03 | issue | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_log.md) | Reveal in Finder / Copy Path on library and Archive rows: one shared menu fragment over the model-resolved post.md path, three pins, rail 735/735 |
|
||||||
|
| 2026-12-03 | issue | [20261203-issue204-fix-cards-jump-to-the-anchor_log.md](20261203-issue204-fix-cards-jump-to-the-anchor_log.md) | Fix Cards gain Jump: the anchor span selected in the editor, the main window keyed, over the #71 caret rail |
|
||||||
|
| 2026-12-03 | milestone | [20261203-release-012-image-drop-fix_log.md](20261203-release-012-image-drop-fix_log.md) | Release 0.1.2 ships the macOS 27.2 image-drop fix: bump, notes, rail 729/729, notarized DMG, forge release id 29, drafts |
|
||||||
|
| 2026-12-03 | generic | [20261203-image-drop-27-2-drag-routing-pastes-path_log.md](20261203-image-drop-27-2-drag-routing-pastes-path_log.md) | macOS 27.2 routes drags to the deepest view: NSTextView pasted the file path; the editor now owns drops through one router (rail 729/729) |
|
||||||
|
| 2026-12-03 | milestone | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_log.md) | Release 0.1.1: apex 1.1.59 refreshed FIRST (full recipe now in the release skill), bump + tag 4a056f9, rail 720/720, DMG notarized; push on go |
|
||||||
|
| 2026-12-01 | milestone | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) | Release 0.1.0: version bump + tag, README feature/usage rewrite, distilled release notes, release.sh (Developer ID DMG, notarize); rail 717/717; Developer ID cert pending |
|
||||||
| 2026-11-30 | fix | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) | Unticketed fix (brief-32, argus cycle-6): the external guest's watch reads through the ONE shared external normalizer — the false #67 conflict on unchanged BOM/CRLF files (re-arming after sibling events and alert answers, blocking departures/quit) is gone; real foreign writes still raise; RED-first 3 pins over the real watch closure; rail 720/720 |
|
| 2026-11-30 | fix | [20261130-external-watch-compares-unnormalized-text_log.md](20261130-external-watch-compares-unnormalized-text_log.md) | Unticketed fix (brief-32, argus cycle-6): the external guest's watch reads through the ONE shared external normalizer — the false #67 conflict on unchanged BOM/CRLF files (re-arming after sibling events and alert answers, blocking departures/quit) is gone; real foreign writes still raise; RED-first 3 pins over the real watch closure; rail 720/720 |
|
||||||
| 2026-11-23 | fix | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) | Unticketed fix (brief-28, argus cycle-5): a Home repoint is a guarded document departure — the gate runs before the preference/binding commit, the refusal keeps Home A and the buffers; document identity is (Home, ID) across the model and re-checked at async completion (card scan, rescan — both mutation-checked); RED-first 6/6 at ca265d3b, review r1 +2 pins (rescan hoist, draft survives); rail 717/717 |
|
| 2026-11-23 | fix | [20261123-home-repoint-retains-old-editor-target_log.md](20261123-home-repoint-retains-old-editor-target_log.md) | Unticketed fix (brief-28, argus cycle-5): a Home repoint is a guarded document departure — the gate runs before the preference/binding commit, the refusal keeps Home A and the buffers; document identity is (Home, ID) across the model and re-checked at async completion (card scan, rescan — both mutation-checked); RED-first 6/6 at ca265d3b, review r1 +2 pins (rescan hoist, draft survives); rail 717/717 |
|
||||||
| 2026-11-19 | fix | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) | Quit routes through the departure gate (#200): conflict-held shutdown, BLOCK-QUIT at applicationShouldTerminate, never-loaded-retype guard; finish-audit fixes; rail 708/708 |
|
| 2026-11-19 | fix | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) | Quit routes through the departure gate (#200): conflict-held shutdown, BLOCK-QUIT at applicationShouldTerminate, never-loaded-retype guard; finish-audit fixes; rail 708/708 |
|
||||||
@@ -87,4 +96,4 @@ Complete history of session logs in this directory, newest first. One-line summa
|
|||||||
| 2026-09-25 | issue | [20260925-issue50-profile-backup-s2-6_log.md](20260925-issue50-profile-backup-s2-6_log.md) | #50 S2.6 daily profile backup: liveness gate, curated copy, retention 7, RESTORE.md — 8 tests green |
|
| 2026-09-25 | issue | [20260925-issue50-profile-backup-s2-6_log.md](20260925-issue50-profile-backup-s2-6_log.md) | #50 S2.6 daily profile backup: liveness gate, curated copy, retention 7, RESTORE.md — 8 tests green |
|
||||||
| 2026-09-16 | issue | [20260916-issue14-acp-bridge-s2-2_log.md](20260916-issue14-acp-bridge-s2-2_log.md) | #14 M0 ACP bridge: NDJSON JSON-RPC client, mentor pane, fix-card round-trip, crash restart — 37 tests green |
|
| 2026-09-16 | issue | [20260916-issue14-acp-bridge-s2-2_log.md](20260916-issue14-acp-bridge-s2-2_log.md) | #14 M0 ACP bridge: NDJSON JSON-RPC client, mentor pane, fix-card round-trip, crash restart — 37 tests green |
|
||||||
| 2026-09-05 | issue | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](20260905-issue48-provisioning-failure-alert-retry-ux_log.md) | #48 shipped: failure card with retry/Not-Now, traversal guard, temp sweep — 30 tests green |
|
| 2026-09-05 | issue | [20260905-issue48-provisioning-failure-alert-retry-ux_log.md](20260905-issue48-provisioning-failure-alert-retry-ux_log.md) | #48 shipped: failure card with retry/Not-Now, traversal guard, temp sweep — 30 tests green |
|
||||||
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |
|
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Museion 0.1.0
|
||||||
|
|
||||||
|
*Released 2026-12-01 · the first release. Entry-by-entry detail with issue numbers: [CHANGELOG.md](../../CHANGELOG.md).*
|
||||||
|
|
||||||
|
Museion is the Agentic Writing Environment: a native macOS app where your text, your library, and a resident AI mentor work under one roof. It is built for long-form writers who want to get better, not ghostwritten — the mentor critiques, demonstrates, and remembers your recurring weaknesses, and nothing ships without your hand on it.
|
||||||
|
|
||||||
|
0.1.0 is the complete v1 loop, three months in the making and dogfooded along the way: write, get critiqued, remember what keeps going wrong, measure whether it stops, publish.
|
||||||
|
|
||||||
|
## What is in it
|
||||||
|
|
||||||
|
**The Mentor Loop.** A user-installed [Hermes](https://hermes-agent.nousresearch.com/docs) engine runs as a child process under three isolated profiles. **Pass 1** critiques structure, argument, and flow; **Pass 2** works at sentence level. Each pass ends in a verdict and a set of **Fix Cards** — mechanical ones apply behind a sheet that shows the exact edit, one card at a time, never all at once; demonstration ones show a single annotated example on your own text. A native deslop lint lands its findings as cards before the engine even sees the piece. Promote a card into **Learnings** and every later pass consults it; dismiss one and it fades, resurfacing on an output clock. **Sessions** are freeform conversations with resume, fork, and compact; a reply can become a new post. **Blind Read** judges the current text against the pass-start snapshot without knowing which is which.
|
||||||
|
|
||||||
|
**A real editor.** A TextKit 2 prose surface with styled markdown source, sub-second autosave, an honest save-state dot, cursor and scroll restored across restarts, and an explicit *Reload / Keep Local* alert when the file changes underneath you — never a silent overwrite. Reading mode, focus mode, image drops that copy into the piece and reference in place, list indentation and folding, and spellcheck on request.
|
||||||
|
|
||||||
|
**Cold Turkey.** A writing lock nested inside focus mode: pick net words or minutes, and Museion holds a fullscreen kiosk until you meet the goal. Quitting asks once. Nothing persists.
|
||||||
|
|
||||||
|
**Outlines.** Nested-bullet outline pieces with LogSeq-style keys, drag-to-reorder and nest, zoom into a branch, and a one-way Convert to Post.
|
||||||
|
|
||||||
|
**A library that is a folder.** Pieces live under projects and fold into an archive, all plain markdown under your **Museion Home** (iCloud Drive by default on fresh installs, `~/Documents/Museion` otherwise; repoint-only, never moved). Grouping by project and Pass State, search across titles and bodies, rename/move/archive/trash from the row menu, and a live file watcher so Finder edits show up without a refresh. Open any `.md` in place as a guest; import `.md` files as posts.
|
||||||
|
|
||||||
|
**Measurable improvement.** Running a pass on an unaided first draft captures four style metrics before the mentor sees anything. The Trends pane charts them across captures with an honest *improving / steady / slipping* verdict per metric.
|
||||||
|
|
||||||
|
**Publishing.** Micro.blog via Micropub: Send as Draft, review, Publish. Illustrations upload and ride inline; a picture without alt text never ships.
|
||||||
|
|
||||||
|
## Milestones
|
||||||
|
|
||||||
|
- **M0 — ACP bridge.** The app spawns Hermes, opens a session, streams replies, cancels, and tears down cleanly on quit.
|
||||||
|
- **M1 — Editor surface.** Posts list over the Home folder, post lifecycle (new, save, rename, trash), the TextKit 2 prose editor with autosave and external-change guard.
|
||||||
|
- **M2 — Passes and Fix Cards.** Pass 1 / Pass 2, the in-app MCP server that receives cards, the Fix Cards palette with ask-before Apply, the native deslop lint.
|
||||||
|
- **M3 — Critique memory.** Learnings: promote with one confirm, consult on every pass, dismiss with decay.
|
||||||
|
- **M4 — Measurable improvement.** First-draft stats capture and the Trends pane.
|
||||||
|
- **M5 — Research and library-light.** Mid-pass research notes kept into the piece with provenance; drill offers; the bundled skill set (Serif stack, deslop, craft canon, VOICE).
|
||||||
|
- **M6 — Micropub publish.** Draft → publish to Micro.blog, illustrations included.
|
||||||
|
- **After v1 scope.** Projects and archive, the outliner, library search, image drops, Cold Turkey, per-surface engines with in-app model settings and Test Connection, Nous Portal, gateless launch, iCloud-default Home, the editorial two-color chrome.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download `Museion-0.1.0.dmg` below, open it, drag Museion to Applications.
|
||||||
|
|
||||||
|
- **macOS 27 or later**, Apple Silicon.
|
||||||
|
- **Hermes** is needed for Passes and Sessions — `curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash`. Museion provisions the profiles and seeds its skills on the next launch. The editor, library, outlines, and publishing work without it.
|
||||||
|
- A provider API key (z.ai, Anthropic, OpenAI, or Nous Portal) under Settings ▸ Provider Keys.
|
||||||
|
|
||||||
|
The app is Developer ID-signed and notarized.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- Long-form structure tools (binder, compile), backlinks and graph views, multi-mind setups, and publish targets beyond Micro.blog are out of v1 scope — see `PRODUCT.md` for the full non-goal list.
|
||||||
|
- Convert to Post is one-way. Opening a mixed-content outline asks how to proceed; opening as an outline normalizes on save.
|
||||||
|
- The Mentor methodology is a bundled skill set, not a trained model — fierce or gentle is a persona blend, not a setting.
|
||||||
|
- One user so far. No testimonials, customers, or benchmarks exist yet, and none are claimed.
|
||||||
|
|
||||||
|
## Numbers
|
||||||
|
|
||||||
|
74 Swift files, about 23,000 lines in the app target; a unit suite of over 700 tests, run through `scripts/full-test.sh`; SwiftFormat and SwiftLint clean repo-wide.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Museion 0.1.1
|
||||||
|
|
||||||
|
*Released 2026-12-03 · a bug-fix release. Entry-by-entry detail: [CHANGELOG.md](../../CHANGELOG.md).*
|
||||||
|
|
||||||
|
0.1.1 fixes one bug that shipped in [0.1.0](0.1.0.md) and refreshes the reading-mode renderer.
|
||||||
|
|
||||||
|
## What is in it
|
||||||
|
|
||||||
|
**No more false "file changed on disk" alerts on guest files.** Opening a `.md` file from outside your library as a guest (⌘O, or a drop) worked — until the file carried a byte-order mark or Windows line endings. Then Museion raised the *Reload / Keep Local* conflict alert on every sibling file event in that folder, even though nothing had changed, and kept re-raising it after either answer. Worse, the false alert blocked every departure: selecting another piece, New Post, quitting. The file watch now reads the disk through the same normalizer the editor uses on open (BOM strip + CRLF→LF), so the compare is like-for-like. A real external write still raises the alert — the guard is not blinded.
|
||||||
|
|
||||||
|
**apex 1.1.59.** The bundled reading-mode renderer moves from 1.1.58 to the current upstream release, packaged exactly as in 0.1.0: arm64 slice of the official universal tarball, checksum verified, Developer ID–signed with the hardened runtime, libyaml vendored beside it. No behavior change in reading mode.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- Unchanged from 0.1.0 — see [0.1.0's known limits](0.1.0.md#known-limits).
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download `Museion-0.1.1.dmg` below, open it, drag Museion to Applications (replaces 0.1.0 in place).
|
||||||
|
|
||||||
|
- **macOS 27 or later**, Apple Silicon.
|
||||||
|
- Hermes and a provider key are needed only for Passes and Sessions; the editor, library, outlines, and publishing work without them — same as 0.1.0.
|
||||||
|
|
||||||
|
The app is Developer ID-signed and notarized.
|
||||||
|
|
||||||
|
## Numbers
|
||||||
|
|
||||||
|
Suite 720 at the tag, run through `scripts/full-test.sh`; SwiftFormat and SwiftLint clean repo-wide.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Museion 0.1.2
|
||||||
|
|
||||||
|
*Released 2026-12-03 · a bug-fix release. Entry-by-entry detail: [CHANGELOG.md](../../CHANGELOG.md).*
|
||||||
|
|
||||||
|
0.1.2 fixes one bug that has been in every build so far and only showed up on macOS 27.2: dropping an image onto a post.
|
||||||
|
|
||||||
|
## What is in it
|
||||||
|
|
||||||
|
**Drop an image onto a post, and it lands in the piece again.** Since macOS 27.2, dragging an image file from Finder onto the prose editor pasted the file's *path* as plain text instead of copying the image into the piece and inserting its reference. The cause was a change in the operating system, not in Museion's code: 27.2 delivers a drag to whichever view sits directly under the pointer, so the editor's text view received the drop and ran its stock behavior — insert the path — while the app's own drop handling never saw it. A markdown file dropped onto the editor had the same symptom.
|
||||||
|
|
||||||
|
Now the editor owns the drops that land on it. An image is copied into the piece's `assets/` folder and `` appears at the drop point with the alt text selected, ready to type over. A markdown file dropped on the editor opens as a guest again. In an outline, a dropped file bounces instead of pasting a path. Dropping *text* — a selection from the editor, text from another app — still inserts text, as it always did.
|
||||||
|
|
||||||
|
Two refusals are deliberate: an image dragged from a web browser gets a notice (there is no file on disk to copy), and so does a file that went missing between the drag and the drop.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- Unchanged from 0.1.0 — see [0.1.0's known limits](0.1.0.md#known-limits).
|
||||||
|
- An image dragged straight from a browser is not downloaded into the piece; save it to disk first, then drop it.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download `Museion-0.1.2.dmg` below, open it, drag Museion to Applications (replaces 0.1.1 in place).
|
||||||
|
|
||||||
|
- **macOS 27 or later**, Apple Silicon.
|
||||||
|
- Hermes and a provider key are needed only for Passes and Sessions; the editor, library, outlines, and publishing work without them — same as 0.1.0.
|
||||||
|
|
||||||
|
The app is Developer ID-signed and notarized.
|
||||||
|
|
||||||
|
## Numbers
|
||||||
|
|
||||||
|
Suite 729 at the tag, run through `scripts/full-test.sh`; SwiftFormat and SwiftLint clean repo-wide.
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
// PROTOTYPE — #207 "Allow setting and creating Micro.blog categories". THROWAWAY; not part of the app target.
|
||||||
|
// Build: swiftc -O -parse-as-library prototypes/MicropubCategoriesPrototype.swift -o /tmp/micropub_categories_proto
|
||||||
|
// Run: copy the binary into /tmp/MicropubCategoriesProto.app/Contents/MacOS/ (Info.plist: CFBundleExecutable=
|
||||||
|
// micropub_categories_proto, CFBundlePackageType=APPL) and `open` that bundle — a bare binary never gets
|
||||||
|
// real keyboard activation. `<binary> --selftest` runs the field-text ↔ list contract checks and exits.
|
||||||
|
// Under test: which control carries the publish sheet's editable "Categories" field (suggestions = the blog's
|
||||||
|
// existing categories). ONE binary, THREE windows around the SAME mock of MicropubPublishSheet — only the
|
||||||
|
// control differs:
|
||||||
|
// A — comma field + a visible "On your blog:" row of link-styled category buttons
|
||||||
|
// B — comma field + the native completion menu (.textInputSuggestions)
|
||||||
|
// C — AppKit NSTokenField (Mail-style tokens + the delegate completion menu)
|
||||||
|
// Each window's mono state line is exactly what the control would write to the piece's frontmatter (contract
|
||||||
|
// below). Launch env PROTO_SEED=1 pre-fills all three with every dummy category, PROTO_B_TEXT=Te pre-types and
|
||||||
|
// focuses B's field, PROTO_MANY=1 swaps in ~40 categories (screenshot scenarios); default is empty/five.
|
||||||
|
|
||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
// MARK: - Tokens (inlined from Museion/DesignTokens.swift)
|
||||||
|
|
||||||
|
enum Tok {
|
||||||
|
static let background = Color(red: 0xFA / 255, green: 0xF9 / 255, blue: 0xF3 / 255)
|
||||||
|
static let muted = Color(red: 0x6B / 255, green: 0x69 / 255, blue: 0x64 / 255)
|
||||||
|
static let accent = Color(red: 0xC9 / 255, green: 0x64 / 255, blue: 0x42 / 255)
|
||||||
|
/// The sheet's label/note face and its field face (MicropubPublishSheet).
|
||||||
|
static let monoNote = Font.system(size: 11, design: .monospaced)
|
||||||
|
static let monoField = Font.system(size: 12, design: .monospaced)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - #207 contract: field text ↔ list ↔ frontmatter
|
||||||
|
|
||||||
|
/// Quote-aware comma split — the field's elements (a comma inside double quotes does not split).
|
||||||
|
func commaSplit(_ text: String) -> [String] {
|
||||||
|
var parts: [String] = []
|
||||||
|
var current = ""
|
||||||
|
var quoted = false
|
||||||
|
for char in text {
|
||||||
|
if char == ",", !quoted {
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
} else {
|
||||||
|
if char == "\"" {
|
||||||
|
quoted.toggle()
|
||||||
|
}
|
||||||
|
current.append(char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Field text → list: split on commas OUTSIDE double quotes, trim, strip one surrounding quote pair, drop
|
||||||
|
/// empties, de-duplicate (first occurrence wins).
|
||||||
|
func parseCategories(_ text: String) -> [String] {
|
||||||
|
var seen = Set<String>()
|
||||||
|
return commaSplit(text).compactMap { part in
|
||||||
|
var name = part.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if name.count >= 2, name.hasPrefix("\""), name.hasSuffix("\"") {
|
||||||
|
name = String(name.dropFirst().dropLast())
|
||||||
|
}
|
||||||
|
guard !name.isEmpty, seen.insert(name).inserted else { return nil }
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List → frontmatter line: a name carrying `,` `[` `]` or `"` is wrapped in double quotes, inner `"` escaped.
|
||||||
|
func frontmatterLine(_ names: [String]) -> String {
|
||||||
|
let cells = names.map { name in
|
||||||
|
name.contains(where: { ",[]\"".contains($0) }) ? "\"" + name.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : name
|
||||||
|
}
|
||||||
|
return "category: [" + cells.joined(separator: ", ") + "]"
|
||||||
|
}
|
||||||
|
|
||||||
|
func stateLine(_ names: [String]) -> String {
|
||||||
|
names.isEmpty ? "No categories → category: []" : "Travels as → " + frontmatterLine(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name as written into the comma FIELD (A/B): quoted when it carries a comma, so the parser reads it back.
|
||||||
|
func fieldForm(_ name: String) -> String {
|
||||||
|
name.contains(",") ? "\"\(name)\"" : name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The word being typed: the last element of the quote-aware split, trimmed and quote-stripped like a
|
||||||
|
/// parsed name ("" when the field is empty or ends with a comma).
|
||||||
|
func partial(_ text: String) -> String {
|
||||||
|
let last = commaSplit(text).last?.trimmingCharacters(in: .whitespaces) ?? ""
|
||||||
|
guard last.count >= 2, last.hasPrefix("\""), last.hasSuffix("\"") else { return last }
|
||||||
|
return String(last.dropFirst().dropLast())
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameName(_ a: String, _ b: String) -> Bool {
|
||||||
|
a.caseInsensitiveCompare(b) == .orderedSame
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last thing typed is itself a known category → nothing is half-typed.
|
||||||
|
func finished(_ text: String, blog: [String]) -> Bool {
|
||||||
|
blog.contains { sameName($0, partial(text)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// B's menu: every category while nothing is typed or the last word is a finished category, else the
|
||||||
|
/// prefix matches (blog order kept); present names are never offered.
|
||||||
|
func suggestions(text: String, blog: [String]) -> [String] {
|
||||||
|
let names = parseCategories(text)
|
||||||
|
let p = partial(text)
|
||||||
|
let candidates = (p.isEmpty || finished(text, blog: blog)) ? blog : blog.filter { $0.lowercased().hasPrefix(p.lowercased()) }
|
||||||
|
return candidates.filter { name in !names.contains { sameName($0, name) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// B — what the field becomes when `name` is picked. The system replaces the WHOLE text with the
|
||||||
|
/// completion, so the completion IS the merge: a pick ADDS (never duplicates); a half-typed word goes.
|
||||||
|
/// Pure (field text, picked name, blog) → String; ported into the real sheet and unit-tested there.
|
||||||
|
func completion(text: String, picking name: String, blog: [String]) -> String {
|
||||||
|
var names = parseCategories(text)
|
||||||
|
let p = partial(text)
|
||||||
|
let halfTyped = !p.isEmpty && !finished(text, blog: blog) && name.lowercased().hasPrefix(p.lowercased()) && !sameName(p, name)
|
||||||
|
if halfTyped, let last = names.last, sameName(last, p) {
|
||||||
|
names.removeLast()
|
||||||
|
}
|
||||||
|
if !names.contains(where: { sameName($0, name) }) {
|
||||||
|
names.append(name)
|
||||||
|
}
|
||||||
|
return names.map(fieldForm).joined(separator: ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `--selftest`: the contract above, run for real (asserts are compiled out under -O).
|
||||||
|
func contractSelfCheck() -> Never {
|
||||||
|
let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||||
|
let swiftBlog = ["Swift", "SwiftUI"]
|
||||||
|
let others = ["Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||||
|
let quotedPick = "Tech, \"Tech, general\""
|
||||||
|
let checks: [(String, Bool)] = [
|
||||||
|
("bare text", parseCategories(" Tech, Notes,, tech ") == ["Tech", "Notes", "tech"]),
|
||||||
|
("quoted comma", parseCategories("\"Tech, general\", Tech") == ["Tech, general", "Tech"]),
|
||||||
|
("dedupe first wins", parseCategories("Notes, \"Notes\"") == ["Notes"]),
|
||||||
|
("empties dropped", parseCategories(" \"\" , ") == []),
|
||||||
|
("line", frontmatterLine(["Tech", "Notes"]) == "category: [Tech, Notes]"),
|
||||||
|
("quoted line", frontmatterLine(["Tech, general", "a\"b"]) == "category: [\"Tech, general\", \"a\\\"b\"]"),
|
||||||
|
("empty state", stateLine([]) == "No categories → category: []"),
|
||||||
|
("state", stateLine(parseCategories("Tech, Notes")) == "Travels as → category: [Tech, Notes]"),
|
||||||
|
("pick on empty field", completion(text: "", picking: "Tech", blog: blog) == "Tech"),
|
||||||
|
("pick adds: Tech + Notes", completion(text: "Tech", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||||
|
("pick adds again: any number of clicks", completion(text: "Tech, Notes", picking: "Essays", blog: blog) == "Tech, Notes, Essays"),
|
||||||
|
("pick replaces the half-typed word", completion(text: "Te", picking: "Tech", blog: blog) == "Tech"),
|
||||||
|
("pick after a comma", completion(text: "Tech, No", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||||
|
("pick keeps both Tech and Tech, general", completion(text: "Tech", picking: "Tech, general", blog: blog) == "Tech, \"Tech, general\""),
|
||||||
|
("pick exact over prefix: Sw + SwiftUI", completion(text: "Sw", picking: "SwiftUI", blog: swiftBlog) == "SwiftUI"),
|
||||||
|
("pick present name: unchanged", completion(text: "Tech, Notes", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||||
|
("pick present name drops the half-typed word", completion(text: "Notes, No", picking: "Notes", blog: blog) == "Notes"),
|
||||||
|
("pick keeps a new name", completion(text: "MyNewCat", picking: "Notes", blog: blog) == "MyNewCat, Notes"),
|
||||||
|
("suggestions: empty → all", suggestions(text: "", blog: blog) == blog),
|
||||||
|
("suggestions: prefix, case-insensitive", suggestions(text: "te", blog: blog) == ["Tech", "Tech, general"]),
|
||||||
|
("suggestions: finished → every other category", suggestions(text: "Tech", blog: blog) == others),
|
||||||
|
("suggestions: after a comma only the prefix", suggestions(text: "Tech, Te", blog: blog) == ["Tech, general"]),
|
||||||
|
("suggestions: a present name is never offered", !suggestions(text: "Notes", blog: blog).contains("Notes")),
|
||||||
|
("suggestions: after a quoted pick, every other category", suggestions(text: quotedPick, blog: blog) == Array(others.prefix(3))),
|
||||||
|
]
|
||||||
|
for check in checks where !check.1 {
|
||||||
|
print("FAIL: \(check.0)")
|
||||||
|
}
|
||||||
|
let failed = checks.filter { !$0.1 }.count
|
||||||
|
print(failed == 0 ? "contract OK (\(checks.count) checks)" : "contract FAILED (\(failed))")
|
||||||
|
exit(failed == 0 ? 0 : 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Mock sheet (mirrors MicropubPublishSheet's idle state; only `control` differs)
|
||||||
|
|
||||||
|
enum Variant: String, CaseIterable {
|
||||||
|
case a, b, c
|
||||||
|
|
||||||
|
var id: String {
|
||||||
|
rawValue.uppercased()
|
||||||
|
}
|
||||||
|
|
||||||
|
var title: String {
|
||||||
|
switch self {
|
||||||
|
case .a: "A — comma field + visible row"
|
||||||
|
case .b: "B — comma field + completion menu"
|
||||||
|
case .c: "C — token field"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SheetMock: View {
|
||||||
|
let variant: Variant
|
||||||
|
@Environment(\.openWindow) private var openWindow
|
||||||
|
@State private var text = "" // A, B
|
||||||
|
@State private var tokens: [String] = [] // C
|
||||||
|
|
||||||
|
/// The writer's existing blog categories — every variant's suggestion source.
|
||||||
|
static let blogCategories: [String] = isMany ? manyCategories : ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||||
|
private static let isMany = ProcessInfo.processInfo.environment["PROTO_MANY"] != nil
|
||||||
|
|
||||||
|
/// PROTO_MANY=1: ~40 names at a real blog's scale — shared prefixes (Swift…), two with commas.
|
||||||
|
private static let manyCategories = [
|
||||||
|
"Tech", "Notes", "Essays", "Fieldwork", "Tech, general",
|
||||||
|
"Swift", "SwiftUI", "Swift Testing", "Swift Format", "Swift Concurrency",
|
||||||
|
"Xcode", "AppKit", "Metal", "macOS", "iOS", "Toolchain", "Builds",
|
||||||
|
"Design", "Typography", "Accessibility", "Hugo", "Static Sites", "Web",
|
||||||
|
"Indie Business", "Pricing", "Marketing", "App Store", "Support, email", "Privacy",
|
||||||
|
"Photography", "Film", "Books", "Reading Notes", "Travel", "Field Notes, abroad",
|
||||||
|
"Coffee", "Cooking", "Music", "Synths", "Keyboards",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Suggestions for a partial word (case-insensitive prefix); empty → all five.
|
||||||
|
static func matches(_ partial: String) -> [String] {
|
||||||
|
blogCategories.filter { $0.lowercased().hasPrefix(partial.lowercased()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 12) {
|
||||||
|
Text("Publish to Micro.blog?")
|
||||||
|
.font(.headline)
|
||||||
|
Text("The expected value of showing")
|
||||||
|
.font(.callout.weight(.semibold))
|
||||||
|
.lineLimit(2)
|
||||||
|
Text("Museion sends it as a draft first — nothing goes out until you publish.")
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(Tok.muted)
|
||||||
|
|
||||||
|
control
|
||||||
|
|
||||||
|
Text(stateLine(variant == .c ? tokens : parseCategories(text)))
|
||||||
|
.font(Tok.monoNote)
|
||||||
|
.foregroundStyle(Tok.muted)
|
||||||
|
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
|
||||||
|
.font(Tok.monoNote)
|
||||||
|
.foregroundStyle(Tok.muted)
|
||||||
|
|
||||||
|
HStack {
|
||||||
|
Button("Publish") {}
|
||||||
|
.buttonStyle(.borderedProminent)
|
||||||
|
.disabled(true)
|
||||||
|
Button("Send as Draft") {}
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
Button("Cancel") {}
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, alignment: .trailing)
|
||||||
|
}
|
||||||
|
.padding(16)
|
||||||
|
.frame(width: 340, alignment: .leading)
|
||||||
|
.frame(width: 340, height: 360, alignment: .topLeading)
|
||||||
|
.background(Tok.background)
|
||||||
|
.task {
|
||||||
|
if variant == .a {
|
||||||
|
// B last: it ends up the key window, so its field is first responder at launch.
|
||||||
|
openWindow(id: Variant.c.id)
|
||||||
|
openWindow(id: Variant.b.id)
|
||||||
|
}
|
||||||
|
if ProcessInfo.processInfo.environment["PROTO_SEED"] != nil {
|
||||||
|
text = Self.blogCategories.map(fieldForm).joined(separator: ", ")
|
||||||
|
tokens = Self.blogCategories
|
||||||
|
}
|
||||||
|
if variant == .b, let typed = ProcessInfo.processInfo.environment["PROTO_B_TEXT"] {
|
||||||
|
text = typed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var control: some View {
|
||||||
|
switch variant {
|
||||||
|
case .a: CommaField(text: $text, mode: .visibleRow)
|
||||||
|
case .b: CommaField(text: $text, mode: .completionMenu)
|
||||||
|
case .c:
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
FieldLabel()
|
||||||
|
TokenField(tokens: $tokens)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sheet's label face (mono 11 muted) above the field.
|
||||||
|
struct FieldLabel: View {
|
||||||
|
var body: some View {
|
||||||
|
Text("Categories")
|
||||||
|
.font(Tok.monoNote)
|
||||||
|
.foregroundStyle(Tok.muted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - A + B: comma-separated TextField (A: visible link row · B: native completion menu)
|
||||||
|
|
||||||
|
struct CommaField: View {
|
||||||
|
enum Mode { case visibleRow, completionMenu }
|
||||||
|
@Binding var text: String
|
||||||
|
let mode: Mode
|
||||||
|
/// Screenshot scenario only (PROTO_B_TEXT=Te): focuses the pre-typed field so the native menu shows.
|
||||||
|
@FocusState private var focused: Bool
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
FieldLabel()
|
||||||
|
switch mode {
|
||||||
|
case .visibleRow:
|
||||||
|
field
|
||||||
|
blogRow
|
||||||
|
case .completionMenu:
|
||||||
|
field
|
||||||
|
// The system filters nothing — it lists every view given here (verified: `Te` typed, all
|
||||||
|
// five provided → five rows). `suggestions` narrows, `completion` is the merged whole text.
|
||||||
|
.textInputSuggestions {
|
||||||
|
ForEach(suggestions(text: text, blog: blog), id: \.self) { name in
|
||||||
|
Text(name).textInputCompletion(completion(text: text, picking: name, blog: blog))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.task {
|
||||||
|
if mode == .completionMenu, ProcessInfo.processInfo.environment["PROTO_B_TEXT"] != nil {
|
||||||
|
focused = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var field: some View {
|
||||||
|
TextField("Tech, Notes", text: $text)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.font(Tok.monoField)
|
||||||
|
.focused($focused)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var blog: [String] {
|
||||||
|
SheetMock.blogCategories
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A: the blog's categories, always visible; a click appends (never duplicates) the name.
|
||||||
|
private var blogRow: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text("On your blog:")
|
||||||
|
.font(Tok.monoNote)
|
||||||
|
.foregroundStyle(Tok.muted)
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
ForEach(SheetMock.blogCategories, id: \.self) { name in
|
||||||
|
Button(name) { append(name) }
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.foregroundStyle(Tok.accent)
|
||||||
|
.pointerStyle(.link)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func append(_ name: String) {
|
||||||
|
var names = parseCategories(text)
|
||||||
|
guard !names.contains(name) else { return }
|
||||||
|
names.append(name)
|
||||||
|
text = names.map(fieldForm).joined(separator: ", ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - C: NSTokenField (Mail-style tokens + the delegate completion menu)
|
||||||
|
|
||||||
|
struct TokenField: NSViewRepresentable {
|
||||||
|
typealias NSViewType = NSTokenField
|
||||||
|
@Binding var tokens: [String]
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator {
|
||||||
|
Coordinator(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mock limitation: inside the representable the field stays one line tall, so wrapped tokens
|
||||||
|
/// clip at the bottom (Mail grows its field) — `sizeThatFits`/`maximumNumberOfLines` did not
|
||||||
|
/// change that; not pursued, the owner ruled for B.
|
||||||
|
func makeNSView(context: Context) -> NSTokenField {
|
||||||
|
let field = NSTokenField()
|
||||||
|
field.placeholderString = "Tech, Notes"
|
||||||
|
field.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
|
||||||
|
field.tokenStyle = .rounded
|
||||||
|
field.delegate = context.coordinator
|
||||||
|
return field
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ field: NSTokenField, context _: Context) {
|
||||||
|
guard (field.objectValue as? [String] ?? []) != tokens else { return }
|
||||||
|
field.objectValue = tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTokenFieldDelegate {
|
||||||
|
let parent: TokenField
|
||||||
|
|
||||||
|
init(_ parent: TokenField) {
|
||||||
|
self.parent = parent
|
||||||
|
}
|
||||||
|
|
||||||
|
func controlTextDidChange(_ obj: Notification) {
|
||||||
|
guard let field = obj.object as? NSTokenField else { return }
|
||||||
|
parent.tokens = field.objectValue as? [String] ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
func tokenField(
|
||||||
|
_: NSTokenField, completionsForSubstring substring: String, indexOfToken _: Int,
|
||||||
|
indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>?,
|
||||||
|
) -> [Any]? {
|
||||||
|
selectedIndex?.pointee = 0
|
||||||
|
return SheetMock.matches(substring)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The contract's de-duplication at the control: a token already present is not added twice.
|
||||||
|
func tokenField(_: NSTokenField, shouldAdd tokens: [Any], at _: Int) -> [Any] {
|
||||||
|
tokens.compactMap { $0 as? String }.filter { !parent.tokens.contains($0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - App: three windows, tiled apart; A opens its siblings
|
||||||
|
|
||||||
|
@main
|
||||||
|
struct CategoriesPrototypeApp: App {
|
||||||
|
init() {
|
||||||
|
if CommandLine.arguments.contains("--selftest") {
|
||||||
|
contractSelfCheck()
|
||||||
|
}
|
||||||
|
// No saved window state: a relaunch would restore B and C, and A's `.task` opens them again.
|
||||||
|
UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows": false])
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some Scene {
|
||||||
|
window(.a, x: 0.18)
|
||||||
|
window(.b, x: 0.5)
|
||||||
|
window(.c, x: 0.82)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Window` (not `WindowGroup`): `openWindow` on an already-open window activates it instead of stacking a twin.
|
||||||
|
private func window(_ variant: Variant, x: CGFloat) -> some Scene {
|
||||||
|
Window(variant.title, id: variant.id) { SheetMock(variant: variant) }
|
||||||
|
.defaultPosition(UnitPoint(x: x, y: 0.5))
|
||||||
|
.windowResizability(.contentSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+135
@@ -0,0 +1,135 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Release packaging: archive → Developer ID export → DMG → notarize → staple.
|
||||||
|
#
|
||||||
|
# Contract:
|
||||||
|
# - Bumps nothing and tags nothing. Run from the commit that already carries
|
||||||
|
# the version in MARKETING_VERSION; the git tag is the caller's job.
|
||||||
|
# - Refuses BEFORE building when no valid "Developer ID Application" identity
|
||||||
|
# is in the keychain. Create it at developer.apple.com ▸ Certificates ▸ + ▸
|
||||||
|
# Developer ID Application from a Keychain Access ▸ Certificate Assistant CSR —
|
||||||
|
# Xcode's Manage Certificates refuses this even for the Account Holder (stale
|
||||||
|
# role cache). The private key lives only on the Mac that made the CSR — a
|
||||||
|
# portal-side certificate without it is not an identity.
|
||||||
|
# - Notarizes through the `museion-notary` notarytool keychain profile, created
|
||||||
|
# once by the Account Holder:
|
||||||
|
# xcrun notarytool store-credentials museion-notary \
|
||||||
|
# --apple-id <apple-id> --team-id <team-id> --password <app-specific-password>
|
||||||
|
# NOTARIZE=0 skips notarize+staple (a Developer-ID-signed DMG Gatekeeper still warns on).
|
||||||
|
# - Output: dist/Museion-<MARKETING_VERSION>.dmg (gitignored). The version is
|
||||||
|
# read from build settings, never from the pbxproj text. Apple Silicon only —
|
||||||
|
# the deployment target is macOS 27, which does not run on Intel.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PROJECT="Museion.xcodeproj"
|
||||||
|
SCHEME="Museion"
|
||||||
|
APP_NAME="Museion.app"
|
||||||
|
CONFIGURATION="Release"
|
||||||
|
IDENTITY="Developer ID Application"
|
||||||
|
NOTARY_PROFILE="museion-notary"
|
||||||
|
DIST="dist"
|
||||||
|
DESTINATION='platform=macOS,arch=arm64'
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.." # repo root — PROJECT is relative (same guard as deploy.sh)
|
||||||
|
|
||||||
|
if ! security find-identity -v -p codesigning | grep -q "\"$IDENTITY:"; then
|
||||||
|
echo "No valid \"$IDENTITY\" identity in the keychain." >&2
|
||||||
|
echo "Create it once: developer.apple.com ▸ Certificates ▸ + ▸ $IDENTITY (CSR from Keychain Access ▸ Certificate Assistant)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
SIGNER=$(security find-identity -v -p codesigning | sed -n 's/.*"\('"$IDENTITY"':[^"]*\)".*/\1/p' | head -1)
|
||||||
|
|
||||||
|
VERSION=$(xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
|
||||||
|
-destination "$DESTINATION" -showBuildSettings 2>/dev/null \
|
||||||
|
| awk -F'= ' '/MARKETING_VERSION = / {print $2; exit}')
|
||||||
|
if [[ -z "$VERSION" ]]; then
|
||||||
|
echo "MARKETING_VERSION not found in build settings" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
TEAM=$(xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
|
||||||
|
-destination "$DESTINATION" -showBuildSettings 2>/dev/null \
|
||||||
|
| awk -F'= ' '/DEVELOPMENT_TEAM = / {print $2; exit}')
|
||||||
|
DMG="$DIST/Museion-$VERSION.dmg"
|
||||||
|
echo "Packaging $SCHEME $VERSION"
|
||||||
|
|
||||||
|
# xcodebuild -quiet prints nothing on success; keep the log to show on failure.
|
||||||
|
log=$(mktemp -t museion-release)
|
||||||
|
trap 'rm -f "$log"' EXIT
|
||||||
|
run() { echo "→ $*"; if ! "$@" >"$log" 2>&1; then echo "Failed: $*" >&2; cat "$log" >&2; exit 1; fi; }
|
||||||
|
|
||||||
|
rm -rf "$DIST"
|
||||||
|
mkdir -p "$DIST"
|
||||||
|
|
||||||
|
run xcodebuild -project "$PROJECT" -scheme "$SCHEME" -configuration "$CONFIGURATION" \
|
||||||
|
-destination "$DESTINATION" -archivePath "$DIST/Museion.xcarchive" -quiet archive
|
||||||
|
|
||||||
|
cat >"$DIST/export-options.plist" <<EOF
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0"><dict>
|
||||||
|
<key>method</key><string>developer-id</string>
|
||||||
|
<key>signingStyle</key><string>automatic</string>
|
||||||
|
<key>teamID</key><string>$TEAM</string>
|
||||||
|
<key>destination</key><string>export</string>
|
||||||
|
</dict></plist>
|
||||||
|
EOF
|
||||||
|
|
||||||
|
run xcodebuild -exportArchive -archivePath "$DIST/Museion.xcarchive" \
|
||||||
|
-exportOptionsPlist "$DIST/export-options.plist" -exportPath "$DIST/export" \
|
||||||
|
-allowProvisioningUpdates -quiet
|
||||||
|
|
||||||
|
APP="$DIST/export/$APP_NAME"
|
||||||
|
if [[ ! -d "$APP" ]]; then
|
||||||
|
echo "Export did not produce $APP" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
run codesign --verify --deep --strict "$APP"
|
||||||
|
# Capture first: `codesign -dvv | grep -q` SIGPIPEs codesign under pipefail (grep
|
||||||
|
# quits at the first Authority line while codesign still writes its Info.plist dump).
|
||||||
|
SIGNATURE=$(codesign -dvv "$APP" 2>&1)
|
||||||
|
grep -q '^Authority=Developer ID Application' <<<"$SIGNATURE" \
|
||||||
|
|| { echo "Export is not Developer ID signed:" >&2; grep '^Authority=' <<<"$SIGNATURE" >&2; exit 1; }
|
||||||
|
# The bundled renderer must run from the SHIPPED layout (rpath → Resources/libyaml.bundle), and
|
||||||
|
# the app must not link libyaml — a bare dylib in the synced Resources folder becomes a link target
|
||||||
|
# silently (Xcode sniffs Mach-O content), which is why the vendored copy sits in a .bundle.
|
||||||
|
if otool -L "$APP/Contents/MacOS/$SCHEME" | grep -q libyaml; then
|
||||||
|
echo "The app links libyaml — it must only be apex's dependency, never the app's" >&2; exit 1
|
||||||
|
fi
|
||||||
|
run "$APP/Contents/Resources/apex" --version
|
||||||
|
|
||||||
|
# A mounted leftover from an earlier run makes the create fail with a busy volume.
|
||||||
|
hdiutil detach "/Volumes/$SCHEME $VERSION" -quiet 2>/dev/null || true
|
||||||
|
STAGE="$DIST/stage"
|
||||||
|
mkdir -p "$STAGE"
|
||||||
|
ditto "$APP" "$STAGE/$APP_NAME" # ditto preserves the bundle's signature and xattrs
|
||||||
|
ln -s /Applications "$STAGE/Applications"
|
||||||
|
# diskutil image create replaces the deprecated `hdiutil create` (macOS 27).
|
||||||
|
run diskutil image create from --format UDZO --volumeName "$SCHEME $VERSION" "$STAGE" "$DMG"
|
||||||
|
rm -rf "$STAGE" "$DIST/export"
|
||||||
|
# Gatekeeper's open-assessment needs the IMAGE signed too; the notary ticket is stapled onto this signature.
|
||||||
|
run codesign --timestamp --sign "$SIGNER" "$DMG"
|
||||||
|
|
||||||
|
if [[ "${NOTARIZE:-1}" == "1" ]]; then
|
||||||
|
# `--wait` exits 0 on Invalid too — the status FIELD is the verdict. (JSON goes to
|
||||||
|
# stdout only; notarytool has no output-path option.)
|
||||||
|
echo "→ xcrun notarytool submit $DMG --keychain-profile $NOTARY_PROFILE --wait"
|
||||||
|
if ! xcrun notarytool submit "$DMG" --keychain-profile "$NOTARY_PROFILE" --wait --output-format json >"$DIST/notary.json" 2>"$log"; then
|
||||||
|
echo "Failed: notarytool submit" >&2; cat "$log" >&2; exit 1
|
||||||
|
fi
|
||||||
|
if ! grep -Eq '"status" *: *"Accepted"' "$DIST/notary.json"; then
|
||||||
|
echo "Notarization not accepted — Apple's log:" >&2
|
||||||
|
xcrun notarytool log --keychain-profile "$NOTARY_PROFILE" \
|
||||||
|
"$(awk -F'"' '/"id" *:/ {print $4; exit}' "$DIST/notary.json")" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# The ticket can reach the CDN a few seconds after "Accepted"; stapler 404s in that window.
|
||||||
|
for attempt in 1 2 3 4 5 6; do
|
||||||
|
xcrun stapler staple "$DMG" && break
|
||||||
|
[[ "$attempt" == 6 ]] && { echo "Stapling failed after 6 attempts; retry: xcrun stapler staple $DMG" >&2; exit 1; }
|
||||||
|
echo " ticket not on the CDN yet, retrying in 10 s ($attempt/6)…"
|
||||||
|
sleep 10
|
||||||
|
done
|
||||||
|
# The Gatekeeper verdict a downloader's Mac will reach.
|
||||||
|
spctl -a -t open --context context:primary-signature -v "$DMG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Built: $DMG"
|
||||||
Reference in new issue
Block a user