agent-orchestrator icon indicating copy to clipboard operation
agent-orchestrator copied to clipboard

Fixing Worker Session Persistence on Respawn ( OpenCode & Aider)

Open whoisasx opened this issue 8 months ago • 2 comments

Fixing Worker Session Persistence on Respawn

1. Problem Statement

When an AO worker session dies (crash, rate limit, OOM, manual kill) and a new worker is spawned for the same issue, the new worker starts completely from scratch — zero conversation history, no knowledge of previous attempts, no awareness of commits already made. It re-reads the issue, re-analyzes the codebase, and potentially repeats the exact mistake that caused the previous failure.

The irony: AO already has a fully working session restore system. The ao session restore <id> CLI command can resurrect a dead session, resume the agent's conversation, and pick up exactly where it left off. But this capability is only available as a manual user action. The automated respawn path (spawn()) completely ignores it.


2. What Already Exists

2.1 The Manual Restore Path — ao session restore

AO has a CLI command (packages/cli/src/commands/session.ts:291) that calls the restore() function in session-manager.ts:2199. This is a complete, tested, production-ready restore flow:

Step-by-step, restore() does:

  1. Finds the session — searches active metadata first, then the archive directory (readArchivedMetadataRaw()) across all projects. Archive files live at {sessionsDir}/archive/{sessionId}_{ISO-timestamp}.

  2. Reconstructs the Session object — calls metadataToSession() to convert the flat key-value metadata back into a typed Session with all fields (branch, issue, PR, worktree path, runtime handle, etc.).

  3. Enriches with live state — calls enrichSessionWithRuntimeState() to check if the runtime (tmux) is actually alive, detect the agent's activity state, and pull agent info (summary, cost).

  4. Validates restorability — the session must be in a terminal state (killed, terminated, done, cleanup, errored) and NOT merged. Uses isRestorable() from types.ts:125.

  5. Restores archived metadata to active — if the session was found in the archive, writes it back to the active metadata directory so future operations can find it.

  6. Validates/restores workspace — checks if the git worktree still exists on disk. If missing, calls plugins.workspace.restore() to recreate it from the branch. If the workspace plugin doesn't support restore or the branch metadata is missing, throws WorkspaceMissingError.

  7. Destroys old runtime — kills the leftover tmux session (best-effort, may already be gone).

  8. Gets the launch command — HERE'S THE KEY PART (session-manager.ts:2361-2366):

    if (plugins.agent.getRestoreCommand) {
      const restoreCmd = await plugins.agent.getRestoreCommand(session, project);
      launchCommand = restoreCmd ?? plugins.agent.getLaunchCommand(agentLaunchConfig);
    } else {
      launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
    }
    

    It calls getRestoreCommand() on the agent plugin. If the agent returns a resume command (e.g., claude --resume <uuid>), it uses that. If the agent returns null or doesn't implement the method, it falls back to a fresh getLaunchCommand().

  9. Creates new runtime — launches the agent in a new tmux session, reusing the original tmuxName from metadata.

  10. Updates metadata — merges status: "spawning", new runtimeHandle, and restoredAt timestamp into the existing metadata, preserving all other fields (issue, PR, branch, createdAt, etc.).

The session keeps its original ID (e.g., app-1). From the user's perspective, it's the same session continuing.

2.2 The Agent Plugin Interface

The Agent interface (types.ts:279) defines an optional getRestoreCommand() method:

export interface Agent {
  getLaunchCommand(config: AgentLaunchConfig): string;        // Required — fresh start
  getRestoreCommand?(session: Session, project: ProjectConfig): Promise<string | null>;  // Optional — resume
  // ... other methods
}

The contract: return a shell command string that resumes a previous conversation, or null to fall back to fresh launch.

2.3 Agent Plugin Implementations

Claude Code — Fully Implemented (agent-claude-code/src/index.ts:806-834)

async getRestoreCommand(session, project) {
  if (!session.workspacePath) return null;

  const projectPath = toClaudeProjectPath(session.workspacePath);
  const projectDir = join(homedir(), ".claude", "projects", projectPath);

  const sessionFile = await findLatestSessionFile(projectDir);
  if (!sessionFile) return null;

  const sessionUuid = basename(sessionFile, ".jsonl");
  if (!sessionUuid) return null;

  const parts = ["claude", "--resume", shellEscape(sessionUuid)];
  // ... adds --dangerously-skip-permissions, --model flags
  return parts.join(" ");
}

How it works:

  • Claude Code stores conversation history as JSONL files at ~/.claude/projects/{encoded-workspace-path}/{uuid}.jsonl
  • toClaudeProjectPath() encodes the workspace path (replaces / and . with -)
  • findLatestSessionFile() finds the most recently modified .jsonl file (excluding agent-*.jsonl)
  • Extracts the UUID from the filename and builds claude --resume <uuid>
  • The agent resumes with full conversation history, tool call outputs, and reasoning

Result: claude --resume abc123-def456 --dangerously-skip-permissions --model claude-sonnet-4-20250514

Codex — Fully Implemented (agent-codex/src/index.ts:802-829)

async getRestoreCommand(session, project) {
  if (!session.workspacePath) return null;

  const sessionFile = await findCodexSessionFileCached(session.workspacePath);
  if (!sessionFile) return null;

  const data = await streamCodexSessionData(sessionFile);
  if (!data?.threadId) return null;

  const parts = [shellEscape(binary), "resume"];
  // ... adds approval flags, model flags
  parts.push(shellEscape(data.threadId));
  return parts.join(" ");
}

How it works:

  • Codex stores sessions at ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl
  • findCodexSessionFileCached() scans recursively, matches by session_meta.cwd field against workspace path (reads first 4KB for matching, 30s cache TTL)
  • streamCodexSessionData() streams the JSONL file line-by-line (files can be 100MB+) to extract the threadId
  • Builds codex resume <threadId> with all necessary flags before the positional argument

Result: codex resume -c check_for_update_on_startup=false --full-auto --model gpt-4.1 thread-abc123

OpenCode — NOT Implemented

OpenCode does NOT implement getRestoreCommand(). Instead, it has a different session reuse mechanism that works only during spawn():

  • During spawn(), if the agent is OpenCode and an issueId is provided, resolveOpenCodeSessionReuse() is called (session-manager.ts:1033-1041)
  • This searches active AND archived metadata for sessions with matching agent=opencode and issue={issueId}, and extracts the stored opencodeSessionId
  • The OpenCode session ID is passed to getLaunchCommand() via agentConfig.opencodeSessionId, which includes --session <id> in the launch command
  • This effectively tells OpenCode "continue this conversation" — but only when spawn() triggers it

The problem: During restore(), there's no getRestoreCommand(), so the code falls through to getLaunchCommand(). This path does check for opencodeSessionId in the metadata and passes it via config, so OpenCode restore partially works — but only if the session ID was captured in metadata before the crash.

Aider — NOT Implemented

Aider does NOT implement getRestoreCommand(). Its getLaunchCommand() (agent-aider/src/index.ts:85-108) simply builds a fresh aider --message <prompt> command every time.

Aider persists conversation history in .aider.chat.history.md in the workspace directory. This file is used for activity detection (getChatHistoryMtime()) but NOT for session resume. Each launch is a clean start — Aider may or may not read this file automatically depending on its version.

2.4 The Metadata Archive System

When a session is killed/cleaned, deleteMetadata() (metadata.ts:184) archives the metadata before deleting:

export function deleteMetadata(dataDir, sessionId, archive = true) {
  // Copies to: sessions/archive/{sessionId}_{ISO-timestamp}
  // Then deletes the original active file
}

What's preserved in archives: worktree, branch, status, tmuxName, issue, pr, prAutoDetect, summary, project, agent, createdAt, runtimeHandle, opencodeSessionId

How archives are read: readArchivedMetadataRaw() (metadata.ts:204) finds the latest archive for a session ID by scanning files with prefix {sessionId}_ and picking the lexicographically last one (ISO timestamps sort correctly). It verifies the character after the underscore is a digit (0-9) to prevent prefix collisions — e.g., session app won't match archive app_v2_2025-....

Session ID format: Validated by /^[a-zA-Z0-9_-]+$/ (metadata.ts:50). Session IDs can contain underscores and hyphens (e.g., app-1, app_v2). Archive filenames use _\d (underscore + digit) as the boundary between session ID and timestamp.

Existing archive helpers (must be reused, not reimplemented):

