Skip to content

Design: native Swift client to replace Hammerspoon (#2) - #10

Closed
STRML wants to merge 8 commits into
DRYCodeWorks:mainfrom
STRML:native-client-spec
Closed

Design: native Swift client to replace Hammerspoon (#2)#10
STRML wants to merge 8 commits into
DRYCodeWorks:mainfrom
STRML:native-client-spec

Conversation

@STRML

@STRML STRML commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Design document for #2. No code — this is the spec the implementation plan will be built from.

Summary

Replaces the Hammerspoon Lua client with a signed, notarised LSUIElement agent. Capture moves in-process, the key stops being copied, and the client stops trusting the server's response.

Two decisions shape everything else:

  • Developer ID is assumed. CI builds, signs and notarises; install-client.sh downloads and verifies rather than compiling. That drops the Xcode command line tools from the machine you dictate from, which is the point of the surrounding dependency work in Drop FastAPI, uvicorn and httpx for the stdlib #4.
  • The hotkey mechanism is deliberately undecided. Carbon versus CGEventTap is settled by a Phase 0 spike with explicit pass/fail criteria, not by argument.

Review

Six non-Claude reviewers (Codex ×5, Gemini ×1), three review rounds plus three verification passes:

Pass Result
Round 1 6/6 REVISE — design defects
Round 2 5 REVISE + 1 APPROVED — unspecified mechanisms
Round 3 6/6 REVISE — two contradictions and a format bug
Verify 1 4 APPROVED + 2 REVISE
Verify 2 2 REVISE — both in the fix, not the original
Verify 3 1 APPROVED + 1 REVISE — bookkeeping and one heuristic

Findings shrank from 84 lines to under 10. Round 1 found wrong; round 3 found underspecified; the verification passes found contradictory. All are fixed in b39bc25.

The panel killed my central argument

Revision 1 chose Carbon RegisterEventHotKey because it "asks for permission to type, not permission to watch you type." Wrong: synthesising ⌘V needs Accessibility, and Accessibility is one atomic grant that also permits an event tap. Revision 1 also claimed the API errors on chord collision; the SDK header says the opposite and exclusivity needs kEventHotKeyExclusive.

I did not accept the reviewer's conclusion to "go straight to CGEventTap". If a keyboard tap additionally needs Input Monitoring — which README.md:266-268 asserts from this project's own experience — Carbon is one grant and the tap is two, and the conclusion survives by a different route than the one I argued. That is Phase 0's first question rather than a guess by either side.

Claims I made that were not true

  • tests/test_audio.py pins the wire format. It validates sample width only (audio.py:45); a stereo 44.1 kHz WAV passes today.
  • Developer ID would be a later flip "without structural change". It means shipping prebuilt binaries, so the on-device compile has to go.
  • Per-host NSExceptionDomains could be generated at install time. They live in the signed Info.plist; writing them invalidates the signature.
  • xcrun stapler on the client — an Xcode-only tool, required 200 lines after claiming the client no longer needs Xcode.
  • The rollback target could be copied at install time. By then client/init.lua is the stub this change introduces, so it would have preserved the broken thing.
  • spctl exercises notarisation "because the download is quarantined". True for browsers; curl + ditto need not preserve the attribute.

Status — 2026-08-01

Rebased onto 8d12f7b. This mattered: the branch was cut from 4e35977, main moved eleven commits, and every line number was stale — in a document the panel had already twice punished for citation errors. All 23 anchors re-resolved by content and verified mechanically.

Item State
Panel 3 rounds + 3 verification passes, all findings addressed
Last verification 1 APPROVED, 1 REVISE (bookkeeping + one heuristic), both fixed in b39bc25
Citations All resolve against 8d12f7b
Repo green on this base 84 pytest, 8 Lua, shellcheck clean
Hotkey mechanism Undecided by design — Phase 0

Two sections changed meaning during the rebase:

  • The zero-frames concern is no longer speculative. Filed as --doctor's microphone check may be a false PASS: rec infers permission from frame count #9, confirmed, fixed in 559aafe. That commit is now the reference implementation for the agent's permission handling rather than something this design invents.
  • Two thirds of the superseded-spec work is already done by ef47aeb and c852392, so the blast radius points at what remains rather than repeating finished work.

Open follow-ups

  • Phase 0 spike — does a keyboard CGEventTap need Input Monitoring, and is kEventHotKeyReleased reliable enough for hold-to-talk. Gates the mechanism; nothing downstream depends on which way it goes.
  • b39bc25 is unreviewed. It is two narrow changes (a confirmation gate and a header correction), but no reviewer has seen it.
  • Keychain-pinned server origin. Any same-UID process can rewrite client.json and redirect the trusted agent; mode 600 does not stop it. Needs its own design.
  • One reviewer wanted stronger-than-heuristic proof for the dangling-symlink case. Resolved by requiring explicit confirmation rather than by finding better evidence, because better evidence does not exist once the target is gone.

Test plan

  • uv run --locked pytest -q — 84 passed on the rebased base
  • lua tests/test_client_record.lua — pass
  • shellcheck install-server.sh install-client.sh — clean
  • Every file:line resolves to the content claimed, verified mechanically against 8d12f7b
  • No implementation yet — plan next, then code

https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX

STRML added 8 commits August 1, 2026 08:14
Spec for DRYCodeWorks#2. Decisions: an LSUIElement bundle with a menu bar status item,
capture absorbed in-process so rec stops being a child binary, config at
~/.config/hark/client.json with the key read from the server's own key file on
a single-machine install, and Carbon RegisterEventHotKey rather than an event
tap.

The hotkey choice is the load-bearing one. RegisterEventHotKey needs no
Accessibility grant, so the agent asks for permission to type rather than
permission to watch you type. An event-tap agent would need exactly the
all-or-nothing grant that made the Hammerspoon arrangement uncomfortable. It
also makes two currently-silent failures visible: a missing Accessibility grant
and a hotkey chord already owned by another app.

Measured while writing this and folded into the design: identical Swift sources
produce a different CDHash on every build. install-client.sh recompiles
unconditionally today, which is harmless only because TCC attributes to
Hammerspoon. Once the agent is the TCC principal, an unguarded rebuild
invalidates its own Accessibility grant, so the installer has to hash its build
inputs and skip the build when they match.

Nothing on the user's machine gets deleted on migration. client/init.lua becomes
a stub that binds no hotkey, so an existing symlink keeps resolving and the two
clients never fight over the hotkey.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
All six reviewers returned REVISE on revision 1, and two of them independently
killed its central argument.

Revision 1 chose Carbon RegisterEventHotKey on the grounds that it asks for
permission to type rather than permission to watch you type. That is wrong:
synthesising Cmd+V needs Accessibility, and Accessibility is one atomic grant
that also permits creating an event tap. It also claimed the API errors when
another app owns the chord; the SDK header says the opposite and exclusivity
needs kEventHotKeyExclusive. The mechanism is now undecided behind a Phase 0
spike, whose real question is whether a keyboard tap additionally needs Input
Monitoring — README:245-247 suggests from this project's own experience that it
might, which would revive the permission argument by a different route.

Assuming a Developer ID deletes rather than fixes a whole section. CI builds,
signs and notarises; the installer downloads instead of compiling, so it can no
longer mint a new CDHash on every re-run and the input-hash guard goes away. It
also drops the Xcode command line tools from the client machine, which is the
point of the surrounding dependency work.

Security findings that were missing entirely: the client never sanitised the
server's response, so a spoofed server on the plaintext two-machine path could
return a newline and have it typed into a terminal. There was no transport
policy and no ATS declaration, so the client would have captured audio and then
failed every POST. 400 was mapped to "microphone permission" inherited from the
Lua client, but capture failures no longer reach the server and the server
returns 400 for every InvalidAudioError, including a malformed header this
client now builds by hand.

Migration was insufficient rather than merely incomplete. A stub does not unload
Lua already running in Hammerspoon, and leaving its grants in place preserves
exactly the privilege escape this work exists to close.

Also corrected: revision 1 claimed tests/test_audio.py pins the wire format. It
validates sample width only, so a stereo 44.1 kHz WAV passes today.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 2 of the panel returned 5 REVISE / 1 APPROVED. Almost every remaining objection was the same shape: the design named a mechanism without saying what it actually does. A length cap with no number is not a security contract, and a generation stamp that bash cannot verify is not a freshness check.

Concrete now: 1 MiB response body enforced before JSON decoding, 8 KiB sanitised text, reject rather than truncate; a 5 s starting deadline separate from a 120 s capture cap, because rec.swift:167 arms its ceiling only after the first buffer; and a status file bound to the agent by PID plus process start time with a 30 s heartbeat, which is something --doctor can check from bash.

The transport section contradicted itself, prohibiting non-loopback HTTP while promising a Tailscale opt-in that had nowhere to live. It now has one: an explicit per-host allowlist in client.json. Tailnets already encrypt at the network layer, so HTTP there is defensible, but it should be a stated choice rather than a silent default.

Two things the panel found in shipped code rather than in the design. app.py:103-107 returns microphone advice for every InvalidAudioError and test_app.py:107 asserts that wording, so a malformed header from this client would send users to the wrong settings pane. And migration cannot claim to confirm Hammerspoon released the hotkey, because macOS exposes no way to ask WindowServer who owns a chord; confirmed process exit is the most that can be said.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 3 found two contradictions I introduced. Per-host NSExceptionDomains cannot follow client.json, because that key lives in the signed Info.plist and writing to it after download invalidates the signature. Restricting insecure HTTP to IP literals lets a static NSAllowsLocalNetworking cover it without the plist naming any host.

The migration also deadlocked: it required the agent verified healthy before quitting Hammerspoon, while the agent cannot register the hotkey until Hammerspoon releases it. Registration is now split out of the health check and happens after handover, with rollback that restores the symlink and relaunches Hammerspoon.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 3 brought the panel down to two contradictions and a format bug, all of
which I had introduced.

Per-host NSExceptionDomains cannot follow client.json: that key lives in the
signed Info.plist, so writing to it after download invalidates the signature and
macOS kills the app at launch. Restricting insecure HTTP to IP literals lets a
static NSAllowsLocalNetworking cover the case without the plist ever naming a
host. A MagicDNS name is consequently not usable over HTTP; use the tailnet IP.

The migration deadlocked. It required the agent verified healthy before quitting
Hammerspoon, while the agent cannot register the hotkey until Hammerspoon
releases it. Registration is now split out of the health check and happens after
handover, with rollback that restores the symlink and relaunches Hammerspoon.

The status file proposed matching an ISO timestamp against ps -o lstart, which
prints a localised non-ISO string. It now stores what ps prints, verbatim, plus
an epoch integer, so --doctor compares strings and integers rather than parsing
dates. It also carries hotkey and login-item state, since a heartbeat that omits
them passes while the product does not work.

Also settled rather than deferred: response bounds now cover the error detail
string, not just the transcript; the paste-target guarantee is stated at
application granularity because that is all it enforces; and the clipboard
self-clears after 90 seconds when changeCount is unchanged, which keeps the
paste-recovery window the original decision wanted while bounding an exposure
any local process could harvest.

Rebased onto 8d12f7b. That matters more than usual here: the branch was cut from
4e35977 and main has since moved by eleven commits, so every line number in the
document was stale. All of them are re-verified against 8d12f7b.

Two sections changed meaning as a result. The zero-frames concern is no longer
speculative, because DRYCodeWorks#9 was confirmed and fixed in 559aafe, and that commit is
now cited as the reference implementation for the agent's permission handling
rather than something this design has to invent. And two thirds of the
superseded-spec work in the blast radius is already done by ef47aeb and c852392,
so the document now points at what remains instead of repeating it.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
The verification pass returned 4 APPROVED / 2 REVISE, and both holdouts found real contradictions.

Rollback restored the symlink, but this same change turns client/init.lua into a no-op stub, so the restored symlink pointed at a client that does nothing. The installer now preserves the working Lua client to ~/.config/hark/legacy-client.lua before cutover and repoints there on failure. It also writes an ownership record, because content-matching the symlink target cannot survive the repo moving: an absolute symlink to a moved checkout is dangling, and there is no content left to match.

Rollback also left the agent installed while SMAppService.register() ran unconditionally at first launch, so a rolled-back install would start the agent at the next login and fight the Hammerspoon it had just restored. Registration is now the last step of a successful cutover rather than part of launch, and rollback unregisters.

And xcrun stapler was required on the client two hundred lines after this document claimed the client no longer needs the Xcode command line tools. stapler ships with Xcode; the staple check moves to CI, where the toolchain already exists, and the client verifies with stock spctl and codesign. A downloaded artifact is quarantined, so spctl exercises the notarisation path anyway.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Both holdout reviewers found the same two flaws, and both were in revision 5's fix rather than in the original design.

Step 0 copied the working client/init.lua to preserve a rollback target. By the time the updated installer runs, the user has already pulled, so that file is the stub this change introduces, and after a repo move the symlink is dangling and resolves to nothing. The working code survives only in git history and in Hammerspoon's memory, neither of which the installer can read. The last functional client is now committed as client/legacy/init-v1.lua and staged from there.

Ownership detection was circular in time: step 0 wrote a record asserting hark owned the symlink, then step 1 trusted that record to decide whether hark owned it. It would have classified an independently managed Hammerspoon config as hark's own, and no existing install can have a record this change introduces. Detection now runs on pre-existing evidence only, and the record is written after a confirmed successful cutover, for later runs.

The quarantine assumption was also wrong. I argued spctl exercises notarisation because the download is quarantined, but curl plus ditto need not preserve com.apple.quarantine the way a browser does, and without it spctl takes a weaker path. The installer sets the attribute explicitly before assessing.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
The dangling-symlink fallback matches on path shape, which is a guess rather than proof of ownership. Everything it gates is disruptive and not silently reversible: quitting Hammerspoon, replacing a symlink, resetting TCC grants. When it is the only evidence, the installer now stops and asks.

Header corrected to revision 6; it still claimed 4 while the body described revision 5 as superseded. Also states plainly that this document ships no code, since a reviewer read the absence of client/legacy/init-v1.lua from HEAD as a defect rather than as the nature of a design PR.

Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
@STRML

STRML commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #12 (the implemented Swift rewrite). Design now landed in code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant