Skip to content

fix(remote): keep fm-remote Herdr servers in the Aqua session - #4090

Merged
kunchenguid merged 3 commits into
mainfrom
fm/fm-remote-agent-keychain-auth-rca-s1
Sep 9, 2026
Merged

kunchenguid merged 3 commits into
mainfrom
fm/fm-remote-agent-keychain-auth-rca-s1

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Captain's intent: Root-cause, from the facts below, WHY the claude agents in the mac mini's fm-remote Herdr session cannot authenticate ("Login expired · Please run /login" / "Not logged in") while claude in the mini's default Herdr session authenticates fine on the same machine and same user account. Deliver a report with the actual root cause, backed by evidence, and a recommended durable fix (one that keeps working across reboots). The captain does NOT want a prescribed solution handed to you - dig from the facts and find the real mechanism yourself. Do not assume any prior hypothesis is correct.

FACTS (observations only - not conclusions):

  1. The mac mini (SSH host alias mac-home, macOS, this same dotfiles setup as the MacBook you run on) hosts persistent Firstmate second-mate agents. Each runs the claude CLI inside a Herdr session named fm-remote, which is kept alive across reboots by a per-user macOS LaunchAgent dev.firstmate.herdr.fm-remote. That LaunchAgent's plist is written/rewritten by bin/fm-remote-doctor.sh (function render_launch_agent) in the firstmate repo.
  2. The captain's private dotfiles (kunchenguid/dotfiles-private) define a home-manager LaunchAgent launchd.agents.herdr-server (in home-manager/common.nix) for the DEFAULT Herdr session. claude under that default-session server AUTHENTICATES CORRECTLY. The captain confirmed the default server is that launch-agent server - he did NOT start it by hand in a terminal.
  3. Symptom: after the mini was rebooted, every claude in the fm-remote session reports login-expired / not-logged-in and cannot run a turn. The default session on the same machine is fine.
  4. claude on this setup stores its credential in the macOS login Keychain (captain-confirmed). A ~/.claude/.credentials.json also exists and was recently modified. (Separately and already RESOLVED: claude --version had been hanging earlier due to a wedged syspolicyd/trustd on the mini; a reboot cleared that. The current problem is ONLY the login-expired auth in fm-remote, not a hang.)
  5. Firstmate launches the mate's claude with a clean environment - the exact command is CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false CLAUDE_CODE_SEND_FEEDBACK=0 claude --dangerously-skip-permissions --settings '{...}' <brief> - with NO HOME, CLAUDE_CONFIG_DIR, or XDG_* override and no env -i (see bin/fm-spawn.sh claude case). So the mate's claude reads the normal HOME and keychain.
  6. Herdr 0.9.0 runs a SEPARATE server per session (each with its own socket); default and fm-remote are distinct servers/sockets.
  7. Actions taken and their OBSERVED outcomes (facts, not the cause):
    a. The fm-remote LaunchAgent was changed (firstmate PR fix: launch remote Herdr through the user login shell #4061, merged and deployed to the mini) so it now starts the server through a login shell: /run/current-system/sw/bin/zsh -l -c "exec /etc/profiles/per-user/kunchen/bin/herdr server --session fm-remote" - matching the login-shell pattern the dotfiles default agent uses. After deploy, login-expired PERSISTED.
    b. Restarting the fm-remote server mid-session - via herdr server stop --session fm-remote then launchctl kickstart -k gui/501/dev.firstmate.herdr.fm-remote, and via the doctor's own launchctl bootout+bootstrap+kickstart - did NOT restore auth.
    c. A bare herdr server --session fm-remote (the old plist form) self-daemonizes/detaches and survives launchctl bootout.
    d. The default agent started at LOGIN (RunAtLoad when the Aqua GUI session came up). The fm-remote agent has, so far, only ever been (re)started MID-SESSION via kickstart since the login-shell change - it has not started fresh at a login/boot with the corrected plist.
  8. You run on the MacBook, which uses the SAME dotfiles and macOS, so you can reproduce the LaunchAgent / Herdr-server / login-keychain / macOS security-session mechanics locally. Read-only inspection of the mini is available, and the captain can run a specific one-off command on the mini if the investigation needs a datum only obtainable there.

Captain's later words: given the CONFIRMED root cause (the SSH remote-client-bridge auto-spawning a keychain-less fm-remote server that pre-empts the launchd agent), should we REVERT the previous merged PR #4061 - the change to bin/fm-remote-doctor.sh render_launch_agent that made the fm-remote launch agent start the herdr server through a login shell? Assess honestly with evidence whether #4061 is (a) still necessary and correct as part of the real fix, (b) irrelevant/redundant, or (c) actively wrong; if keep, say whether any part should still be adjusted.

The captain authorized implementing the durable fix the report recommends. The substance of that recommendation, in the captain's terms: the fm-remote server that owns the session socket must be the one spawned by launchd in the user's Aqua login session (gui/), because only that birth carries login-keychain access, and Herdr's SSH remote attach (the captain's saved machine "mini" reconnecting through herdr --session fm-remote remote-client-bridge) otherwise starts a keychain-less server first at every boot and within seconds of every stop. The mini's live datum confirmed it: the fm-remote server was a child of the SSH bridge with SSH_CONNECTION in its environment and no XPC_SERVICE_NAME, while launchd's own job sat at "spawn scheduled", 239 runs, last exit code 1, its log repeating "herdr server is already running". The durable fix: the launch agent runs a Firstmate-owned guard through the login shell (keep #4061's <login-shell> -l -c 'exec ...' launcher) with KeepAlive={SuccessfulExit=false} and ThrottleInterval=10 instead of unconditional KeepAlive; the guard finds the socket owner, execs the server in the foreground when nothing owns the socket, exits 0 when an Aqua-born server (launchd-born or the Aqua remote-job worker) already owns it, and otherwise stops the foreign server, waits for the socket to be released, and execs the server immediately so the socket is rebound before the SSH attach can start another foreign server; a takeover closes the session's panes and the parent firstmate's liveness sweep relaunches the mates. The doctor must be honest: report a session served by a server born outside the Aqua login session as fixable (naming the pid and birth) and let --fix retake it through launchd, and wait for launchd's own Aqua-born owner rather than for any server that answers. Verdict on #4061: keep it, it is neither cause nor cure - a bare Aqua LaunchAgent and the login-shell form behave identically for the keychain, the login shell only provides environment parity - but change its unconditional KeepAlive to SuccessfulExit=false, exec the guard instead of herdr directly, and correct the comments and docs that claimed the login shell grants login-keychain access. The pre-existing tests/fm-pi-primary-types.test.sh failure also fails on main and is out of scope for this change.

What Changed

  • Add an Aqua-scoped launchd guard that detects the fm-remote socket owner, replaces SSH-born servers, and preserves existing Aqua-born owners.
  • Update the remote doctor to verify server birth, repair foreign ownership through launchd, and use conditional KeepAlive supervision.
  • Document the macOS keychain mechanism and add coverage for owner classification, guard takeover, and doctor diagnostics.

Risk Assessment

✅ Low: The change is well-bounded, matches the authorized durable takeover design, and the prior Aqua-classification issue is corrected with launchd-domain evidence.

Testing

Focused fixture tests covered the guard decision table, doctor repair contract, and entrypoint behavior; live Herdr checks demonstrated foreground ownership and SSH-server takeover, while a read-only live doctor run correctly reported the ambient unproven owner as fixable. Actual launchd bootstrap/reboot validation was not performed because this phase may not modify host launchd or user state.

  • Live validation: ✅ go - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
An empty isolated session starts as a foreground Herdr server owned by the guard process ✅ pass live Live guard foreground ownership: the real socket owner equaled the guard PID, and both exited cleanly after herdr server stop.
A reconnect-style SSH-born server is stopped and immediately replaced by the guard ✅ pass live Live SSH-born Herdr server takeover: real socket ownership changed from SSH-marked PID 45469 to guard-exec PID 45577.
The doctor reports a running server whose Aqua birth cannot be proven as fixable and identifies the takeover action ✅ pass live Live read-only fm-remote doctor diagnosis reported PID 92247 as unknown, outside the Aqua login session, and exited unready with a --fix action.
An Aqua-only launchd or remote-worker owner is left running, while a user-domain, inherited-XPC, or unprovable owner is rejected ⏸️ untested no Live validation requires authority to create and bootstrap disposable jobs in gui/&lt;uid&gt; and user/&lt;uid&gt;, which would modify host launchd state and user LaunchAgents outside the worktree. Provide a…
Doctor --fix installs the Aqua-scoped guarded LaunchAgent and remains durable across logout or reboot ⏸️ untested no A live repair/reboot would write under ~/Library/LaunchAgents, alter launchd state, close ambient fm-remote panes, and require reboot authority, all prohibited in this test phase. Provide a disposab…
Evidence: Live guard foreground ownership

Source: Live guard foreground ownership

scenario=empty isolated session starts under the real guard
session=fm-lab-live-89732
herdr=/etc/profiles/per-user/kunchen/bin/herdr
fm-remote-herdr-guard: no server owns session fm-lab-live-89732
fm-remote-herdr-guard: starting the herdr server for session fm-lab-live-89732 inside this launch agent (pid 89738)
herdr server running; you can use any herdr CLI command in another terminal.
api socket: .nmh/.config/herdr/sessions/fm-lab-live-89732/herdr.sock
client socket: .nmh/.config/herdr/sessions/fm-lab-live-89732/herdr-client.sock
logs: .nmh/.config/herdr/sessions/fm-lab-live-89732/herdr-server.log
did you mean to open the Herdr TUI? run `herdr`; you do not need `herdr server`.
guard_pid=89738
socket=.nmh/.config/herdr/sessions/fm-lab-live-89732/herdr.sock
socket_owner=89738
89738 89732 /etc/profiles/per-user/kunchen/bin/herdr server --session fm-lab-live-89732
guard_exit=0
result=PASS: guard exec remained the foreground Herdr socket owner and exited after server stop
Evidence: Live SSH-born Herdr server takeover

Source: Live SSH-born Herdr server takeover

scenario=real SSH-marked server is stopped and atomically replaced by guard
session=fm-lab-takeover-45446
herdr server running; you can use any herdr CLI command in another terminal.
api socket: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr.sock
client socket: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr-client.sock
logs: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr-server.log
did you mean to open the Herdr TUI? run `herdr`; you do not need `herdr server`.
foreign_pid=45469
socket_owner_before=45469
fm-remote-herdr-guard: session fm-lab-takeover-45446 is served by pid 45469 born outside the Aqua login session (ssh); its panes cannot reach the login keychain, taking the session over
fm-remote-herdr-guard: session fm-lab-takeover-45446 released its socket after 0 tenths of a second
fm-remote-herdr-guard: starting the herdr server for session fm-lab-takeover-45446 inside this launch agent (pid 45577)
herdr server running; you can use any herdr CLI command in another terminal.
api socket: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr.sock
client socket: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr-client.sock
logs: .nmh/.config/herdr/sessions/fm-lab-takeover-45446/herdr-server.log
did you mean to open the Herdr TUI? run `herdr`; you do not need `herdr server`.
guard_pid=45577
socket_owner_after=45577
foreign_exit=0
guard_exit=0
result=PASS: real socket ownership transitioned from SSH-marked pid 45469 to guard-exec pid 45577
Evidence: Live read-only fm-remote doctor diagnosis

Source: Live read-only fm-remote doctor diagnosis

mode=check
path=~/.pi/agent/bin:~/.local/libexec/pi-launcher/bin:~/.nvm/versions/node/v24.14.1/bin:~/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/opt/homebrew/bin:/opt/homebrew/sbin:~/.local/libexec/pi-launcher/bin:/etc/profiles/per-user/kunchen/bin:/run/current-system/sw/bin:~/.local/bin:~/go/bin:/Library/Frameworks/Python.framework/Versions/3.13/bin:~/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/usr/local/libexec/mosh-signed:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/.cargo/bin:~/bin:/usr/local/sbin
entrypoint=no
note: not launched through the fixed remote entrypoint; the reported PATH is this caller environment.
platform=darwin
required git=/etc/profiles/per-user/kunchen/bin/git
required jq=/etc/profiles/per-user/kunchen/bin/jq
required herdr=/etc/profiles/per-user/kunchen/bin/herdr
required tasks-axi=~/.nvm/versions/node/v24.14.1/bin/tasks-axi
required treehouse=/etc/profiles/per-user/kunchen/bin/treehouse
required harness=claude:~/.local/bin/claude
optional tmux=/etc/profiles/per-user/kunchen/bin/tmux
optional no-mistakes=~/.local/bin/no-mistakes
optional gh=/opt/homebrew/bin/gh
check herdr=ok: /etc/profiles/per-user/kunchen/bin/herdr
check gui-session=ok: gui/501
check remote-job-worker=fixable: ~/Library/LaunchAgents/dev.firstmate.remote-job.plist does not match the Firstmate-owned Aqua worker contract
check remote-job-worker-loaded=fixable: dev.firstmate.remote-job is not loaded in gui/501
check remote-job-probe=fixable: the remote job worker has not reported a fresh probe
check launchagent=fixable: no Firstmate herdr launch agent at ~/Library/LaunchAgents/dev.firstmate.herdr.fm-remote.plist
check launchagent-scope=skip: no launch agent is installed yet
check launchagent-loaded=fixable: dev.firstmate.herdr.fm-remote is not loaded into gui/501
check herdr-server=fixable: session fm-remote is served by pid 92247 born outside the Aqua login session (unknown), so its panes cannot reach the login keychain
check entrypoint-link=skip: this run did not come through the fixed remote entrypoint
action: remote-job-worker: rerun this command with --fix to write dev.firstmate.remote-job
action: remote-job-worker-loaded: rerun this command with --fix to bootstrap the worker
action: remote-job-probe: rerun this command with --fix to restart the worker, then rerun through fm-on.sh
action: launchagent: rerun this command with --fix to install it
action: launchagent-loaded: rerun this command with --fix to bootstrap and start it
action: herdr-server: rerun this command with --fix so the launch agent takes the session over (its current panes close and the parent firstmate relaunches its mates)
error: this host is not ready for a remote second mate; unresolved: remote-job-worker remote-job-worker-loaded remote-job-probe launchagent launchagent-loaded herdr-server

exit_code=1

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed ✅
  • 🚨 bin/fm-remote-herdr-owner-lib.sh:111 - Any process with XPC_SERVICE_NAME is classified as Aqua-born, but the recorded evidence in docs/verification/runtime-backends.md explicitly shows a user/501 Background LaunchAgent also has an XPC service while keychain access fails with exit 36. A Background-born fm-remote owner therefore reaches fm_remote_herdr_birth_is_aqua, is left running by the guard, and is reported ready by the doctor, preserving the authentication failure. Restrict this shared classifier to markers that actually prove the known gui/<uid> jobs, or inspect the audit session directly.
  • 🚨 bin/fm-remote-herdr-guard.sh:67 - The guard merely execs the same herdr server --session command that the supplied evidence says self-daemonizes and survives launchctl bootout; exec replaces the guard but cannot prevent Herdr from detaching. Once that launcher exits successfully, KeepAlive={SuccessfulExit=false} rests permanently. If the detached Aqua server later stops, the reconnecting SSH bridge can again create a keychain-less owner with no launchd retry to retake it. This contradicts the required durable, foreground-supervised fix. The remedy needs an authorized foreground mode or additional supervision/retry lifecycle machinery, so confirm that mechanism with the user rather than relying on exec alone.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
An empty isolated session starts as a foreground Herdr server owned by the guard process ✅ pass live Live guard foreground ownership: the real socket owner equaled the guard PID, and both exited cleanly after herdr server stop.
A reconnect-style SSH-born server is stopped and immediately replaced by the guard ✅ pass live Live SSH-born Herdr server takeover: real socket ownership changed from SSH-marked PID 45469 to guard-exec PID 45577.
The doctor reports a running server whose Aqua birth cannot be proven as fixable and identifies the takeover action ✅ pass live Live read-only fm-remote doctor diagnosis reported PID 92247 as unknown, outside the Aqua login session, and exited unready with a --fix action.
An Aqua-only launchd or remote-worker owner is left running, while a user-domain, inherited-XPC, or unprovable owner is rejected ⏸️ untested no Live validation requires authority to create and bootstrap disposable jobs in gui/&lt;uid&gt; and user/&lt;uid&gt;, which would modify host launchd state and user LaunchAgents outside the worktree. Provide a…
Doctor --fix installs the Aqua-scoped guarded LaunchAgent and remains durable across logout or reboot ⏸️ untested no A live repair/reboot would write under ~/Library/LaunchAgents, alter launchd state, close ambient fm-remote panes, and require reboot authority, all prohibited in this test phase. Provide a disposab…
  • bash tests/fm-remote-herdr-guard.test.sh
  • bash tests/fm-remote-doctor.test.sh
  • bash tests/fm-remote-entrypoint.test.sh
  • Started bin/fm-remote-herdr-guard.sh with Herdr 0.9.0 in an isolated HOME and verified its PID owned the session socket until clean server shutdown
  • Started a real Herdr server carrying SSH_CONNECTION, ran the guard, and verified socket ownership transitioned from the foreign PID to the guard-exec PID
  • Ran bin/fm-remote-doctor.sh read-only against the host's running fm-remote session and captured its birth/readiness diagnosis
  • Confirmed the temporary .nmh HOME and isolated Herdr processes were removed
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

A herdr server keeps the macOS audit session of whatever started it, and
only the Aqua login session (gui/<uid>) can read the login keychain
without a prompt. Herdr's SSH remote attach starts the fm-remote server
as its own child when it finds none, wins the socket at boot because sshd
accepts connections before the login session exists, and every claude
pane under that server then gets `security` exit 36, falls back to a stale
plaintext credentials file, and reports "Login expired". launchd's own job
lost the socket on every KeepAlive retry and the doctor still reported the
session ready because it only asked whether any server answered.

- Add bin/fm-remote-herdr-guard.sh, the launch agent's exec target: start
  the server in the foreground when nothing owns the socket, exit 0 when an
  Aqua-born server does, and otherwise stop the foreign server, wait for the
  socket, and exec the server at once.
- Add bin/fm-remote-herdr-owner-lib.sh, the single owner of socket-owner
  discovery (lsof; pgrep cannot see herdr's argv on macOS) and the birth
  markers (SSH_*, XPC_SERVICE_NAME, FM_REMOTE_JOB_ACTIVE, sshd or
  remote-client-bridge ancestry matched on argv[0] and whole arguments).
- Render the agent as the login shell exec'ing the guard with
  KeepAlive={SuccessfulExit=false} and ThrottleInterval=10, check the loaded
  job's successful-exit semaphore, and report a session served outside the
  Aqua login session as fixable so --fix retakes it through launchd; the
  reload waits for an Aqua-born owner rather than any running server.
- Correct the doctor and docs: the launch shell provides environment parity,
  the launchd domain provides keychain access.
- Pin the guard's decision table and the doctor's verdicts against real
  marker-carrying processes, and record the dated audit-session evidence.
@kunchenguid
kunchenguid merged commit 78318e2 into main Sep 9, 2026
14 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-remote-agent-keychain-auth-rca-s1 branch September 9, 2026 18:55
adibirzu added a commit to adibirzu/firstmate that referenced this pull request Sep 15, 2026