Helper Location Purpose
listArchivedSessionIds(sessionsDir) session-manager.ts:347 Returns unique session IDs from archive. Uses regex /^([a-zA-Z0-9_-]+)_\d/ — handles underscores in session IDs correctly.
readArchivedMetadataRaw(sessionsDir, sessionId) metadata.ts:204 Reads latest archive for a session ID. Has its own prefix collision prevention.
sortSessionIdsForReuse(ids) session-manager.ts:544 Sorts session IDs most-recent-first.
parseKeyValueContent(content) key-value.ts Parses key=value metadata format.
metadataToSession(sessionId, raw, projectId) session-manager.ts Converts raw metadata back to typed Session.

Important limitation: Archives are keyed by session ID, not by issue ID. There is no built-in way to ask "find me all archived sessions for issue X." The only exception is findOpenCodeSessionIds() (session-manager.ts:564-596), which scans all archives filtering by issue and agent=opencode — but this is OpenCode-specific.

2.5 The spawn() Function — Where the Gap Is

spawn() (session-manager.ts:893-1194) is the function that creates new worker sessions. Here's what it does:

  1. Validates the project and checks for rate limit pause
  2. Resolves agent selection and plugins
  3. Validates the issue exists
  4. Reserves a new session ID (incrementing: app-1, app-2, app-3...)
  5. Creates a fresh workspace (new git worktree)
  6. For OpenCode only: resolves a reusable opencodeSessionId from archives
  7. Builds the prompt from the issue
  8. Calls getLaunchCommand() — always fresh, never restore (session-manager.ts:1060):
    const launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
    
  9. Creates the runtime (tmux session)
  10. Writes metadata, runs postLaunchSetup

spawn() never:

  • Checks for previous sessions for the same issue (except OpenCode's internal session ID)
  • Calls getRestoreCommand()
  • Reuses a previous session's workspace/worktree
  • Injects context about what a previous worker did
  • Checks the archive at all (except for OpenCode)

3. The Gaps

Gap 1: spawn() Never Calls getRestoreCommand()

This is the central problem. The restore logic exists at session-manager.ts:2361-2366, but spawn() at line 1060 always uses getLaunchCommand(). For Claude Code and Codex, this means:

  • A worker crashes while 80% done with an issue
  • The orchestrator respawns a new worker for the same issue
  • spawn() creates a brand new session (app-2), a brand new worktree, and launches the agent fresh
  • The agent re-reads the issue, re-analyzes the code, and starts from scratch
  • The previous session's conversation history (in ~/.claude/projects/ or ~/.codex/sessions/) sits unused on disk

What's needed: Before launching fresh, spawn() should check if a previous session for the same issue exists in the archive. If it does, and the agent supports getRestoreCommand(), try to resume that conversation.

Sub-problem — archive search by issue: Currently there's no generic function to find archived sessions by issue ID. findOpenCodeSessionIds() does this but is hardcoded to agent=opencode. We need a general-purpose version.

Sub-problem — workspace reuse (already solved): The existing restore() path (session-manager.ts:2323-2358) already handles this. It checks if the old worktree exists on disk — if yes, reuses it as-is; if missing, calls plugins.workspace.restore() which recreates the worktree from the stored branch name via git worktree add <path> <branch>. Committed work survives because the branch still exists in git. The spawn() resume path can leverage the same workspace strategy.

Gap 2: OpenCode and Aider Lack getRestoreCommand()

Even if spawn() is fixed to call getRestoreCommand(), two out of four agents don't implement it:

OpenCode: Has a session reuse mechanism but it works differently — session IDs are passed via --session flag during launch, not via a separate restore command. Implementing getRestoreCommand() for OpenCode could just delegate to getLaunchCommand() with the stored opencodeSessionId, making the restore path work the same way spawn already handles it.

Aider: Has no native session resume capability. The .aider.chat.history.md file may be read automatically on launch, but there's no explicit flag to control this. Implementing getRestoreCommand() would require either:

  • Verifying and using Aider's --restore-chat-history flag (if it exists)
  • Or accepting that Aider will always fall through to fresh launch and relying on the context injection fallback (Gap 3)

Gap 3: No Context Injection Fallback

When native resume isn't possible (agent doesn't support it, session files are corrupted, agent was switched between sessions), the worker starts completely blind. There's no mechanism to tell it:

  • "A previous worker session worked on this issue"
  • "It made these git commits on branch feat/INT-100"
  • "It modified these files"
  • "It opened PR #42"
  • "It ended with status: killed/errored"

