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.

Add the ScmProject seam with a git implementation that only delegates

Adam Hafez01622a0165b6
diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.ts
index 560625f70..5671d0018 100644
--- a/cli/src/lib/agentProject.ts
+++ b/cli/src/lib/agentProject.ts
@@ -202,6 +202,12 @@ async function metadataStamp(cwd: string, project: AgentProject): Promise<string
} catch { return null }
}
+/** A `cwd` worth running Git in: absolute, bounded, printable. Exported for the SCM seam
+ * (`scm/scmProjects.ts`), which must answer null for exactly the folders this does. */
+export function validProjectCwd(cwd: string | null | undefined): cwd is string {
+ return !!cwd && isAbsolute(cwd) && cwd.length <= 4096 && !/[\x00-\x1f\x7f]/.test(cwd)
+}
+
export function createAgentProjectReader(lookup: (cwd: string) => Promise<AgentProject> = inspect) {
type Entry = { at: number; gitAt: number; pending: boolean; stamp: string | null; value: Promise<AgentProject> }
const cache = new Map<string, Entry>()
@@ -214,7 +220,7 @@ export function createAgentProjectReader(lookup: (cwd: string) => Promise<AgentP
}
}
const read = (cwd: string | null, now = Date.now()): Promise<AgentProject | null> => {
- if (!cwd || !isAbsolute(cwd) || cwd.length > 4096 || /[\x00-\x1f\x7f]/.test(cwd)) return Promise.resolve(null)
+ if (!validProjectCwd(cwd)) return Promise.resolve(null)
const found = cache.get(cwd)
if (found && (found.pending || now - found.at < 15_000)) {
cache.delete(cwd)
diff --git a/cli/src/scm/gitScmProject.spec.ts b/cli/src/scm/gitScmProject.spec.ts
new file mode 100644
index 000000000..853ff0816
--- /dev/null
+++ b/cli/src/scm/gitScmProject.spec.ts
@@ -0,0 +1,121 @@
+import { execFile } from 'node:child_process'
+import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { promisify } from 'node:util'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { agentProject } from '../lib/agentProject.js'
+import { readGitProject } from '../lib/gitProject.js'
+import { prepareProjectFolder } from '../lib/projectFolder.js'
+import { GitScmProject } from './gitScmProject.js'
+import type { ScmProject } from './types.js'
+
+const exec = promisify(execFile)
+// Real Git in a temporary repository, as gitProject.spec.ts does: the wrapper is only worth a test
+// against the thing it wraps. Several worktrees a test: slower than the default 5s under a full run.
+describe('GitScmProject wraps the git path without changing it', { timeout: 30_000 }, () => {
+ let root: string, repo: string
+ const scm = new GitScmProject()
+ const git = async (cwd: string, ...args: string[]) => (await exec('git', ['-C', cwd,
+ '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])).stdout.trim()
+ const exists = (path: string) => stat(path).then(() => true, () => false)
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'harness-scm-git-'))
+ repo = join(root, 'app')
+ await mkdir(repo)
+ await git(repo, 'init', '--quiet', '-b', 'main')
+ await git(repo, 'remote', 'add', 'origin', '[email protected]:Org/App.git')
+ await writeFile(join(repo, 'file'), 'one')
+ await git(repo, 'add', '.')
+ await git(repo, 'commit', '--quiet', '-m', 'initial')
+ })
+ afterEach(() => rm(root, { recursive: true, force: true }))
+
+ it('detect answers exactly what readGitProject answers, named, behind the same fence', async () => {
+ // The fixture lives in the temp directory, outside the browsable home, so the read names it.
+ const fence = { knownRoots: [root] }
+ expect(await scm.detect(repo, fence)).toEqual({ kind: 'git', git: await readGitProject(repo, fence) })
+ const plain = join(root, 'plain')
+ await mkdir(plain)
+ expect(await scm.detect(plain, fence)).toEqual({ kind: 'none' })
+ expect(await scm.detect(repo)).toEqual({ kind: 'none', error: 'FORBIDDEN' })
+ expect(await scm.detect('relative/path')).toEqual({ kind: 'none', error: 'INVALID_PATH' })
+ })
+
+ it('describe answers exactly what agentProject answers, named, and nothing for a folder outside a repository', async () => {
+ const nested = join(repo, 'nested')
+ await mkdir(nested)
+ const described = await scm.describe(nested)
+ expect(described).toEqual({ kind: 'git', ...await agentProject(nested) })
+ expect(described).toMatchObject({ kind: 'git', cwd: nested, remote: 'github.com/org/app', branch: 'main' })
+ const plain = join(root, 'plain')
+ await mkdir(plain)
+ expect(await scm.describe(plain)).toBeNull()
+ })
+
+ it('forget drops the cached description, so the next describe reads the checkout again', async () => {
+ expect(await scm.describe(repo)).toMatchObject({ branch: 'main' })
+ await git(repo, 'switch', '--quiet', '-c', 'other')
+ expect(await scm.describe(repo)).toMatchObject({ branch: 'main' })
+ scm.forget(repo)
+ expect(await scm.describe(repo)).toMatchObject({ branch: 'other' })
+ })
+
+ it('prepareIsolated makes the worktree prepareGitProject makes, marked as a placeholder, and a git launch record', async () => {
+ const harnesses = join(root, 'harnesses')
+ const { cwd, launchRecord } = await scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main' })
+ expect(launchRecord).toEqual({ kind: 'git' })
+ expect(cwd.startsWith(join(harnesses, 'worktrees', 'app') + '/')).toBe(true)
+ expect(await exists(join(cwd, 'file'))).toBe(true)
+ const branch = await git(cwd, 'branch', '--show-current')
+ expect(await git(repo, 'config', `branch.${branch}.harness`)).toBe('placeholder')
+ expect(await scm.describe(cwd)).toMatchObject({ kind: 'git', worktree: true, branchPending: true, branch })
+ // The same request through projectFolder.ts lands beside it, under the same repository folder.
+ const second = await prepareProjectFolder({ source: 'worktree', gitSource: repo, branchRef: 'refs/heads/main' }, { root: harnesses })
+ expect(second.startsWith(join(harnesses, 'worktrees', 'app') + '/')).toBe(true)
+ expect(second).not.toBe(cwd)
+ })
+
+ it('prepareIsolated passes a chosen name, an existing branch and the placeholder flag through unchanged', async () => {
+ const harnesses = join(root, 'harnesses')
+ await git(repo, 'branch', 'kept')
+ const named = await scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main', name: 'feature/one' })
+ expect(await git(named.cwd, 'branch', '--show-current')).toBe('feature/one')
+ expect(await git(repo, 'config', 'branch.feature/one.harness')).toBe('created')
+ const existing = await scm.prepareIsolated(repo, { root: harnesses, name: 'kept', existing: true })
+ expect(await git(existing.cwd, 'branch', '--show-current')).toBe('kept')
+ await expect(git(repo, 'config', 'branch.kept.harness')).rejects.toThrow()
+ const placeholder = await scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main', name: 'made-up', placeholder: true })
+ expect(await git(repo, 'config', 'branch.made-up.harness')).toBe('placeholder')
+ await expect(scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main', name: 'kept' }))
+ .rejects.toMatchObject({ code: 'BRANCH_EXISTS' })
+ expect(placeholder.launchRecord).toEqual({ kind: 'git' })
+ })
+
+ 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')
+ expect(renamed).toBeTruthy()
+ expect(await git(cwd, 'branch', '--show-current')).toBe(renamed)
+ expect(await git(repo, 'config', `branch.${renamed}.harness`)).toBe('created')
+ expect(await scm.rename(cwd, 'A later title')).toBeNull()
+ expect(await scm.rename(repo, 'Not a placeholder')).toBeNull()
+ expect(await scm.rename(cwd, null)).toBeNull()
+ })
+
+ it('sweep removes an idle, unused worktree, as sweepWorktrees does', async () => {
+ const harnesses = join(root, 'harnesses')
+ const idle = await scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main' })
+ const busy = await scm.prepareIsolated(repo, { root: harnesses, base: 'refs/heads/main' })
+ const later = Date.now() + 8 * 24 * 3600_000
+ expect(await scm.sweep({ root: harnesses, inUse: [busy.cwd, null, undefined], now: later })).toEqual([idle.cwd])
+ expect(await exists(idle.cwd)).toBe(false)
+ expect(await exists(busy.cwd)).toBe(true)
+ expect(await scm.sweep({ root: harnesses, inUse: [busy.cwd], now: later })).toEqual([])
+ })
+
+ it('launchEnv asks nothing of the pane, and there is no prepareWrite: a worktree is the folder the row already names', () => {
+ expect(scm.launchEnv({ kind: 'git' })).toEqual({})
+ expect((scm as ScmProject).prepareWrite).toBeUndefined()
+ })
+})
diff --git a/cli/src/scm/gitScmProject.ts b/cli/src/scm/gitScmProject.ts
new file mode 100644
index 000000000..a799d720d
--- /dev/null
+++ b/cli/src/scm/gitScmProject.ts
@@ -0,0 +1,63 @@
+/**
+ * The git implementation of `ScmProject`: a thin wrapper over the modules that already do the work.
+ * It delegates rather than moves them — `gitProject.ts`, `agentProject.ts`, `branchNaming.ts` and
+ * `worktreeSweep.ts` keep their exports, their specs and their call shapes — so the seam's arrival is
+ * invisible to a git project. The only thing this file adds to a frame is `kind: 'git'`.
+ *
+ * What is deliberately NOT here: any git knowledge of its own. The `refs/…` regex, the `.git` file
+ * marker, the `branch.<name>.harness` mark and `git status --porcelain` all stay behind the wrapped
+ * functions, which is the point — a caller of the seam cannot pick one of them up by accident.
+ */
+import { agentProject, forgetAgentProject } from '../lib/agentProject.js'
+import { nameBranchAfterSession } from '../lib/branchNaming.js'
+import { prepareGitProject, readGitProject } from '../lib/gitProject.js'
+import { sweepWorktrees } from '../lib/worktreeSweep.js'
+import type { PrepareOptions, ScmDescription, ScmDetectOptions, ScmDetectResult, ScmLaunchRecord, ScmProject } from './types.js'
+
+export class GitScmProject implements ScmProject {
+ readonly kind = 'git' as const
+
+ async detect(path: string, options: ScmDetectOptions = {}): Promise<ScmDetectResult> {
+ const found = await readGitProject(path, options)
+ if ('error' in found) return { kind: 'none', error: found.error }
+ return 'root' in found ? { kind: 'git', git: found } : { kind: 'none' }
+ }
+
+ /** Exactly the call `projectFolder.ts` makes for `source: 'worktree'`: the branch trio travels
+ * together or not at all, because `prepareGitProject` reads `existingBranch` and `placeholder` only
+ * alongside a `branchName`. */
+ async prepareIsolated(source: string, options: PrepareOptions): Promise<{ cwd: string; launchRecord: ScmLaunchRecord }> {
+ const cwd = await prepareGitProject(source, {
+ root: options.root, worktree: true, ref: options.base,
+ ...(options.name !== undefined ? {
+ branchName: options.name, existingBranch: options.existing === true, placeholder: options.placeholder === true,
+ } : {}),
+ ...(options.pick ? { pick: options.pick } : {}),
+ })
+ return { cwd, launchRecord: { kind: 'git' } }
+ }
+
+ /** `agentProject`'s answer, named. A folder outside any repository (`root: null`) is not git's to
+ * describe, so it is null here and the seam reports it as `kind: 'none'` with the same fields. */
+ async describe(cwd: string): Promise<ScmDescription | null> {
+ const project = await agentProject(cwd)
+ return project && project.root !== null ? { kind: 'git', ...project } : null
+ }
+
+ rename(cwd: string, title: string | null): Promise<string | null> {
+ return nameBranchAfterSession(cwd, title)
+ }
+
+ sweep(input: { root: string; inUse: Iterable<string | null | undefined>; now?: number; idleMs?: number }): Promise<string[]> {
+ return sweepWorktrees(input)
+ }
+
+ /** A worktree is a folder, and the folder is the row's `cwd`: nothing to re-apply. */
+ launchEnv(_record: ScmLaunchRecord): Record<string, string> {
+ return {}
+ }
+
+ forget(cwd: string): void {
+ forgetAgentProject(cwd)
+ }
+}
diff --git a/cli/src/scm/scmProjects.spec.ts b/cli/src/scm/scmProjects.spec.ts
new file mode 100644
index 000000000..cb14477b7
--- /dev/null
+++ b/cli/src/scm/scmProjects.spec.ts
@@ -0,0 +1,120 @@
+import { execFile } from 'node:child_process'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { basename, join } from 'node:path'
+import { promisify } from 'node:util'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { agentProject } from '../lib/agentProject.js'
+import { readGitProject } from '../lib/gitProject.js'
+import { sweepWorktrees } from '../lib/worktreeSweep.js'
+import { GitScmProject } from './gitScmProject.js'
+import {
+ describeScmProject, detectScmProject, forgetScmProject, prepareScmWrite, renameScmProject, scmByKind, scmLaunchEnv, scmProjects, sweepScmProjects,
+} from './scmProjects.js'
+import { parseScmLaunchRecord, type ScmDetectResult, type ScmProject } from './types.js'
+
+const exec = promisify(execFile)
+describe('the SCM seam, with git as its only implementation', { timeout: 30_000 }, () => {
+ let root: string, repo: string, plain: string
+ const git = async (cwd: string, ...args: string[]) => (await exec('git', ['-C', cwd,
+ '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])).stdout.trim()
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'harness-scm-seam-'))
+ repo = join(root, 'app')
+ plain = join(root, 'plain folder')
+ await mkdir(repo)
+ await mkdir(plain)
+ await git(repo, 'init', '--quiet', '-b', 'main')
+ await writeFile(join(repo, 'file'), 'one')
+ await git(repo, 'add', '.')
+ await git(repo, 'commit', '--quiet', '-m', 'initial')
+ })
+ afterEach(() => rm(root, { recursive: true, force: true }))
+
+ it('knows git, and nothing else yet', () => {
+ expect(scmProjects.map(scm => scm.kind)).toEqual(['git'])
+ expect(scmByKind('git')?.kind).toBe('git')
+ expect(scmByKind('none')).toBeNull()
+ })
+
+ it('describes a folder exactly as agentProject does, plus its kind — none is a real answer, an implausible cwd is not', async () => {
+ expect(await describeScmProject(repo)).toEqual({ kind: 'git', ...await agentProject(repo) })
+ expect(await describeScmProject(plain)).toEqual({ kind: 'none', ...await agentProject(plain) })
+ expect(await describeScmProject(plain)).toEqual({ kind: 'none', name: basename(plain), cwd: plain, root: null, remote: null, branch: null })
+ expect(await describeScmProject(null)).toBeNull()
+ expect(await describeScmProject(undefined)).toBeNull()
+ expect(await describeScmProject('relative')).toBeNull()
+ expect(await describeScmProject('/x\u0000y')).toBeNull()
+ })
+
+ it('forgets through the seam what the git implementation cached', async () => {
+ expect(await describeScmProject(repo)).toMatchObject({ branch: 'main' })
+ await git(repo, 'switch', '--quiet', '-c', 'other')
+ forgetScmProject(repo)
+ expect(await describeScmProject(repo)).toMatchObject({ kind: 'git', branch: 'other' })
+ })
+
+ it('detects a repository as git_project_info would, and reports none or the probe failure otherwise', async () => {
+ const fence = { knownRoots: [root] }
+ expect(await detectScmProject(repo, fence)).toEqual({ kind: 'git', git: await readGitProject(repo, fence) })
+ expect(await detectScmProject(plain, fence)).toEqual({ kind: 'none' })
+ expect(await detectScmProject(repo)).toEqual({ kind: 'none', error: 'FORBIDDEN' })
+ expect(await detectScmProject('relative')).toEqual({ kind: 'none', error: 'INVALID_PATH' })
+ })
+
+ it('asks every SCM at once and reads the answers in order: a slow probe holds nobody back, a throwing one fails only itself', async () => {
+ const order: string[] = []
+ const none = (error?: string): ScmDetectResult => ({ kind: 'none', ...(error ? { error } : {}) })
+ const slow = { kind: 'git', detect: async () => { await new Promise(resolve => setTimeout(resolve, 50)); order.push('slow'); return none('GIT_UNAVAILABLE') } }
+ const fast = { kind: 'git', detect: async () => { order.push('fast'); return none() } }
+ expect(await detectScmProject(plain, {}, [slow, fast] as unknown as ScmProject[])).toEqual(none('GIT_UNAVAILABLE'))
+ expect(order).toEqual(['fast', 'slow'])
+ const throws = { kind: 'git', detect: async () => { throw new Error('boom') } }
+ expect(await detectScmProject(repo, { knownRoots: [root] }, [throws as unknown as ScmProject, new GitScmProject()])).toMatchObject({ kind: 'git' })
+ expect(await detectScmProject(repo, {}, [throws as unknown as ScmProject])).toEqual(none('UNAVAILABLE'))
+ })
+
+ it('renames through the seam and answers null where git would', async () => {
+ expect(await renameScmProject(plain, 'A title')).toBeNull()
+ expect(await renameScmProject(repo, 'A title')).toBeNull()
+ })
+
+ it('sweeps what sweepWorktrees sweeps, reading a one-shot iterable of in-use folders only once', async () => {
+ const harnesses = join(root, 'harnesses')
+ const worktrees = join(harnesses, 'worktrees', 'app')
+ await mkdir(worktrees, { recursive: true })
+ await git(repo, 'worktree', 'add', '--quiet', '-b', 'harness/idle', join(worktrees, 'idle'), 'main')
+ await git(repo, 'worktree', 'add', '--quiet', '-b', 'harness/busy', join(worktrees, 'busy'), 'main')
+ const later = Date.now() + 8 * 24 * 3600_000
+ function* inUse() { yield join(worktrees, 'busy'); yield null }
+ expect(await sweepScmProjects({ root: harnesses, inUse: inUse(), now: later })).toEqual([join(worktrees, 'idle')])
+ expect(await sweepWorktrees({ root: harnesses, inUse: [join(worktrees, 'busy')], now: later })).toEqual([])
+ expect(await sweepScmProjects({ root: join(root, 'nowhere'), inUse: [] })).toEqual([])
+ })
+
+ it('has no launch environment for git, and nothing for a missing record', () => {
+ expect(scmLaunchEnv({ kind: 'git' })).toBeUndefined()
+ expect(scmLaunchEnv(null)).toBeUndefined()
+ expect(scmLaunchEnv(undefined)).toBeUndefined()
+ })
+
+ it('prepares a write as a no-op for git, and asks an SCM that has the hook, in order', async () => {
+ await expect(prepareScmWrite(repo, ['AGENTS.md'])).resolves.toBeUndefined()
+ await expect(prepareScmWrite(plain, ['AGENTS.md'])).resolves.toBeUndefined()
+ const asked: Array<[string, readonly string[]]> = []
+ const writer = { kind: 'git', prepareWrite: async (cwd: string, paths: readonly string[]) => { asked.push([cwd, paths]) } }
+ await prepareScmWrite(repo, ['AGENTS.md', 'CLAUDE.md'], [new GitScmProject(), writer as unknown as ScmProject])
+ expect(asked).toEqual([[repo, ['AGENTS.md', 'CLAUDE.md']]])
+ })
+
+ it('rehydrates a launch record from the registry file and refuses anything else', () => {
+ expect(parseScmLaunchRecord({ kind: 'git' })).toEqual({ kind: 'git' })
+ expect(parseScmLaunchRecord({ kind: 'git', extra: 1 })).toEqual({ kind: 'git' })
+ expect(parseScmLaunchRecord({ kind: 'none' })).toBeNull()
+ expect(parseScmLaunchRecord({ kind: 'svn' })).toBeNull()
+ expect(parseScmLaunchRecord({})).toBeNull()
+ expect(parseScmLaunchRecord(null)).toBeNull()
+ expect(parseScmLaunchRecord('git')).toBeNull()
+ expect(parseScmLaunchRecord(undefined)).toBeNull()
+ })
+})
diff --git a/cli/src/scm/scmProjects.ts b/cli/src/scm/scmProjects.ts
new file mode 100644
index 000000000..dd10cfe25
--- /dev/null
+++ b/cli/src/scm/scmProjects.ts
@@ -0,0 +1,90 @@
+/**
+ * The SCMs this daemon knows, and the one-call-per-stage functions the rest of the daemon uses
+ * instead of naming an implementation. Callers (`agentFrame`, the workspaces service's rename and sweep,
+ * `projectFolder`, `launchOverrides`, the instruction-file writers) ask "whichever SCM this is" and
+ * get an answer; a second SCM is one more entry in `scmProjects`, not one more branch at each call site.
+ *
+ * Order matters: the first implementation that claims a folder wins. Git is first and, today, alone.
+ * A folder none claims is `kind: 'none'` — a real answer a frame carries, not an error — with the
+ * same `root: null` fields `agentProject` reports.
+ *
+ * The optional `scms` parameters are test seams; the daemon always uses `scmProjects`.
+ */
+import { basename } from 'node:path'
+import { validProjectCwd } from '../lib/agentProject.js'
+import { GitScmProject } from './gitScmProject.js'
+import type { ScmDescription, ScmDetectOptions, ScmDetectResult, ScmKind, ScmLaunchRecord, ScmProject } from './types.js'
+
+export const scmProjects: readonly ScmProject[] = [new GitScmProject()]
+
+export function scmByKind(kind: ScmKind, scms: readonly ScmProject[] = scmProjects): ScmProject | null {
+ return scms.find(scm => scm.kind === kind) ?? null
+}
+
+/** The `scm_project_info` answer: the first SCM that claims `path`, else `none` with the first
+ * failure code any of them raised (a probe that could not run is not the same as a plain folder).
+ * Asked together and read in order, so one SCM's slow probe never holds another's answer back, and a
+ * probe that throws is that SCM's failure, never the others'. */
+export async function detectScmProject(path: string, options: ScmDetectOptions = {},
+ scms: readonly ScmProject[] = scmProjects): Promise<ScmDetectResult> {
+ const answers = await Promise.all(scms.map(scm =>
+ scm.detect(path, options).catch((): ScmDetectResult => ({ kind: 'none', error: 'UNAVAILABLE' }))))
+ let error: string | undefined
+ for (const found of answers) {
+ if (found.kind !== 'none') return found
+ error ??= found.error
+ }
+ return { kind: 'none', ...(error ? { error } : {}) }
+}
+
+/** What `AgentFrame.project` carries for `cwd`; null for no or an implausible `cwd`, exactly as
+ * `agentProject` answers, so a frame never gains a project it did not have. */
+export async function describeScmProject(cwd: string | null | undefined, scms: readonly ScmProject[] = scmProjects): Promise<ScmDescription | null> {
+ if (!validProjectCwd(cwd)) return null
+ for (const scm of scms) {
+ const described = await scm.describe(cwd)
+ if (described) return described
+ }
+ return { kind: 'none', name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }
+}
+
+/** The session's title reaches the workspace's line of work, once (`branchNaming.ts` for git). */
+export async function renameScmProject(cwd: string, title: string | null, scms: readonly ScmProject[] = scmProjects): Promise<string | null> {
+ for (const scm of scms) {
+ const renamed = await scm.rename(cwd, title)
+ if (renamed) return renamed
+ }
+ return null
+}
+
+/** Every SCM sweeps its own idle workspaces under `root`; the paths removed, in SCM order. `inUse`
+ * is read once here, because an iterable handed to two implementations would be empty for the second. */
+export async function sweepScmProjects(input: {
+ root: string
+ inUse: Iterable<string | null | undefined>
+ now?: number
+ idleMs?: number
+}, scms: readonly ScmProject[] = scmProjects): Promise<string[]> {
+ const inUse = [...input.inUse]
+ const removed: string[] = []
+ for (const scm of scms) removed.push(...await scm.sweep({ ...input, inUse }))
+ return removed
+}
+
+/** The pane environment a workspace's record asks for, or undefined when there is none to ask —
+ * shaped for `mergedLaunchEnv` (core/agents/launchEnv.ts), which treats "no env" and "empty env" the same way. */
+export function scmLaunchEnv(record: ScmLaunchRecord | null | undefined, scms: readonly ScmProject[] = scmProjects): Record<string, string> | undefined {
+ if (!record) return undefined
+ const env = scmByKind(record.kind, scms)?.launchEnv(record) ?? {}
+ return Object.keys(env).length ? env : undefined
+}
+
+/** Before Harness writes into project files an SCM may hold read-only. Nothing runs for an SCM with
+ * no `prepareWrite` (git), so a git workspace sees no new subprocess and no file access from this. */
+export async function prepareScmWrite(cwd: string, paths: readonly string[], scms: readonly ScmProject[] = scmProjects): Promise<void> {
+ for (const scm of scms) await scm.prepareWrite?.(cwd, paths)
+}
+
+export function forgetScmProject(cwd: string, scms: readonly ScmProject[] = scmProjects): void {
+ for (const scm of scms) scm.forget?.(cwd)
+}
diff --git a/cli/src/scm/types.ts b/cli/src/scm/types.ts
new file mode 100644
index 000000000..6302de1e5
--- /dev/null
+++ b/cli/src/scm/types.ts
@@ -0,0 +1,101 @@
+/**
+ * The source-control seam: what Harness asks of a project's SCM, in one shape, so a second system can
+ * be added beside git rather than swapped in — the rule CONTRIBUTING.md already sets for multiplexers.
+ * Today the only implementation wraps the git path — `gitProject.ts` (detect, prepare),
+ * `agentProject.ts` (describe), `branchNaming.ts` (rename), `worktreeSweep.ts` (sweep) — and changes
+ * nothing about it. The git assumptions those modules make (the `.git` file marker,
+ * `branch.<name>.harness` config keys, `refs/heads/…` validation, `git status --porcelain` as
+ * "dirty") stay inside the git implementation and never reach a caller.
+ *
+ * Nothing in this file runs a subprocess. `parseScmLaunchRecord` is here rather than beside the
+ * implementations because the registry rehydrates rows with it and must not pull the implementations
+ * (and their git modules) in just to validate one field — the same split `gridLaunch.ts` makes with
+ * `parseGridLaunchOverride`.
+ */
+import type { AgentProject } from '../lib/agentProject.js'
+import type { readGitProject } from '../lib/gitProject.js'
+
+/** `none` is a folder no SCM claims: a real answer, not an error. */
+export type ScmKind = 'git' | 'none'
+
+/** What `git_project_info` answers when the folder IS a repository: `readGitProject`'s found shape. */
+export type GitProjectInfo = Extract<Awaited<ReturnType<typeof readGitProject>>, { root: string }>
+
+/**
+ * The read-only probe's answer (`scm_project_info`). `kind: 'none'` with no `error` is a folder no SCM
+ * claims; `error` carries the first implementation's failure code (`GIT_UNAVAILABLE`, `INVALID_PATH`,
+ * `FORBIDDEN`) when one could not even look. `git` is present exactly when `kind` is `git`.
+ */
+export type ScmDetectResult = { kind: ScmKind; git?: GitProjectInfo; error?: string }
+
+/** What the launcher's probe passes through to `readGitProject`: the same fence and refresh. */
+export interface ScmDetectOptions {
+ refresh?: boolean
+ knownRoots?: string[]
+}
+
+/**
+ * What `AgentFrame.project` carries: a superset of `AgentProject`, with the SCM named. `kind: 'none'`
+ * is a folder no SCM claims — `root`, `remote` and `branch` are null, exactly as `agentProject`
+ * reports them. `worktree` and `branchPending` keep their names for wire compatibility; another SCM
+ * sets them with the same meaning (an isolated workspace; a name still the made-up one).
+ */
+export type ScmDescription = AgentProject & { kind: ScmKind }
+
+/**
+ * What a pane has to be launched WITH for the workspace to be the same one on every relaunch — the
+ * SCM's half of what `gridLaunchRecord` is for a grid. Kept on the registry row (`scmLaunch`), so a
+ * pane recreated after a reboot or respawned in place gets the same environment `agent_create` gave
+ * it. Git needs nothing: the worktree is a folder and the folder is the row's `cwd`. A tagged union, so
+ * an SCM whose workspace binding travels in environment variables adds its own member.
+ */
+export type ScmLaunchRecord = { kind: 'git' }
+
+/** A record as the registry file has it, or null for anything else — an unknown kind, a half-formed
+ * record, a hand-edited row. A dropped record is relaunched without, never with a guess. */
+export function parseScmLaunchRecord(raw: unknown): ScmLaunchRecord | null {
+ if (!raw || typeof raw !== 'object') return null
+ const record = raw as Record<string, unknown>
+ if (record.kind === 'git') return { kind: 'git' }
+ return null
+}
+
+/** `prepareGitProject`'s worktree options, with SCM-neutral names. */
+export interface PrepareOptions {
+ /** Harness's own folder (`~/harnesses`); the isolated workspace is made under it. */
+ root: string
+ /** What the workspace's work starts from — git: a `refs/heads/…` or `refs/remotes/…` ref.
+ * Absent: the SCM's own default (git: `HEAD`). */
+ base?: string
+ /** The name the workspace's line of work takes — git: its branch. Absent: made up. */
+ name?: string
+ /** `name` exists already and is taken as it is, rather than created from `base`. */
+ existing?: boolean
+ /** `name` was made up (`brave-otter`): the session's title replaces it once there is one (`rename`). */
+ placeholder?: boolean
+ /** Test seam for the made-up name (`agentNames.placeholderBranch`). */
+ pick?: (n: number) => number
+}
+
+export interface ScmProject {
+ readonly kind: Exclude<ScmKind, 'none'>
+ /** Read-only probe for the launcher (today: `readGitProject` → `git_project_info`). Never mutates. */
+ detect(path: string, options?: ScmDetectOptions): Promise<ScmDetectResult>
+ /** Make an isolated workspace for one harness (today: `prepareGitProject` with `worktree: true`). */
+ prepareIsolated(source: string, options: PrepareOptions): Promise<{ cwd: string; launchRecord: ScmLaunchRecord }>
+ /** What a frame says about `cwd` (today: `agentProject`), or null when `cwd` is not this SCM's. */
+ describe(cwd: string): Promise<ScmDescription | null>
+ /** Once the session has a title (today: `nameBranchAfterSession`): the new name, or null when nothing was renamed. */
+ rename(cwd: string, title: string | null): Promise<string | null>
+ /** Remove idle isolated workspaces nothing uses (today: `sweepWorktrees`); the paths removed. */
+ sweep(input: { root: string; inUse: Iterable<string | null | undefined>; now?: number; idleMs?: number }): Promise<string[]>
+ /** Env to put in the pane at launch and every relaunch (git: nothing). */
+ launchEnv(record: ScmLaunchRecord): Record<string, string>
+ /** Before Harness itself writes into project files the SCM may hold read-only (the instruction files
+ * a harness or saved APIs append to). `paths` are relative to `cwd` and need not exist. Git has
+ * nothing to do and leaves this out, so no subprocess runs. */
+ prepareWrite?(cwd: string, paths: readonly string[]): Promise<void>
+ /** Forget what `describe` cached for `cwd`, as after a rename (today: `forgetAgentProject`). The
+ * cache is the implementation's, so its invalidation is too. */
+ forget?(cwd: string): void
+}