Compare commits

..
22 Commits
Author SHA1 Message Date
AlexKucera 36393a9e8e feat(microblog): post summary for Micro.blog
A piece's `summary:` frontmatter line now travels to Micro.blog
beside `category:`. A first send carries the summary when it is not
empty; a re-send replaces the post's summary only when the piece has
the line (opt-in by key; an empty value clears it; no line leaves the
blog's). The same rule as categories, so a piece that never gained
the line cannot blank a summary set on Micro.blog itself.

The publish sheet gains a Summary field and an AI summary button. The
button drafts a first-person teaser from the open piece on a fresh
one-shot engine on the chat profile (the Blind Read's rail — the
resident session is never touched); the reply fills the field for the
writer to edit, and nothing is written until the send stamps the
line. The sheet is modal, so while its own turn runs the button is
the Stop; a Pass or Blind Read that owns the rail disables the button
with the reason on hover and refuses from behind it.

The summary is read off the RAW frontmatter line, never through the
lenient decode — which trims every edge quote — and the read walks
the block the way the lenient reader does. A `split`-based read finds
no block in a mixed-ending file while the lenient reader still sees
the key, and the empty value it answers would have been sent over a
live post's summary.

Reviewed twice (two-axis during the build, three-reviewer
finish-audit after): the mixed-ending read, an unfenced body line
claiming the key, the uncancellable modal turn, and the wrapper rule
eating a teaser's edge quotes were found and fixed before this
commit. Every guard was watched fail on its own pin. Rail 814/814;
SwiftFormat and SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, and the devlog.

Closes #208
2026-12-05 12:32:38 +01:00
AlexKucera 6db4cf8cf1 feat(microblog): set and create categories
A piece's `category:` frontmatter line now travels to Micro.blog: a
first send carries the list beside title and content, and a re-send
replaces the post's categories with exactly the piece's list — only
when the piece has the line (opt-in by key; `[]` clears; no line
leaves the blog's). Naming a category Micro.blog doesn't know creates
it there, so there is no separate create step.

The publish sheet gains a Categories field: a comma list with the
system completion menu over the blog's own categories. The system
replaces the whole field text with a completion, so the completion is
the merge — a pick adds, a half-typed last word is replaced. The edit
lands on the piece at the send (a failed write refuses with nothing
on the wire); Publish with a pending edit applies it first and flips
the post that send touched.

The one-line codec lives in PostFrontmatter (line-bounded; backslashes
and quotes escaped; a Set de-duplicates). Import keeps an imported
`category:` line — the writer's classification, unlike the micropub
bookkeeping keys.

Reviewed twice (two-axis during the build, finish-audit after): the
stale pending baseline after a failed step, the backslash round-trip,
and the publish targeting the caller's possibly-stale URL were found
and fixed before this commit. 39 of the 40 new or changed pins were
watched fail on their own guard. Rail 791/791; SwiftFormat and
SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, the devlog, and the swift wiki (text
completion is a whole-text contract).

Closes #207
2026-12-05 08:09:57 +01:00
AlexKucera 6aa31a419a feat(microblog): show Micro.blog publish status
The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
2026-12-04 17:45:35 +01:00
AlexKucera 6938826101 feat(microblog): add app token settings page and honest 5xx wording
The app 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. The new Settings → Micro.blog page
writes the same `MicropubTokenStore` slot the sheet reads, with a
status row read back from the Keychain after every write so a locked
keychain fails visibly instead of claiming "stored". The sheet now
names the stored token a send carries when its field is hidden.

Micro.blog's errors arrive as HTML pages, never Micropub JSON, so
`decodeFailure` fell through to a bare `HTTP 503` that said nothing
about whose side it was on. Any 5xx without a JSON description now
reads "unavailable on their side — retry in a few minutes"; a
described 5xx keeps its description and a 4xx keeps the bare status.
One decode covers create, publish, q=config, and media uploads.

Docs: AGENTS.md bullets, CHANGELOG [Unreleased] Added/Fixed, and the
devlog for this task plus the 0.1.2 release log.
2026-12-04 15:06:00 +01:00
AlexKucera 9aa0314564 feat(posts): reveal in Finder and copy path
Every piece row gains a Finder hand-off: Reveal in Finder opens
the piece's post.md selected, Copy Path puts its absolute path on
the clipboard (#205). One shared FinderHandOffButtons fragment in
the workspace chrome serves both menus - the library column
(between Move to Archive and the destructive Trash) and the
Archive pane (appended after Convert). Both act on
PostsModel.fileURL(for:), which resolves the piece through the
one PostStore.folder(of:home:) resolver against the watched Home
(never the scan snapshot) and answers nil when the piece is gone,
so a vanished row no-ops instead of revealing a stale path.

fileURL lives in PostsModelIdentity - the (Home, ID) file - not
the write rail: a pure read, nothing written, no strip. A
View-extension wrapper was tried and deleted as a Middle Man; the
menus mount the struct directly.

+3 tests (projects/ resolve, archive/ resolve, vanished -> nil),
flip-verified: bypassing the resolver reddens exactly the
vanished and archive pins (733/735). Rail 735/735; SwiftFormat
and SwiftLint clean. Reviews: standards + spec (two rounds), then
finish-audit (general, security, ponytail) - the audit added the
archive-root pin and fixed three stale headers. DOX: five
Museion/AGENTS bullets.

The release 0.1.2 log's rows still belong to another session and
stay in the working tree; INDEX and the AGENTS window here carry
only the #205 row.

Closes #205
2026-12-03 18:16:12 +01:00
AlexKucera dd8637e7c7 docs(devlog): #204 session log, INDEX row, window
The Fix Cards Jump log: the four grilling answers, the caret-rail
reuse decision, both review rounds, and the flip-verified pins.
INDEX and the AGENTS window carry the row; the rolling window
drops issue192's entry. The release 0.1.2 log's rows belong to
another session and stay in the working tree.
2026-12-03 17:48:55 +01:00
AlexKucera 97893147a6 feat(fix-cards): jump to the anchor
Jump on a Fix Card selects the anchor's span in the piece's
editor and makes the main window key (#204). 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: caretHint widens from a
(location, token) tuple to FixCardRevealRequest (SwiftLint
large_tuple), one shared token counter so a jump and a flip-back
can never collide, a zero-length range stays a bare caret and a
non-zero range selects. A jump leaves reading mode first
(reading = false, not exitReading, which stamps its own
zero-length hint), writes nothing, and re-fires per click.

The palette offers Jump on every non-stale card that still shows
an action row; stale anchors have nothing to land on. The
landing math is ProseTextView.landingSpan - a bare caret hops
past leading blanks, a span never does (a quote that IS the
leading blanks selects those blanks) - and appliedText now
routes through anchorRange so Apply and Jump share one
occurrence math.

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 - the Coordinator makes
tv.window key instead); a cursor record taken before the scroll.

+3 tests (anchorRange occurrence math with a UTF-16 fixture, the
model's reveal stamp, landingSpan), each flip-verified. Rail
732/732; SwiftFormat and SwiftLint clean. DOX: Museion/AGENTS,
MuseionTests/AGENTS, GLOSSARY gains Jump.
2026-12-03 17:48:55 +01:00
AlexKucera d183d735d7 chore: ignore .hermes directory 2026-12-03 16:44:34 +01:00
AlexKucera c959b67f14 chore(release): 0.1.2
Patch bump for a bug-fix cut (the release skill's rule):
MARKETING_VERSION 0.1.1 → 0.1.2 on every target and configuration,
CURRENT_PROJECT_VERSION unchanged. The changelog's former
[Unreleased] entry — the macOS 27.2 image-drop fix — moves under the
0.1.2 heading with a pointer to the notes. apex stays at 1.1.59:
GitHub's latest release is still the bundled version. Rail 729/729 on
this tree; SwiftFormat and SwiftLint clean.
2026-12-03 16:44:07 +01:00
AlexKucera 653ca69d1f build(release): 0.1.2 release notes
Human-readable notes for 0.1.2 in the 0.1.1 shape: the image-drop
fix told for a reader who never saw the ticket (the macOS 27.2 drag
routing in one paragraph, what the editor does now, the two
deliberate refusals), known limits unchanged from 0.1.0, install
copy, suite 729 at the tag.
2026-12-03 16:43:53 +01:00
AlexKucera 1b0c23ae5b docs(release): clarify patch vs minor version bump in release skill 2026-12-03 16:41:39 +01:00
AlexKucera 46e87e678c fix(editor): editor owns file drops on macOS 27.2
Dropping an image file on the prose editor pasted the file path
instead of ingesting it (#141 follow-up, unticketed; dogfood on
macOS 27.2.1). #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, so its stock
performDragOperation pasted the path and the window destination
never fired — the same for a markdown file dropped on the editor.

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; the outline rows bounce; text-only drags keep the stock
drop; the pasteboard probe is memoized per changeCount. A web URL
refuses with the type strip, a vanished file refuses as missing.

+9 tests (a real NSDraggingInfo mock drives the overrides; the
router's guest/lock/ingest branches pinned), all flip-verified.
Finish-audit: three reviewers; the text-drag regression and the
outline rows' identical exposure fixed, two pre-existing ceilings
deferred in the devlog. Rail 729/729, swiftformat 0/153, swiftlint 0.
2026-12-03 16:36:47 +01:00
AlexKucera 64a7eaa37e docs: add buy me a coffee announcement to release runbook and readme
The release skill (0.2.0 → 0.3.0) now ends with a Buy Me a Coffee
announcement left as a draft, mirroring the Micro.blog draft: step 12
fixes the INPUT (`create`, `mode: "draft"`, `audience: "public"`) and
delegates the browser mechanics to the `buymeacoffee-post` skill, done
only when `RESULT.mode` is "draft" and `RESULT.editUrl` is a real edit
URL. Ego Browser logged in to BMC joins the prerequisites, and the
verification section checks both drafts. Neither announcement is ever
published by the agent; both wait in Alexander's queues.

The README gains a "Support Museion" section linking the Buy Me a Coffee
page, since the app suite is the author's only income.
2026-12-03 12:22:56 +01:00
AlexKucera d5a515091a docs(devlog): release 0.1.1 session log; release skill gains the Micro.blog draft step
Session log for the 0.1.1 cut: apex 1.1.59 refreshed first, bump + tag
4a056f9, rail 720/720 with the freshness proof, notarized DMG sha256
e7add45a…, the go (push + Gitea release id 28, token-authenticated
download byte-identical), and the Micro.blog announcement left as a
draft. The gotchas table carries the six post-go traps: silent
tea releases create, Gitea's tag_name, no PyYAML on the system python,
security add-generic-password needing </dev/null, and an account with
no default microblog.

Release skill 0.2.0: new step 11 posts the announcement to Micro.blog as
post-status: draft — token in the login keychain under its own service
(never the app's production micropub slot), mp-destination mandatory
because q=config shows three blogs and none is default, mp-channel
default, q=source read-back before reporting. Intro, Prerequisites,
Quick Reference, Pitfalls and Verification updated to match; root
AGENTS.md Child DOX Index row mentions the draft step.
2026-12-03 08:02:06 +01:00
AlexKucera 4a056f9c53 chore(release): 0.1.1
Bug-fix release. MARKETING_VERSION 0.1.0 → 0.1.1 on all six
target/configuration pairs (CURRENT_PROJECT_VERSION stays at 1);
CHANGELOG gains the [0.1.1] - 2026-12-03 heading over the external-watch
normalizer fix that sat under [Unreleased], a Changed entry for the
apex 1.1.59 refresh, a fresh empty [Unreleased] above, and a pointer to
docs/releases/0.1.1.md. Rail at this tree: 720/720.
2026-12-03 07:47:43 +01:00
AlexKucera 570abb32c0 fix(reading): bump bundled apex to 1.1.59
The reading-mode renderer moves from 1.1.58 to the current upstream
release, packaged exactly as the 0.1.0 bundling (ADR-0011): the arm64
slice of the official universal release tarball, .sha256 verified against
the published checksum, the three CI/Homebrew rpaths stripped and
replaced by the single @executable_path/../Resources/libyaml.bundle,
Developer ID-signed with the hardened runtime. 1.1.59 still links
libyaml dynamically, so the vendored libyaml.bundle stays beside it;
--no-mixed-lists (ADR-0011's load-bearing flag) is still present. Proven
in a scratch Resources/ layout before the copy: --version reports
1.1.59 and a mixed bullet/ordered list renders as two lists.
2026-12-03 07:47:35 +01:00
AlexKucera bba4688dcb build(release): add the release skill and 0.1.1 release notes
.agents/skills/release/SKILL.md is the end-to-end runbook: refresh the
bundled apex renderer, bump, changelog heading, notes, the verify rail,
sliced commits, annotated tag, release.sh DMG, then a go-gated push and
Gitea release. Step one is now an unconditional apex refresh with the
full recipe inline (GitHub releases/latest → .sha256 → lipo arm64 →
strip every rpath → add the libyaml.bundle rpath → Developer ID sign
with the hardened runtime → prove it in a scratch Resources/ layout
before it touches the tree) instead of a "compare --version" check that
read as optional. Homebrew is a fallback only: its formula trailed the
GitHub release by a version on the 0.1.1 cut day. The skill bumps its
own version to 0.1.1.

docs/releases/0.1.1.md distills the CHANGELOG section for humans — the
false #67 conflict on BOM/CRLF guest files and the apex 1.1.59 refresh
— and becomes the Gitea release body. Root AGENTS.md gains the
.agents/skills/ Child DOX Index row.
2026-12-03 07:47:29 +01:00
AlexKucera 2d5073e421 Merge pull request 'museion/external-watch-compares-unnormalized-text: guest watch reads through the ONE shared external normalizer — false #67 conflict gone' (#203) from fix/external-watch-compares-unnormalized-text into main
CI / ci (push) Canceled after 0s
2026-12-03 07:36:51 +01:00
AlexKucera 07da076f41 merge main (3197b927) into fix/external-watch-compares-unnormalized-text (0.1.0 release wave)
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
Conflict resolution (keep-both, nothing from either side lost):
- CHANGELOG.md: the branch external-watch entry stays under [Unreleased]
  (unreleased fix, PR #203); the owner 0.1.0 release entries stay in [0.1.0].
- docs/devlog/INDEX.md: union of rows, newest-first — the 2026-12-01 release
  row above the 2026-11-30 external-watch row.

Purity: code dirs carry trunk 3197b927 hunks verbatim (diff-of-diffs cmp clean);
fix code and the branch devlog are byte-identical to reviewed 822b1b5.
2026-12-01 20:19:29 +01:00
AlexKucera 822b1b562e docs: brief-32 session log, INDEX row, changelog entry
CI / ci (pull_request) Canceled after 0s
CI / ci (push) Canceled after 0s
Devlog records the class-site re-derivation (post-side rescan
disclosed as representation-consistent with evidence), the helper
location decision (EditorSession.swift beside readDocument — no
ceiling pressure, no new file), and the RED/GREEN evidence chain.
2026-11-30 22:19:19 +01:00
AlexKucera 70dd47ed8c fix(editor): normalize the guest watch's disk read
The external guest's watch read disk raw while the session's text and
lastFlushedText came through readDocument's normalizing external
branch, so diskTextChanged saw a difference on every BOM/CRLF file and
raised conflictAlert on unchanged content — re-arming after each
sibling directory event and after either alert answer, blocking
departures and quit until the user's own flush rewrote the file
normalized (finding museion/external-watch-compares-unnormalized-text,
argus cycle-6; unticketed, brief-32).

Extract the external branch (BOM strip + CRLF->LF) into
EditorSession.readExternalDocument(at:) — one shared normalizer, two
callers: the open read (readDocument) and the watch's onEvent. The #67
compare is now normalized-to-normalized; what readDocument loads is
unchanged.
2026-11-30 22:17:13 +01:00
AlexKucera b69ddd3963 test(editor): pin the external watch's false 67 conflict
CI / ci (push) Canceled after 0s
The external guest's watch (PostsModelImports.startExternalWatch)
reads disk raw while the session's text/lastFlushedText came through
readDocument's normalizing external branch (BOM strip + CRLF->LF), so
diskTextChanged raised conflictAlert on unchanged BOM/CRLF files —
re-arming after every sibling directory event and after either alert
answer, blocking departures and quit (brief-32, argus cycle-6).

Three RED pins over the real watch closure
(externalWatcher.onEvent): no conflict on an unchanged BOM/CRLF
guest, no re-arm after yes-reload or keep-local, and the load-bearing
negative — a real foreign write still raises. Targeted rail at base:
11 executed / 8 passed / 3 failed (all three new pins), 164
SwiftCompile lines.
2026-11-30 22:15:58 +01:00
70 changed files with 5671 additions and 393 deletions

No files matched your search

+166
View File
@@ -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.
+1
View File
@@ -9,3 +9,4 @@ CLAUDE.md
.claude/
*.profraw
.secrets
.hermes
+24 -11
View File
@@ -115,6 +115,7 @@ When the user requests a durable behavior change, record it here or in the relev
| `MuseionTests/AGENTS.md` | Swift Testing unit suite (hosted in the app) |
| `MuseionUITests/` | XCUITest smoke test — single file, no child doc yet |
| `scripts/` | Verify rail + hooks + build/deploy/release-packaging scripts — contracts live in each script's header; full-test.sh is the sanctioned verify rail (#190), release.sh cuts the DMG from an already-bumped commit, no child doc |
| `.agents/skills/` | Project-local agent skills (cross-tool convention, committed) — `release/`: the end-to-end release runbook (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 |
| `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 |
@@ -145,12 +146,17 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- A bash function invoked before its definition no-ops (`command not found`) under `set -uo` without `-e` — hoist definitions above first use and guard rig verdicts by executed-check count, never the banner (#190)
- GitNexus `detect-changes` in this machine's multi-repo registry needs `--repo /absolute/path` — it aborts on ambiguity but rejects the `name (path)` label form it prints (#193)
- When splitting a file, re-derive each side's imports from symbol usage, never copy the old import block — Swift has no unused-import warning, so a stranded import (PostsPaneView's AppKit) survives lint and only a diff review catches it (#193)
- 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)
- A modal sheet hides every Cancel behind it — a one-shot turn it starts must be stoppable from inside the sheet (the trigger button doubles as Stop) or a hung turn wedges the sheet (#208)
### 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.
- 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)
- 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 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)
- 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)
@@ -162,10 +168,17 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
- A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147)
- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180)
- A rig hook that releases a HELD engine turn must poll for the PARK first — the caller-side flag (`runningPass`) flips before the one-shot engine even spawns; firing the release into that window false-fails under parallel-suite load (#181)
- `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)
- A flip that reddens NOTHING means the pin observes a downstream state another guard also holds — assert the guard's own output (`lastError` text), then re-flip; `runningPass == nil` held through the host's one-shot lock while the refusal under test was disabled (#208)
### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33)
- 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)
- Two readers of one frontmatter file must agree on where the block ends — a `split`-based read finds no block in a mixed-ending file while `parse` sees the key, and the `""` it answers rides the wire over a live post (#208)
## Session Logs
@@ -173,15 +186,15 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
| --- | --- |
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](docs/devlog/20261201-release-010-readme-notes-packaging_log.md) |
| 2026-11-23 | [20261123-home-repoint-retains-old-editor-target_log.md](docs/devlog/20261123-home-repoint-retains-old-editor-target_log.md) |
| 2026-11-19 | [20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md](docs/devlog/20261119-issue200-gate-quit-time-flushes-through-departure-gate_log.md) |
| 2026-11-17 | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](docs/devlog/20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) |
| 2026-11-17 | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](docs/devlog/20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) |
| 2026-11-17 | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](docs/devlog/20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) |
| 2026-11-17 | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](docs/devlog/20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) |
| 2026-11-17 | [20261117-issue190-full-test-verify-rail-pre-push-hook_log.md](docs/devlog/20261117-issue190-full-test-verify-rail-pre-push-hook_log.md) |
| 2026-11-16 | [20261116-failed-flush-discarded-on-document-switch_log.md](docs/devlog/20261116-failed-flush-discarded-on-document-switch_log.md) |
| 2026-11-13 | [20261113-fold-typing-budget-pin_log.md](docs/devlog/20261113-fold-typing-budget-pin_log.md) |
|------|-----|
| 2026-12-05 | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_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-12-04 | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) |
| 2026-12-04 | [20261204-microblog-5xx-wording-token-settings-page_log.md](20261204-microblog-5xx-wording-token-settings-page_log.md) |
| 2026-12-03 | [20261203-issue205-reveal-in-finder-copy-path_log.md](20261203-issue205-reveal-in-finder-copy-path_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-12-03 | [20261203-release-012-image-drop-fix_log.md](20261203-release-012-image-drop-fix_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-12-03 | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_log.md) |
| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) |
<!-- write-log: window-end -->
+38
View File
@@ -4,6 +4,44 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
### Added
- **publish:** Micro.blog summaries travel (#208) — the piece's `summary:` frontmatter line rides the send beside `category:`. A first send carries the summary when non-empty; a re-send replaces the post's summary only when the piece has the line (no line leaves whatever the blog has; an empty `summary:` clears it) — the same opt-in-by-key rule as categories, so a piece that never gained the line can't blank a summary set on Micro.blog itself. The publish sheet has a **Summary** field (line breaks become spaces, the sink is one line) and an **AI summary** button that drafts a first-person teaser from the open piece on a fresh one-shot engine on the chat profile; the reply fills the field for the writer to edit, nothing is written until the send stamps the line. The edit lands at the send like a category edit (a failed write refuses with nothing on the wire; Publish applies it first). While the turn runs the AI button is the Stop — the sheet is modal, so the pass bar's Cancel sits behind it — and a Pass or Blind Read that owns the one-shot rail disables the button with the reason on hover (and refuses from behind it). The AI button refuses while the piece can't be flushed or the engine isn't ready, with the field's text kept. Import keeps an imported `summary:` line. The field reads its text off the RAW frontmatter line, never through the lenient decode (which trims every edge quote — a teaser's closing `"why"` would vanish through that door), walking the block the way the lenient reader does so a mixed-ending file can't fuse the closing fence onto the last block line (which would have sent an empty summary over a live post's). +23 tests (the wire contract for create and update, the one-line codec incl. quote-bearing round-trips and the mixed-ending and unfenced-body reads, apply-at-send with the failed-write refusal, publish-applies-first, the end-to-end clear, the import keeping the line, the sheet field's trimmed-string pending-edit rule, the prompt and reply cleanup, and the model's summarize turn over the scripted engine incl. refusal, rail-busy refusal, and cancel); each guard was watched fail on its own pin. Suite 814
- **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
- **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).
+24
View File
@@ -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.
_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**:
Closing a Fix Card because the writer rewrote the span — the demonstration lane's terminal, beside Apply and Skip. Records nothing.
_Avoid_: applied, complete
@@ -152,3 +156,23 @@ _Avoid_: permission mode
**Provenance**:
The origin record carried by a Fix Card or Learning (piece, date, engine).
_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
### Summary
A Micro.blog post summary carried as the Piece's one-line `summary:` frontmatter scalar — a first-person teaser that entices the reader to read the full piece, typed by the writer or drafted by the AI summary button (a one-shot chat-profile engine; the reply fills the field, the writer edits). One line by construction (line breaks become spaces); a value with a quote at either edge renders quoted so the lenient read never trims it. Travels like Category: a create carries it when non-empty, a re-send replaces it only when the line exists, an empty value clears the post's. Import keeps it — the writer's words, unlike the Publish Record keys.
_Avoid_: excerpt (the body is never cut), description, teaser (the field is the summary wherever it came from)
+6 -6
View File
@@ -424,7 +424,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -461,7 +461,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.Museion;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -484,7 +484,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -506,7 +506,7 @@
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -526,7 +526,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -546,7 +546,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 0.1.0;
MARKETING_VERSION = 0.1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
+20 -17
View File
@@ -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`.
- 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.
- 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`.
## 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/`.
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller).
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`.
- `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`. 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).
- `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.
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `![alt](assets/…)` builder.
- `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/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` 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`), `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). #208 the one-line `summary:` scalar: `summaryValue(_:)` renders it (every run of whitespace — a newline included — collapses to one space, control characters drop; a value holding a quote or backslash renders QUOTED with both escaped — the category codec's own escape, ONE grammar for both keys) and `summary(inText:)` reads it back off the RAW line, never through `parse`: the lenient decode trims EVERY edge quote, so a teaser's closing `"why"` would vanish through that door — the wire (`updateRememberedOrCreate`, `openPieceSummary`) and the sheet's settle all read the raw line. The read walks the block the way `parse` does (past the opening fence to the next `---`) — NOT via `split`, whose closing-fence check a mixed-ending file defeats (a stray `\r` fuses `---` onto the last block line: `parse` sees the key, `split` sees no block) — and cuts a fused `\r\n---` tail off the value; a BODY line named `summary:` never claims the key (no fence, no block). Empty/blank/absent = `""` — the field's settled empty.
- `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 `![alt](assets/…)` builder. `stampMicropub` / `forgetMicropub` — the frontmatter-only micropub stamps (`micropub_url`, the #206 publish record `micropub_published`, #207 the `category:` line, and #208 the `summary:` line a sheet edit writes at the send — `[]` renders `category: []`, a cleared summary renders `summary:` empty; 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).
- `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.
@@ -40,18 +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).
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- `SummaryPrompt.swift` — #208: the AI post summary's prompt vocabulary (pure) — `prompt(title:body:)` carries the Title and body inline and asks for a first-person teaser that entices the reader to read the full piece; `cleaned(_:)` is the reply as the field's text (trimmed, ONE leading `Summary:` label dropped — colon required, so prose opening with the word keeps it; one pair of surrounding quotes stripped; then the codec's round-trip — `summaryValue` → the raw-line read — so the FIELD shows exactly the text the wire will carry, one line, no escapes). The model half is `PostsModelMicropubSummary.swift`; the summary's HOME is the frontmatter `summary:` line the SEND stamps — this half only drafts text for the publish sheet's field.
- 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); #208 the piece's `summary:` line travels the same way — a create carries `properties.summary` ONLY when non-empty, a re-send carries `summary` in `replace` only when the piece has the line (opt-in by key, `""` is sent and CLEARS the post's summary); 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 `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form; `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). #208 the sheet's Summary field — the same discipline over the one-line `summary:` scalar: a multi-line `TextEditor` with an `AI summary` button (a bordered small control in the label row) that runs `posts.summarize(mentor:)` — the sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own; the ONE construction site) and the reply fills the field for the writer to edit; the button and the field hold still while the turn runs; the button is ALSO disabled while a Pass or Blind Read owns the one-shot rail, with the hover reason saying so (the pass bar's disabled-with-reason idiom — the guard behind it is `guardOpenPieceRun`), and a refusal shows inline with the field's text kept. The sheet is MODAL — the pass bar's Cancel sits behind it — so while this sheet's own summary turn runs the AI button IS the Stop (the spinner stays clickable, `cancelPass` ends the turn on the shared rail); `summarizing` is the MODEL's flag (`PostsModel.summarizing`, the third rider beside `runningPass`/`runningBlindRead`), read by the sheet, the pass bar's Cancel visibility, and `cancelPass`/`guardOpenPieceRun` through the ONE `oneShotRailBusy` predicate — a fourth rider joins the predicate and every site follows. The edit-for-send test is `MicropubSummaryField.pendingSummary` — a STRING compare on trimmed text, so whiLine truncated
- `PostsModelMicropubSummary.swift` — #208: the AI summary's model half — `summarize(mentor:)`: the shared open-piece guard rail (`guardOpenPieceRun`, the brief-28 Home identity) → flush-first → ONE disk read feeds the prompt → `mentor.runSummary` on a fresh one-shot chat-profile engine → `SummaryPrompt.cleaned`. Returns the text or nil with `lastError` naming the blocker; a stale guard refusal never survives into the strip (`lastError` cleared once the guards pass). Writes NOTHING — the text is the publish sheet's to place, and the SEND stamps the `summary:` line.
- `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; #208 a non-nil `summary:` edit lands the same way, sanitized through `summaryValue`) → ONE disk read serves the wire fields, the categories, the summary, and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update (`stampCategories` + `stampSummary` + `updateRememberedOrCreate` are its steps); `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), #207/#208 runs `micropubSend` FIRST when `categories:` or `summary:` 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.
- `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`).
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
- `OutlineRowTextView.swift` — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, `sizeThatFits` floors at 21 (no focus jump).
- Editor core — `ProsePresenter.swift` (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). `EditorSession.swift` — per-document session: `SessionTarget` (post | external file), ~1 s debounce → `flush` (⌘S / selection change / quit also flush); externals write in place with NO sidecar; `loadFailed` never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; `adoptText` = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar `.museion-state.json` in the piece folder, written separately (a failed sidecar is not a failed save). `PostEditorView`/`ProseTextView` — plain NSTextView representable, loads keyed by `loadGeneration` (never per keystroke); spellcheck off by default (markdown on disk carries the spelling).
- `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).
- `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).
- 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.
- 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.
@@ -77,7 +80,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## 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).
- `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).
- `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.
@@ -85,8 +88,8 @@ 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.
- `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).
- `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).
- `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); #208 the AI post summary rides the same rail (`runSummary` — chat profile, label `Summary · <piece>`, the reply read back through `draftCandidateText`; one-shot exclusivity unchanged: a summary refuses while a Pass or Blind Read runs); 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; #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).
## Work Guidance
+3
View File
@@ -134,6 +134,9 @@ struct ArchivePaneView: View {
model.stageConversion(post)
}
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post)
}
}
}
+13 -2
View File
@@ -157,15 +157,26 @@ final class EditorSession {
private static func readDocument(_ target: SessionTarget) -> String? {
switch target {
case let .post(id, home):
return PostStore.readBody(id: id, home: home)
PostStore.readBody(id: id, home: home)
case let .externalFile(url):
readExternalDocument(at: url)
}
}
/// #67/brief-32: the ONE external-target disk read — raw UTF-8, BOM
/// stripped, CRLF normalized to LF. Every reader of an external file's
/// bytes goes through here (the open read above, the guest watch in
/// PostsModelImports, Yes-reload, keep-local), so the #67 compare is
/// always normalized-to-normalized: the watch used to read raw and
/// raised a false conflict on every directory event over an unchanged
/// BOM/CRLF file.
static func readExternalDocument(at url: URL) -> String? {
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") {
text.removeFirst()
}
return text.replacingOccurrences(of: "\r\n", with: "\n")
}
}
/// Target-aware write: posts → `PostStore.overwrite` (+ sidecar);
/// external → the whole text, in place, no sidecar (#93).
+89
View File
@@ -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)?) {}
}
+16 -6
View File
@@ -153,6 +153,20 @@ nonisolated enum FixCardStore {
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)
/// #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
/// patch. The caller owns the ask and the file write.
static func appliedText(of card: StoredFixCard, in text: String) -> String? {
guard card.lane == .mechanical,
card.anchor.occurrence >= 1,
!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)
guard card.lane == .mechanical, let range = anchorRange(of: card, in: text) else { return nil }
return (text as NSString).replacingCharacters(in: range, with: card.fix)
}
// MARK: - Submit
+20 -11
View File
@@ -3,8 +3,8 @@
// Museion
//
// #25 (S3.3): the Fix Cards palette becomes the card work surface. Open
// cards lead with their actions — Apply (a blocking ask), Skip, Done —
// closed cards dim behind them. No apply-all, no batch, nothing applies
// cards lead with their actions — Apply (a blocking ask), Skip, Done,
// 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.
//
@@ -106,9 +106,10 @@ private struct CardList: View {
/// One card: pattern title, problem + fix body, rank · pass · lane ·
/// emitter mono meta (ADR-0006). A stale anchor reads distinct — orange —
/// and never offers Apply. Closed cards dim, record their status in the
/// meta, and offer no actions. The blocking Apply ask is the ROW's own
/// sheet: one card asks at a time, by construction (S3.3).
/// and never offers Apply or Jump (#204). Closed cards dim, record their
/// status in the meta, and keep only Promote and Jump — a closed card that
/// 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 {
let card: FixCardStore.StoredFixCard
@Environment(AppGateState.self) private var gate
@@ -134,14 +135,22 @@ private struct CardRow: View {
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(stale ? .orange : DesignTokens.muted)
if open || card.promotedAt == nil {
// The actions this card offers (#25 S3.3, #26 S4.1):
// mechanical + valid → Apply (the blocking ask) and Skip;
// demonstration → Done and Skip (never 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
// The actions this card offers (#25 S3.3, #26 S4.1, #204):
// Jump on every card whose anchor still resolves (closed cards
// included — the span is still a real place; stale anchors offer
// none — nothing to land on); mechanical + valid → Apply (the
// blocking ask) and Skip; demonstration → Done and Skip (never
// 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).
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 card.lane == .mechanical {
Button("Apply") { asking = true }
+20 -4
View File
@@ -9,8 +9,10 @@
import SwiftUI
/// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// One post row per the export: title + a mono-11 meta line — origin, or
/// (#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
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// 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).
// r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge.
Text(post.origin.rawValue)
// #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))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
.help(post.origin.rawValue)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
@@ -89,6 +95,16 @@ struct LibraryPostRow: View {
// help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
.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: ", ")
}
}
+1 -1
View File
@@ -525,7 +525,7 @@ private struct PassBarView: View {
/// #122: the Blind Read trigger sits beside Run — advisory-only.
private var actions: some View {
HStack(spacing: 7) {
if posts?.runningPass != nil || posts?.runningBlindRead == true {
if posts?.oneShotRailBusy == true {
MonoButton(title: "Cancel", style: .outline) {
posts?.cancelPass(mentor: model)
}
+21 -4
View File
@@ -912,14 +912,15 @@ extension MentorSessionModel {
return outcome
}
/// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read): a
/// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read,
/// #208 the AI summary): a
/// fresh engine on `profile` via the host (spawn → slim handshake →
/// body → teardown — never resident past the body's end, even on thrown
/// errors), a transient unrostered transcript, one turn. Same lifecycles
/// for both riders — the cancel rail (stopStreaming) and the read-only
/// for all three riders — the cancel rail (stopStreaming) and the read-only
/// composer guard key on the transient entry and need no per-rider
/// branches. `name` ("Pass 1" / "Blind Read") composes the entry label —
/// callers can't pass a title-inconsistent one.
/// branches. `name` ("Pass 1" / "Blind Read" / "Summary") composes the
/// entry label — callers can't pass a title-inconsistent one.
private func runOneShot(profile: String, name: String, prompt: String, pieceTitle: String) async -> TurnOutcome {
guard phase.isReady, !isStreaming, !host.isOneShotRunning, host.binaryPath != nil else { return .failed }
let label = "\(name) · \(pieceTitle)"
@@ -1276,4 +1277,20 @@ extension MentorSessionModel {
}
return nil
}
/// #208: the AI summary — a fresh one-shot engine on the museion
/// profile drafts a teaser from the prompt; the reply text comes
/// back to the caller (nil when the turn did not end normally or
/// said nothing). Never rostered, never saved — the caller owns
/// where the text goes (the publish sheet's field).
func runSummary(prompt: String, pieceTitle: String) async -> String? {
let outcome = await runOneShot(
profile: ProfileSurface.chat.profileName,
name: "Summary",
prompt: prompt,
pieceTitle: pieceTitle,
)
guard case let .ended(stopReason) = outcome, stopReason == "end_turn" else { return nil }
return Self.draftCandidateText(in: transcripts[Self.passTranscriptKey]?.rows ?? [])
}
}
+439 -82
View File
@@ -6,12 +6,26 @@
// Two-step publish (G2/G11): create with `post-status: draft`, review,
// then `action=update` flips the draft to published. Bearer app-token
// auth — no OAuth in v1; the token lives in the Keychain, entered
// once. Frontmatter `category:` is permitted but inert (v1 never
// sends it — the request carries name + content only).
// once. #207: the piece's `category:` list TRAVELS — a create carries
// 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
// The blog's own list for the sheet's suggestions: MicropubCategories.swift.
// #208: the piece's `summary:` line TRAVELS the same way — a create
// carries it when non-empty, a re-send carries it in `replace` only
// when the piece has the line ("" clears). The AI half that drafts it
// rides a one-shot engine (SummaryPrompt.swift / PostsModelMicropubSummary.swift).
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// 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,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -32,9 +46,17 @@ nonisolated enum Micropub {
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
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
/// No open saved piece (model guard) — nothing went out.
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 requestFailed(status: Int, detail: String)
case unreachable(String)
@@ -52,57 +74,100 @@ nonisolated enum Micropub {
// 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)
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: object, options: [.sortedKeys])
return request
}
static func makeDraftRequest(title: String, body: String, token: String, categories: [String] = [], summary: String = "") -> URLRequest {
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
// illustration refs, which REWRITE to their uploaded URLs on
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// (GLOSSARY: any carve-out rewrites on the WIRE only — the piece
// on disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"type": ["h-entry"],
"properties": [
// #207: the categories travel — naming one Micro.blog doesn't
// know creates it there; no list, no key.
// #208: the summary travels when non-empty.
var properties: [String: Any] = [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], options: [.sortedKeys])
return request
]
if !categories.isEmpty {
properties["category"] = categories
}
if !summary.isEmpty {
properties["summary"] = [summary]
}
return jsonPost(["type": ["h-entry"], "properties": properties], token: token)
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
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: [
jsonPost([
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
], token: token)
}
// 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.
/// #208: `summary` opts the summary into `replace` the same way —
/// a string (even empty: it clears it) is sent as written; nil
/// leaves whatever the post has.
static func makeUpdateRequest(
url: String,
title: String,
body: String,
token: String,
categories: [String]? = nil,
summary: String? = nil,
) -> URLRequest {
var replace: [String: Any] = [
"name": [title],
"content": [body],
]
if let categories {
replace["category"] = categories
}
if let summary {
replace["summary"] = [summary]
}
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
/// 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(
title: String,
body: String,
token: String,
categories: [String] = [],
summary: String = "",
transport: Transport = urlSessionTransport,
) 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, summary: summary)
return await run(request, transport: transport, decodeDraftURL: true)
}
/// Step 2: publish the draft — flip its post-status. Needs the
@@ -116,6 +181,30 @@ nonisolated enum Micropub {
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. #208:
/// `summary` non-nil also replaces the post's summary.
static func update(
url: String,
title: String,
body: String,
token: String,
categories: [String]? = nil,
summary: String? = nil,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let request = makeUpdateRequest(url: url, title: title, body: body, token: token, categories: categories, summary: summary)
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
/// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create
@@ -152,10 +241,12 @@ nonisolated enum Micropub {
/// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
/// Format-only by design — ponytail: a well-formed foreign URL still
/// passes (the label shows its full text); host-allowlist when v2's
/// q=config surface names the blog's real domains.
/// and `Post.scan`'s read-back. Format-only by design — ownership is
/// settled upstream, not here: the import boundary drops the micropub
/// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
/// 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 {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
@@ -166,15 +257,38 @@ nonisolated enum Micropub {
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
/// 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 {
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 {
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 +346,15 @@ nonisolated enum MicropubTokenStore {
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
// MARK: - #33 (S6.1) / #206 Micropub draft → publish
extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// as a draft (h=entry, name = Title, markdown content, post-status
/// draft — category frontmatter never travels). runPass's guard set
/// minus the engine gates (no engine involved); flush-first so the
/// wire carries the editor's latest. On success the piece remembers
/// the draft URL (`micropub_url` stamp) — a stamp failure never
/// 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.
/// The OPEN saved library piece as the micropub pair (id, Home) —
/// the identity guard both publish steps share. brief-28: the open
/// session must target THIS library's selected piece; the wire and
/// every stamp below act on the piece actually sent (Home, ID),
/// never the current Home's same-slug file. Nil = nothing to send.
private var openMicropubPiece: (id: String, home: URL)? {
guard let session,
let id = session.postID,
let home = watchedHome,
@@ -263,18 +363,85 @@ extension PostsModel {
draft == nil,
externalSession == 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))
}
/// #208: the open piece's summary as it is on DISK — what the
/// publish sheet's field syncs to (the Categories discipline,
/// never the scan snapshot). The raw line read: the lenient parse
/// would trim a teaser's closing quote. No open saved piece or no
/// line → "".
func openPieceSummary() -> 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.summary(inText: 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.
/// #208: `summary` rides the same posture — nil = no edit, the
/// piece's line is used as written; non-nil = that text is written
/// to the piece FIRST (sanitized to one line), after the flush and
/// before the one disk read. A 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,
summary: String? = nil,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
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.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
if let refused = stampCategories(categories, piece: piece) {
return refused
}
if let refused = stampSummary(summary, 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
// 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,
// GLOSSARY). No scan dependency: the list can lag the open piece.
guard let dir = PostStore.folder(of: id, home: home),
// GLOSSARY), the remembered URL, the categories, and the summary.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
@@ -295,25 +462,176 @@ extension PostsModel {
return outcome
}
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
body: wireBody,
return await updateRememberedOrCreate(
raw: raw,
wireBody: wireBody,
piece: piece,
token: token,
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
}
/// #208: the sheet's summary edit lands on the piece HERE — the
/// Categories posture (after the flush, before the one read that
/// feeds the wire). nil is no edit. The refusal when the line
/// cannot land: the send stops here and nothing goes out.
private func stampSummary(_ summary: String?, piece: (id: String, home: URL)) -> Micropub.Outcome? {
guard let summary else { return nil }
do {
try PostStore.stampMicropub(piece.id, home: piece.home, [("summary", PostFrontmatter.summaryValue(summary))])
} catch {
return .refused("Couldn't save this piece's summary — 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.
/// #208: the summary rides the same rule — a create carries it
/// when non-empty; an update carries `summary` only when the piece
/// HAS the line (opt-in by key, `""` clears, no line leaves the
/// blog's). Read off the raw line (`summary(inText:)`): the lenient
/// parse trims a closing quote the teaser may own.
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)
let summaryLine = matter["summary"] != nil
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,
summary: summaryLine ? PostFrontmatter.summary(inText: raw) : 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),
summary: PostFrontmatter.summary(inText: raw),
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. 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 (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)
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
}
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.
/// #208: `summary` rides the same applies-first posture.
func micropubPublish(
url: String,
token: String,
categories: [String]? = nil,
summary: 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 categories != nil || summary != nil {
switch await micropubSend(token: token, categories: categories, summary: summary, 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
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
@@ -342,11 +660,6 @@ extension PostsModel {
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
@@ -361,8 +674,36 @@ extension PostsModel {
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
}
/// 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
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
@@ -370,8 +711,9 @@ extension PostsModel {
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
// The `where` skips a later payload with the same bytes as one
// uploaded earlier in this batch.
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
@@ -382,11 +724,26 @@ extension PostsModel {
)
switch outcome {
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):
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
}
}
+48
View File
@@ -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 }
}
}
+47 -1
View File
@@ -16,8 +16,11 @@
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`;
// `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
nonisolated extension Micropub {
@@ -105,8 +108,14 @@ nonisolated extension Micropub {
// MARK: q=config (hop 1)
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)!
components.queryItems = [URLQueryItem(name: "q", value: "config")]
components.queryItems = [URLQueryItem(name: "q", value: q)]
var request = URLRequest(url: components.url!)
request.timeoutInterval = 30
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
/// and the rewrite can never drift). The alt class is single-line
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
+467 -56
View File
@@ -7,34 +7,173 @@
// sheet owns the whole two-step flow over the OPEN piece: Send as
// Draft (h=entry, name, markdown content) → review on Micro.blog →
// Publish (the post-status update against the piece's remembered
// draft URL). The app token is entered here ONCE and lives in the
// Keychain (G11; re-offered only on an auth failure). Refusals show
// draft URL). The app token is entered here when none is saved and
// 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).
// #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).
// #208: a Summary field — the piece's `summary:` scalar, typed or
// drafted by the `AI summary` button (a one-shot chat-profile
// engine; the reply fills the field, the writer edits). Same
// discipline as Categories: the edit lands AT THE SEND, the field
// syncs on open/forget and settles from disk after a send. While the
// turn runs the button is the sheet's own Stop (the sheet is modal).
//
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
}
}
/// #208: the publish sheet's Summary field — its pure rules. The
/// edit-for-send test is a STRING compare (not a list), so a
/// trailing-space difference is not an edit and equal empties stay
/// nil (a piece without a line never gains an empty key).
nonisolated enum MicropubSummaryField {
/// The sheet's edit for the model: nil when the field IS the
/// settled one (both trimmed — whitespace alone is not an edit);
/// else the field's text ("" = cleared — the model writes
/// `summary:` empty and the re-send clears the post's).
static func pendingSummary(field: String, settled: String) -> String? {
let f = field.trimmingCharacters(in: .whitespacesAndNewlines)
return f == settled.trimmingCharacters(in: .whitespacesAndNewlines) ? nil : f
}
}
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let mentor: MentorSessionModel
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
/// Never sent — nothing on Micro.blog yet.
case idle
case drafting
/// A draft is on Micro.blog, not published (fresh or remembered).
case drafted
case updating
case updated
case publishing
/// The publish record — this session's Publish, or the piece's stamp.
case published
}
@State private var phase: Phase = .idle
/// The draft URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (a draft sent in an earlier session).
@State private var draftURL: String?
/// The post URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (sent in an earlier session) — a draft's
/// 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 refusal: String?
@State private var tokenField = ""
@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
/// #208: the Summary field as typed, and the text it rests on (the
/// disk read on open, or a successful send's canonical form — the
/// pending-edit baseline).
@State private var summaryField = ""
@State private var settledSummaryField = ""
/// Token entry shows when none is saved — or again after an auth
/// failure (the entered-once token can be replaced, never a dead end).
@@ -42,16 +181,89 @@ struct MicropubPublishSheet: View {
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)
}
/// #208: the Summary field's edit for the send — nil when nothing changed.
private var pendingSummary: String? {
MicropubSummaryField.pendingSummary(field: summaryField, settled: settledSummaryField)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?")
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
.font(.headline)
Text(pieceTitle)
.font(.callout.weight(.semibold))
.lineLimit(2)
if phase == .idle {
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.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)
}
// #208: the Summary field, in every phase — a send is possible in all of them.
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 6) {
Text("Summary")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
Button {
draftSummary()
} label: {
if summarizing {
ProgressView().controlSize(.small)
} else {
Text("AI summary")
}
}
.buttonStyle(.bordered)
.controlSize(.small)
// Disabled-with-reason (the pass bar's idiom) while ANOTHER
// rider owns the rail or a send runs — but never while this
// sheet's own summary turn runs: the spinner is the Stop.
.disabled(busy || (!summarizing && posts.oneShotRailBusy))
.help(summarizing ? "Stop the summary turn." : summaryButtonHelp)
.accessibilityLabel(summarizing ? "Stop summary" : "AI summary")
}
TextEditor(text: $summaryField)
.font(.system(size: 11, design: DesignTokens.mono))
.frame(height: 72)
.scrollContentBackground(.hidden)
.background(RoundedRectangle(cornerRadius: 6).stroke(DesignTokens.muted.opacity(0.35)))
.disabled(busy || posts.summarizing)
.accessibilityLabel("Summary")
Text("Shown by Micro.blog in feeds and cross-posts. One or two sentences, first person — line breaks become spaces.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if showsTokenField {
SecureField("App token", text: $tokenField)
@@ -60,20 +272,26 @@ struct MicropubPublishSheet: View {
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
.font(.system(size: 11, design: DesignTokens.mono))
.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()
}
if let url = statusURL {
// The draft lives on Micro.blog — the preview link goes
// there for review; once published it's the post itself.
if let label = statusLabel {
// A published piece's link is the post itself; a draft's
// is its review page.
VStack(alignment: .leading, spacing: 4) {
Text(phase == .published ? "Published" : "Draft on Micro.blog")
Text(label)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) {
if let link = statusLink {
Link(destination: link) {
Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono))
@@ -90,24 +308,25 @@ struct MicropubPublishSheet: View {
}
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() }
.buttonStyle(.borderedProminent)
} else {
Button("Publish") { publish() }
.buttonStyle(.borderedProminent)
.disabled(draftURL == nil || phase == .drafting || phase == .publishing)
if draftURL != nil {
// The piece changed since the draft — a fresh send
// replaces it (and the remembered URL).
Button("Send Again") { sendDraft() }
.disabled(postURL == nil || busy)
// The piece changed since the draft — a re-send
// updates that same draft (never a second post).
Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
} else {
Button("Send as Draft") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
}
.disabled(busy)
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
@@ -115,19 +334,23 @@ struct MicropubPublishSheet: View {
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(16)
.frame(width: 340, alignment: .leading)
.frame(width: 420, alignment: .leading)
.onAppear {
// A draft sent in an earlier session is still publishable:
// the piece remembers its URL.
if draftURL == nil, let id = posts.session?.postID {
if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL {
draftURL = remembered
}
}
// A piece sent in an earlier session still has its record:
// the remembered URL, and (#206) its publish stamp.
guard postURL == nil, let id = posts.session?.postID,
let post = posts.posts.first(where: { $0.id == id })
else { return }
postURL = post.micropubURL
publishedAt = post.micropubPublished
phase = settledPhase
syncFieldFromDisk()
syncSummaryFromDisk()
loadSuggestions()
}
}
// MARK: Steps
// MARK: Status
/// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback).
@@ -135,9 +358,48 @@ struct MicropubPublishSheet: View {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
}
private var statusURL: String? {
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil
private var statusLabel: String? {
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
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
@@ -153,29 +415,49 @@ struct MicropubPublishSheet: View {
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()
syncSettledSummaryFromDisk()
}
/// 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 {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .drafting
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSendDraft(token: token) {
switch await posts.micropubSend(token: token, categories: pendingCategories, summary: pendingSummary) {
case let .drafted(url, preview):
draftURL = url
postURL = url
previewURL = preview
phase = .drafted
sendLanded()
case let .updated(url):
postURL = url
phase = .updated
sendLanded()
case let .authFailed(detail):
reentry = true // the entered-once token may be wrong
refusal = "Micro.blog rejected the token: \(detail)"
phase = draftURL == nil ? .idle : .drafted
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = draftURL == nil ? .idle : .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = draftURL == nil ? .idle : .drafted
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .published:
break
}
@@ -183,29 +465,158 @@ struct MicropubPublishSheet: View {
}
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."
return
}
refusal = nil
phase = .publishing
Task {
switch await Micropub.publish(url: url, token: token) {
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories, summary: pendingSummary) {
case .published:
publishedAt = Date()
phase = .published
settle()
syncSummaryFromDisk()
case let .authFailed(detail):
reentry = true
refusal = "Micro.blog rejected the token: \(detail)"
phase = .drafted
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = .drafted
case .drafted:
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .drafted, .updated:
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()
syncSummaryFromDisk()
}
// 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 fields settle, 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()
syncSummaryFromDisk()
if !suggestionsLoaded {
loadSuggestions()
}
}
// MARK: Summary (#208)
/// The piece's `summary:` line as it is on DISK (the model's read).
private var diskSummaryText: String {
posts.openPieceSummary()
}
/// The field AND its baseline take the disk's line (on open, after a forget).
private func syncSummaryFromDisk() {
summaryField = diskSummaryText
settledSummaryField = summaryField
}
/// Only the BASELINE follows the disk (a failed step — the send
/// writes the line before the wire; the Categories discipline).
private func syncSettledSummaryFromDisk() {
settledSummaryField = diskSummaryText
}
/// #208: the AI button's hover reason — the disabled state says why
/// (the pass bar's idiom).
private var summaryButtonHelp: String {
posts.oneShotRailBusy
? "A Pass, Blind Read, or summary is running — the engine is busy."
: "Drafts a first-person teaser from the piece — edit it before sending."
}
/// #208: the AI draft — a fresh one-shot chat-profile engine reads
/// the piece and the reply fills the field for the writer to edit.
/// A refusal shows inline (the field keeps its text). While the turn
/// runs the button is the sheet's OWN Stop (the sheet is modal — the
/// pass bar's Cancel sits behind it): `cancelPass` ends the turn on
/// the shared rail, and `summarizing` follows the model's flag so a
/// stop from anywhere clears the spinner.
private var summarizing: Bool {
posts.summarizing
}
private func draftSummary() {
guard !summarizing else {
// The spinner IS the stop: a hung engine must not hold the
// sheet.
posts.cancelPass(mentor: mentor)
return
}
refusal = nil
Task {
// The model owns the flag; the reply fills the field, a
// refusal lands inline.
if let text = await posts.summarize(mentor: mentor) {
summaryField = text
} else {
refusal = posts.lastError ?? "The engine didn't return a summary — try again."
}
}
}
}
+20 -5
View File
@@ -16,11 +16,9 @@ import SwiftUI
@MainActor
@Observable
final class AppGateState {
/// #141: the live prose text view — the window-level drop destination
/// (the ONLY destination that ever fires; nested editor-level SwiftUI
/// targets are never consulted, and AppKit views registered for file
/// drags are starved by it — field-verified 2026-11-02) routes image
/// drops to the editor through this handle.
/// #141: the live prose text view — the window-level SwiftUI destination
/// (drops landing OUTSIDE the editor) reaches it through this handle;
/// routing lives in `routeFileDrop`.
let proseDrop = ProseDropBridge()
let gateModel = EngineGateModel()
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
+5 -2
View File
@@ -127,8 +127,11 @@ struct OutlineRowTextView: NSViewRepresentable {
}
}
/// The row NSTextView: structural key interception.
final class RowTextView: NSTextView {
/// The row NSTextView: structural key interception. `FileDropTextView`
/// 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?
override func keyDown(with event: NSEvent) {
+86 -35
View File
@@ -47,9 +47,10 @@ struct PostEditorView: View {
/// #68: reading is a transient act of inspection — no persistence; a
/// fresh open always lands in editing.
@State private var reading = false
/// Flip-back caret (#68): source location + a token so repeated flips to
/// the same location re-apply. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: (location: Int, token: Int)?
/// Flip-back caret (#68) and #204 jump span: a zero-length range is a
/// bare caret landing, a non-zero range selects the anchor; the token
/// re-applies repeats. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: FixCardRevealRequest?
@State private var flipToken = 0
/// Reading scroll state (#68 mapping): entry caret + live top block.
@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 {
if draftMirror.isEmpty {
draftMirror = draftText ?? ""
@@ -182,6 +199,7 @@ struct PostEditorView: View {
focused: gate.isFocused,
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
@@ -196,6 +214,7 @@ struct PostEditorView: View {
},
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
@@ -218,7 +237,7 @@ struct PostEditorView: View {
flipToken += 1
// Toggle-back maps the reading scroll back (top visible block);
// 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
}
@@ -338,8 +357,8 @@ private struct SaveStateDot: View {
// MARK: - TextKit2 surface (the lifted spike pane)
/// #141: the SwiftUI drop target's handle down to the live prose text
/// view (weak — dies with the editor surface).
/// #141: the window-level SwiftUI destination's handle down to the live
/// prose text view (weak — dies with the editor surface).
@MainActor
final class ProseDropBridge {
weak var textView: ProseListTextView?
@@ -348,8 +367,9 @@ final class ProseDropBridge {
/// NSTextView in a scroll view; attributes are presentation-only over a plain
/// store. Session mode: edits → session.edit (debounce), cursor → session,
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
/// #71: `caretHint` (location + token) lands the caret after a flip back
/// from reading — applied once per token, after any generation load.
/// #71/#204: `caretHint` (range + token) lands a bare caret after a flip
/// back from reading or SELECTS a card's anchor span after a Jump — applied
/// once per token, after any generation load.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
@@ -361,22 +381,24 @@ struct ProseTextView: NSViewRepresentable {
var spellChecking = false
/// #21: focus mode — the text ground joins the workspace background.
var focused = false
var caretHint: (location: Int, token: Int)?
var caretHint: FixCardRevealRequest?
/// #141: the piece folder dropped images ingest into — saved posts
/// only (drafts have no folder until first save; the external guest
/// isn't a piece). Nil = image drags refuse loudly.
var ingestFolder: URL?
/// #141: the drop bridge — the WINDOW-level SwiftUI drop target
/// reaches this text view through it (app-scoped, passed down from
/// the gate at both call sites — never optional).
/// #141: the window-level SwiftUI destination's handle to the live
/// view (drops landing OUTSIDE the editor); the gate's router for drops
/// landing ON it — both handed down from the gate at both call sites.
var dropBridge: ProseDropBridge
var routeDrop: ([URL]) -> Bool
init(
session: EditorSession,
spellChecking: Bool = false,
focused: Bool = false,
caretHint: (location: Int, token: Int)? = nil,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.session = session
@@ -386,6 +408,7 @@ struct ProseTextView: NSViewRepresentable {
self.onTextChange = onTextChange
ingestFolder = session.postID != nil ? session.folderURL : nil
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
init(
@@ -393,8 +416,9 @@ struct ProseTextView: NSViewRepresentable {
spellChecking: Bool = false,
focused: Bool = false,
onEdit: @escaping (String) -> Void,
caretHint: (location: Int, token: Int)? = nil,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.draft = draft
@@ -404,6 +428,7 @@ struct ProseTextView: NSViewRepresentable {
self.caretHint = caretHint
self.onTextChange = onTextChange
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
/// 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
/// the title, rendering as a detached terracotta stroke at the canvas
/// top. Programmatic landings (cursor restore, reading flip-back) hop
/// over leading blanks to the first content line; interactive
/// placements (click, drag, typing) never route through here.
/// over leading blanks to the first content line — zero-length landings
/// 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 {
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 {
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
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.allowsUndo = true
tv.isAutomaticQuoteSubstitutionEnabled = false
@@ -485,6 +524,7 @@ struct ProseTextView: NSViewRepresentable {
tv.isContinuousSpellCheckingEnabled = spellChecking
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
dropBridge.textView = tv // #141: idempotent re-point
tv.onFileDrop = routeDrop // #141: idempotent re-point
// #21: the ground follows focus in/out without a remount.
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
tv.backgroundColor = ground
@@ -532,25 +572,9 @@ struct ProseTextView: NSViewRepresentable {
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
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 {
context.coordinator.appliedCaretToken = hint.token
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))
}
context.coordinator.applyCaretHint(hint, tv: tv, session: session)
}
}
@@ -576,6 +600,33 @@ struct ProseTextView: NSViewRepresentable {
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) {
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
let sel = tv.selectedRange()
+218 -11
View File
@@ -12,6 +12,10 @@
// on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out
// of scope (#180); their dismiss stamp rides the generic update posture
// without redesigning its shape.
// #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
@@ -24,7 +28,9 @@ import Foundation
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
/// with our three owned keys winning in place (importFile, #95).
/// 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:
/// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss).
@@ -33,6 +39,19 @@ import Foundation
/// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order.
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`
/// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this
@@ -108,6 +127,178 @@ nonisolated enum PostFrontmatter {
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) + "]"
}
/// #208: the piece's summary from its raw frontmatter text — ONE
/// line by construction (the read is line-bounded). Walks the block
/// the way the lenient `parse` does (past the opening fence to the
/// next `---`), but keeps the line's own quotes: `parse`'s scalar
/// trim strips EVERY edge quote character, which would eat a
/// teaser's closing `"why"`. A quoted value (the shape `summaryValue`
/// renders) unescapes through the category codec's one unescape; a
/// bare value is taken as written. No block, or no line → `""`, the
/// field's settled empty: a piece without a line never gains one, and
/// a BODY line named `summary:` never claims the key.
static func summary(inText text: String) -> String {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard trimmed.hasPrefix("summary:") else { continue }
// A stray \r before the newline fuses the closing fence onto
// this line (the last block line of a mixed-ending file) —
// the fence is never part of the value.
var raw = trimmed.dropFirst("summary:".count).trimmingCharacters(in: .whitespaces)
if let fused = raw.range(of: "\r\n---") {
raw = raw[..<fused.lowerBound].trimmingCharacters(in: .whitespaces)
}
if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 {
return categoryUnescaped(String(raw.dropFirst().dropLast()))
}
return raw
}
return ""
}
/// #208: the one-line `summary:` value `summary(inText:)` reads
/// back. Control characters drop and every run of whitespace — a
/// newline included — collapses to one space: the frontmatter sink
/// is line-bounded, so the value is ONE line or nothing. A value
/// holding a quote or backslash renders QUOTED with both escaped —
/// the category codec's own escape, so ONE grammar serves both keys:
/// the lenient `parse` trims every edge quote (a teaser's closing
/// `"why"` would vanish through that door), so the summary is read
/// off its raw line and the wire never ships an altered teaser.
static func summaryValue(_ text: String) -> String {
let flattened = text
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }
let cleaned = String(flattened)
let needsQuoting = cleaned.contains(where: { "\"'\\".contains($0) })
guard needsQuoting else { return cleaned }
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
// MARK: - Write postures
/// The known-key table: Museion's three owned keys in stamp order —
@@ -139,8 +330,9 @@ nonisolated enum PostFrontmatter {
/// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the
/// pairs.
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
/// pairs. `dropping` removes those keys' lines outright, first (#206:
/// 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)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
@@ -159,18 +351,16 @@ nonisolated enum PostFrontmatter {
// the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// 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 })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
lines[index] = "\(key): \(value)"
seen.insert(key)
}
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
@@ -181,13 +371,30 @@ nonisolated enum PostFrontmatter {
/// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post). The update posture over the known-key table.
/// 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:
/// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String {
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
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
View File
@@ -28,10 +28,18 @@ nonisolated struct Post: Identifiable, Equatable {
var project: String
/// True when the piece lives under archive/ (#107).
var isArchived: Bool
/// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter
/// `micropub_url`) — set when a draft was sent, the target the
/// publish step updates. Inert to everything else.
/// #33 (S6.1): the remembered Micro.blog post URL (frontmatter
/// `micropub_url`) — set when a draft was sent; the target the
/// 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?
/// #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
/// `captureFirstDraftStats` stamped the piece at a pass invocation
/// (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.
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).
static let defaultProject = "posts"
@@ -58,7 +75,7 @@ nonisolated struct Post: Identifiable, Equatable {
/// reads "steady" in the verdict (finish-audit #32).
init?(frontmatter: [String: String]) {
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 typeTokenRatio = frontmatter["stats_type_token_ratio"].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
/// non-finite doubles Swift's `Double(String)` happily parses.
private static func finite(_ raw: String) -> Double? {
@@ -189,15 +197,12 @@ nonisolated struct Post: Identifiable, Equatable {
type: stamp.type,
project: project,
isArchived: isArchived,
// #33: the remembered Micro.blog draft URL —
// one flat key, read leniently like the rest.
// #33 audit: imported frontmatter rides
// verbatim, so the read-back gates on the same
// format guard the decode applies — a hostile
// value never pre-arms the publish sheet.
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #33: the remembered Micro.blog URL — one flat key
// through the ONE trust gate (an import drops the key,
// #206, so a hostile value never pre-arms the publish
// sheet); #206: the publish stamp beside it.
micropubURL: Micropub.rememberedURL(frontmatter),
micropubPublished: frontmatter["micropub_published"].flatMap(parseStamp),
// #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which
// 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,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
+38 -13
View File
@@ -166,7 +166,9 @@ nonisolated enum PostStore {
/// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// 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,
/// no mtime preservation (#96).
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 }
let stats = DraftStats.compute(body: body)
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_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
@@ -675,22 +677,37 @@ nonisolated extension PostStore {
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
/// publish step's target (a frontmatter-only change: the body and
/// Stamp micropub keys in place (`micropub_url`, the publish record
/// `micropub_published`, #207 the `category:` line, and #208 the
/// `summary:` line) — a
/// frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires). A vanished piece throws
/// (write-never-resurrects, `writeNew` is the only creator).
static func stampMicropubURL(id: String, url: String, home: URL) throws {
/// readBody-based echo check never fires, and every later editor
/// save re-reads the block (the stamps survive it). A vanished piece
/// 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 {
throw CocoaError(.fileReadNoSuchFile)
}
let file = dir.appendingPathComponent("post.md")
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)
}
/// #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)
@@ -756,6 +773,12 @@ struct IngestError: LocalizedError {
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
/// (research/promote posture: the #34 rail would refuse the send).
static func hostileAssets() -> IngestError {
@@ -790,10 +813,12 @@ nonisolated extension PostStore {
// AS a link (finish-audit 2026-11-02), and the #34 rail then
// refuses the whole send — nothing enters assets/ that can't ship.
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard source.isFileURL, let values,
values.isDirectory != true, values.isSymbolicLink != true
else {
throw values?.isSymbolicLink == true ? IngestError.isLink(name) : IngestError.isFolder(name)
guard source.isFileURL, let values else { throw IngestError.missing(name) }
if values.isSymbolicLink == true {
throw IngestError.isLink(name)
}
if values.isDirectory == true {
throw IngestError.isFolder(name)
}
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
if FileManager.default.fileExists(atPath: assets.path) {
+3
View File
@@ -218,6 +218,9 @@ struct PostsLibraryColumn: View {
Button("Move to Archive") {
model.archivePost(post)
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post)
Button("Move to Trash", role: .destructive) {
model.trash(post)
}
+17
View File
@@ -130,6 +130,17 @@ final class PostsModel {
/// bar's Run ↔ Cancel swap.
/// #146: setter internal — the split-out domain extensions set it.
var runningBlindRead = false
/// #208: the AI summary turn currently drafting over the open piece —
/// the third rider of the one-shot rail; false = idle. Shares the
/// pass bar's Run ↔ Cancel swap like the Blind Read's.
var summarizing = false
/// The one-shot rail is owned by a rider — the pass bar's Cancel
/// shows, and every other rider refuses. ONE predicate, so a fourth
/// rider joins here and every site follows.
var oneShotRailBusy: Bool {
runningPass != nil || runningBlindRead || summarizing
}
/// #122: does the OPEN piece have a Pass-start snapshot on disk (the
/// Blind Read's comparison base)? Refreshed with the cards at the
/// rescan tail and open transitions.
@@ -140,6 +151,12 @@ final class PostsModel {
/// submitted; nil session (draft/guest/nothing) shows none.
/// #146: setter internal — the split-out domain extensions set it.
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).
/// #146: setter internal — the split-out domain extensions set it.
var lastError: String?
+27 -1
View File
@@ -4,7 +4,8 @@
//
// #146: the fix-card extensions of PostsModel — stored-card surfacing
// (#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
@@ -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)
/// #26 (S4.1): what Promote did — the Learning landed, or the operation
+16
View File
@@ -8,6 +8,9 @@
// card refresh, Micropub. The bare `session.postID == id` comparison is
// retired: two libraries can hold the same slug, and the id alone matched
// a session retained from another library (the repoint finding's seam).
// #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
@@ -22,4 +25,17 @@ extension PostsModel {
guard let session, let home = watchedHome else { return false }
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")
}
}
+6 -3
View File
@@ -62,11 +62,14 @@ extension PostsModel {
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. PostsWatcher fires on the
/// main actor already; no re-hop needed.
/// check, reused verbatim for foreign files. The disk read goes through
/// the shared external normalizer (brief-32): the session's text is
/// normalized on open, so a raw read raised a false conflict on every
/// directory event over an unchanged BOM/CRLF file. PostsWatcher fires
/// on the main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
guard let self, let session = externalSession, let disk = EditorSession.readExternalDocument(at: url) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(urls: [url.deletingLastPathComponent()])
+57
View File
@@ -0,0 +1,57 @@
//
// PostsModelMicropubSummary.swift
// Museion
//
// SummaryPrompt.swift's model half — #208: PostsModel.summarize drafts
// a first-person summary of the OPEN piece on a fresh one-shot
// chat-profile engine and hands the text to the caller. The write is
// NOT here — the send stamps the frontmatter `summary:` line
// (PostFrontmatter, slice 1).
//
import Foundation
@MainActor
extension PostsModel {
/// #208: draft a first-person summary of the OPEN piece on a fresh
/// one-shot chat-profile engine. Flush-first (the engine reads
/// disk); the guards are the shared open-piece rail's. Returns the
/// cleaned reply, or nil with `lastError` set naming the blocker
/// (nothing running / not ready / no open piece / the engine said
/// nothing). Writes NOTHING — the text is the caller's to place.
/// `summarizing` is live while the turn runs: the pass bar's Cancel
/// ends it (the Blind Read posture) and a Pass refuses meanwhile.
func summarize(mentor: MentorSessionModel) async -> String? {
guard let (id, _, home) = guardOpenPieceRun("a summary", mentor: mentor) else { return nil }
guard flushOrAbort(id) else { return nil }
// House posture (blindRead): the run is firing — a stale guard
// refusal no longer owns the error strip.
lastError = nil
// brief-28: the guard answered the session's OWN library; disk is
// the truth post-flush — ONE read feeds the prompt AND the title
// (the scan snapshot can lag a just-flushed heading).
guard let dir = PostStore.folder(of: id, home: home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
lastError = "Couldn't read the piece before summarizing."
return nil
}
let body = PostFrontmatter.split(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
lastError = "This piece has no text to summarize."
return nil
}
summarizing = true
defer { summarizing = false }
let pieceTitle = Post.title(of: raw)
let reply = await mentor.runSummary(
prompt: SummaryPrompt.prompt(title: pieceTitle, body: body),
pieceTitle: pieceTitle,
)
guard let summary = reply.map(SummaryPrompt.cleaned), !summary.isEmpty else {
lastError = "The engine didn't return a summary — try again."
return nil
}
return summary
}
}
+6 -1
View File
@@ -34,6 +34,10 @@ extension PostsModel {
lastError = "A Blind Read is already running."
return nil
}
guard !summarizing else {
lastError = "A summary is already running."
return nil
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return nil
@@ -125,7 +129,8 @@ extension PostsModel {
/// rail stops the agent; nothing advances (runPass reads .cancelled).
/// #122: the Blind Read shares the rail — Cancel ends either run.
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil || runningBlindRead else { return }
// Any one-shot rider — a summary turn ends like a Blind Read's.
guard oneShotRailBusy else { return }
mentor.stopStreaming()
}
}
+1 -1
View File
@@ -90,7 +90,7 @@ struct PostsPaneView: View {
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
MicropubPublishSheet(posts: model)
MicropubPublishSheet(posts: model, mentor: mentor)
}
}
+14 -5
View File
@@ -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
/// identity when an edit above shifts offsets) + the hidden scope
/// (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
}
/// #141's SwiftUI entry — the window `.dropDestination`'s perform
/// routes here after markdown forwarding is ruled out upstream.
/// #141's ingest entry — `AppGateState.routeFileDrop` routes here
/// 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 SwiftUI closure's location proved unusable, dogfood 2026-11-02).
/// 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
// can't ship ever enters assets/. A mixed md+image set refuses
// here too (only pure-markdown sets are forwarded upstream).
guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
// here too (only pure-markdown sets are forwarded upstream), and
// 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.")
return false
}
@@ -416,7 +420,12 @@ final class ProseListTextView: NSTextView {
private var ingestNotice: NSTextField?
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) {
lastIngestNotice = text
let strip: NSTextField
if let ingestNotice {
strip = ingestNotice
+2 -2
View File
@@ -3,11 +3,11 @@
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.58 (`apex`)
## 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.58 release binary (checksum
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.
Binary file not shown.
+80 -1
View File
@@ -6,7 +6,9 @@
// in-memory SettingsModel — one page per LLM surface (provider select,
// registry combobox with first-class free text, per-provider effort menu)
// 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.
//
@@ -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
/// selected segment filled with the foreground ink. Toggling swaps the
/// endpoint family (the model guards a custom endpoint).
+9 -4
View File
@@ -5,9 +5,9 @@
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
// #135 (Profiles S2): reworked to the #130 prototype's variant C verdict —
// a Settings sidebar + detail column (System Settings shape): destinations
// Content · Pass 1 · Pass 2 · Chat · Provider Keys. Content keeps the #17
// Home control unchanged; the surface and keys pages live in
// SettingsPagesView.swift.
// Content · Pass 1 · Pass 2 · Chat · Provider Keys · Micro.blog. Content
// keeps the #17 Home control unchanged; the surface, keys, and Micro.blog
// pages live in SettingsPagesView.swift.
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
// CLI/.env rail) and hydrates from the profiles at pane open.
//
@@ -109,6 +109,8 @@ struct SettingsPaneView: View {
SurfaceSettingsPage(model: model, surface: .chat)
case .keys:
ProviderKeysPage(model: model)
case .microblog:
MicroblogSettingsPage()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -116,13 +118,15 @@ struct SettingsPaneView: View {
}
/// 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 {
case content
case pass1
case pass2
case chat
case keys
case microblog
var id: String {
rawValue
@@ -135,6 +139,7 @@ enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
case .pass2: "Pass 2"
case .chat: "Chat"
case .keys: "Provider Keys"
case .microblog: "Micro.blog"
}
}
+62
View File
@@ -0,0 +1,62 @@
//
// SummaryPrompt.swift
// Museion
//
// #208: the AI summary — a first-person teaser a fresh one-shot engine
// on the museion profile drafts from the open piece. The prompt and the
// reply cleanup live here, pure; the model half is PostsModel.summarize
// (PostsModelMicropubSummary.swift). The summary's home is the
// frontmatter `summary:` line the SEND stamps — this half only drafts
// text for the publish sheet's field.
//
import Foundation
/// #208: the AI summary's prompt vocabulary — the title and body travel
/// inline, the ask is a first-person teaser, and the reply is the
/// summary text and nothing else.
nonisolated enum SummaryPrompt {
/// The ask: a first-person teaser that entices the reader to read
/// the full piece. Title and body travel inline; the reply is the
/// summary text and nothing else.
static func prompt(title: String, body: String) -> String {
"Summary — a first-person teaser for the piece below.\n\n"
+ "Title: \(title)\n\n\(body)\n\n"
+ "Write a short summary in first person that entices the reader to read the full piece. "
+ "Reply with the summary text only — no preamble, no quotes, no markdown heading."
}
/// The engine's reply as the field's text: trimmed; a reply that
/// wraps its answer in a leading label ("Summary: …") drops the
/// label; surrounding double quotes strip; "" when blank. Internal
/// newlines collapse to one space through the codec's own
/// `summaryValue` — the sink is line-bounded and the FIELD shows
/// one line too.
static func cleaned(_ reply: String) -> String {
var text = reply.trimmingCharacters(in: .whitespacesAndNewlines)
// ONE leading label, case-insensitive; the colon is required so a
// reply that merely opens with the word "Summary" keeps it.
if let label = text.range(of: #"^summary:\s*"#, options: [.regularExpression, .caseInsensitive]) {
text.removeSubrange(label)
}
// ONE pair of surrounding double quotes — a WRAPPER, not prose: a
// reply whose inner text still holds a `"` is a teaser that opens
// and closes on quoted words, and its edge quotes are the writer's.
if Self.isQuotedWrapper(text) {
text = String(text.dropFirst().dropLast())
}
// The codec's round-trip, not just its render: `summaryValue`
// quotes a quote-bearing value for the line-bounded sink, and
// the raw-line read gives it back — so the FIELD shows exactly
// the text the wire will carry (no escapes ever reach the eyes).
// Fenced: the read takes the block `split` finds, like disk.
return PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n")
}
/// Edge quotes around text that holds no other `"` — a WRAPPER the
/// model put around its reply, not a teaser opening on a quoted word.
private static func isQuotedWrapper(_ text: String) -> Bool {
text.count >= 2 && text.hasPrefix("\"") && text.hasSuffix("\"")
&& !text.dropFirst().dropLast().contains("\"")
}
}
+43 -1
View File
@@ -4,9 +4,11 @@
//
// #193: the shared workspace chrome, moved from WorkspaceView.swift
// (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
/// 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)
}
}
}
}
+5 -18
View File
@@ -56,27 +56,14 @@ struct WorkspaceView: View {
}
}
}
// #91: drag a markdown file onto the window — same guest slot as
// File ▸ Open… Non-markdown drops are refused.
// #91/#141: drops landing OUTSIDE the editor (over the editor the
// text view takes the drag itself — FileDropTextView); one router.
.dropDestination(for: URL.self) { urls, _ in
// #162: no new buffers while a Cold Turkey block holds —
// the open Piece is the one being counted.
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)
let landed = gate.routeFileDrop(urls)
if landed {
selection = .posts
return true
}
guard let textView = gate.proseDrop.textView else { return false }
return textView.ingestDrop(urls)
return landed
}
// #21: left-edge hover slides rail+library back in as an overlay.
// Library only while the window width allows it (#17 verdict stands:
+5 -5
View File
@@ -31,7 +31,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on. Mode strings (mirroring the retired zsh fake): full/crashAfterHandshake/hangOnPrompt/hangOnPromptLoad/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/summaryOnPrompt (#208 — a summary-shaped two-chunk reply, a normal end, NO fix-card tool call; placed AHEAD of the `full` mode's `Hello mentor.` chunks, which concatenate into the one agent row)/loadReplay*/strictMcp.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
@@ -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.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests`, `MicropubSummaryTests` — 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); #208 `MicropubSummaryTests` — the summary travels (create when non-empty; re-send opt-in by key, `""` clears), the one-line codec (`summaryValue`/`summary(inText:)` — the raw-line read; newlines collapse, controls drop, quote-bearing values render quoted and round-trip), apply-at-send with the failed-write refusal, the model's `openPieceSummary()` read, an edge-quote summary reaching the wire exactly as typed, + the sheet field's trimmed-string pending-edit rule. `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.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
- `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`, `SummaryGenerationTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, #208 the AI post summary (`SummaryGenerationTests` — the pure prompt + `cleaned`, and `summarize` over the `summaryOnPrompt` rig: a fresh chat-profile one-shot drafts and the cleaned reply comes back with NOTHING written and the roster untouched; refusals — no open piece, the one-shot rail busy, a refused/empty turn), 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.
- `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.
- `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).
+107 -1
View File
@@ -14,6 +14,16 @@
// 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.
//
// #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
@testable import Museion
@@ -284,7 +294,103 @@ struct FixCardApplyTests {
#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
/// the Learning under the open piece's Home, refreshes the palette's
+248 -4
View File
@@ -25,6 +25,66 @@ import Foundation
@testable import Museion
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
struct ImageIngestTests {
/// 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))
}
// 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 {
let (_, folder) = try ingestHome()
@@ -129,6 +190,189 @@ struct ImageIngestTests {
#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("![alt](assets/sketch.png)"))
#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("![alt](assets/sketch.png)"))
// 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
@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 {
// The window destination forwards only PURE-markdown sets (#91);
// a mixed set must reach this refusal, not vanish behind the md.
// The router forwards only PURE-markdown sets (#91); a mixed set
// must reach this refusal, not vanish behind the md.
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
+86
View File
@@ -25,6 +25,16 @@ private func writeExternal(_ name: String, _ body: String) throws -> URL {
return url
}
/// brief-32: the guest-watch pins' own temp dir — `startExternalWatch`
/// observes the file's CONTAINING folder, so their guest must live where
/// no sibling test ever writes.
private func watchedDir() throws -> URL {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-watch-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir
}
@Suite(.serialized)
@MainActor
struct ImportExternalTests {
@@ -190,4 +200,80 @@ struct ImportExternalTests {
#expect(!session.conflictAlert)
#expect(session.text == "# C\n\nForeign edit.")
}
// MARK: - The guest watch (brief-32: the #67 compare's disk read)
@Test func `external watch raises no 67 conflict on an unchanged BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("watched.md")
// Windows-authored file: BOM + CRLF. The open read normalizes
// (readDocument's external branch); the watch must read in the
// SAME representation or every directory event reads as #67.
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
#expect(session.text == "# Title\n\nBody line.\n")
// Sibling directory events re-fire the compare (the watch observes
// the containing folder): representation alone must never raise.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch still conflicts on a real write and never re-arms after yes-reload`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("foreign.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
// A REAL external modification (different content, same BOM/CRLF
// representation): the departure gate must still see it.
try "\u{FEFF}# Title\r\n\r\nRewritten underneath.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// Yes-reload takes the foreign content, normalized:
session.reloadFromDisk()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nRewritten underneath.\n")
// The next directory event reads the same unchanged bytes — the
// false conflict must not re-arm.
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
@Test func `external watch never re-arms after keep-local on a BOM and CRLF file`() throws {
let model = PostsModel()
let dir = try watchedDir()
let ext = dir.appendingPathComponent("kept.md")
try "\u{FEFF}# Title\r\n\r\nBody line.\r\n".write(to: ext, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: dir) }
model.openExternal(ext)
let session = try #require(model.externalSession)
try "\u{FEFF}# Title\r\n\r\nForeign body.\r\n".write(to: ext, atomically: true, encoding: .utf8)
model.externalWatcher.onEvent?()
#expect(session.conflictAlert)
// No: keep local — the disk state is seen, the local buffer stays
// and stays pending.
session.keepLocal()
#expect(!session.conflictAlert)
#expect(session.text == "# Title\n\nBody line.\n")
#expect(session.saveState == .changed)
model.externalWatcher.onEvent?()
#expect(!session.conflictAlert)
}
}
+547
View File
@@ -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")
}
}
+28 -48
View File
@@ -23,7 +23,7 @@ struct MicropubModelTests {
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
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 {
let (model, _) = try makeModelHome()
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -57,7 +57,7 @@ struct MicropubModelTests {
let (model, _) = try makeModelHome()
model.newPost() // staged draft — no folder, no session
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -76,7 +76,7 @@ struct MicropubModelTests {
model.select(post.id)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(
let outcome = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", log: log),
)
@@ -88,26 +88,21 @@ struct MicropubModelTests {
#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 post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
model.select(post.id)
// The writer's own category frontmatter — permitted, inert.
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
let raw = try String(contentsOf: fileURL, encoding: .utf8)
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\ncategory: Essays\n")
.write(to: fileURL, atomically: true, encoding: .utf8)
// The writer's own category frontmatter — #207: a bare scalar
// is ONE category, and it rides the create as `category`.
try model.select(plantedPiece(home, frontmatter: "category: Essays\n"))
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
_ = await model.micropubSend(
token: "tok",
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
)
let request = try #require(log.requests.first)
let wire = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? ""
#expect(!wire.lowercased().contains("category"))
#expect(!wire.contains("Essays"))
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["category"] as? [String] == ["Essays"])
}
@Test @MainActor func `a failed draft stamps nothing`() async throws {
@@ -116,7 +111,7 @@ struct MicropubModelTests {
model.select(post.id)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(
_ = await model.micropubSend(
token: "tok",
transport: micropubCanned(500, body: "{}", log: log),
)
@@ -124,28 +119,11 @@ struct MicropubModelTests {
#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
/// 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)
model.select(post.id)
let dir = try #require(PostStore.folder(of: post.id, home: home))
@@ -162,20 +140,21 @@ struct MicropubModelTests {
)
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))
// The three hops, in order: q=config → upload → create.
#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(log.requests[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)?.url?.absoluteString == "https://micro.blog/micropub/media")
#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
// — exactly where the writer placed it (2026-11-01: the photo
// PROPERTY rendered at the bottom, position lost), alt in the
// 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![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after."
#expect(props["content"] as? [String] == [expected])
#expect(props["photo"] == nil)
@@ -197,7 +176,7 @@ struct MicropubModelTests {
)
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 {
Issue.record("expected refused, got \(outcome)")
@@ -228,7 +207,7 @@ struct MicropubModelTests {
)
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 {
Issue.record("expected refused, got \(outcome)")
@@ -246,13 +225,14 @@ struct MicropubModelTests {
)
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))
// config + ONE upload + create — the FILE uploads once, not once per ref.
#expect(log.requests.count == 3)
#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)
// Both refs share the one uploaded URL.
#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
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 {
Issue.record("expected refused, got \(outcome)")
@@ -281,10 +261,10 @@ struct MicropubModelTests {
model.select(post.id)
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.
#expect(log.requests.count == 1)
#expect(log.requests[0].url == Micropub.endpoint)
#expect(log.request(0)?.url == Micropub.endpoint)
}
}
+423
View File
@@ -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![A winding path.](assets/path.png)\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("![A winding path.](https://micro.blog/uploads/2026/ink.png)") == 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
}
}
+377
View File
@@ -0,0 +1,377 @@
// MicropubSummaryTests.swift
// MuseionTests
//
// #208: a post summary for Micro.blog — the wire + codec half. The
// sheet's Summary field is sheet state (the Categories discipline);
// the edit lands on the piece AT THE SEND as a one-line `summary:`
// key, and the wire reads from disk: a CREATE carries
// `properties.summary` when non-empty; a RE-SEND carries `summary`
// in `replace` ONLY when the piece has the line (opt-in by key —
// an empty string is sent and clears the post's summary; no line →
// `replace` names exactly name + content, the blog keeps whatever it
// has). The AI half (the one-shot engine drafting the summary) rides
// its own file; the sheet itself is not pinned here.
//
// Pins: S1 the codec reads the line · S2 create carries it · S3 the
// re-send opt-in by key · S4 the edit lands at the send (sanitized,
// one line, readable through the model; a failed write refuses).
//
// ## Scenario: the summary travels on the wire
// From #208
//
// Given a saved Post whose frontmatter carries a one-line `summary:`
// When the writer sends it to Micro.blog or re-sends over the
// remembered post
// Then a CREATE carries `properties.summary` (only when non-empty);
// a RE-SEND carries `summary` in `replace` ONLY when the piece has
// the line (`""` is sent and clears; no line leaves the blog's).
//
// ## Scenario: the edit lands at the send
// From #208
//
// Given a sheet Summary edit (the model's `summary:` argument)
// When the writer sends
// Then the line is written to the piece AFTER the flush and BEFORE
// the one disk read that feeds the wire — disk and blog never
// disagree; a write that cannot land REFUSES the send with nothing
// on the wire.
//
import Foundation
@testable import Museion
import Testing
@Suite("MicropubSummaryTests")
struct MicropubSummaryTests {
/// A saved piece opened in the model, with `frontmatter` planted
/// after the owned keys; 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` — through `request(_:)`, never a
/// subscript (#206).
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])
}
// MARK: S1 — the codec reads the one-line summary (pure)
@Test func `summary read is the raw line's scalar and empty when absent`() {
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left the city.\n---\n") == "Why I left the city.")
#expect(PostFrontmatter.summary(inText: "---\nsummary: Padded. \n---\n") == "Padded.")
// A hand-quoted scalar reads back as the bare text.
#expect(PostFrontmatter.summary(inText: "---\nsummary: \"Quoted, with comma\"\n---\n") == "Quoted, with comma")
// Empty, blank, or absent → "" (a piece without a line never gains one).
#expect(PostFrontmatter.summary(inText: "---\nsummary:\n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\nsummary: \n---\n") == "")
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n") == "")
// A body line named summary: never claims the key.
#expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n\nsummary: not frontmatter\n") == "")
// No block at all → nothing.
#expect(PostFrontmatter.summary(inText: "# Title\n\nBody.\n") == "")
// A body line named summary: never claims the key — fenced or not.
#expect(PostFrontmatter.summary(inText: "# Title\n\nsummary: body prose\n") == "")
// ponytail: a CRLF post.md is one grapheme-cluster "line" to every
// `\n` split in the corpus (PostStore: LF-only by design, CRLF is
// normalized at the boundaries) — no reader sees its block, this
// one included. The MIXED shape (an LF block with a stray trailing
// \r on one line) is where parse and a `.whitespaces` trim would
// diverge — pinned at the wire in `a mixed-line-ending piece…`.
#expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left.\r\n---\n") == "Why I left.")
}
@Test func `summary value strips newlines so the line-bounded sink is safe`() {
// The frontmatter sink is line-bounded — a summary can never ride
// a newline into the block; the value is one line or nothing.
let value = PostFrontmatter.summaryValue("Line one.\nLine two.")
#expect(!value.contains("\n"))
#expect(PostFrontmatter.summary(inText: "---\nsummary: \(value)\n---\n") == "Line one. Line two.")
// Leading/trailing whitespace trims; a blank becomes "".
#expect(PostFrontmatter.summaryValue(" ") == "")
}
@Test func `summary value round-trips through the raw line read without losing edge quotes or controls`() {
// The lenient parse trims EVERY leading/trailing quote char, so
// the wire and the sheet read the raw line (`summary(inText:)`);
// the render QUOTES anything holding a quote or backslash, so
// `asked "why"` ships exactly as typed.
let read = { text in PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n") }
#expect(read(#"I finally asked "why""#) == #"I finally asked "why""#)
#expect(read(#""Why did you leave?" haunted me."#) == #""Why did you leave?" haunted me."#)
// An inner quote and a newline together: flattened AND round-tripped.
#expect(read("Line \"one\".\nLine two.") == "Line \"one\". Line two.")
// A backslash survives too (the category codec's escape).
#expect(read(#"C:\path "x""#) == #"C:\path "x""#)
// Control characters (NUL, ESC) never reach the sink — the
// category codec's rule; whitespace still collapses to one space.
#expect(PostFrontmatter.summaryValue("a\u{0}b\u{1B} c") == "ab c")
// A plain value renders bare.
#expect(PostFrontmatter.summaryValue("Why I left.") == "Why I left.")
}
// MARK: S2 — a create carries the summary when non-empty (builder + model)
@Test func `draft request carries summary only when non-empty`() throws {
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", summary: "Why I left.")
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
#expect(props["summary"] as? [String] == ["Why I left."])
#expect(props["name"] as? [String] == ["T"])
#expect(props["content"] as? [String] == ["B"])
// No summary → no key at all (a create never carries an empty one).
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
#expect(bare["summary"] == nil)
}
@Test @MainActor func `create carries the piece's summary 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/summarized"], log: log)
_ = try openPiece(model, home, frontmatter: "summary: Why I left the city.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .drafted(url: "https://example.micro.blog/summarized", preview: nil))
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["Why I left the city."])
// No line at all → no key; an empty line → no key either.
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 1)["summary"] == nil)
_ = try openPiece(model, home, frontmatter: "summary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(try createProperties(log, 2)["summary"] == nil)
}
// MARK: S3 — a re-send replaces, opt-in by key (the model)
@Test @MainActor func `a re-send carries the line's summary in replace and clears on an empty one`() 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)\nsummary: Why I left.\n")
let outcome = await model.micropubSend(token: "tok", transport: transport)
#expect(outcome == .updated(url: url))
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
#expect(replace["name"] as? [String] == ["Titled"])
// An empty summary IS sent — it clears the post's.
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary:\n")
_ = await model.micropubSend(token: "tok", transport: transport)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] 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 summary edit lands on the piece before the wire`() async throws {
let (model, home) = try makeModelHome()
let id = try openPiece(model, home) // no summary 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", summary: "A teaser.", 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; the body is byte-identical.
#expect(PostFrontmatter.split(after).block.contains("\nsummary: A teaser.\n"))
#expect(PostFrontmatter.split(after).body == before)
let props = try createProperties(log, 0)
#expect(props["summary"] as? [String] == ["A teaser."])
}
@Test @MainActor func `a refused send with a summary 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", summary: "A teaser.", transport: micropubCanned(201, log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
#expect(try readPost(home, post.id) == before) // the edit never reached the disk
}
@Test @MainActor func `a summary 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 summary line cannot land.
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", summary: "A teaser.", 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 summary — nothing was sent."))
#expect(log.requests.isEmpty)
#expect(try PostFrontmatter.summary(inText: readPost(home, id)) == "")
}
@Test @MainActor func `an edge-quote summary reaches the wire exactly as typed`() async throws {
// The review's finding: the lenient parse trims every edge quote,
// so a teaser closing in `"why"` must still ship whole — on a
// create AND on a re-send, and reopen whole in the sheet's read.
let (model, home) = try makeModelHome()
let teaser = #"I finally asked "why""#
let log = MicropubRequestLog()
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/quoted"], log: log)
_ = try openPiece(model, home)
_ = await model.micropubSend(token: "tok", summary: teaser, transport: transport)
#expect(try createProperties(log, 0)["summary"] as? [String] == [teaser])
#expect(model.openPieceSummary() == teaser)
// A re-send reads the stamped line back — still whole. The piece
// remembers its post from the first send, so this is the update.
_ = await model.micropubSend(token: "tok", transport: transport)
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 1)["summary"] as? [String] == [teaser])
}
@Test @MainActor func `the sheet's disk read is the open piece's summary line`() async throws {
let (model, home) = try makeModelHome()
#expect(model.openPieceSummary() == "") // nothing open
_ = try openPiece(model, home)
#expect(model.openPieceSummary() == "") // no line yet
_ = await model.micropubSend(
token: "tok",
summary: "A teaser.",
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: MicropubRequestLog()),
)
#expect(model.openPieceSummary() == "A teaser.") // read from disk, never a snapshot
}
@Test @MainActor func `a mixed-line-ending piece re-sends its real summary never an empty clear`() async throws {
// The trimmed() rule. A pure CRLF file is ONE grapheme "line" to
// every `\n` split in the corpus (LF-only by design, normalized at
// the boundaries) — no reader sees its block, so nothing can
// disagree. The shape that CAN: an LF block carrying a stray
// trailing \r on the summary line (a half-converted edit) — parse's
// trimmed() sees the key, a `.whitespaces` trim would leave `\r`
// on the fence and read "" → replace summary [""] over the live post.
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n")
let id = try #require(model.selectedPostID)
let file = try #require(PostStore.folder(of: id, home: home)?.appendingPathComponent("post.md"))
try String(contentsOf: file, encoding: .utf8)
.replacingOccurrences(of: "summary: Why I left.\n", with: "summary: Why I left.\r\n")
.write(to: file, atomically: true, encoding: .utf8)
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 1)
let replace = try updateReplace(log, 0)
#expect(replace["summary"] as? [String] == ["Why I left."])
}
@Test @MainActor func `publish with only a summary edit updates first then flips the status`() async throws {
// The applies-first condition is `categories != nil || summary != nil` —
// a summary-only edit must still send before the flip, or Publish
// would publish the stale post and silently drop the edit.
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 outcome = await model.micropubPublish(url: url, token: "tok", summary: "A teaser.", transport: micropubCanned(200, log: log))
#expect(outcome == .published)
// TWO requests, in order: the update carrying the edit, THEN the flip.
#expect(log.requests.count == 2)
#expect(try updateReplace(log, 0)["summary"] as? [String] == ["A teaser."])
let flip = try #require(log.request(1))
let flipReplace = try #require(micropubJSON(flip)["replace"] as? [String: Any])
#expect(flipReplace["post-status"] as? [String] == ["published"])
#expect(flipReplace["summary"] == nil)
#expect(model.openPieceSummary() == "A teaser.")
#expect(try PostFrontmatter.split(readPost(home, id)).block.contains("micropub_published: "))
}
@Test @MainActor func `clearing a sent summary writes the empty line and clears the post's`() async throws {
// End to end through the model's own written form (not a hand-planted
// line): send, then clear → the update carries summary [""].
let (model, home) = try makeModelHome()
let url = "https://example.micro.blog/live"
let log = MicropubRequestLog()
let transport = micropubCanned(200, headers: ["Location": url], log: log)
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
_ = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport)
#expect(model.openPieceSummary() == "A teaser.")
let outcome = await model.micropubSend(token: "tok", summary: "", transport: transport)
#expect(outcome == .updated(url: url))
#expect(log.requests.count == 2)
let cleared = try updateReplace(log, 1)
#expect(cleared["summary"] as? [String] == [""])
let id = try #require(model.selectedPostID)
let disk = try readPost(home, id)
#expect(PostFrontmatter.split(disk).block.contains("\nsummary: \n"))
#expect(model.openPieceSummary() == "")
}
@Test func `an imported summary line rides through import`() throws {
let home = try storeHome()
// The summary is the writer's content, like `category:` — it stays;
// only Museion's bookkeeping drops at the boundary (#206).
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("summarized-\(UUID().uuidString).md")
try "---\nsummary: Why I left.\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 disk = try readPost(home, post.id)
let matter = try PostFrontmatter.parse(disk)
#expect(PostFrontmatter.summary(inText: disk) == "Why I left.")
#expect(matter["micropub_url"] == nil)
}
// MARK: S5 — the sheet field's pending-edit rule (pure)
@Test func `a summary edit is pending only when the trimmed field differs from the settled one`() {
#expect(MicropubSummaryField.pendingSummary(field: "Why I left.", settled: "Why I left.") == nil)
// Trailing whitespace is not an edit.
#expect(MicropubSummaryField.pendingSummary(field: "Why I left. ", settled: "Why I left.") == nil)
// Clearing a piece that had a line sends an empty summary.
#expect(MicropubSummaryField.pendingSummary(field: "", settled: "Why I left.") == "")
#expect(MicropubSummaryField.pendingSummary(field: "New", settled: "") == "New")
// A piece without a line never gains an empty key.
#expect(MicropubSummaryField.pendingSummary(field: " ", settled: "") == nil)
}
}
+51 -6
View File
@@ -10,8 +10,9 @@
// confirms publish
// Then Micro.blog receives an h=entry create (markdown content, name,
// post-status=draft) followed by an update flipping post-status to
// published — the piece's frontmatter `category:` never travels, and
// the draft URL is remembered on the piece.
// published; #207: the piece's `category:` list rides the create (its
// own pins: MicropubCategoryTests) — and the draft URL is remembered
// on the piece.
//
// Wire facts live-verified against microblog.dev/api/posting and
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
@@ -43,6 +44,18 @@ final class MicropubRequestLog: @unchecked Sendable {
defer { lock.unlock() }
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 {
@@ -73,6 +86,19 @@ nonisolated func micropubJSON(_ request: URLRequest) -> [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")
struct MicropubTests {
// 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 {
let log = MicropubRequestLog()
let outcome = await Micropub.publish(
@@ -247,7 +292,7 @@ struct MicropubTests {
// 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
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: 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)
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)
#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
}
@Test func `stampMicropubURL throws on a vanished piece`() throws {
@Test func `stampMicropub throws on a vanished piece`() throws {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
#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/")])
}
}
+33
View File
@@ -8,6 +8,8 @@
// #179: the write-rail pins — one seam pairs every library store write
// with exactly one rescan and owns the error strip; the model owns the
// Home (no method takes one).
// #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
@@ -68,6 +70,37 @@ func makeModelHome() throws -> (PostsModel, URL) {
#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 {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home)
+1 -1
View File
@@ -322,7 +322,7 @@ extension ProseFoldRekeyTests {
debounce: .seconds(3600),
)
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.setSelectedRange(NSRange(location: 0, length: 0))
+10
View File
@@ -334,6 +334,16 @@ extension ScriptedEngine {
continuation.resume(returning: .object(["stopReason": .string("refusal")]))
return
}
if mode == "summaryOnPrompt" {
// #208: a summary-shaped reply — two chunks of one sentence,
// a normal end, NO fix-card tool call (the draft IS the reply
// text). Ahead of the "Hello mentor." chunks so the summary
// pins read the reply exactly.
chunk(sid, "agent_message_chunk", "I left the city because ")
chunk(sid, "agent_message_chunk", "the noise never stopped.")
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return
}
chunk(sid, "user_message_chunk", "echo")
chunk(sid, "agent_thought_chunk", "weighing the structure")
chunk(sid, "agent_message_chunk", "Hello ")
+176
View File
@@ -0,0 +1,176 @@
//
// SummaryGenerationTests.swift
// MuseionTests
//
// ## Scenario: the AI drafts a first-person summary
// From #208
//
// Given an open saved piece and an idle one-shot rail
// When the writer asks for an AI summary
// Then a fresh one-shot engine on the museion profile receives the
// piece's Title and body (flushed to disk first) with a prompt that
// asks for a first-person teaser, and the reply text comes back to
// the caller — nothing is written to disk, the roster is untouched,
// and the transcript it ran in is transient.
//
import Foundation
@testable import Museion
import Testing
@Suite("SummaryGenerationTests")
struct SummaryGenerationTests {
// MARK: The pure prompt (SummaryPrompt)
@Test func `prompt carries the title and body and asks for first person`() {
let prompt = SummaryPrompt.prompt(title: "T", body: "B")
#expect(prompt.contains("T"))
#expect(prompt.contains("B"))
#expect(prompt.lowercased().contains("first person"))
#expect(prompt.lowercased().contains("entice"))
}
@Test func `cleaned trims drops a leading label and surrounding quotes`() {
#expect(SummaryPrompt.cleaned(" Summary: Why I left. ") == "Why I left.")
#expect(SummaryPrompt.cleaned("\"Why I left.\"") == "Why I left.")
#expect(SummaryPrompt.cleaned("Line one.\nLine two.") == "Line one. Line two.")
#expect(SummaryPrompt.cleaned(" ") == "")
// A reply that merely opens with the word keeps it.
#expect(SummaryPrompt.cleaned("Summary opens the piece.") == "Summary opens the piece.")
// Prose bracketed by quoted words is a teaser, not a wrapper — the
// edge quotes are the writer's and stay.
let bracketed = "\"Why did you leave?\" I asked. She said \"never.\""
#expect(SummaryPrompt.cleaned(bracketed) == bracketed)
// Label and wrapper together.
#expect(SummaryPrompt.cleaned("Summary: \"Why I left.\"") == "Why I left.")
}
// MARK: The model half (PostsModel.summarize over the scripted rig)
/// A saved `# Titled` piece opened in the model, waited into the
/// library scan (the label and the prompt read the library's title).
@MainActor private func openPiece(_ rig: ScriptedRig) async throws -> String {
let id = try plantedPiece(rig.home)
rig.model.select(id)
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
return id
}
/// How many `museion` (chat-profile) engines spawned — the resident
/// plus every one-shot (BlindReadTests' countable).
@MainActor private func museionSpawns(_ rig: ScriptedRig) -> Int {
rig.engines.spawnedProfiles.filter { $0 == "museion" }.count
}
@Test @MainActor func `summarize runs a fresh chat-profile engine and returns the cleaned reply`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == "I left the city because the noise never stopped.")
// A fresh CHAT-profile engine drafted (the resident is the only
// other `museion` spawn; pass profiles never ran).
#expect(museionSpawns(rig) == 2)
#expect(!rig.engines.spawnedProfiles.contains { $0.contains("museion-pass") })
// The prompt carried the piece's body inline (the engines' prompt log).
let asked = rig.engines.engines.flatMap(\.promptLog).map(\.text).joined()
#expect(asked.contains("Body."))
// The transient label renders; the roster never grew; nothing was
// written — the piece on disk carries no summary line.
#expect(textRows(of: rig.mentor).contains("Summary · Titled"))
#expect(rig.mentor.roster.count == rosterBefore)
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(!onDisk.contains("summary:"))
#expect(rig.model.lastError == nil)
}
@Test @MainActor func `summarize refuses when no piece is open`() async throws {
let rig = try makeScriptedRig(mode: "summaryOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("Open a saved post") == true)
// Nothing ran beyond the resident engine.
#expect(museionSpawns(rig) == 1)
}
@Test @MainActor func `summarize refuses while the one-shot rail is busy`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
for _ in 0 ..< 250 where rig.model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == .pass1)
// Exclusivity — the summary refuses while the pass owns the rail.
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("already running") == true)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
for _ in 0 ..< 250 where rig.model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningPass == nil)
rig.mentor.shutdown() // frees the held turn if the rail regressed — bounds the await
_ = await run.value
}
@Test @MainActor func `a cancelled summary turn returns nil and frees the rail`() async throws {
// A hung engine must not hold the sheet's spinner forever: the pass
// bar's Cancel (cancelPass) ends the summary turn like a Blind Read's.
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let run = Task { await rig.model.summarize(mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.summarizing) // the flag the pass bar's Cancel keys on
// Reverse exclusivity: a Pass refuses while the summary owns the
// rail — and the refusal NAMES the summary (the guard, not the
// host's engine lock downstream).
await rig.model.runPass(.pass1, mentor: rig.mentor)
#expect(rig.model.lastError == "A summary is already running.")
#expect(rig.model.runningPass == nil)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
let summary = await run.value
#expect(summary == nil)
for _ in 0 ..< 250 where rig.model.summarizing {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(!rig.model.summarizing)
#expect(!rig.mentor.isStreaming) // the rail is free again
}
@Test @MainActor func `a refused or empty turn returns nil`() async throws {
let rig = try makeScriptedRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openPiece(rig)
let summary = await rig.model.summarize(mentor: rig.mentor)
#expect(summary == nil)
#expect(rig.model.lastError?.contains("didn't return a summary") == true)
}
}
+1 -1
View File
@@ -119,7 +119,7 @@ From the 2026-08-28 sessions (Sudowrite/Muse learnings; issues #9, #10). None of
### 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. A frontmatter `summary:` line travels the same way since #208 — the publish sheet's Summary field takes a one-line teaser (typed, or drafted by its AI summary button on a one-shot chat engine, edited before it lands) and is stamped on the piece at the send.
- **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)
+9 -1
View File
@@ -49,7 +49,7 @@ Running a pass on an unaided first draft captures four style metrics — burstin
### 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.
**[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
@@ -89,6 +89,14 @@ The app is signed with a Developer ID and notarized with Apple, so it opens like
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 |
@@ -0,0 +1,135 @@
# brief-32 — the external guest's watch compares normalized text
> **Date:** 2026-11-30
> **Type:** fix (unticketed)
> **Reference:** finding `museion/external-watch-compares-unnormalized-text` (argus cycle-6 bugs pass, `museion-bugs.md` finding 1; MEDIUM, certain) — branch `fix/external-watch-compares-unnormalized-text` off `main` at `5341c4ee53291ad74b30e812ca84fc5cbdbf990b`
## Goal
`startExternalWatch`'s onEvent read the open external guest's disk text RAW
(`String(contentsOf: url, encoding: .utf8)`, PostsModelImports.swift:69) and
handed it straight to `session.diskDidChange(diskText:)` — no BOM strip, no
CRLF→LF. But the session's `text` and `lastFlushedText` came through
`readDocument`'s external branch (EditorSession.swift:162-166), which strips a
`\u{FEFF}` prefix and maps `\r\n`→`\n`. `diskDidChange` raises the #67
`conflictAlert` when the handed text differs from BOTH `lastFlushedText` and
`text` — which it ALWAYS did for a file whose bytes carry a BOM or CRLF, even
with content unchanged.
Blocking surface: the alert makes `sessionMayDepart` refuse → `select`,
`newPost`, `newOutline`, `openExternal` (via `departOpenDocuments`) and quit
(via `documentsMayDepart` riding `WritingLockAppDelegate`) all block. Both
alert answers clear the state for the moment, but the watcher observes the
containing DIRECTORY (PostsModelImports.swift:72), so the next sibling-file
event re-fires the raw compare and re-arms the false conflict — until the
user's own flush rewrites the file normalized. A quit-blocking false alarm
that keeps coming back.
## Class-site re-derivation (pattern-exhaustive, from root cause)
Re-derived from the pin myself (basis: `grep -rn 'diskDidChange|readDocument|
readBody|String(contentsOf' Museion/*.swift` plus a full read of the seam):
every site that feeds `diskDidChange` or seeds session text —
| # | Site | Read path | Verdict |
|---|------|-----------|---------|
| 1 | PostsModelImports.swift:69 — the external watch's onEvent | raw `String(contentsOf:)` | **the defect** (fixed) |
| 2 | PostsModelWatcher.swift:157/197 — the post-side rescan's #67 read | `PostStore.readBody` | representation-consistent: `readDocument`'s POST branch reads through the same `readBody` (EditorSession.swift:160), so both sides of that compare are byte-identical reads of the same file |
| 3 | EditorSession.swift:136 (init seed), :269 (reloadFromDisk), :316 (keepLocal) | `readDocument` | the normalized baseline itself — all three stay on it |
| 4 | Sites seeding session text otherwise: `edit(_:)` (the editor surface), `adoptText(_:)` (Fix Card apply, caller-computed) | — | not disk reads; not in the class |
No sites beyond the scanner's seed table were found; the one seeded site
believed unexposed (the post-side rescan, #2) is disclosed above with its
consistency evidence. The other `String(contentsOf:)` reads in
`PostsModelOutline`/`Micropub`/`FixCardStore`/`PostStore` internals feed other
consumers, never the #67 compare.
## What Was Done
**ONE shared normalization for the external read path — two callers, no
second normalizer at the compare site:**
- `EditorSession.readExternalDocument(at:) -> String?` (EditorSession.swift,
internal static, extracted byte-identically from `readDocument`'s external
branch): raw UTF-8 read → BOM prefix strip → CRLF→LF. This is now the ONE
external-target disk read — `readDocument`'s external case calls it, and
the guest watch calls it. `reloadFromDisk`/`keepLocal` already read through
`readDocument`, so all four external readers (open, watch, yes-reload,
keep-local) funnel through the same helper: the #67 compare is
normalized-to-normalized by construction.
- `PostsModelImports.startExternalWatch`'s onEvent now reads
`EditorSession.readExternalDocument(at: url)` instead of the raw
`String(contentsOf:)`. Nothing else in the closure changes.
- `readDocument` itself only re-dispatches (both switch cases are now single
expressions; swiftformat's `redundantReturn` rewrites it to the implicit
switch-expression form — syntax-only, semantics identical). **What
`readDocument` loads is unchanged**: the fix adds a caller, not a second
normalizer. `diskDidChange`'s compare is untouched — deliberately: a
normalize-at-compare site would be a parallel second normalizer, exactly
what the fix direction rules out.
**Helper location decision** (called by the brief): it lives in
EditorSession.swift beside `readDocument`/`writeDocument`. The session owns
document reading (the `readDocument`/`writeDocument` pair is the existing
contract), no new file was warranted for 11 lines, and
`file_length`/`type_body_length` are disabled in this repo's `.swiftlint.yml`
— no ceiling pressure either way.
**Tests (RED-first):** three pins in `ImportExternalTests` driving the REAL
watch closure (`model.externalWatcher.onEvent?()` — the exact code a
directory event runs), over a dedicated temp dir (the watch observes the
containing folder, so the guest lives where no sibling test writes):
1. `external watch raises no 67 conflict on an unchanged BOM and CRLF file` —
BOM+CRLF guest (`"\u{FEFF}# Title\r\n\r\nBody line.\r\n"`) opened through
`openExternal`; pins the normalized open (`session.text`), then fires the
watch closure twice: no alert, ever.
2. `external watch still conflicts on a real write and never re-arms after
yes-reload` — the load-bearing negative: a REAL foreign write (different
content, same BOM/CRLF representation) still raises the alert (the
departure gate must not go blind); yes-reload takes the foreign content
normalized; the next watch event over the unchanged file does NOT re-arm.
3. `external watch never re-arms after keep-local on a BOM and CRLF file` —
the No answer's leg: keep-local sees the (normalized) disk state, the
local buffer stays and stays pending (`saveState == .changed`); no
re-arm.
## Verification
- **RED at the pinned base** (5341c4ee + tests only, commit b69ddd3's tree):
`./scripts/full-test.sh start -- -only-testing:MuseionTests/ImportExternalTests`
→ run dir `20261130T211504Z-Museion`: **11 executed / 8 passed / 3 failed**
(xcodebuild exit 65; all three failures are the new pins on
`!session.conflictAlert`), 164 SwiftCompile lines (cold build, real
compile — #197 clear). Suite-name filter per #195/#31/#134 (the file also
holds the suite; filter by SUITE name, never file name).
- **GREEN targeted** (fix tree, pre-format-pass):
same filter, run dir `20261130T211616Z-Museion`: **11 executed / 11
passed / 0 failed** (xcodebuild exit 0), 59 SwiftCompile lines.
- **GREEN full rail** at the fix commit 70dd47e (exact committed tree,
post-format): `./scripts/full-test.sh start` → run dir
`20261130T211720Z-Museion`: **720 executed / 720 passed / 0 failed /
0 skipped, xcodebuild exit 0**, 3 SwiftCompile lines (incremental rebuild
of the touched files — nonzero, #197 clear). 720 = the 717 baseline + the
3 new pins; the 717 rail re-covers the untouched open path (acceptance 3).
- **swiftformat** `.`: 0/152 files formatted, 278 skipped, rc 0.
- **swiftlint** `.`: 0 violations, 0 serious, 141 files, rc 0.
- GitNexus impact analysis: not run — no `.gitnexus/`, no gitnexus binary, no
`.claude/skills/gitnexus/` in this clone (root AGENTS.md's GitNexus block
is stale, as the cycle-6 audit disclosed); the manual caller trace above is
the impact analysis. No AGENTS.md file was written by this session
(consent-gated): the intended root-window row and the Museion/AGENTS.md
EditorSession-bullet delta ship as the owner-apply patch
`~/daedalus-builds/museion/brief-32-agents-owner-apply.patch`
(`git apply --check` clean at the branch head).
Evidence classes: failing-test proof (RED 3/3 at base), coupled-run proof
(targeted GREEN + full-rail GREEN at the committed head), structural proof
(caller-trace table above).
## Commits
- b69ddd3 `test(editor): pin the external watch's false 67 conflict` (RED,
pushed first)
- 70dd47e `fix(editor): normalize the guest watch's disk read`
- docs: CHANGELOG [Unreleased] entry + this log + INDEX row
@@ -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 `![alt](…)` 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 `![…](images/…png)` 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, `![alt](…)` 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*
@@ -0,0 +1,82 @@
# Post Summary for Micro.blog (#208)
> **Date:** 2026-12-05
> **Type:** issue
> **Reference:** https://git.babylondreams.de/alex/Museion/issues/208
## Goal
Give the publish dialog a post-summary field plus an "AI summary" button. The summary is first-person, entices the reader to read the full piece, and travels to Micro.blog with the send.
## What Was Done
- **Wire** (`Micropub.swift`): `makeDraftRequest`/`makeUpdateRequest`/`update`/`sendDraft` carry a `summary:` parameter. A create adds `properties.summary` only when non-empty; an update carries `summary` in `replace` only when the piece has the line (opt-in by key — `nil` leaves the post's summary alone, `""` clears it). One read (`updateRememberedOrCreate`) serves the wire fields, the categories, the summary, and the remembered URL.
- **Codec** (`PostFrontmatter.swift`): `summaryValue(_:)` renders one line (whitespace runs — newlines included — collapse to one space, control characters drop; a value holding a quote or backslash renders QUOTED with the category codec's own escapes — one grammar for both keys). `summary(inText:)` reads it back off the RAW line: a parse-style block walk (past the opening fence to the next `---`) with a fused `\r\n---` tail strip, never through the lenient `parse` (which trims every edge quote) and never via `split` (whose closing-fence check a mixed-ending file defeats). `summary(in:)` — the lossy decoded read — was deleted (zero production consumers).
- **Model** (`PostsModelMicropubSummary.swift`, `PostsModel.swift`, `PostsModelPasses.swift`): `summarize(mentor:)` = the shared open-piece guard rail → flush → ONE disk read feeds the prompt → `mentor.runSummary` on a fresh one-shot chat-profile engine → `SummaryPrompt.cleaned`. Writes nothing. `PostsModel.summarizing` is the one-shot rail's third rider; `oneShotRailBusy` is the ONE predicate the sheet, the pass bar's Cancel, `cancelPass`, and `guardOpenPieceRun` all consult. `micropubSend(categories:summary:)` stamps a pending summary edit at the send (write-before-wire — a failed stamp refuses with nothing on the wire); `micropubPublish` applies a pending edit first.
- **Engine** (`MentorSessionModel.swift`): `runSummary(prompt:pieceTitle:)` rides `runOneShot` (label `Summary · <piece>`, reply read through `draftCandidateText`); exclusivity unchanged — a summary refuses while a Pass or Blind Read runs, and vice versa.
- **Prompt** (`SummaryPrompt.swift`): `prompt(title:body:)` asks for a first-person teaser that entices the reader, reply = summary text only. `cleaned(_:)` trims, drops ONE leading `Summary:` label (colon required), strips ONE pair of surrounding quotes only when the inner text holds no other `"` (a wrapper, not a teaser that opens on a quoted word), then round-trips through the codec so the field shows exactly the text the wire will carry.
- **Sheet** (`MicropubPublishSheet.swift`, `PostsPaneView.swift`): a Summary `TextEditor` (mono-11, 72pt) with the `AI summary` button in the label row; the reply fills the field for the writer to edit. The sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own — the one construction site). Sync points mirror the Categories field: disk on open and after a forget, canonical one-line text after a successful send/publish, baseline only after a failed step. `MicropubSummaryField.pendingSummary` is a trimmed-STRING compare (whitespace alone is not an edit; equal empties stay nil — a piece without the line never gains an empty key).
- **Cancel** (`MentorPaneView.swift`, `PostsModelPasses.swift`): the sheet is modal, so while its own summary turn runs the AI button IS the Stop (click → `cancelPass`); the pass bar's Cancel shows on `oneShotRailBusy`.
- **Tests**: `MicropubSummaryTests.swift` (16 pins) + `SummaryGenerationTests.swift` (7 pins), plus `ScriptedEngine` mode `summaryOnPrompt` (a two-chunk summary-shaped reply, normal end, no fix-card call). 814 total (791 before).
- **Docs**: `Museion/AGENTS.md` (SummaryPrompt, PostsModelMicropubSummary, the Micropub bullet, PostFrontmatter, PostStore, MentorSessionModel), `MuseionTests/AGENTS.md`, `GLOSSARY.md` Summary term, `PRD.md` S6.1, `CHANGELOG.md` [Unreleased].
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| The summary lives in a frontmatter `summary:` line, stamped at the send like `category:` (owner ruling) | Survives reopen, rides every re-send, visible in the file — the same discipline the category line established in #207. A sheet-only value would be lost on every reopen and could never be re-sent. |
| The AI summary runs on the one-shot engine on the chat profile, never the resident session (owner ruling) | The resident session is the writer's conversation; a drafting side-quest would pollute its transcript. The one-shot rail (ADR-0014) spawns, drafts, and tears down — the Blind Read's proven shape. |
| Create carries `summary` only when non-empty; update carries it in `replace` only when the line exists (opt-in by key); `""` clears | Mirrors #207 exactly. Without the opt-in, every re-send of a piece without a line would wipe a summary set on Micro.blog itself. |
| The reader walks the RAW line, never `parse` | The lenient decode trims every edge quote — a teaser ending in `"why"` would lose its quotes through that door. Raw-line read + codec unescape keeps the writer's text exact. |
| `summary(in:)` deleted rather than kept beside `summary(inText:)` | Zero production consumers and lossy by design. Two readers for one key invite the wrong one at a new call site. |
| `oneShotRailBusy` as ONE computed predicate over three riders | The sheet, both Cancels, the guard, and `cancelPass` all need the same answer. One predicate: a fourth rider joins here and every site follows. |
| `lastError` for refusals (not a `Result` return) | House posture — `blindRead` and `runPass` report through `lastError`; the sheet already renders the strip. A typed result would be the only one of its kind. |
| Refusals keep the field's text | The writer may have typed a summary by hand before clicking AI; a refusal must not eat it. |
| The AI button is the Stop during its own turn | The sheet is modal — the pass bar's Cancel is unreachable behind it. Without this, a hung turn would wedge the sheet with no way out. |
| `cleaned` strips edge quotes only when no `"` remains inside | A reply opening and closing on quoted words is a teaser; its edge quotes are the writer's. Only a true wrapper (nothing quoted inside) strips. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---|---|---|
| A mixed-ending `post.md` (a stray `\r` on the last block line) fused the closing fence; the lenient reader still saw the key → re-send path, a `split`-based reader found no block → `""` → `replace summary [""]` would wipe a LIVE post's summary | Two readers of one file disagreed on where the block ends | `summary(inText:)` walks the block the way `parse` does and strips a fused `\r\n---` tail; the mixed-ending wire pin went red on exactly this guard (FLIP-A) |
| An unfenced body line named `summary:` was read as the summary | The reader did not require a fence | The parse-style walk requires an opening fence; body prose never claims the key |
| A hung summary turn could not be cancelled from the modal sheet | The AI button had no Stop behavior and the pass bar's Cancel was behind the sheet | Model `summarizing` flag + `oneShotRailBusy`; the AI button doubles as Stop; `cancelPass` and `guardOpenPieceRun` consult the predicate. Flip: disabling `cancelPass`'s guard hangs the cancel pin (the timeout is the red). |
| The first cancel pin's observable was wrong — asserting `runningPass == nil` held through the host's own one-shot lock, so the flip reddened nothing | A third belt masked the guard under test | The pin asserts `lastError == "A summary is already running."` instead; the flip then reddened exactly that pin |
| `cleaned`'s wrapper rule stripped the edge quotes of prose bracketed by quoted words | The rule matched any string starting and ending with `"` | Strip only when the inner text holds no further `"`; pinned, flip-verified (FLIP-B) |
| The audit round's own edits left 3 lint regressions (a missing blank line after a computed property; a lone `{` under a wrapped condition; a 144-char test line) | Hand edits after the last lint run | Fixed; the lone-brace was the house trap (#142/#179) — hoisted an `isQuotedWrapper` predicate |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/Micropub.swift` | `summary:` on the draft/update builders; create carries when non-empty, update in `replace` by key; one read serves wire fields + categories + summary + URL |
| `Museion/PostFrontmatter.swift` | `summaryValue` (one-line render, quote-aware) + `summary(inText:)` (raw-line read, parse-style walk, fused-fence strip); `summary(in:)` deleted |
| `Museion/PostsModelMicropubSummary.swift` | new — `summarize(mentor:)`: guard rail → flush → one disk read → `runSummary` → `cleaned`; nil + `lastError` on refusal |
| `Museion/SummaryPrompt.swift` | new — the prompt + `cleaned` (label drop, wrapper-only quote strip, codec round-trip) |
| `Museion/PostsModel.swift` | `summarizing` flag; `oneShotRailBusy` predicate; `micropubSend(categories:summary:)`; `micropubPublish` applies a pending edit first |
| `Museion/PostsModelPasses.swift` + `Museion/MentorPaneView.swift` | `cancelPass` + `guardOpenPieceRun` honor `oneShotRailBusy`; the pass bar's Cancel shows on it |
| `Museion/MicropubPublishSheet.swift` | Summary field + AI summary button (doubles as Stop); sync mirrors the Categories field |
| `Museion/PostsPaneView.swift` | the sheet takes the pane's own `mentor` |
| `Museion/MentorSessionModel.swift` | `runSummary` over `runOneShot` |
| `Museion/PostStore.swift` | `stampMicropub` carries the `summary:` line |
| `MuseionTests/ScriptedEngine.swift` | `summaryOnPrompt` mode |
| `MuseionTests/MicropubSummaryTests.swift` | new — 16 pins |
| `MuseionTests/SummaryGenerationTests.swift` | new — 7 pins |
| `GLOSSARY.md`, `PRD.md`, `CHANGELOG.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | Summary term, S6.1 clause, [Unreleased] entry, DOX rows |
## Verification
- Finish-audit gates (final tree): `swiftformat --lint .` 0/161 · `swiftlint --strict .` 0 violations · `full-test.sh` **814/814** (run `20261205T095042Z-Museion`; 791 → 814, +23). The three files edited during the audit compiled in that run (SwiftCompile lines present).
- Flips: fused-fence strip → exactly the 2 mixed-ending pins red; `cleaned` wrapper rule → exactly the bracketed-prose pin; `guardOpenPieceRun` summarizing refusal → exactly the reverse-exclusivity pin; `cancelPass` guard → the cancel pin hangs. All restored byte-exact (`cmp` + sha256).
- Baseline before the audit: 809/809 on the pre-audit tree.
## Open Items & Next Steps
- [ ] Owner to try the live sheet: the AI button's Stop behavior and the one-shot rail refusal are SwiftUI wiring, not host-testable.
- [ ] Ticket candidate: Convert to Post rebuilds frontmatter and drops a piece's `summary:` line (#114 posture — same as `category:`).
- [ ] Ticket candidate: a malformed frontmatter block lets a stamp land in the wrong place — pre-existing for every stamp, not #208's seam.
---
*Log written by write-log skill*
+10
View File
@@ -5,7 +5,17 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-12-05 | issue | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_log.md) | Micro.blog summary travels with the piece; publish sheet Summary field + AI summary button on the one-shot rail (rail 814/814) |
| 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-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-17 | fix | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) | Unticketed fix (brief-27, argus cycle-4): stdin writes move to a dedicated writer queue — engine backpressure can no longer defeat the request deadline, Stop, or a bounded reaping close; neverRead/serverPing fake modes, 3 RED-first smokes + healthy-contract pin, suite 697/697 |
+28
View File
@@ -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.
+31
View File
@@ -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 `![alt](assets/…)` 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)
}
}