All of this information is available in the archived metadata and the git history on the branch, but spawn() never assembles or injects it.

What's needed: A fallback that prepends context about the previous session to the new worker's prompt. This works for ALL agents regardless of their getRestoreCommand() support. Sources of context:

Source What it provides Availability
Archived metadata summary field Agent-generated summary of what it did If agent wrote one before crash
Archived metadata status field Why the session ended (killed, errored, etc.) Always available
Archived metadata pr field PR number if one was opened If agent opened a PR
Git log on the branch Concrete commits made by the previous worker If worktree/branch still exists
Git diff against main Files modified If worktree/branch still exists

4. Proposed Changes

4.1 New Helper: findArchivedSessionForIssue()

A general-purpose function to search archived sessions by issue ID and agent name. This generalizes the pattern from findOpenCodeSessionIds() but returns AO session metadata instead of agent-internal session IDs.

Location: packages/core/src/session-manager.ts (alongside findOpenCodeSessionIds)

Must reuse existing helpers — listArchivedSessionIds(), readArchivedMetadataRaw(), and sortSessionIdsForReuse() — instead of raw filesystem scanning. The original approach of using file.indexOf("_") to split archive filenames is broken for session IDs containing underscores (e.g., app_v2_2025-06-15T12-00-00-000Z → indexOf("_") returns 3 → extracts "app" instead of "app_v2"). The existing helpers use regex /^([a-zA-Z0-9_-]+)_\d/ which handles this correctly.

function findArchivedSessionForIssue(
  sessionsDir: string,
  issueId: string,
  agentName: string,
): { sessionId: string; raw: Record<string, string> } | null {
  // sortSessionIdsForReuse gives most-recent-first ordering,
  // so the first match is the most recent session for this issue.
  for (const sessionId of sortSessionIdsForReuse(listArchivedSessionIds(sessionsDir))) {
    const raw = readArchivedMetadataRaw(sessionsDir, sessionId);
    if (!raw) continue;
    if (raw["issue"] === issueId && raw["agent"] === agentName) {
      return { sessionId, raw };
    }
  }
  return null;
}

4.2 Modify spawn() to Attempt Resume

In spawn(), after building agentLaunchConfig and before creating the runtime (around line 1058-1060), add a resume attempt:

// --- Attempt to resume previous session for same issue ---
let launchCommand: string;
let resumedFromSession: string | null = null;

const respawnStrategy = project.workerRespawnStrategy ?? "resume";

if (
  respawnStrategy !== "fresh" &&
  spawnConfig.issueId &&
  plugins.agent.getRestoreCommand
) {
  const archived = findArchivedSessionForIssue(
    sessionsDir,
    spawnConfig.issueId,
    selection.agentName,
  );

  if (archived) {
    const archivedSession = metadataToSession(archived.sessionId, archived.raw, spawnConfig.projectId);
    archivedSession.workspacePath = workspacePath; // Use current worktree, not archived one

    try {
      const restoreCmd = await plugins.agent.getRestoreCommand(archivedSession, project);
      if (restoreCmd) {
        launchCommand = restoreCmd;
        resumedFromSession = archived.sessionId;
        log.info(`Resuming conversation from archived session ${archived.sessionId} for issue ${spawnConfig.issueId}`);
      }
    } catch (err) {
      log.warn(`Failed to build restore command from archived session ${archived.sessionId}: ${err}`);
    }
  }
}

if (!launchCommand) {
  launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
}

4.3 Context Injection Fallback

When native resume isn't possible (agent doesn't support getRestoreCommand(), or it returned null), inject a context summary into the prompt. This is the universal fallback for all agents.

New helper function in session-manager.ts or a new file session-context-builder.ts:

