Repository navigation
Feat: Add agentop setup - #1245
Conversation
Setup reports each step as one checklist line: ✓ done, ! advice, ✗ failed, with the label padded to a column and detail lines under it. On a terminal a running step shows a spinner and its elapsed time. Off a terminal, or with NO_COLOR, the output is plain text with no carriage returns, escape codes or timings, so a log or CI capture reads the same as the screen minus the animation. Colour follows the writer it is drawn to (one lipgloss renderer per writer), not the process's stdout. Ending a running line is idempotent, so a Close after Done, or a Fail after Close, does nothing twice. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
These are the pieces setup's steps share. Each ports a rule install.sh
already follows, so that setup leaves the same files behind:
- File snapshots that restore a file's exact bytes and mode, keep a
symlink a symlink, and remove a file that did not exist. Writes go
through a temp sibling, fsync and rename.
- The PATH block and its marker line, byte for byte as install.sh writes
them, and install.sh's profile choice: ~/.zshrc for zsh; for bash the
first of .bash_profile, .bashrc, .profile, else .bash_profile.
- configMigrationPending: it dry-runs the listener-pin and Bob-pricing
migrations in memory, and reports pending only when one would change the
file. Otherwise every re-run would show a consent screen for a config the
migrations cannot change. The Bob pricing check is now shared with
migrateBobPricing.
- Supervisor, port and proxy probes:
- The supervisor probe is `launchctl list` or `systemctl --user
show-environment`. `launchctl print gui/<uid>` succeeds inside a
sandbox, where launchd is unusable.
- The port holder comes from lsof, falling back to ss when lsof is
missing or names no pid.
- The pidfile rule accepts digits only.
- A check says whether a port's holder is this install's proxy.
- startUnsupervised: the no-supervisor path. It starts the proxy in its
own session, writes ~/.cortex/proxy.pid and waits for /healthz.
samePath now resolves a path whose last component is missing through its
parent's links before cleaning "..". Before, it cleaned the text first,
which could name a different directory than the kernel would. The only
other caller, adoptablePID, can match a few more paths now, and none
fewer.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
A step has two halves. - plan looks without touching anything. It returns what the step would do, or a problem that stops the run before the consent prompt. - apply makes the change. It returns the detail to print and an undo. The runner applies the planned steps in order and keeps their undos. When a step fails, or a SIGINT/SIGTERM arrives, it runs the undos in reverse. A signal is acted on once the running step returns. - Each undo that runs prints a dim "undone <label>" line. - An undo that fails prints "could not roll back <label>: <why>", followed by "do it yourself: <command>". - A rollback that had nothing to undo says "nothing had been changed" rather than claiming changes were undone. A step that fails mid-way returns an undo for whatever it already did. The previous service, if one was serving, is brought back last, after the files it runs from have been restored. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Six steps make up setup. They write the files install.sh writes today, with
two deliberate differences:
- the unsupervised proxy's pidfile and log are created 0600;
- the config migrations run even when there is no supervisor.
- **binaries**: installs agentop and cortex into ~/.local/bin (plus
cortex-session-dump when it is staged). Binaries it replaces go to
~/.cortex/previous/ until the new service answers /healthz, so a failed
upgrade can put them back.
- **cleaned up**: moves the pre-rename abctl and authbridge-proxy aside,
under install.sh's remove_stale guards. A binary the service unit or the
pidfile's process may still run is kept, and the step says why.
- **PATH**: adds the marked block to the shell profile when ~/.local/bin
is not on PATH. A symlinked profile is written through to its target. A
dangling link is appended through to a new 0644 target. A profile that
cannot be written gets advice and the export line, the way install.sh
warns and carries on.
- **config**: writes ~/.cortex/config.yaml with `cortex --local
--write-config` when there is none, and runs the listener-pin and
Bob-pricing migrations itself, so its undo can restore the bytes.
- A pin migration that fails is fatal only when listeners are exposed
(runServiceInstall's rule).
- A Bob-pricing failure is a warning.
- **started**: installs and starts the launchd/systemd service through
runServiceInstall.
- Where no supervisor is usable, such as a sandbox, it starts cortex in
the background instead.
- The foreign-port check uses the config's forward port.
- New pins force a restart.
- It will not start a second proxy beside a supervised Cortex.
- On a failed upgrade it restores the unit and stamp bytes, and the
runner reloads the previous service.
- **routed** (--claude-code only): routes Claude Code through Cortex.
- It plans from the config in hand, because config.yaml may not exist
until the config step runs.
- Its undo restores settings.json's exact bytes rather than running
disable, so an edit made before setup survives.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
`agentop setup` plans every step, shows one consent screen, applies the
steps with a live checklist, and rolls back on failure. install.sh will
hand off to it (a later PR). The flags that handoff uses are fixed from
here on, because a `--ref=main` install can run main's script against
binaries built one commit earlier:
--from DIR, --claude-code, --yes/-y, --no-service, --install-only,
--no-modify-path, --restart, the hidden --handoff-bytes and
--handoff-seconds, and --local (accepted and ignored).
Consent:
- The prompt is `[Y/n]`, read from /dev/tty.
- With no terminal and no --yes, setup prints the plan, changes nothing
and exits 3.
- A decline also exits 3.
- A plan problem exits 1 with "Nothing was changed."
- When the handoff flags mark the run as install.sh's, setup deletes the
staging dir, because exec skips the shell's EXIT trap.
Also in this change:
- **Rollback tests over the real steps.**
- A step made to fail in place of applying, at each position in the run,
leaves HOME's files as they were. proxy.log is left out of that check.
- A broken upgrade reverts to the previous version, which serves again.
- A developer install (`--no-modify-path --restart`) keeps its ./bin and
never edits a profile.
- **A stopped service stays stopped.** An upgrade over a stopped service
that rolls back stops it again, with `agentop service stop`'s semantics.
- **The new version's log.** A failed service step shows what the new
cortex wrote to proxy.log, under its ✗ line.
- **Small downloads.** The downloaded line shows kB below 1 MB.
- **Linux test build.** The tests use unix.Getsid, so they build on Linux;
golang.org/x/sys becomes a direct dependency.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Five fixes. A review of the whole branch found the first three. The other
two came up while those fixes were reviewed.
- **A v0.7.0 Cortex counts as this install's.**
- That release runs ~/.local/bin/authbridge-proxy, under the same
launchd label or from ~/.cortex/proxy.pid.
- Before, setup read it as a stranger on the port. It refused a
supervised upgrade, and left an unsupervised one running with no
pidfile.
- It now matches adoptablePID's rule, which also covers the
--supervise child.
- The unsupervised path stops a pre-rename proxy before it starts the
new one, and restarts that binary on rollback (install.sh's
pre_rename_proxy_running).
- **A replaced background Cortex comes back.** runServiceInstall stops a
pidfile proxy when it installs the service. Rollback now starts that
proxy again, provided it is gone and the new job is unloaded.
- **A signal before apply.** A SIGINT/SIGTERM while setup is planning or
waiting at the prompt now deletes the staging dir and prints "Not
changed.", exiting 3. Before, Go's default handler exited 130/143 and
left the stage behind.
- **A failed unload is reported.** If removing a just-installed service
fails, rollback names the supervisor's own commands to finish the job,
and does not say "the changes above are undone". It also will not start
a background copy beside the job that is still loaded.
- **Waiting out launchd's bootout.** `launchctl bootout` returns before
the job is gone, so the service undo waits for it, as loadService
already does. Without the wait, the restore above saw the departing job
and refused.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The minor findings from the per-step reviews and the whole-branch review. Plans refuse earlier, before the consent prompt: - An exposed config whose listener pins cannot be added. This is runServiceInstall's rule; before, setup reached it only at apply. - A shell profile whose symlinks loop. Directories the PATH edit needs that cannot be written get advice, and the advice keeps the reason. Undos only touch what changed: - The binaries, cleanup and Claude Code steps return no undo when they changed nothing. - Undos remove the directories their step created. - A PATH undo restores only files it actually wrote. Rollback's manual commands: - They name what works for the case: the supervisor's own commands after a fresh install, "re-run agentop setup" when the unit is gone, and a start-by-hand line for a background Cortex. - They are spelled so any shell runs them, fish included. What setup prints: - The header and the upgrade row show the staged version. - A stray argument is named rather than exiting silently. `-help` is help, while `--from help` is a path. - The ending says "healthy" only when a health check ran, and keeps advice lines. `--install-only` says to open a new terminal. - Paths under HOME show as ~, matched only as a whole path. - service install's warnings appear under ✓ started. - A stranger holding the forward port is shown with the service job behind it, when there is one. - The consent row shows the config's forward address. - A failed start whose log is empty says "(it wrote nothing)". Other changes: - Tests are steady under CLICOLOR_FORCE. - serviceReadyTimeout and serviceBootoutTimeout are vars, so tests can wait less. - golangci-lint's errcheck is clean on these lines. - The pending-listener-pins check lives in one helper, and an unused setupEnv field is gone. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 34 minutes. View limit detailsLimit details: You’ve used the included review currently available. Review configuration: ⚙️ Run configuration
📒 Files selected for processing (36)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Fixes review: a background or hand-run Cortex answering /healthz beside a unit stopped with agentop service stop read as the supervised prior, so a rollback reloaded the stopped job and did not restart the background proxy Files: - cmd/agentop/setup_prior_test.go - cmd/agentop/setup_step_service.go - cmd/agentop/setup_step_service_test.go Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
mrsabath
left a comment
There was a problem hiding this comment.
Review
Verified against a checkout of the PR head rather than read alone.
| Check | Result |
|---|---|
go test -race -count=1 ./... |
tui, checklist, apiclient, cluster, edit, money, toolscan all pass |
gofmt -l . / go vet ./... |
clean |
GOOS=linux go vet + go test -c |
clean |
go mod tidy -diff |
clean |
| Test isolation claim | holds — logSupervisorCalls reads the PATH stub and t.Fatalfs if it is not the fake, so no test can drive the real io.rossoctl.cortex; HOME is t.Setenv-redirected |
| 0600 pidfile/log claim | holds — setup_unsupervised.go:24,38 create both 0600, where install.sh uses shell redirection (umask default) |
| Exit-code contract | exitDeclined = 3 reused from cmd_claudecode.go, pinned by e2e tests, with a test asserting it does not collide with 0/1/2 |
Two tests fail in my sandbox (TestServiceStepUnsupervisedFailureShowsTheLog, TestServiceStepBackgroundRestoreRefusesBesideALoadedUnhealthyJob). Both trace to detachedSleeperAt running exec.Command("/bin/sh", ...), which my sandbox denies (/private/var/select/sh: Operation not permitted) — not PR defects. CI runs them unsandboxed and all 28 checks pass.
The rollback core is correct on the four properties that matter, each checked against the code rather than the comments: undos run in true reverse order (setup_runner.go:300); a partially-applied step is undone, because applySteps appends the undo before testing the error (:241); a failed undo does not abort the remaining undos; and restorePrior runs after all undos, so the old binary is back first. Every snapshot is taken before its mutation, in all four snapshotting steps.
A note on how I reviewed this
The "From review, not fixed here" list is unusually complete, and it changed the approach: re-reporting anything on it adds nothing, so I went looking for what is not on it. Three items below, all low-severity, none blocking. Nothing I found contradicts a claim the PR makes.
Body finding — cmd/agentop/cmd_claudecode.go:754
Not inline because this PR does not touch that file, so GitHub will not anchor a comment there. Worth stating anyway, and the irony is the point: the line survives unexamined because nothing here touches it, which is also why it was not reconsidered when setup put it on a rollback path.
writeSettings stages at the fixed path + ".tmp" (~/.claude/settings.json.tmp) with no cleanup on failure, and the claudeCode undo snapshots only settings, settings+".bak" and state. If the rename fails — read-only dir, cross-device, or a concurrent Claude Code write — the step fails, the rollback restores the three tracked paths, and a 0600 file holding the full env block (where API tokens live, per the comment one line above) stays behind. Every other writer in this PR uses os.CreateTemp + the ok-guarded defer os.Remove in setup_files.go:124-134. Pre-existing code, newly load-bearing — reasonable to fold into PR 3 rather than here.
Verdict
No must-fix. The frozen handoff interface is the right thing to pin before PR 4, and the exit codes are test-enforced rather than merely documented.
LGTM.
| if serviceLoaded(env.goos) { | ||
| return err | ||
| } | ||
| } else if err := waitUnloaded(env.goos); err != nil { |
There was a problem hiding this comment.
On a fresh install, a waitUnloaded failure returns before unitSnap.restore() / stampSnap.restore() — and on a fresh install that restore is the removal of the new .plist and proxy.sha256.
So a launchd teardown slower than serviceBootoutTimeout (30s) leaves both on disk after a run that printed rolled back, and serviceInstalled() then reports an install the rollback claimed to remove.
The known-issues list covers the 30s wait; it does not cover the stamp surviving it. The adjacent comment accounts for the unit file ("Either way the unit then stays, for the manual fix") but not the stamp, and unloadByHand only removes the unit.
macOS-only — waitUnloaded no-ops on Linux. Mirror case just above: when unloadService fails but serviceLoaded() is false, the unit is removed without ever calling waitUnloaded.
No setup-rollback test pins the stamp's removal; the existing stampFile tests are all service install / uninstall.
| if err != nil { | ||
| return "", undo{}, err | ||
| } | ||
| madeDirs := missingDirs(filepath.Dir(target)) |
There was a problem hiding this comment.
nit, and close to unreachable — flagging only because it is cheap to bound.
madeDirs := missingDirs(filepath.Dir(target)) tracks only the target's directory, but apply also writes prof + ".bak", whose writeFileAtomic does its own MkdirAll(filepath.Dir(prof), 0o755).
For a symlinked profile whose link and target sit in different (both missing) directories, the rollback removes the target's dirs and leaves the one created for the .bak. Needs a dangling-symlink profile with a missing parent, so it is near-unreachable in practice.
What
This adds
agentop setup, which installs and starts Cortex on a laptop.This is PR 2 of 4 in the laptop-installer redesign. PR 1, #1227 (seams in the existing install code), is merged.
agentop setupagentop doctorandagentop uninstallinstall.shinto a thin script that downloads (with a progress bar), verifies, stages, thenexecsagentop setup --from <stage>. Also switchesmake dev-installover.Until PR 4 lands, nothing calls
setup.install.shandmake dev-installbehave exactly as they do today.The steps
The steps write the files
install.shwrites today, with two deliberate differences:The steps:
~/.local/bin. The binaries an upgrade replaces are kept in~/.cortex/previous/until the new service answers/healthz.abctlandauthbridge-proxyare moved aside, underinstall.sh's guards.config.yamlif there is none, and runs the listener-pin and Bob-pricing migrations.runServiceInstall. Where no supervisor is usable, for example in a sandbox, it starts Cortex in the background instead.--claude-code; routes Claude Code through Cortex.Rollback
Each step's undo restores exact bytes from a snapshot. It does not run the inverse command. If an undo fails, setup prints
could not roll back …and the command to finish the job by hand. When that happens, setup does not claim the changes were undone.These cases are covered by tests that run the real steps against a fake HOME and a fake supervisor:
authbridge-proxy) install;bootout;The handoff interface (fixed from here on)
These are the flags PR 4's
install.shwill pass. A--ref=maininstall can run main's script against binaries built one commit earlier, so these flags can't change after this PR:--from DIR--claude-code--yes/-y--no-service--install-only--no-modify-path--restart--handoff-bytesand--handoff-seconds--local(accepted and ignored)Exit codes:
--yesTesting
From
cmd/agentop:From the repo root:
sh scripts/install_test.sh.I also ran the module's tests on Linux, in a
golang:1.26container (podman run --init, uid 1000,GOWORK=off). Two tests fail there and also fail onmain:TestServiceInstall_RefusesABrokenConfigneeds a realsystemctl, andTestReportSessionInterruptionneedslsof.No test reaches the real launchd/systemd, HOME, or ports 47600–47604. The supervisor,
lsofandssare stubbed through PATH, and a guard refuses to wrap anything but the fakes.Left for later
Deferred to PR 4:
help <docs URL>line. agentop prints no doc URLs today.install.shmust always pass--handoff-bytes> 0, as an integer. Setup treats the run as the installer's only when a handoff value is > 0.Known limits, accepted and noted in the code:
systemctl --user stop(still enabled) reads as loaded. A failed upgrade then leaves the new job running./healthztakes more than about 2s reads as not serving.cortex --write-configruns with no timeout.kill -9.From review, not fixed here:
proxy.pidCortex, still counts as the prior service. The rollback reloads that job and does not restart the background proxy.systemctl --user stop, which stays enabled.cortexbytes under a new proxy that is still running, and the rollback still says the changes are undone.loadServicereportsreplacedon every error, including a refused bootout. That produces a false "could not roll back the previous Cortex".restorePriorprints "reverted … running again · healthy" even after the binaries undo failed.| teecan kill setup partway through apply, with no rollback.launchctlor--write-config./dev/tty. With stdout redirected, setup looks hung.pscan't see processes, the cleanup step's plan skips the guards its apply checks, so a re-run never reaches "already current".lsoforssto name the port holder.loadCandidate's dry run needs a writable$TMPDIR.install.shwarns and continues.--fromstage that has already been deleted.install.shparity tests compare against hard-coded copies, notscripts/install.sh./healthzwait row starts before the stop and bootout waits, so it can read past its limit.~/.local/bin, and a failed copy intoprevious/leaves an empty dir.installerOneLineruses the legacyauthbridge/install.shURL.startByHanddoes not quote its path.--install-onlydrops--claude-code,--restartand--no-service.holderJobmatches the--supervisechild, not its parent.setup_step_cleanup.go.serviceLoaded's doc says that a launchctl which cannot tell makes each caller claim less. ForpriorServiceit claims more.priorService's readers incmd_setup.goandsetup_e2e_test.gostill describe health alone.Assisted-By: Claude Code