Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Keep an SCM launch record on the registry row and re-apply it at relaunch

Adam Hafeze1238d4096bf
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index a8e797d0a..69310658b 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1833,6 +1833,37 @@ describe('BackendSocket outbound queue', () => {
}
})
+ it('hands the launch the SCM record the prepared workspace reported, and none for a folder no SCM made', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:scm', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ const prepare = vi.spyOn(projectFolder, 'prepareProjectFolder').mockImplementation(async (project, options) => {
+ if (project.source === 'worktree') options?.onPrepared?.({ cwd: '/remote/harnesses/worktrees/repo/brave-otter', scmLaunchRecord: { kind: 'git' } })
+ return project.source === 'worktree' ? '/remote/harnesses/worktrees/repo/brave-otter' : '/remote/harnesses/codex-2026-09-24-12-00'
+ })
+ const create = vi.fn(async (_input: Record<string, unknown>) => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))
+ socket.onCreateAgent = create
+ const ask = (requestId: string, choices: Record<string, unknown>) =>
+ socket.handleLocalFrame('local:scm', { type: 'agent_create', payload: { requestId, creationId: randomUUID(), engine: 'claude', ...choices } })
+ try {
+ ask('worktree', { projectSource: 'worktree', gitSource: '/remote/repo', branchRef: 'refs/heads/main' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'worktree', state: 'failed' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/harnesses/worktrees/repo/brave-otter', scmLaunchRecord: { kind: 'git' } }))
+ ask('new', { projectSource: 'new' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'new', state: 'failed' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/harnesses/codex-2026-09-24-12-00', scmLaunchRecord: null }))
+ // A create that names its own folder prepared nothing, and says nothing about an SCM.
+ ask('cwd', { cwd: '/remote/own' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'cwd' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/own' }))
+ expect(create.mock.lastCall?.[0]).not.toHaveProperty('scmLaunchRecord')
+ expect(prepare).toHaveBeenCalledTimes(2)
+ } finally {
+ await socket.unregisterLocalClient('local:scm')
+ await socket.stop()
+ }
+ })
+
it('checks an unknown creation without spawning and rejects malformed creation ids before launch', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 618a6e507..9595c3dd1 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -68,6 +68,7 @@ import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject
import { projectPreview } from './lib/projectPreview.js'
import { readGitProject } from './lib/gitProject.js'
import { detectScmProject } from './scm/scmProjects.js'
+import type { ScmLaunchRecord } from './scm/types.js'
import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { installedDsh, listInstalledDsh } from './dsh/installed.js'
@@ -568,6 +569,9 @@ export class BackendSocket {
* only between turns, `now` whatever it is doing (then tells it to continue), `wait` when its
* turn ends. Absent, one open elsewhere is refused and the refusal says whether it is busy. */
takeOver?: 'idle' | 'now' | 'wait' | null
+ /** What the SCM that prepared `cwd` needs on every relaunch (registry `scmLaunch`). Present only
+ * when this create prepared a folder, and null when no SCM made it (a new folder, a clone). */
+ scmLaunchRecord?: ScmLaunchRecord | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
/** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */
@@ -2948,8 +2952,12 @@ export class BackendSocket {
input.grid = target
}
let preparedFolder: string | undefined
+ let scmLaunchRecord: ScmLaunchRecord | null = null
if (projectFolder) {
- try { preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine) }) }
+ try {
+ preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),
+ onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })
+ }
catch (error) {
return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',
detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }
@@ -2988,7 +2996,7 @@ export class BackendSocket {
}
} catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }
}
- const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)
+ const result = await create(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)
if (result.ok) return { state: 'created', agentId: result.session.agentId }
// tmux may have executed before a timeout; registration cleanup is best-effort.
// Neither can prove that no process started, so never encourage another launch.
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index aa647445d..2e337ab4b 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -40,6 +40,7 @@ import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import { TMUX_SESSION_ENV_MIN, tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'
import type { Adoption } from './adopt.js'
+import { scmLaunchEnv } from '../../scm/scmProjects.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
@@ -79,7 +80,7 @@ export function createAgentCreator({
prepareApiTools, hookPort, hooksDisabled, gridLaunchMachine, terminalHintMachineName, blocksFolder, gridSetup,
privateGridName,
}: CreateAgentDeps) {
- const createAgent: CreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver }) => {
+ const createAgent: CreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver, scmLaunchRecord }) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
// A conversation Harness did not start opens in its own folder, under its own title — taken over
// from the terminal that has it, when asked to.
@@ -285,10 +286,12 @@ export function createAgentCreator({
cwd,
sessionLabel: label,
argv,
- env: freshHarnessEnvironment(engine, mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv), !!grid || !!resumeSessionId,
+ env: freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv),
+ scmLaunchEnv(scmLaunchRecord)), !!grid || !!resumeSessionId,
permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
+ scmLaunchRecord: scmLaunchRecord ?? null,
codexHome,
dsh,
dshRuntime: dsh ? label : null,
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
index 091ce03ad..3356509cd 100644
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@ -23,6 +23,7 @@ import { forkName, planFork } from '../../lib/forkAgent.js'
import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
+import { scmLaunchEnv } from '../../scm/scmProjects.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
@@ -123,9 +124,11 @@ export function createAgentForker({
cwd: source.cwd,
sessionLabel: label,
argv,
- env: mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv),
+ env: mergedLaunchEnv(mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv), scmLaunchEnv(source.scmLaunch)),
grid: null,
gridLaunchRecord: null,
+ // Same folder as the source, so the same workspace binding.
+ scmLaunchRecord: source.scmLaunch ?? null,
codexHome: source.codexHome ?? null,
dshRuntime: source.dsh ? label : null,
dsh: source.dsh ?? null,
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index 7442b1894..00f591d63 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -45,7 +45,7 @@ export function createLaunchHelpers({ prepareApiTools, savedApis, launchOverride
}
}
}
- return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source, gridLaunch }, session.agentId)
+ return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch }, session.agentId)
}
/**
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 3235e7b07..7794803ba 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -14,6 +14,7 @@
import { homedir } from 'node:os'
import type { AgentEngine } from '../engines/types.js'
import type { GridLaunchRecord } from './gridLaunch.js'
+import type { ScmLaunchRecord } from '../scm/types.js'
import type { ForkOrigin, RegisteredSession } from './registry.js'
import type { TerminalBackend } from './terminalBackend.js'
import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'
@@ -30,6 +31,7 @@ export interface CreateAgentPaneDeps {
cwd?: string | null
grid?: { baseUrl: string; model: string | null } | null
gridLaunchRecord?: GridLaunchRecord | null
+ scmLaunchRecord?: ScmLaunchRecord | null
codexHome?: string | null
dsh?: string | null
dshRuntime?: string | null
@@ -57,6 +59,9 @@ export interface CreateAgentPaneDeps {
/** The grid launch behind `grid` (credential included — what restore/restart relaunch the pane with)
* and what building it decided about web search (what the app shows for this agent). */
gridLaunchRecord?: GridLaunchRecord | null
+ /** What the workspace's SCM needs re-applied on every relaunch (`scmLaunch` on the row); null or
+ * absent for a folder no SCM prepared. The record, not the launch — `env` already carries it. */
+ scmLaunchRecord?: ScmLaunchRecord | null
/** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */
codexHome?: string | null
/** The domain-specific harness this agent is created as, if any. */
@@ -99,6 +104,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
cwd: deps.cwd,
grid: deps.grid,
gridLaunchRecord: deps.gridLaunchRecord,
+ scmLaunchRecord: deps.scmLaunchRecord,
codexHome: deps.codexHome,
dsh: deps.dsh,
dshRuntime: deps.dshRuntime,
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index bf3aab5b0..41a569cbb 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -27,6 +27,8 @@ import {
} from './gridLaunch.js'
import { TMUX_SESSION_ENV_MIN } from './tmuxVersion.js'
import { harnessEnvToClear, type DshLaunch } from '../dsh/launch.js'
+import { scmLaunchEnv } from '../scm/scmProjects.js'
+import type { ScmLaunchRecord } from '../scm/types.js'
export interface LaunchOverrides {
/** Layered over the pane's inherited environment. The grid key lives here, and only here. */
@@ -97,6 +99,11 @@ export interface LaunchSource {
dshRuntime?: string | null
/** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */
cwd?: string | null
+ /**
+ * What the workspace's SCM needs re-applied to the pane — the registry row's `scmLaunch`. A git
+ * worktree asks for nothing. Absent or null: no SCM prepared this folder, or the row predates it.
+ */
+ scmLaunch?: ScmLaunchRecord | null
/**
* The engine's named agent this pane was opened as (`agent_create`'s `agent`, opencode
* `--agent <name>`). Part of every relaunch, unlike a first prompt: a pane opened as `harness-compute`
@@ -169,6 +176,11 @@ export async function buildLaunchOverrides(
extraArgs: [...overrides.extraArgs, ...dsh.args],
}
}
+ // The workspace's own SCM binding layers last: it is the daemon's, like `HARNESS_*`, and neither a
+ // grid nor a DSH has a say in which workspace the pane is bound to. Nothing for git, so a git row's
+ // overrides are exactly what they were.
+ const scmEnv = scmLaunchEnv(source.scmLaunch)
+ if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }
// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
// engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),
// so the guard is for a row edited by hand — it relaunches as a general session rather than
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index 117d5af3b..40d635d2c 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -4,6 +4,8 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import { plausibleBranchName, projectFolderName, projectFolderSlug } from './agentNames.js'
import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'
+import { scmByKind } from '../scm/scmProjects.js'
+import type { ScmLaunchRecord } from '../scm/types.js'
/** `name` on a new project is what the person called it; without one the folder is named after the
* harness and the time. `suggested` marks a name the app made up (from the first task — the phone has
@@ -95,18 +97,31 @@ export async function prepareProjectFolder(
/** Who the harness is ("Codex", "Blender"): a new project folder is named after it and the time. */
label?: string | null
now?: () => Date
+ /** Told, before the folder is returned, what the SCM that made an isolated workspace needs on its
+ * every relaunch (`scmLaunch` on the registry row). A new folder, a clone or the folder itself on a
+ * branch reports nothing. A callback rather than a wider return so the folder stays the answer
+ * here, for every caller. */
+ onPrepared?: (prepared: { cwd: string; scmLaunchRecord: ScmLaunchRecord }) => void
} = {},
): Promise<string> {
const root = options.root ?? projectsRoot()
let staging: string | undefined
try {
- if (project.source === 'worktree' || project.source === 'branch') {
+ if (project.source === 'worktree') {
+ // The isolated-workspace path, through the SCM seam. The git implementation makes exactly the
+ // prepareGitProject call this used to make.
+ const { cwd, launchRecord } = await scmByKind('git')!.prepareIsolated(project.gitSource, {
+ root, base: project.branchRef,
+ ...(project.branchName ? { name: project.branchName, existing: project.existingBranch === true, placeholder: project.placeholder === true } : {}),
+ })
+ options.onPrepared?.({ cwd, scmLaunchRecord: launchRecord })
+ return cwd
+ }
+ if (project.source === 'branch') {
+ // The folder itself, on a branch: git's own in-place mode, not an isolated workspace.
return await prepareGitProject(project.gitSource, {
- root, worktree: project.source === 'worktree', ref: project.branchRef,
- ...(project.source === 'worktree' && project.branchName ? {
- branchName: project.branchName, existingBranch: project.existingBranch === true, placeholder: project.placeholder === true,
- } : {}),
- ...(project.source === 'branch' && project.branchName ? { branchName: project.branchName } : {}),
+ root, worktree: false, ref: project.branchRef,
+ ...(project.branchName ? { branchName: project.branchName } : {}),
})
}
await mkdir(root, { recursive: true })
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 85bdacc78..6b85ebd37 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -44,6 +44,7 @@ import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/roll
import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord, type GridWebSearchStatus } from './gridLaunch.js'
+import { parseScmLaunchRecord, type ScmLaunchRecord } from '../scm/types.js'
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
import { agyTranscriptPath } from '../engines/agy/session.js'
import { copilotTranscriptPath } from '../engines/copilot/session.js'
@@ -130,6 +131,14 @@ export interface RegisteredSession {
* built, so there is nothing to say); absent on a row written before this field existed.
*/
gridWebSearch?: GridWebSearchStatus | null
+ /**
+ * What the workspace's SCM needs re-applied to the pane on every relaunch (scm/types.ts) — the
+ * SCM's half of `gridLaunch`. A git worktree's record only says it is one and asks for nothing.
+ * Written by `agent_create` from what `prepareProjectFolder` made, carried forward like
+ * `gridLaunch`, never re-derived. Absent on a row from before the seam and on a folder no SCM
+ * prepared — absent, not null, so a row that never had one is written exactly as before.
+ */
+ scmLaunch?: ScmLaunchRecord | null
/**
* The engine's OWN model this agent was on immediately before it moved to a grid.
*
@@ -558,10 +567,13 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
// Taken out of the spread and put back only when it is a real moment: the spread would otherwise
// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.
- const { lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, ...rest } = row
+ const { lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, ...rest } = row
const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
+ // Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.
+ const scmLaunch = parseScmLaunchRecord(rawScmLaunch)
return {
...rest,
+ ...(scmLaunch ? { scmLaunch } : {}),
...(normalizedClosePlan(rawClosePlan) ? { closePlan: normalizedClosePlan(rawClosePlan)! } : {}),
schemaVersion: 2,
active,
@@ -970,6 +982,7 @@ class Registry {
// see RegisteredSession.codexHome.
const rawCodexHome = raw?.codexHome ?? undefined
const rawGridLaunch = normalizedGridLaunch(raw?.gridLaunch)
+ const rawScmLaunch = parseScmLaunchRecord((raw as { scmLaunch?: unknown })?.scmLaunch)
let repairedCodexTranscript = false
if (engine === 'codex' && transcriptPath) {
const meta = readCodexRolloutMeta(transcriptPath)
@@ -1031,6 +1044,7 @@ class Registry {
agent: normalizedAgentName((raw as { agent?: unknown }).agent),
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),
+ ...(rawScmLaunch ? { scmLaunch: rawScmLaunch } : {}),
// ⚠️ Rehydrated EXPLICITLY, like every field above it. A row is rebuilt from this list on
// load, so a field added to the type and the setter but not to this list is written to
// disk and then silently dropped by the next load — which is exactly what happened, and
@@ -1301,6 +1315,8 @@ class Registry {
grid?: GridAssignment | null
/** The grid launch this pane was opened with and what it decided — the pair `setGridLaunch` keeps. */
gridLaunchRecord?: GridLaunchRecord | null
+ /** What the prepared workspace's SCM needs on every relaunch — see RegisteredSession.scmLaunch. */
+ scmLaunchRecord?: ScmLaunchRecord | null
codexHome?: string | null
dsh?: string | null
dshRuntime?: string | null
@@ -1334,6 +1350,7 @@ class Registry {
grid: input.grid ?? null,
gridLaunch: input.gridLaunchRecord?.override ?? null,
gridWebSearch: input.gridLaunchRecord?.webSearch ?? null,
+ ...(input.scmLaunchRecord ? { scmLaunch: input.scmLaunchRecord } : {}),
codexHome: input.codexHome ?? null,
// A pane Harness opens starts in the default home; `hermes -p` is the person's own doing, and
// the row learns it from the session that lands in it. See RegisteredSession.hermesHome.
@@ -1579,6 +1596,9 @@ class Registry {
gridLaunch: existing?.gridLaunch ?? null,
// What that launch decided — it travels with the launch, or it is lost at the first hook.
gridWebSearch: existing?.gridWebSearch ?? null,
+ // The workspace's SCM record, for the same reason: a bind rebuilds the row, and a relaunch
+ // without it would come back without the environment the workspace was created with.
+ ...(existing?.scmLaunch ? { scmLaunch: existing.scmLaunch } : {}),
// ⚠️ Carried forward for the same reason, and it was missed once: a bind REBUILDS the row from
// named fields, so a field the rebuild does not name survives on disk and vanishes from
// memory the moment the engine reports in. The symptom is a move back to the engine's own
diff --git a/cli/src/scm/gitScmProject.spec.ts b/cli/src/scm/gitScmProject.spec.ts
index 853ff0816..76c964a4c 100644
--- a/cli/src/scm/gitScmProject.spec.ts
+++ b/cli/src/scm/gitScmProject.spec.ts
@@ -92,6 +92,19 @@ describe('GitScmProject wraps the git path without changing it', { timeout: 30_0
expect(placeholder.launchRecord).toEqual({ kind: 'git' })
})
+ it('prepareProjectFolder reports the record a worktree needs at relaunch, and nothing for the folder itself or a new one', async () => {
+ const harnesses = join(root, 'harnesses')
+ const reported: unknown[] = []
+ const onPrepared = (prepared: unknown) => { reported.push(prepared) }
+ const cwd = await prepareProjectFolder({ source: 'worktree', gitSource: repo, branchRef: 'refs/heads/main' }, { root: harnesses, onPrepared })
+ expect(reported).toEqual([{ cwd, scmLaunchRecord: { kind: 'git' } }])
+ await git(repo, 'branch', 'aside')
+ expect(await prepareProjectFolder({ source: 'branch', gitSource: repo, branchRef: 'refs/heads/aside' }, { root: harnesses, onPrepared })).toBe(repo)
+ expect(await git(repo, 'branch', '--show-current')).toBe('aside')
+ expect(await prepareProjectFolder({ source: 'new', name: 'fresh' }, { root: harnesses, onPrepared })).toBe(join(harnesses, 'fresh'))
+ expect(reported).toHaveLength(1)
+ })
+
it('rename names a placeholder branch after the session once, as nameBranchAfterSession does', async () => {
const { cwd } = await scm.prepareIsolated(repo, { root: join(root, 'harnesses'), base: 'refs/heads/main' })
const renamed = await scm.rename(cwd, 'Fix the login page')
diff --git a/cli/src/scm/scmLaunch.spec.ts b/cli/src/scm/scmLaunch.spec.ts
new file mode 100644
index 000000000..7dfd525d8
--- /dev/null
+++ b/cli/src/scm/scmLaunch.spec.ts
@@ -0,0 +1,122 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createAndRegisterPane } from '../lib/createAgentPane.js'
+import { buildLaunchOverrides, type LaunchOverridesDeps } from '../lib/launchOverrides.js'
+import type { TerminalCreateResult, TmuxRuntimeRef } from '../lib/terminalTypes.js'
+import * as scmProjects from './scmProjects.js'
+import type { ScmLaunchRecord } from './types.js'
+
+let dataDir = ''
+
+// Mirrors lib/registry.spec.ts's loadRegistryModule(): a fresh registry module per test, backed by
+// its own temp state dir. The reload is the point of half these tests — a row is rebuilt from an
+// explicit field list on load, and a field missing from that list survives the write and dies there.
+async function loadRegistryModule() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ process.env.CLAUDE_PROJECTS_DIR = dataDir
+ process.env.CODEX_HOME = dataDir
+ process.env.CURSOR_HOME = dataDir
+ return import('../lib/registry.js')
+}
+
+const GIT: ScmLaunchRecord = { kind: 'git' }
+
+function deps(): LaunchOverridesDeps {
+ return {
+ machine: () => ({ hermesSystemManaged: false }),
+ writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,
+ tmuxSupportsSessionEnv: async () => true,
+ installCodexHooks: () => {},
+ readCodexConfig: () => null,
+ }
+}
+
+describe('the SCM launch record on the registry row', () => {
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-scm-')) })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ it('is written at create, survives a reload and the first hook bind, and is absent — not null — when nothing prepared the folder', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const prepared = registry.openPendingAgent({
+ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo', scmLaunchRecord: GIT,
+ })!
+ expect(prepared.scmLaunch).toEqual(GIT)
+ const plain = registry.openPendingAgent({
+ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/plain',
+ })!
+ expect(plain).not.toHaveProperty('scmLaunch')
+ const nulled = registry.openPendingAgent({
+ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/nulled', scmLaunchRecord: null,
+ })!
+ expect(nulled).not.toHaveProperty('scmLaunch')
+
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(prepared.agentId)?.scmLaunch).toEqual(GIT)
+ expect(reloaded.byAgent(plain.agentId)).not.toHaveProperty('scmLaunch')
+
+ // A hook bind rebuilds the row from named fields; a field the rebuild does not name is still on
+ // disk while memory has already forgotten it.
+ const transcriptPath = join(dataDir, 'session-scm.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const bound = reloaded.register({ sessionId: 'session-scm', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
+ expect(bound?.entry.agentId).toBe(prepared.agentId)
+ expect(bound?.entry.scmLaunch).toEqual(GIT)
+ const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
+ expect(saved.find(row => row.agentId === prepared.agentId)).toMatchObject({ scmLaunch: GIT })
+ expect(saved.find(row => row.agentId === plain.agentId)).not.toHaveProperty('scmLaunch')
+ })
+
+ it('drops an unrecognised or half-formed record from disk rather than relaunching with it', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const row = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/tmp/demo', scmLaunchRecord: GIT })!
+ const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
+ const damaged = saved.map(entry => entry.agentId === row.agentId ? { ...entry, scmLaunch: { kind: 'svn', url: 'x' } } : entry)
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(damaged))
+ const { registry: reloaded, strictPersistedRow } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(row.agentId)).not.toHaveProperty('scmLaunch')
+ // The same rule for a row read back from elsewhere (a stopped harness's saved row).
+ expect(strictPersistedRow({ ...saved[0], scmLaunch: { kind: 'svn' } })).not.toHaveProperty('scmLaunch')
+ expect(strictPersistedRow({ ...saved[0], scmLaunch: GIT })).toMatchObject({ scmLaunch: GIT })
+ })
+
+ it('goes from the pane create to the row to every relaunch, where its env layers last', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const create = vi.fn(async (): Promise<TerminalCreateResult<TmuxRuntimeRef>> => ({ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%1' } }))
+ const tmuxBackend = { create, kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })) }
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'claude', cwd: '/tmp/demo', sessionLabel: 'harness-claude-1', argv: ['claude'], scmLaunchRecord: GIT,
+ })
+ if (!result.ok) throw new Error(result.error)
+ const row = registry.byAgent(result.pending.agentId)!
+ expect(row.scmLaunch).toEqual(GIT)
+
+ // The git record asks for nothing, so a git row's overrides are exactly what they were.
+ const before = await buildLaunchOverrides(deps(), 'claude', { ...row, scmLaunch: undefined }, row.agentId)
+ expect(await buildLaunchOverrides(deps(), 'claude', row, row.agentId)).toEqual(before)
+ expect(await buildLaunchOverrides(deps(), 'claude', { ...row, scmLaunch: null }, row.agentId)).toEqual(before)
+
+ // An SCM whose workspace binding travels in the environment: its env goes over the DSH's.
+ vi.spyOn(scmProjects, 'scmLaunchEnv').mockImplementation(record => record ? { SCM_WORKSPACE: 'bound' } : undefined)
+ const built = await buildLaunchOverrides({ ...deps(), dshLaunch: () => ({ env: { SCM_WORKSPACE: 'not-this-one', HARNESS_DSH: 'x' }, args: ['--dsh'] }) },
+ 'claude', { ...row, dsh: 'x', cwd: '/tmp/demo' }, row.agentId)
+ expect(built).toMatchObject({ ok: true, overrides: {
+ env: { HARNESS_DSH: 'x', SCM_WORKSPACE: 'bound' },
+ extraArgs: expect.arrayContaining(['--dsh']),
+ } })
+ })
+})