async function buildPreviousSessionContext(
  archivedRaw: Record<string, string>,
  workspacePath: string,
): Promise<string | null> {
  const parts: string[] = [];
  parts.push("## Previous Session Context");
  parts.push(`A previous worker session worked on this same issue and ended with status: ${archivedRaw["status"] ?? "unknown"}.`);

  // Agent-generated summary
  if (archivedRaw["summary"]) {
    parts.push(`\n### Agent Summary\n${archivedRaw["summary"]}`);
  }

  // Git commits on the branch
  const branch = archivedRaw["branch"];
  if (branch && existsSync(workspacePath)) {
    try {
      const { stdout } = await execAsync(
        `git -C ${shellEscape(workspacePath)} log --oneline ${shellEscape(branch)} --not origin/main -- 2>/dev/null`
      );
      if (stdout.trim()) {
        const commits = stdout.trim().split("\n").slice(0, 20);
        parts.push(`\n### Commits Made\n${commits.map(c => `- ${c}`).join("\n")}`);
      }
    } catch { /* best effort */ }
  }

  // PR info
  if (archivedRaw["pr"]) {
    parts.push(`\nA PR was opened: ${archivedRaw["pr"]}. Check its status and review comments before continuing.`);
  }

  parts.push(`\n### Instructions\nDo NOT start over from scratch. Review the previous work and continue from where it left off. If the previous approach had issues, learn from them and try a different approach.`);

  // Only return context if we have something meaningful beyond the header
  if (!archivedRaw["summary"] && parts.length <= 3) return null;

  return parts.join("\n");
}

Integration into spawn() — extends the resume logic:

// After the getRestoreCommand() attempt fails or is unavailable:
if (!launchCommand && respawnStrategy !== "fresh" && archived) {
  const context = await buildPreviousSessionContext(archived.raw, workspacePath);
  if (context) {
    // Prepend context to the issue prompt
    agentLaunchConfig.prompt = `${context}\n\n---\n\n${composedPrompt}`;
  }
  launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
}

if (!launchCommand) {
  launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
}

4.4 Configuration

The user decides the respawn strategy — it's a per-project setting in agent-orchestrator.yaml, following the same pattern as the existing orchestratorSessionStrategy (config.ts:168-169).

# agent-orchestrator.yaml
projects:
  my-app:
    repo: owner/repo
    path: /path/to/repo
    workerRespawnStrategy: "resume"   # or "context-inject" or "fresh"

Add to ProjectConfig in types.ts:

/** Strategy for handling previous sessions when spawning for the same issue.
 * - "resume" (default): try getRestoreCommand(), fall back to context injection, then fresh
 * - "context-inject": don't resume agent conversation, but inject context summary into prompt
 * - "fresh": always start fresh (current behavior, no change)
 */
workerRespawnStrategy?: "resume" | "context-inject" | "fresh";

Add to ProjectConfigSchema in config.ts:

workerRespawnStrategy: z.enum(["resume", "context-inject", "fresh"]).optional(),

4.5 Track Lineage in Metadata

Add resumedFrom to the metadata written by spawn():

writeMetadata(sessionsDir, sessionId, {
  // ... existing fields ...
  resumedFrom: resumedFromSession,  // Session ID we resumed from, or undefined
});

This creates a lineage chain: app-3 → resumedFrom app-2 → resumedFrom app-1.

4.6 OpenCode getRestoreCommand() (Optional)

Since OpenCode already has session reuse via --session in getLaunchCommand(), a getRestoreCommand() implementation could simply delegate:

async getRestoreCommand(session, project) {
  const opencodeSessionId = asValidOpenCodeSessionId(session.metadata?.opencodeSessionId);
  if (!opencodeSessionId) return null;

  // Delegate to getLaunchCommand with the session ID injected
  // This ensures the --session flag is included
  return this.getLaunchCommand({
    ...config,
    projectConfig: {
      ...project,
      agentConfig: { ...project.agentConfig, opencodeSessionId },
    },
  });
}

This makes OpenCode work through the restore path without any special-casing in spawn().


5. The Full Fallback Chain

After these changes, when spawn() is called for an issue that had a previous session:

1. Is workerRespawnStrategy "fresh"?
   └─ YES → skip everything, launch fresh (current behavior)
   └─ NO ↓

2. Does a previous archived session exist for this issue + agent?
   └─ NO → launch fresh
   └─ YES ↓

3. Does the agent implement getRestoreCommand()?
   └─ YES → call it
   │   └─ Returns command string → USE IT (native resume) ✅
   │   └─ Returns null → fall through ↓
   └─ NO → fall through ↓

