Repository navigation
Description
Why
When the machine Codeman runs on reboots, tmux dies and every agent pane with it. Since #442 (the fix for #411), Codeman shows a banner after a reboot that offers to rebuild the lost sessions. That banner only covers local Claude Code sessions: it resumes the conversation with claude --resume <id>, and the terminal history does not come back.
Sessions running Codex, OpenCode, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP or a plain shell, and every remote SSH or Docker session, are passed over, and their records are deleted at boot. After a reboot they have to be recreated by hand. A remote agent is worse off: it keeps running on the remote host, but Codeman no longer knows it exists.
This issue is the plan to close that gap:
- what each CLI supports for resuming;
- what Codeman has to learn and store while a session is alive;
- 15 PR-sized steps in a recommended order;
- 14 open decisions.
It also lists bugs in the restore that ships today. Those are worth fixing whatever happens to the rest.
No code has been written yet. The plan was checked against master at a8a8bb7 (1.41.1) on 2026-10-14 and against the --help output of the CLIs installed on the dev machine; no model session was started. Line numbers refer to that commit. Sections 2 and 4 to 7, the per-PR detail and the appendices are collapsed; expand them for the full mechanics.
0. TL;DR
- Today the reboot banner rebuilds local claude sessions only, resumes the conversation with
claude --resume <id>, and brings back no scrollback. Everything else is passed over (unsupported-mode,remote-or-docker) and its record is pruned at boot. - Every agent CLI already has a resume form in the CLI registry (
launch.params.resumeId+legacyConfigAliases.resumeId;resumeAppendfor all but claude and opencode). The missing piece is knowing the conversation id after the reboot. Only claude (always) and omp (once captured) persist it today. - pi 1.1.0
--session-idcreates OR reuses a caller-chosen id, so one flag covers fresh launch and resume. grok 1.0.52--session-idonly creates (it refuses an existing id), so grok needs--resume <id>on every later launch. - Codex 0.162 broke Codeman's originator link (
CODEX_INTERNAL_ORIGINATOR_OVERRIDE=codeman_<id>): Codeman-spawned rollouts since 2026-10-08 carryoriginator: codex-tui. Likely cause is codex's new shared app-server daemon; codex 0.162 has a--no-daemonflag worth measuring as the fix. - Four latent bugs block a naive rollout: a tmux server that dies before Codeman persists
pid: nullfor every session (all then refused asnot-running); non-claude env overrides are never persisted (a store-relocatingCODEX_HOME/DSH_HOMEis lost); version gates are evaluated against claude's version for every CLI; the remote alive probe hardcodes-L codeman-remote. - Remote sessions are the cheapest big win: a local reboot leaves the remote agent running in
tmux -L codeman-remote, but Codeman forgets it at boot and remote discovery cannot see that socket. Reattaching restores process AND remote scrollback with no model cost. - Recommended first PRs: A1 (harden the shipped path), A2 (stop a dying tmux server from erasing
pid), B (durable plan + exact boot detection), C1/C2 (shared clamps, then the generic resume model).
1. Findings that shape the plan
| # | Finding | Evidence | Consequence |
|---|---|---|---|
| F1 | Restore is claude-only by a transcript capability check | planRebootRestore() in src/reboot-restore.ts:231 rejects any mode whose capabilities.transcript !== 'claude-jsonl' |
The gate must become an explicit restore capability per CLI |
| F2 | The plan is in memory only | RebootRestoreRegistry (src/web/reboot-restore-registry.ts), built once inside restoreMuxSessions() |
Any server restart between boot and click (self-update, crash, deploy) loses the offer for good: cleanupStaleSessions() already pruned the unpinned records |
| F3 | Both workspace checks use unbounded existsSync |
src/web/server.ts:3303 (boot, inside a SYNC planRebootRestore callback) and src/web/routes/reboot-restore-routes.ts:148 (click) |
Breaks the #516 rule; a dead network mount freezes boot or the click. probePathKind() is async, so the caller must pre-probe unique dirs and pass a kind lookup into the pure planner |
| F4 | Restored sessions lose their tab group and Focus mark | Route calls ctx.addSession(session) with no hint; SessionPlacementHint (src/tab-layout-service.ts:79) carries tabGroupId only; stale cleanup removed the refs |
Capture group, focus and position at plan time; extend the hint with focus, applied in the same sessionCreated() write (setTabFocus() exists in src/tab-layout.ts:412) |
| F5 | Owned remote sessions are orphaned after a LOCAL reboot | reconcileSessions() (src/tmux-manager.ts:3015) marks them dead (local ssh pane gone); plan rejects remote-or-docker; record pruned; remote discovery lists tmux -L codeman only (src/remote-hosts.ts:455) while owned sessions live on -L codeman-remote (src/tmux-manager.ts:1059) |
Running remote agents become invisible and keep burning quota. Restore by reattach |
| F6 | Codex originator stamping no longer works | Rollout heads in ~/.codex/sessions: 0.147.0 (2026-09-24 UTC, 5 files) codeman_<uuid>; 0.162.0/0.162.1 (2026-10-08 UTC onward, including rollouts from Codeman beta instances) codex-tui. codex --help 0.162 lists agents ("shared local app-server daemon") and --no-daemon |
findActiveCodexFile() step 1 silently falls through. History correlation still works. Candidate fix: launch with --no-daemon (measure first) |
| F7 | pi and grok take a caller-chosen id, with different semantics | pi --help 1.1.0: --session-id <id> Use exact project session ID, creating it if missing; grok --help 1.0.52: -s, --session-id "for a new conversation (must be a valid UUID and must not already exist ...). Does not resume existing sessions" |
pi: one flag for every launch. grok: --session-id on the first launch only, --resume <id> afterwards (fallback chain + respawn pin, see PR F2) |
| F8 | SIGTERM already flushes state | shutdown() (src/cli.ts:1097) calls server.stop(): mux.destroy() (stops the pane-exit watcher), persistDeb.flushAll, _persistSessionStateNow() per session, store.flushAll(); state saves debounce 500 ms (src/state-store.ts:47) |
A shutdown hook adds little for state. Its value is scrollback, an exact reboot marker, and the window between logind's PrepareForShutdown and SIGTERM |
| F9 | Resume ids failing a token pattern are dropped silently | renderArg() (src/config/cli-registry/argv.ts) returns null when resolveParam() rejects the value; only _buildRespawnPaneOptionsWithResumePin() logs it, claude only |
A "resume" could silently start a fresh conversation. Validate against launch.params.resumeId first and refuse with a reason |
| F10 | A tmux server that dies before Codeman persists erases pid |
Interactive PTY onExit (src/session.ts:3055) sets _pid = null, and the exit listener (src/web/session-listener-wiring.ts:153) persists it; stop() then persists the same nulled state |
Every such session is refused as not-running. Likely on macOS (launchd signals tmux concurrently) and for non-service runs (codeman web -d, npm run dev: logind kills the session scope at once). Linux service installs are safe (KillMode=process: tmux outlives Codeman's stop()). Measure, then fix (PR A2) |
| F11 | Non-claude env overrides are not persisted | getEnvOverridesForPersist() (src/session.ts:2022) keeps CLAUDE_CODE_* + CLAUDE_CONFIG_DIR only |
A restored codex/dsh/grok/gemini/pi session loses CODEX_HOME, DSH_HOME, DSH_PERMISSION_MODE, PI_CODING_AGENT_SESSION_DIR, XAI_API_KEY, GOOGLE_*. The store-relocating ones make resume <id> look in the wrong store. Persist key NAMES always, and values only for a registry-declared non-secret list (decision 12) |
| F12 | Version gates use claude's version for every CLI | buildSpawnCommandFromRegistry() (src/session-cli-registry-bridge.ts:228) falls back to getClaudeCliVersion(); tmux-manager passes no version; resolveSessionCliVersion(mode) exists (src/utils/cli-resolver.ts:267) but only stamps the session |
A pi/grok capabilities.gates entry would be judged against claude 2.1.296. PR F1 must route the gate through the CLI's own version first |
| F13 | A non-granted owner's CLAUDE_CONFIG_DIR is stripped on restore |
Route calls clampEnvOverridesForOwner(); CLAUDE_CONFIG_DIR is a claude privilegedEnvKeys entry |
claude --resume X finds no transcript in the default dir, the || --session-id <id> fallback starts a FRESH conversation on a different account. Refuse instead (config-dir-revoked) |
| F14 | Unprivileged busctl monitor --system is refused |
Measured: Call to org.freedesktop.DBus.Monitoring.BecomeMonitor failed: Access denied; gdbus monitor --system --dest org.freedesktop.login1 runs unprivileged |
PR K uses gdbus monitor (feature-detected), not busctl monitor |
| F15 | The remote alive probe cannot see attached sessions | buildRemoteSessionAliveCommand() (src/remote-hosts.ts:365) hardcodes tmux -L codeman-remote; an attached (owned:false) session lives on -L codeman (remoteTmuxLocation(), src/tmux-manager.ts:1084). It also runs execAsync outside remote-ssh-limiter.ts |
PR D passes the socket from remoteTmuxLocation() and runs the probe under the limiter |
2. Current behavior, precisely
Timeline, heuristic, eligibility, rebuild, why it is claude-only, what persists
2.1 Timeline
| When | Where | What happens |
|---|---|---|
| Shutdown (systemd/launchd SIGTERM) | src/cli.ts shutdown(), WebServer.stop() (src/web/server.ts:4004) |
Logs server_stopped, mux.destroy(), flushes the persist debounce, persists every session, store.flushAll(). Does NOT kill tmux (unit has KillMode=process). 10 s force-exit budget (SHUTDOWN_FORCE_EXIT_MS) |
| Power loss | n/a | state.json is at most ~600 ms stale (100 ms persistDeb + 500 ms SAVE_DEBOUNCE_MS) |
| tmux dies first (F10) | PTY onExit |
pid: null persisted for every session before SIGTERM arrives |
| Boot | restoreMuxSessions() (src/web/server.ts:3495) |
mux.reconcileSessions() lists panes on the instance socket; every tracked session without a pane goes to dead |
| Same pass | planRebootRestoreOffer(dead, alive.length) (src/web/server.ts:3287) |
Heuristic, then planRebootRestore(); entries into rebootRestoreRegistry (memory). Own try/catch, so a throw never fails recovery |
| Same pass | finalizeRestoredState() (src/web/server.ts:3862) |
cleanupStaleSessions() deletes every unpinned record not live (and its tab-layout refs via runStaleSessionCleanup), then reconcileAfterRestoration() |
| Page load / SSE reconnect | initRebootRestoreBanner() / refreshRebootRestoreBanner() (src/web/public/reboot-restore-ui.js) |
GET /api/reboot-restore (ownership-filtered) shows "Restore N sessions from before the reboot"; button title says history does not return. Strings are English-only |
| Click | POST /api/reboot-restore/restore |
Rebuild, see 2.4. Dismiss posts /api/reboot-restore/dismiss. Plan expires after 24 h (PLAN_TTL_MS) |
2.2 Heuristic (looksLikeHostReboot, decides whether to ASK only)
All must hold: deadSessionCount > 0, livePaneCount === 0, newestPersistedActivityAt > 0, and now - os.uptime()*1000 > newestPersistedActivityAt. Known gaps: in a container os.uptime() is the host's, so a container-only restart (Compose self-update) shows no banner; an OOM-killed or hand-killed tmux server on a long-uptime host shows none either (by design).
2.3 Eligibility (planRebootRestore)
| Reason | Rule |
|---|---|
no-persisted-record |
unpinned kill already deleted the record |
intentionally-ended |
status not in idle/busy/error (pinned kill demotes to stopped) |
not-running |
pid null/undefined at last persist (also hit by F10) |
agent-exited |
isCleanPaneExit(state.paneExit) (explicit status 0, #446) |
respawn-blocked |
PTY-exit breaker tripped |
remote-or-docker |
state.remote or state.docker |
unsupported-mode |
transcript capability is not claude-jsonl |
no-working-dir, workspace-missing |
missing or existsSync false |
click-time: already-live, capacity-reached, workspace-forbidden, rebuild-failed |
see 2.4 |
resolveResumeConversationId(state) = tail of claudeSessionChain (first-hand hook ids, survives /clear while workspace hooks are on) else resumeSessionId else the session id (claude was launched with --session-id <id>).
2.4 Rebuild (click)
beginSpending(owner)single-flight per owner (409 otherwise), thentake()synchronously BEFORE the first await. Entries not built go back viareleaseFlight()infinally, exceptalready-live.- Per entry, re-read live sets fresh:
rejectAlreadyLive()on session ids andsession.claudeSessionId. sessionCapacityMessage(ctx.sessions, entry.owner),existsSync(workingDir),isWorkingDirAllowedForUsername(entry.owner, ...), keyed on the OWNER.new Session({ id: saved.id, mode, name, nameSource, createdAt, claudeMode: resolveClaudeModeForUsername(..., saved.owner), resumeSessionId, envOverrides: clampEnvOverridesForOwner(saved.owner, __envOverrides), effort, model, advisorModel, attachmentHistory, lastSubmitAt, claudeSessionChain, lastActivityAt, owner, parentSessionId }). No<Mode>Configis passed, although every one is persisted bytoState()(src/session.ts:1973).ctx.addSession,reapplyPersistedSessionState(before-spawn), listeners,startInteractive(),reapplyPersistedSessionState(after-spawn, { rearmAutoResumeSchedule: false }), persist,applyWorkspaceHooks(whenhooks: 'always'),seedAgentSessionPreamble, lifecyclerecovered, broadcastsession:created, restart stats collection.- Comes back attached, idle and disarmed. Failure is undone with
discardPartiallyBuiltSession(). Success is declared whenstartInteractive()resolves; nobody checks that the agent survived its first seconds.
2.5 Why claude-only
The rebuild hands the id through the top-level resumeSessionId, which only claude's launch reads (legacyConfigAliases: { resumeId: 'resumeSessionId' }, no legacyConfigField). Every other CLI reads its resume id from its own <Mode>Config (codexConfig.resumeSessionId, openCodeConfig.continueSession, geminiConfig.resumeSession, antigravityConfig.resumeConversationId, piConfig/grokConfig/deepSeekConfig/ompConfig.resumeSessionId), and the route passes none of them. For most of them Codeman never stored an id to pass.
2.6 What persists across a reboot today
| Data | Store | Survives? | Notes |
|---|---|---|---|
| Session records | state.json .sessions |
Until boot pruning | Unpinned dead records deleted by cleanupStaleSessions(); pinned kept |
<Mode>Config objects |
same | Yes | Persisted whole by toState(), unused by restore |
| Env overrides | same (__envOverrides) |
Partly | CLAUDE_CODE_* + CLAUDE_CONFIG_DIR only (F11) |
| Plan | memory | Until next server stop | F2 |
| Tab groups + order | state.json tabLayouts, sessionOrder |
Groups yes (an emptied group survives), refs of dead sessions no | F4 |
| Mux records | mux-sessions.json |
Dead ones removed at reconcile | |
| Conversations | each CLI's own store | Yes | Resume list (resumeHistorySession(), src/web/public/terminal-ui.js:3633): claude by exact id; codex by exact id only when the rollout scanner supplied resumeId; opencode/pi/grok/omp by continueSession (newest in dir); deepseek by bare --resume; gemini/antigravity not wired |
| Lifecycle log | session-lifecycle.jsonl |
Yes | Has server_stopped; tells clean shutdown from power loss |
| Scrollback | tmux server memory | No | Remote panes keep theirs on the remote host (its history-limit, 2,000 lines unless raised) |
3. Per-CLI resume matrix
Flags verified by --help on the installed binaries only (no model session started); see Appendix A.
| CLI | Installed here | Resume syntax (evidence) | Id chosen by Codeman at launch? | How Codeman knows the id today | Persisted today | Verdict |
|---|---|---|---|---|---|---|
| claude | 2.1.296 | -r, --resume [value], --session-id <uuid>, -c, --fork-session |
Yes: --session-id <codeman id> |
The id; claudeSessionChain from first-hand hook session_id (src/web/routes/hook-event-routes.ts:131) |
Yes | Resumable (shipped) |
| codex | 0.162.0 | codex resume [SESSION_ID] ("UUID or session name"), --last, codex fork; --no-daemon |
No flag | Originator stamp (broken, F6); resolveCodexThreadFromHistory() (src/web/routes/session-routes.ts:2870) correlates lastSubmitAt with a 64 KiB tail of ~/.codex/history.jsonl, response viewer only |
codexConfig.resumeSessionId only if resumed; lastSubmitAt yes |
Partially: learn and store |
| opencode | 1.3.0 (~/.opencode/bin, not on PATH) |
-s, --session <id>, -c, --fork; opencode session list --format json -n <N>, opencode export [sessionID]; store ~/.local/share/opencode/opencode.db |
No | Nothing | openCodeConfig.continueSession if resumed |
Partially: needs a learner |
| gemini | not installed | --resume (latest), --resume <index|uuid>, --list-sessions; store ~/.gemini/tmp/<project_hash>/chats/ (upstream docs, unverified here) |
No | Nothing | geminiConfig.resumeSession if resumed |
Partially, unverified |
antigravity (agy) |
1.3.4 | --conversation <id>, --continue/-c; no list subcommand; store ~/.gemini/antigravity-cli/conversations/ (empty here) + conversation_summaries.db |
No | Nothing | antigravityConfig.resumeConversationId if resumed |
Not resumable for fresh sessions without a hook or store reader |
| pi | 1.1.0 | --session <path|id> (partial UUID ok), --session-id <id> (create or reuse), -c, -r picker, --fork, --session-dir, env PI_CODING_AGENT_SESSION_DIR |
Yes | Nothing | piConfig.resumeSessionId if resumed |
Resumable after F1 |
| grok | 1.0.52 | -r, --resume [<ID_OR_TITLE>] ("UUID-shaped values always mean IDs"), -c, -s, --session-id (new only, refuses an existing id), --fork-session; grok sessions list/search/delete |
Yes, first launch only | Nothing | grokConfig.resumeSessionId if resumed |
Resumable after F2 |
deepseek (dsh) |
0.1.1-rc.2 | dsh --profile tui --resume <session> ("arguments after the launcher flags reach the app"); registry renders --resume <id> or bare --resume |
No | findDeepSeekTranscript() (src/deepseek-transcript.ts:532) returns a PATH paired by header cwd + 60 s window; header reader is private |
deepSeekConfig.resumeSessionId if resumed |
Partially; resume handling lives in the third-party TUI profile |
| omp | not installed | --resume <id>, --continue (registry omp entry) |
No | _maybeCaptureOmpSessionId() (first idle) and _pinOmpRespawnId() (src/session.ts:3614, :2513) via resolveAndClaimOmpSessionId() |
Yes (ompConfig.resumeSessionId) |
Resumable (code-only verification) |
| shell | n/a | none | n/a | n/a | n/a | Not resumable: new login shell in the same directory |
3.1 How Codeman should learn and keep each id
Principle: learn the id while the pane is alive, validate it, persist it, so the boot-time plan never scans a store. One generic field rather than the live launch config:
// SessionState (persisted, also in toState())
conversationRef?: { id: string; source: 'launch' | 'hook' | 'history' | 'store'; at: number };Rules for every learner: the id must pass the CLI's launch.params.resumeId pattern BEFORE it is stored (store contents are written by a prompt-injectable agent); pair only inside the session's own workingDir (in multi-user mode every Codeman user shares the OS account's CLI stores); never fall back to "newest in store"; call persistSessionState() after a change. claude keeps claudeSessionChain. Restore resolves: claude chain logic, else conversationRef.id, else the mode config's resume id.
| CLI | Learner | Trigger | Cost and caveats |
|---|---|---|---|
| claude | unchanged | hooks | 0. Without workspace hooks the chain misses /clear |
| pi | mint: every launch renders --session-id <codeman id> unless resumeId/continueSession is set; conversationRef = { id, source: 'launch' } |
spawn | 0. Version gate (needs F12 fix). Older pi: omp-style store resolver |
| grok | mint: first launch --session-id <codeman id>; every later launch --resume <id> (variants resume then new, chain: 'fallback') |
spawn | 0. Version gate. Measure grok's exit status on an unknown --resume id and on a user quit before shipping the chain |
| omp | existing capture; also write conversationRef |
first idle, respawn | existing |
| codex | extract resolveCodexThreadFromHistory() into src/codex-thread-resolver.ts; run it debounced ~5 s after lastSubmitAt changes; honour the session's own CODEX_HOME (today it reads the server env only) |
each Enter through Codeman | one 64 KiB tail read. Misses panes driven from tmux directly (no lastSubmitAt). Docker: history.jsonl is not shared, so no learner there |
| deepseek | export the header reader; take ONLY the in-window match from findDeepSeekTranscript() (its laterMatch fallback can be a sibling started later) then the header id; claim set like omp |
first idle | bounded header reads. Needs the session's DSH_HOME (F11) |
| opencode | bounded execFile of opencode session list --format json -n 20 with cwd: workingDir (sessions are project-scoped), timeout + maxBuffer, pick the unclaimed one created in the window |
first idle | one short subprocess that may touch the SQLite db. JSON field names to verify |
| gemini | scan ~/.gemini/tmp/<hash>/chats/ for files created after createdAt, pair like dsh |
first idle | Verify on a machine with gemini |
| antigravity | none safe today; option: Codeman-owned hook (herdr reportedly uses a PreInvocation hook in ~/.gemini/config/hooks.json; that file does not exist here and the path is unverified) |
n/a | Owner decision 7 |
The Session constructor's alias line (src/session.ts:942, resumeSessionId || ompConfig.resumeSessionId || codexConfig.resumeSessionId || id) becomes a registry-driven conversationIdOf() reading the mode's resume alias plus conversationRef, so the unified list folds pi/grok/dsh rows and rejectAlreadyLive() sees every CLI's conversation. No CLI-id branches (test/cli-registry-no-id-branching.test.ts).
3.2 When no id is known
| Option | Behaviour | Risk |
|---|---|---|
| Skip (today) | not offered | user re-creates by hand |
| Fresh in the same folder (recommended) | relaunch with the saved config and no resume flag; row says "starts a new conversation" | none beyond a new conversation |
Continue-latest (--continue, -c, --last) |
resumes the newest conversation in that dir | can grab a SIBLING's conversation (the _pinOmpRespawnId() comment documents a live occurrence). Not recommended |
4. Scrollback
What exists, measured capture cost, options, recommended design
4.1 What exists
capturePaneBuffer(..., { fullHistory: true })(src/tmux-manager.ts:4003) runscapture-pane -p -e -J -S -<N>throughexecSync; history limit 100,000 lines (DEFAULT_TMUX_HISTORY_LIMIT).- Claude panes were measured with
history_size=0; for claude the transcript, which--resumerepaints, IS the history. Shells, inline renderers, opencode and pi keep real tmux history. - Remote sessions: the remote tmux keeps its own history (
history-limit, 2,000 lines by default) andremote-pane-history.tssplices it (scrollbackOverride), so a reattach brings it back.
4.2 Measured cost (private throwaway socket, 200x50 pane, 100k colored lines, two runs)
-S -N |
Time | Bytes | gzip |
|---|---|---|---|
| 5,000 | 0.04 s | 434 to 495 KB | 19 to 29 KB |
| 20,000 | 0.15 to 0.17 s | 1.7 to 2.0 MB | 76 to 113 KB |
| 100,000 | 0.74 to 0.75 s | 8.6 to 9.8 MB | 377 to 564 KB |
tmux is single-threaded: a 0.75 s capture stalls output for every pane on the socket, and through execSync it also blocks the Node event loop. Synthetic text compresses ~20x; expect 5x to 10x on real output.
4.3 Options
| Option | How | Pros | Cons |
|---|---|---|---|
| S1 Periodic snapshots | every 10 min, only sessions whose lastActivityAt advanced, async execFile, one pane at a time, last 5,000 lines |
survives power loss | up to 10 min stale; disk holds secrets |
| S2 On-shutdown snapshot | inside stop() BEFORE mux.destroy(), total budget ~3 s (inside the 10 s force-exit) |
freshest | clean shutdown only; macOS may kill tmux concurrently |
| S1 + S2 (recommended) | both, same writer | best coverage | |
| R1 Read-only viewer (recommended first) | "Terminal history from before the reboot" panel | zero risk to the live pane | not inline |
| R2 Replay into the pane (shell only) | new pane runs cat <snapshot> before exec $SHELL (tmux-resurrect's approach) |
feels native | changes the shell launch; agent TUIs repaint over it |
4.4 Recommended design
- Opt-in setting
paneHistorySnapshotsEnabled(SYNCED, default OFF), pluspaneHistorySnapshotLines(default 5,000, max 20,000). - Files
dataPath('pane-history', '<sessionId>.ansi.gz'), dir 0700, files 0600, tmp+rename. Per-file cap 2 MiB compressed, total cap 64 MiB, oldest-first eviction. - Sanitize to printable text + SGR only before write (strip OSC 8/52, titles, DCS as defense in depth); the viewer renders through xterm, never HTML.
- Local mux sessions only; skip remote (own history), docker (nested tmux keeps no host-side history), discovered sessions.
- Lifetime: deleted by
cleanupSession(), on Dismiss, after restore once viewed, and at plan TTL. Never indexed by/api/search, never in exports. Read only through an ownership-checked route (findSessionOrFailwithreq). - New async capture
capturePaneHistoryAsync(muxName, lines)(neverexecSyncon a timer).
5. Saving before shutdown
What SIGTERM already does, systemd-logind, launchd, the exit-persistence race, exact reboot detection
5.1 Already done today
SIGTERM, SIGINT and SIGHUP run server.stop(). systemd unit (scripts/codeman-web.service, buildSystemdUnit() in src/service-installer.ts:189) uses KillMode=process: the tmux server stays in the unit cgroup, is not signalled when the main process stops, and dies later with the user manager. launchd plist (buildLaunchAgentPlist(), :150) has no ExitTimeOut (default 20 s). Non-service runs (codeman web -d, a terminal) sit in the login session scope, which logind kills all at once (F10).
5.2 Linux (systemd-logind)
- Delay inhibitor + signal watch with stock tools (no native D-Bus binding):
- hold
systemd-inhibit --what=shutdown --mode=delay --who=Codeman --why="Saving sessions" <long-lived child>; - watch
gdbus monitor --system --dest org.freedesktop.login1 --object-path /org/freedesktop/login1and parsePrepareForShutdown (true,). NOTbusctl monitor(F14: unprivilegedBecomeMonitoris denied).gdbusships with glib (libglib2.0-binon Debian), so feature-detect it. - On
PrepareForShutdown(true): setshuttingDown, snapshot (4.4), writedataPath('last-shutdown.json'){ at, bootId, reason: 'logind' }, flush, then kill the inhibitor child to release. On(false)re-acquire.
- hold
- Bounded by logind's
InhibitDelayMaxSec(default 5 s); never blocks shutdown. Verify polkit allowsorg.freedesktop.login1.inhibit-delay-shutdownfor a headless lingering user. - Skip when a binary is missing, under
VITEST, inside containers.
5.3 macOS (launchd)
- The SIGTERM launchd sends at restart or logout IS the hook; Node cannot see
NSWorkspaceWillPowerOffNotificationwithout native code. - Add
<key>ExitTimeOut</key><integer>30</integer>to the generated plist. tmux may be killed concurrently (F10), so periodic snapshots (S1) carry the guarantee there.
5.4 The sweep and exit-persistence race
stop() already stops the pane-exit watcher (mux.destroy()), so the clean-exit sweep (src/pane-exit-sweep.ts, 2 confirming reads, 10 s minimum lifetime) can only race in the window BEFORE SIGTERM (after PrepareForShutdown, or when tmux dies first). A shuttingDown flag set on PrepareForShutdown and first thing in stop() must freeze both the sweep and the F10 exit persistence.
5.5 Exact reboot detection
Store { bootId, startedAt } in dataPath('host-boot.json') at each start. Linux: /proc/sys/kernel/random/boot_id; macOS: sysctl -n kern.boottime (bounded execFile). A changed boot id plus zero live panes is a certain reboot; keep the uptime test as fallback. In a container (isRunningInContainer(), src/web/self-update.ts:461) use PID 1's start time (/proc/1/stat field 22), which closes the Compose self-update gap.
6. Remote SSH and Docker cases
Owned and attached remote sessions, Wake-on-LAN, owned and adopted Docker containers
| Case | After a LOCAL reboot | Restore action | Never |
|---|---|---|---|
| Remote, owned | local ssh pane gone; remote tmux -L codeman-remote session codeman-ssh-<id8> still runs unless the remote also rebooted |
Probe at CLICK time (never at boot) with remoteTmuxSessionAlive() on the socket from remoteTmuxLocation(), under the ssh limiter, with connection options re-read from remote-hosts.json. true/false: rebuild with remote metadata; buildRemoteLaunchCommand's new-session -A reattaches when alive and otherwise launches, and claude's remote command already resumes (--session-id X || --resume X), omp's renders --resume/--continue, others start fresh (row label says so). undefined: keep on offer as "host unreachable" |
relaunch on undefined; any hand-built ssh line (use buildSshConnectionArgs); local resolveCliLaunchError (the CLI lives on the remote) |
Remote, attached (owned: false) |
same | only re-attach (buildRemoteAttachCommand, tmux -L codeman attach); false drops the entry |
create or kill anything remote |
| Remote, dismissed | the remote agent keeps running with nothing to find it | Dismiss of an owned entry says so and offers "Stop remote agent" (owned only, existing kill builder) | silent orphaning |
| Wake-on-LAN | host may be asleep | never at boot or plan time; the click MAY call ensureHostAwake() (decision 5) |
wake from the boot pass |
| Docker, owned | container stopped (--restart no, src/docker-hosts.ts:503), in-container tmux gone; workspace, claude projects/, codex sessions/, omp sessions/ on bind mounts; pi/grok stores live in the container's writable layer |
quick-start's docker preflight: case exists, owner, drift (checkDockerConfigDrift), availableModes, daemon reachable (bounded); launch chain restarts the SAME container; claude via claudeDockerPaneCommand (--session-id X || --resume X), others via appendResumeFlag with conversationRef |
--privileged, docker socket, secrets via -e; recreating a drifted container (that deletes pi/grok conversations) |
Docker, adopted (owned: false) |
container state is the user's | restore only if running; else keep on offer as "container not running" | start, stop or create it |
| Codeman itself in Compose | host uptime long, container restarted | 5.5 PID-1 detection |
Session id reuse (id: saved.id) is load-bearing: remote reattach derives codeman-ssh-<id8> from it, and pi/grok minted ids equal it.
7. Security and multi-user
Click-time checks against the entry owner, and the edge cases each PR must handle
Every check runs at CLICK time against the entry's OWNER (never the caller), because an admin may spend another user's entry and grants change between boot and click.
| Check | Today | Needed |
|---|---|---|
List / take / dismiss scoped by canAccessOwned |
yes | keep |
| Owner still exists (multi-user) | no (findUser miss reads as role user) |
refuse owner-missing, kept on offer for an admin to dismiss |
Workspace confinement isWorkingDirAllowedForUsername(owner) |
yes | keep; probe BOUNDED (F3), unknown stays on offer as workspace-unreachable, never "missing" |
Claude permission mode resolveClaudeModeForUsername |
yes | keep |
Env clamp clampEnvOverridesForOwner |
yes | keep; if it strips CLAUDE_CONFIG_DIR, refuse config-dir-revoked (F13) |
External CLI privilege clamp (codex bypass, gemini yolo, agy skip-permissions, pi approveProjectTrust, grok alwaysApprove, dsh DSH_PERMISSION_MODE) |
n/a | move clampExternalCliBypassForOwner() (src/web/routes/session-routes.ts:529) into a shared module and apply it to the persisted <Mode>Config (materialize branch included) |
Shell is arbitrary execution (capabilities.privilegedCommandGate) |
n/a | canUsernameRunPrivilegedCommands(owner) or refuse (kept on offer) |
CLI available (resolveCliLaunchError, src/utils/cli-launcher.ts:67; enabled: false; dsh runnable profile) |
n/a | refuse cli-unavailable, kept on offer. Local sessions only |
| Resume id shape | claude only | validate against launch.params.resumeId before render (F9); ids from CLI stores are untrusted |
| Remote | rejected | attached entries need the owner to still be admin (same gate as attachRemoteSession, BEFORE host lookup); owned entries need the RemoteCase to still exist and belong to the owner, and the host to still exist; per-host commands overrides come from the CURRENT host record |
| Docker | rejected | adoption admin-only; adopted container never started; drift refuses |
Custom model (__customModel) |
endpoint existence only (_rebuildCustomModelEnv) |
same as mux recovery; optional: drop the selection when customModelEndpointsEnabled is now off |
| Nothing auto-runs | click-only; respawn, Ralph, auto-resume stamp disarmed | keep; auto-restore is decision 2, never in multi-user mode |
| New files | n/a | plan file and snapshots 0600 in 0700 dirs, tmp+rename, dataPath() only; the plan file is parsed defensively (malformed = no plan) and holds the same fields as state.json (__envOverrides filtered, __customModel keys only, __attachmentHistory) |
7.1 Edge cases the PRs must handle
| Case | Handling |
|---|---|
| Two entries resolve to one conversation | dedupe at plan time (keep newest lastActivityAt); the per-entry rejectAlreadyLive() catches the rest once conversationIdOf() is generic |
| Conversation already resumed by hand in Codeman | already-live (exists for claude; generic after C2) |
| Conversation open OUTSIDE Codeman (plain terminal, another instance) | undetectable (no CLI lock to read); documented residual |
| Workspace deleted / mount dead | workspace-missing only on absent; unknown = workspace-unreachable, kept on offer |
| CLI upgraded across the reboot | gates evaluated at click time with a fresh probe (never a cached failure); post-start check: if the agent pane is dead within ~15 s (paneExit non-zero), report resume-failed in the response and toast, keep the session row |
| CLI removed | cli-unavailable, kept on offer |
| Owner deleted, grant withdrawn | owner-missing, workspace-forbidden, clamps re-run |
| Remote host also rebooted / asleep / unreachable | false relaunch per 6; asleep needs decision 5; undefined kept on offer |
| Session closed on purpose just before the reboot | unpinned close deletes the record, pinned close demotes to stopped; a power loss inside the ~600 ms debounce can resurrect it (accepted: click-only) |
| Second reboot before the click | PR B carries unexpired entries forward into the new boot's plan (their records are already gone) |
| Server restart before the click | PR B durable plan |
Agent-spawned workers (parentSessionId) and cron runs |
offered, but unchecked by default once per-row choice exists (PR L) |
| Secrets in saved scrollback | opt-in, 0600, caps, TTL, deleted on Dismiss, never searched or exported |
| Disk growth | snapshot caps (2 MiB/file, 64 MiB total); plan file bounded by MAX_CONCURRENT_SESSIONS records |
8. Phased rollout
8.1 PR list
| PR | Title | Size | Risk |
|---|---|---|---|
| A1 | Harden the shipped path: bounded probe, group/focus placement, dedupe, owner-missing, config-dir refusal, zh-CN | S | low |
| A2 | Keep a dying tmux server from erasing pid (F10), measured first |
S | low-med |
| B | Durable plan, exact boot detection, carry-forward | M | low-med |
| C1 | Move the owner clamps into a shared module (no behaviour change) | S | low |
| C2 | Generic restore model: capabilities.restore, conversationRef, env-key bookkeeping, resume-id validation, post-start check, shell restore |
M | med |
| D | Remote sessions: reattach or resume | M | med |
| F1 | Per-CLI version gates (F12) + pi mints its id | S | low-med |
| F2 | grok mints its id (resume variant, chain, respawn pin) | S | med |
| E | Codex + omp: learn and keep the id; codex --no-daemon investigation (F6) |
M | med |
| G1/G2/G3 | dsh, opencode, gemini learners (one PR each) | S each | med |
| H | Docker sessions | M | med |
| I | Scrollback snapshots (opt-in) | M | med |
| J | Pre-reboot history viewer | S | low |
| K | Shutdown hook (logind via gdbus, launchd ExitTimeOut, shuttingDown) |
M | med |
| L | Banner v2: per-row choice, labels, defaults | S | low |
8.0 Shared E2E recipe: simulated reboot on an isolated instance
Never on the shared checkout, never on tmux -L codeman, never touching w1/w2/w3. Scratch workspaces only (a beta DELETE removes the workspace's upload dirs).
# in a worktree of the PR branch
npm install && npm run build
export CODEMAN_INSTANCE=rrbeta CODEMAN_PORT=5191 # data ~/.codeman-rrbeta, socket codeman-rrbeta
node dist/index.js web & # or scripts/run-beta.sh
# create one session per CLI via POST /api/sessions + /interactive, drive one turn each
kill -TERM <beta pid> # Linux-service order: Codeman first
tmux -L codeman-rrbeta kill-server # ONLY the beta socket
jq '.sessions | map_values(.pid)' ~/.codeman-rrbeta/state.json # every pid must be non-null
BOOT_MS=$(( $(date -d "$(uptime -s)" +%s) * 1000 ))
SCRATCH=<a scratch dir, not /tmp>; TMP="$SCRATCH/rr.json"
jq --argjson t $((BOOT_MS - 3600000)) \
'.sessions |= map_values(.lastActivityAt = $t | .createdAt = $t)' \
~/.codeman-rrbeta/state.json > "$TMP" && mv "$TMP" ~/.codeman-rrbeta/state.json
node dist/index.js web &
curl -s localhost:5191/api/reboot-restore | jq
# Playwright: waitUntil 'domcontentloaded', wait 3-4 s, banner visible, click Restore
tmux -L codeman-rrbeta capture-pane -p -t <pane> # the resumed conversation is on screenVariants: tmux-first order (tmux -L codeman-rrbeta kill-server BEFORE kill -TERM) reproduces F10 and must still offer every session after PR A2. After PR B the jq step becomes a fake host-boot.json with a different bootId. Multi-user variants run the beta with --multiuser and two users. A real reboot runs once on a Linux VM and once on a macOS testbed (PR A2, PR K).
Per-PR scope, files, tests and E2E (A1 to L)
PR A1: Harden the shipped path
- Scope:
- Boot: probe each unique
workingDirwithprobePathKind()(stall cap kept, it is a bulk scan) BEFOREfinalizeRestoredState(), in parallel;planRebootRestore()takes a(dir) => PathProbeKindlookup and stays pure.absent=workspace-missing,unknown= newworkspace-unreachable(kept on offer), a non-directory =workspace-missing. - Click:
probePathKind(dir, { pastCap: true })per entry (the user asked for this path). - Placement: in
planRebootRestoreOffer(), readstore.getTabLayout(ownerOf(record))(@singlewhen multi-user is off) and recordtabGroupId,focus, index. ExtendSessionPlacementHintwithfocus?: trueand applysetTabFocus()inside the samesessionCreated()write; pass{ tabGroupId, focus }toctx.addSession(). Unknown group = ignored (existing behaviour). Exact index is a follow-up (append is today's rule). - Dedupe entries resolving to one conversation id.
owner-missing(multi-user,findUsermiss) andconfig-dir-revoked(F13) refusals, both kept on offer.- zh-CN for banner and toast strings through
i18n.js; new reasons inrebootSkipReason().
- Boot: probe each unique
- Files:
src/reboot-restore.ts,src/web/server.ts,src/tab-layout-service.ts,src/web/routes/reboot-restore-routes.ts,src/web/public/reboot-restore-ui.js,src/web/public/i18n.js,docs/architecture-invariants.md#reboot-restore,docs/api-reference.md(new reasons, additive). - Tests:
test/reboot-restore.test.ts(unknownis neverworkspace-missing; dedupe),test/routes/reboot-restore-routes.test.ts(group + focus round-trip in ONE layout write; unreachable/owner-missing/config-dir kept on offer), an i18n test in the style oftest/tile-grid-i18n.test.ts. - E2E: 8.0 with two sessions in a named group, one focused; after restore both are back in the group and the focus shortcut is back. A third session on a
CLAUDE_CONFIG_DIRfor a non-granted owner stays on offer. - Risk: low; placement only through
sessionCreated()(never a follow-up PUT).
PR A2: Keep a dying tmux server from erasing pid
- Measure first: 8.0 tmux-first variant on Linux; real restart on the macOS testbed;
codeman web -don Linux with a logout. Record which order each setup produces. - Scope (direction, final shape after measuring): when an attach PTY exits, ask the mux whether the tmux SERVER is gone (one bounded
list-sessionsfor the whole burst, cached ~1 s); if so, do not persistpid: null/idlefor that session, and setshuttingDown-like suppression until the next start. Alternative if that proves flaky: persist a durablelastLiveAtand let the planner treat "pid null but live within N s of the newest activity" as eligible. - Files:
src/session.ts(exit bookkeeping),src/web/session-listener-wiring.ts,src/tmux-manager.ts(server-alive probe),src/reboot-restore.ts. - Tests: a fake mux reporting "server gone" keeps
pidin the persisted record; a single agent exit with the server alive still nulls it (no regression for Sessions whose CLI exited stay on the board as idle rows #446). - Risk: low-med; must not keep a genuinely dead single session looking alive.
PR B: Durable plan, exact boot detection, carry-forward
- Scope: persist the plan to
dataPath('reboot-restore-plan.json')(0600, tmp+rename) onset(),take(),releaseFlight(),clear(); load at boot when not expired; delete when empty. On a NEW boot, merge unexpired entries of the previous plan into the new one (records are already pruned, so this is the only copy), dedupe by session id.host-boot.json+bootIdChangedevidence inlooksLikeHostReboot()(uptime kept as fallback); container PID-1 start time. - Files:
src/web/reboot-restore-registry.ts(persistence port injected; stays IO-free in tests), newsrc/host-boot.ts(pure parse + small IO),src/reboot-restore.ts,src/web/server.ts. - Tests: registry round-trip with a fake port; malformed file = empty plan; boot-id evidence table; container start-time parse; carry-forward across a second simulated boot; parked entries never written as available.
- E2E: 8.0, restart the beta server once more before clicking, banner still there; then a second simulated reboot, banner still offers the first reboot's sessions.
- Risk: a stale file re-offering sessions after a manual restore; guarded by the already-live check and delete-on-spend.
PR C1: Shared owner clamps
- Scope: move
clampExternalCliBypassForOwner()(and its test hook) out ofsession-routes.tsintosrc/session-privilege-clamp.ts(or next toclampEnvOverridesForOwner()insrc/session-env-clamp.ts);session-routes.tsandcron-service.tsimport it. No behaviour change. - Tests: existing clamp tests move with the function and stay green.
PR C2: Generic restore model
- Scope:
- Registry capability
capabilities.restore: { kind: 'resume-by-id' | 'relaunch-in-dir' | 'none' }(clauderesume-by-id, shellrelaunch-in-dir, othersnoneuntil their PR). Schema insrc/config/cli-registry/schema.ts;npm run generate:cli-catalogif the catalogue carries it. SessionState.conversationRefpersisted and intoState();conversationIdOf()replaces the alias line.- Env bookkeeping (F11): persist
__envOverrideKeys(names only) for every mode, plus values for a registry-declared non-secret list (env.persistableKeys, decision 12); a row whose non-persistable keys were set gets the label "environment not restored" (or is refused per decision 12). - Route builds the persisted
<Mode>Configgenerically (legacyConfigField+legacyConfigAliases.resumeId), applies the C1 clamp,resolveCliLaunchError(),privilegedCommandGate, resume-id pattern check (F9), and a post-start liveness check (resume-failed). - Entry gains
kindandresumeId?;GET /api/reboot-restoreitems gainkind(additive). - Shell restore: new login shell in
workingDir, owner must passcanUsernameRunPrivilegedCommands.
- Registry capability
- Files:
src/config/cli-registry/{types,schema,stock}.ts,src/types/session.ts,src/session.ts,src/session-manager.ts+src/web/server.ts(persist key names),src/reboot-restore.ts,src/web/routes/reboot-restore-routes.ts,src/web/schemas.ts, docs. - Tests: no-id-branching tests green; shell refused for a non-granted owner and kept on offer; codex bypass clamped for a non-granted owner; invalid resume id refused, never fresh; a pane dead within the window reports
resume-failed; env key names persisted, values of non-listed keys never on disk (grep the written file in the test). - E2E: 8.0 with a claude and a shell session, single-user and multi-user.
- Risk: medium; create paths unchanged (C1 moved the helpers).
PR D: Remote sessions
- Scope: plan kind
remote-reattach; the boot pass never touches the network. Click: owner/admin gates, host andRemoteCasestill exist, connection options andcommandsfrom the current host record (asrestoreMuxSessions()does withreadRemoteHosts), alive probe with the socket fromremoteTmuxLocation()(F15) underremote-ssh-limiter.ts, branches per section 6, optionalensureHostAwake()per decision 5. Dismiss of an owned entry offers "Stop remote agent" (decision 13). Never seed the agent preamble or install workspace hooks for remote. - Files:
src/remote-hosts.ts(probe takes the socket),src/reboot-restore.ts,src/web/routes/reboot-restore-routes.ts,src/web/server.ts. - Tests: probe command per socket (owned vs attached);
true/false/undefinedbranches with an injected probe (VITEST returnstrue); attached session never relaunched; non-admin refused before host lookup; deleted host or case refused. - E2E: beta instance with a remote case on a test host with a throwaway case, 8.0 locally only; the remote agent and its scrollback are back and
tmux -L codeman-remote lson the host shows one session, not two. Repeat after killing the remote session: claude resumes its conversation. - Risk: medium (ssh); relaunch only on a definite
false.
PR F1: Per-CLI version gates + pi
- Scope:
buildSpawnCommandFromRegistry()resolves the gate version from the entry's own CLI (resolveSessionCliVersion(entry.id), or the session's stampedcliVersion), nevergetClaudeCliVersion()for a non-claude entry (F12); docker and remote overlays keep failing closed. Then pi: asessionIdFlaggate and an arg--session-id <sessionId>whenresumeIdis unset andcontinueSessionis not true;conversationRef = { id: session.id, source: 'launch' }when the gate passed. - Measure first: minimum pi version with
--session-id; pi accepts a v4 UUID and creates<ts>_<uuid>.jsonl; a second launch with the same id resumes. - Files:
src/session-cli-registry-bridge.ts,src/config/cli-registry/stock.ts(+npm run generate:cli-catalog; commitconfig/clis.stock.jsonand theinstall.shblock if affected). - Tests: a non-claude gate judged on its own version (regression test for F12); pane-command goldens with the gate on and off.
- E2E: 8.0 with pi.
PR F2: grok
- Scope: grok variants
resume(--resume <resumeId>) andnew(--session-id <sessionId>),chain: 'fallback', version-gated. Restore and dead-pane respawn setresumeIdfromconversationRef. Generalize_buildRespawnPaneOptionsWithResumePin(): its existence probe (claudeTranscriptExists) is claude-specific, so a non-claude fallback CLI pinsconversationRef.idwhensource === 'launch'instead of probing~/.claude/projects. - Measure first: grok's exit status for
--resume <unknown uuid>and for an ordinary user quit (a non-zero quit would run the--session-idfallback, which then fails because the id exists). - Tests: goldens; respawn pin for a launch-minted grok id.
- E2E: 8.0 with grok.
PR E: Codex and omp
- Scope: extract
resolveCodexThreadFromHistory()and the rollout lookup intosrc/codex-thread-resolver.ts; take the sibling set as a parameter (at click time the siblings are plan entries, notctx.sessions); honour the session's ownCODEX_HOME. Learner writesconversationRef(sourcehistory). Click-time fallback runs the same correlation over a larger bounded tail (1 MiB) only when no ref was learned. omp writes its captured id intoconversationRef. Flip both toresume-by-id. F6: measure whether--no-daemon(or disablingdaemon_auto_start) restores thecodeman_<id>originator; if so, gate it on version in its own commit (decision 11). - Tests: resolver with fixture
history.jsonl(sibling panes, 15 s window, plan-sibling set); persisted id used on restore; codex launch renderscodex resume <id>. - E2E: 8.0 with codex. omp: code + unit tests only unless a machine with omp is available.
- Risk: misses panes driven only from tmux (no
lastSubmitAt); falls back to 3.2.
PR G1/G2/G3: deepseek, opencode, gemini learners
- Scope: one PR per CLI, each a first-idle learner (3.1) writing
conversationRefwith a claim set, then flipping the CLI toresume-by-id. dsh: in-window match only, exported header reader, sessionDSH_HOME. opencode: subprocess withcwd: workingDir, verify the JSON fields first. gemini needs a machine with gemini installed. - Tests: pairing fixtures (a sibling in the same dir started 2 min later is never picked; a pre-session conversation never eligible; an id failing the pattern is never stored).
- Risk: medium; pairing is heuristic, so the row says "resumes the conversation from ".
PR H: Docker sessions
- Scope: plan kind
docker-relaunch; click through quick-start's docker preflight (case exists, ownership, drift refuses rather than recreates, adopted-not-running stays on offer,availableModes, bounded daemon probe withunknownkept on offer); non-claude CLIs getconversationRefviaappendResumeFlag(quick-start seeds only Claude'slastClaudeSessionIdtoday). Label pi/grok rows "resume only if the container is reused". - Tests: adopted stopped container stays on offer and nothing is started; drift refuses; daemon
unknownkept. - E2E: 8.0 with an owned docker case (
node scripts/build-agent-image.mjs --no-cachefirst).
PR I: Scrollback snapshots (opt-in)
- Scope: section 4.4.
src/pane-history-snapshot.ts(pure policy), async capture inTmuxManager, writer timer throughCleanupManager, SIGTERM snapshot instop()BEFOREmux.destroy()with a 3 s budget, deletion incleanupSession()and on Dismiss. - Tests: policy (changed-only, caps, eviction, skips), file modes, writer never uses
execSync, sanitizer strips OSC/DCS,test/memory-leak-prevention.test.tsgreen. - E2E: enable, produce output in a shell session, wait one cycle, check mode and size, simulated reboot, file still there.
PR J: Pre-reboot history viewer
- Scope:
GET /api/sessions/:id/pre-reboot-history(ownership viafindSessionOrFailwithreq), banner and tab hint, read-only overlay xterm. R2 replay only after decision 4. - Tests: route ownership (multi-user 403/404), Playwright overlay render (browser suite, run
npm run test:browserby hand).
PR K: Shutdown hook
- Scope:
shuttingDownflag (set onPrepareForShutdownand first instop()) honoured by the sweep and the A2 exit path;last-shutdown.json; Linux logind watcher viagdbus monitor+systemd-inhibit(opt-out or opt-in per decision 8); plistExitTimeOut30. - Files: new
src/logind-shutdown-watch.ts(pure line parser split out),src/web/server.ts,src/service-installer.ts,src/pane-exit-sweep.tscaller. - Tests:
gdbus monitorline parser, inhibitor child lifecycle with a fake spawner, plist golden. - E2E: real reboot on a Linux VM with a lingering user service (journal shows the save before shutdown, snapshot files fresh); macOS testbed restart.
PR L: Banner v2
- Scope: per-row checkboxes using the existing
sessionIdsbody field; per-row kind label (resumes conversation / reattaches remote / new shell / new conversation / environment not restored / history only); skip reasons per row; agent-spawned workers and cron runs unchecked by default; zh-CN.
9. Recommended order
- A1 and A2 (in parallel; both fix the shipped feature, A2 can silently disable it on macOS).
- B (offer survives restarts and a second reboot; exact detection; fixes the Compose gap).
- C1, then C2 (foundation, clamps, env bookkeeping, shell).
- D (largest user-visible win) in parallel with F1 then F2.
- E (codex is the most used non-claude CLI; F6 investigation).
- G1 to G3, H.
- I, J, then K; L once the row kinds exist.
10. Open decisions for the owner
- No id known: "new conversation in the same folder" (recommended), skip, or continue-latest (not recommended, sibling-grab risk)?
- Auto-restore after reboot: keep click-only (recommended), or opt-in (default OFF, never multi-user, never remote/docker)?
- Scrollback snapshots: opt-in default OFF (recommended), or default ON for shell sessions only? Line cap (5,000 proposed) and retention (plan TTL proposed).
- Shell history replay into the live pane (
catbefore the shell) or read-only viewer only? - Wake-on-LAN on the restore click for a sleeping remote host: allowed (explicit request) or never?
- Remote session whose remote tmux is gone: relaunch (claude and omp resume, others start fresh, labelled) or drop it?
- Antigravity: install a Codeman-owned hook into the user's real agy config (path unverified here) or leave agy non-resumable for fresh sessions?
- logind delay inhibitor: on by default for Linux service installs, or opt-in?
- Plan TTL once durable: keep 24 h or extend to 72 h?
- Where the learned id lives: new
conversationReffield (recommended) or each<Mode>Configresume alias (changes live respawn behaviour; omp already does this)? - Codex F6: fix in its own PR now if
--no-daemonproves out (it also repairs the response viewer and per-pane env), or fold into PR E? - Non-claude env overrides (F11): persist values for a registry-declared non-secret list (
CODEX_HOME,DSH_HOME,PI_CODING_AGENT_SESSION_DIR,GROK_HOME; privileged ones re-clamped), and for rows whose secret keys cannot come back: restore with a label, or refuse? - Dismissed owned remote entry: leave the remote agent running (today) or offer "Stop remote agent"?
- OOM-killed or hand-killed tmux server on a long-uptime host: keep "no banner" (today), or offer restore when PR K's markers show no clean shutdown?
Appendix A: Evidence log
Commands run and what they printed
Commands run read-only from a scratch dir with NO_COLOR=1; no model session was started.
| Command | Relevant output |
|---|---|
claude --version, claude --help |
2.1.296; -r, --resume [value], --session-id <uuid>, -c, --continue, --fork-session, -n, --name |
codex --version, codex resume --help, codex --help, codex features list |
codex-cli 0.162.0; codex resume [OPTIONS] [SESSION_ID] [PROMPT] ("Session id (UUID) or session name"), --last; agents ("shared local app-server daemon"), --no-daemon ("Run without the shared background server"), feature daemon_auto_start stable true |
~/.opencode/bin/opencode --version, --help, session list --help |
1.3.0; -s, --session, -c, --continue, --fork; session list --format json, -n, --max-count |
agy --version, agy --help |
1.3.4; --conversation "Resume a previous conversation by ID", --continue; subcommands have no conversation list; ~/.gemini/config holds config.json, mcp_config.json, projects (no hooks.json) |
pi --version, pi --help |
1.1.0; --session <path|id>, --session-id <id> "Use exact project session ID, creating it if missing", --session-dir, --fork, --continue |
grok --version, grok --help, grok sessions --help |
1.0.52; -r, --resume [<SESSION_ID_OR_TITLE>], -s, --session-id (new only, must not already exist), --fork-session; sessions list/search/delete; a leader daemon socket ~/.grok/leader.sock |
dsh --version, dsh --help |
0.1.1-rc.2; example dsh --profile tui --resume <session> |
gemini, omp, herdr |
not installed here |
Rollout session_meta heads in ~/.codex/sessions |
0.147.0 (2026-09-24 UTC): originator codeman_<uuid>, source cli; 0.162.0/0.162.1 (2026-10-08 UTC onward): originator codex-tui, source vscode or cli |
busctl monitor --system ... as the service user |
BecomeMonitor failed: Access denied; gdbus monitor --system --dest org.freedesktop.login1 runs |
| Private tmux socket, 100k colored lines (two runs) | section 4.2 |
Appendix B: herdr and Codeman side by side
Where herdr 0.9.4 stands, where Codeman stands today, and after this plan
herdr facts are from its public docs and were not verified here (herdr is not installed).
| Capability | herdr 0.9.4 | Codeman today | After this plan |
|---|---|---|---|
| Layout | snapshot restore, 48 snapshots kept | groups survive, restored sessions land outside them | sessions return into their group with focus (A1) |
| Directories | yes | yes (claude only) | every mode (C2) |
| Agent resume | ~18 agents via integrations reporting the session id | claude only | claude, omp, pi, grok, codex, dsh, opencode, gemini; agy pending decision 7 |
| Running processes | live persistence / handoff | tmux survives server restarts | unchanged; remote agents reattached (D) |
| Screen history | opt-in pane_history, replayed only without agent resume |
none | opt-in snapshots + viewer (I, J) |
| Save before shutdown | logind delay (Linux), macOS restart, Windows shutdown | SIGTERM flush | + logind delay, plist ExitTimeOut, shuttingDown (K) |
| User confirmation | automatic on attach (default on) | banner click | banner click (decision 2) |
| Multi-user privilege model | n/a | owner-confined, clamped | extended to every CLI (C1, C2) |
Activity