4. Is workerRespawnStrategy "resume" or "context-inject"?
   └─ YES → build context from archived metadata + git history
   │   └─ Context available → prepend to prompt, launch fresh with context ✅
   │   └─ No context → launch completely fresh ✅
   └─ NO → launch completely fresh ✅

Per-agent behavior after fix:

Agent Step 3 (Native Resume) Step 4 (Context Injection)
Claude Code claude --resume <uuid> — full conversation history Fallback if JSONL file is missing/corrupt
Codex codex resume <threadId> — full thread state Fallback if session file is missing
OpenCode Via --session <id> (if getRestoreCommand() added) Primary path if getRestoreCommand() not added
Aider Not available (no implementation) Primary path — always gets context injection

6. Files to Modify

File Change
packages/core/src/session-manager.ts Add findArchivedSessionForIssue(), modify spawn() with resume + context injection fallback chain
packages/core/src/session-context-builder.ts New file — buildPreviousSessionContext() helper
packages/core/src/types.ts Add workerRespawnStrategy to ProjectConfig
packages/core/src/config.ts Add workerRespawnStrategy to ProjectConfigSchema (Zod)
packages/core/src/metadata.ts Add resumedFrom field serialization
packages/plugins/agent-opencode/src/index.ts Add getRestoreCommand() (optional, low priority)

7. Test Suite

All tests use Vitest following existing patterns: setupTestContext()/teardownTestContext() from test-utils.ts for session-manager tests, mkdtempSync for isolated file I/O, vi.fn() for mocks, makeSession()/makeHandle() factories.

7.1 findArchivedSessionForIssue() — session-manager/find-archived-session.test.ts

Setup: create a temp sessionsDir with archive/ subdirectory, write archive files as key=value content.

Test Setup Expected
No archive directory Remove archive dir Returns null
Empty archive directory Empty dir Returns null
No match for issue ID Archive with issue=INT-200 Returns null for INT-100
Issue matches but agent doesn't Archive with agent=codex Returns null for claude-code
Finds matching session Archive with matching issue + agent Returns { sessionId, raw } with correct fields
Picks most recent across multiple sessions Two archives: app-1 (older) and app-3 (newer) for same issue Returns app-3
Session IDs with underscores Archive for session app_v2 Returns sessionId: "app_v2" (not "app")
Filters by agent across mixed archives Archives: app-1 (codex) + app-2 (claude-code) for same issue Returns app-2 for claude-code
Malformed archive files One garbage file + one valid Skips garbage, returns valid match
Missing issue field in archive Archive without issue= key Returns null

7.2 buildPreviousSessionContext() — session-context-builder.test.ts

Setup: temp workspace dir, mock execAsync for git commands.

Test Input Expected
No meaningful context { status: "killed" } (no summary, no PR) Returns null
Includes status { status: "errored", summary: "..." } Contains "ended with status: errored"
Defaults missing status { summary: "..." } (no status key) Contains "ended with status: unknown"
Includes agent summary { summary: "Fixed auth", status: "killed" } Contains "### Agent Summary" + summary text
Includes PR info { pr: "https://...pull/42", summary: "..." } Contains PR URL + "Check its status"
Includes git commits Mock execAsync returns commit lines Contains "### Commits Made" + formatted commits
Git failure is best-effort Mock execAsync throws Still returns context (from summary), no commits section
Missing workspace dir Non-existent path Still returns context, no commits section
Truncates commits to 20 Mock returns 30 commits Commit list has ≤20 entries
Always includes instructions Any valid context Contains "Do NOT start over from scratch"
All sections present Summary + PR + git commits + status All 4 sections appear in output

7.3 spawn() Resume Integration — session-manager/spawn-resume.test.ts

Setup: setupTestContext(), helper to create archived sessions with writeFileSync to archive/ dir.

Strategy: "resume" (default)

Test Setup Expected
Calls getRestoreCommand when archive exists Archive for issue, mock returns restore cmd runtime.create called with restore command
Falls back to getLaunchCommand when restore returns null Mock getRestoreCommand → null getLaunchCommand called
Falls back when getRestoreCommand throws Mock throws error getLaunchCommand called, error logged as warning
No archive → no restore attempt No archived sessions getRestoreCommand not called
Agent without getRestoreCommand → skips Delete method from mock getLaunchCommand called directly
No issueId → skips Spawn without issueId getRestoreCommand not called
Passes NEW workspace path Archive has old worktree path Session arg to getRestoreCommand has current worktree, not archived one
Writes resumedFrom on success Mock returns restore cmd Metadata contains resumedFrom=<old-session-id>
No resumedFrom on fresh launch No archive Metadata does not contain resumedFrom
Only matches same agent Archive with agent=codex, spawning mock-agent getRestoreCommand not called

Strategy: "context-inject"

Test Setup Expected
Skips getRestoreCommand entirely Archive exists, agent supports restore getRestoreCommand not called
Injects context into prompt Archive with summary getLaunchCommand config prompt contains "## Previous Session Context"
Falls back to fresh when no context Archive without summary or PR Prompt does not contain context header

Strategy: "fresh"

Test Setup Expected
Never attempts resume Archive exists, agent supports restore getRestoreCommand not called, prompt has no context

Context injection fallback in resume mode

Test Setup Expected
Injects context when getRestoreCommand returns null Archive with summary + PR Prompt contains context
Injects context when agent lacks getRestoreCommand Delete method, archive with summary Prompt contains context

7.4 Config Schema — extend existing config.test.ts

Test Input Expected
Accepts "resume" workerRespawnStrategy: "resume" Parses successfully
Accepts "context-inject" workerRespawnStrategy: "context-inject" Parses successfully
Accepts "fresh" workerRespawnStrategy: "fresh" Parses successfully
Defaults to undefined Field omitted workerRespawnStrategy is undefined
Rejects invalid values workerRespawnStrategy: "invalid" Throws Zod validation error

7.5 Metadata resumedFrom — extend existing metadata.test.ts

Test Setup Expected
Writes and reads resumedFrom writeMetadata with resumedFrom: "app-1" readMetadataRaw returns resumedFrom=app-1
Preserves through archive cycle Write → delete (archive) → read archive Archived metadata contains resumedFrom
Omits when not provided writeMetadata without resumedFrom Field absent from metadata

7.6 Edge Cases — session-manager/spawn-resume-edge-cases.test.ts

Test Setup Expected
Multiple archives for same issue — picks most recent Two archived sessions (app-1, app-3) for INT-100 Tries restore from app-3
Cross-agent mismatch Archive with agent=claude-code, spawning codex No restore attempt
No infinite loop getRestoreCommand returns null Called exactly once, getLaunchCommand called exactly once
Merged session still found Archive with status=merged findArchivedSessionForIssue matches (filtering is by issue+agent, not status)

8. Risks and Mitigations

Risk Mitigation
Resumed conversation has stale context (issue changed) Agent sees full history and will re-read the issue naturally. Context injection includes "check for updates" instruction.
Resumed conversation exceeds context window Agent handles this natively (Claude Code truncates old messages). This is not a new problem — ao session restore has the same characteristic.
Archive scanning is slow with many sessions Archive directories are small (tens of files per project). Scan is O(n) in archive size. Could add an issue→session index file later if needed.
getRestoreCommand() succeeds but agent can't actually resume Agent will error or start fresh. Lifecycle manager detects the failure. No infinite resume loop because we only try resume once per spawn.
Context injection makes prompts too long Cap context at ~4000 chars. Truncate commit lists, keep summary and instructions.
Cross-agent resume (session was Claude Code, respawn uses Codex) findArchivedSessionForIssue() filters by agent name — only matches same agent. Context injection still works cross-agent.

9. Execution Order

  1. findArchivedSessionForIssue() helper — the foundation for everything else
  2. buildPreviousSessionContext() module — context extraction and formatting
  3. Modify spawn() with the full fallback chain — resume → context inject → fresh
  4. Add workerRespawnStrategy config — lets users opt out
  5. Track resumedFrom in metadata — lineage tracking
  6. (Optional) OpenCode getRestoreCommand() — can be done independently later

Steps 1-3 deliver the core value. Steps 4-5 are small additions. Step 6 is independent.

whoisasx avatar Apr 03 '26 19:04 whoisasx

@whoisasx this looks like a big change, would you be presenting on the discord office hours sometime?

OrcInc avatar Apr 07 '26 17:04 OrcInc

Hit this in the wild today while trying to spawn a worker on #1048. Concrete in-the-wild reproduction of the stale-worktree-path failure mode that this issue's proposed fix already addresses (via the archivedSession.workspacePath = workspacePath; // Use current worktree, not archived one line). Posting as evidence that the bug is observable today in a normal spawn flow, not just a theoretical concern.

Reproduction (today, ~2 minutes of effort)

  1. ao spawn 1048 → created ao-140 with opencode session ses_28deb3230ffeN4BeX55XIKrEVV; agent started working in /home/harsh/.worktrees/agent-orchestrator/ao-140/.
  2. ao-140 was killed by the lifecycle manager after ~8 min of active work (separate observability bug: #1073). Metadata persisted opencodeSessionId=ses_28deb3230ffeN4BeX55XIKrEVV and status=killed.
  3. ao spawn 1048 again → created fresh ao-141 with a fresh worktree at /home/harsh/.worktrees/agent-orchestrator/ao-141/.
  4. ao-141's metadata was written with the same opencodeSessionId=ses_28deb3230ffeN4BeX55XIKrEVV (confirmed by reading ~/.agent-orchestrator/<hash>-<project>/sessions/ao-141).
  5. The opencode process inside the ao-141 tmux pane was launched with --session ses_28deb3230ffeN4BeX55XIKrEVV, which restored ao-140's conversation history.
  6. The resumed conversation had file paths baked in from ao-140's worktree. Looking at tmux capture-pane, the agent was reading:
    /home/harsh/.worktrees/agent-orchestrator/ao-140/packages/cli/src/commands/start.ts
    /home/harsh/.worktrees/agent-orchestrator/ao-140/packages/core/src/session-manager.ts
    /home/harsh/.worktrees/agent-orchestrator/ao-140/packages/core/src/__tests__/session-manager/restore.test.ts
    
    …from inside the ao-141 tmux session, whose bash/opencode cwd was actually /home/harsh/.worktrees/agent-orchestrator/ao-141/.
  7. Any edits from this point would have landed in the dead ao-140 worktree (on detached HEAD, with a separate Sisyphus conversation running concurrently in its surviving tmux pane) — not in ao-141 where the metadata said they should go.

Where the reuse is happening today

  • packages/core/src/session-manager.ts:1064-1072 — resolveOpenCodeSessionReuse is called with strategy: \"reuse\", no alive-check on the returned session:
    const opencodeIssueSessionStrategy = project.opencodeIssueSessionStrategy ?? \"reuse\";
    const reusedOpenCodeSessionId =
      plugins.agent.name === \"opencode\" && spawnConfig.issueId
        ? await resolveOpenCodeSessionReuse({
            sessionsDir,
            criteria: { issueId: spawnConfig.issueId },
            strategy: opencodeIssueSessionStrategy,
          })
        : undefined;
    
  • packages/core/src/session-manager.ts:541-573 — findOpenCodeSessionIds matches by issueId only and happily returns mappings from killed AO sessions (just filters by raw[\"agent\"] !== \"opencode\").
  • packages/plugins/agent-opencode/src/index.ts:218-224 — plugin passes --session <id> blindly without verifying the ID is still valid for the current workspace:
    const existingSessionId = asValidOpenCodeSessionId(
      (config.projectConfig.agentConfig as OpenCodeAgentConfig | undefined)?.opencodeSessionId,
    );
    if (existingSessionId) {
      options.push(\"--session\", shellEscape(existingSessionId));
    }
    

What this adds to this issue's proposal

Nothing new in terms of the fix — the proposal here already contains the right idea. But I wanted to drop concrete evidence that:

  1. The failure mode is reachable in a normal spawn-after-death flow, not only in exotic configurations.
  2. It produces silent wrong-worktree edits (not a loud error), which makes it particularly dangerous for automated workflows.
  3. When combined with #1073 (silent kills) and #1074 (ao send reporting success on killed sessions), you can end up with the debugging experience I had today: a fresh spawn that looks like it's working on the right issue but is reading/editing files from a dead session's worktree, and the operator has no log trail explaining any of it.

Happy to split this off into its own bug if you'd rather track it distinctly — but it seemed more useful as evidence attached to the existing fix proposal.

harsh-batheja avatar Apr 09 '26 12:04 harsh-batheja