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.

Ask the SCM before Harness writes into a project's instruction files

Adam Hafezfa0b7d22a5b7
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 2e337ab4b..49481ab3e 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -40,7 +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 { prepareInstructionWrites, scmLaunchEnv } from '../../scm/scmProjects.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
@@ -128,6 +128,7 @@ export function createAgentCreator({
// The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
// `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
const label = buildHarnessSessionLabel(engine)
+ await prepareInstructionWrites(cwd)
// Prepare the harness workspace, then bind its session context to the selected engine.
// Missing packages or invalid runtimes refuse the launch before the agent is started.
let dshEnv: Record<string, string> | undefined
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
index 3356509cd..87f202e9f 100644
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@ -23,7 +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 { prepareInstructionWrites, scmLaunchEnv } from '../../scm/scmProjects.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
@@ -73,6 +73,7 @@ export function createAgentForker({
if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
const label = buildHarnessSessionLabel(engine)
+ await prepareInstructionWrites(source.cwd)
// Fork the source's saved harness context. Workspace templates and init are not run again.
let dshEnv: Record<string, string> | undefined
let dshArgs: string[] = []
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index 00f591d63..fe8ea692f 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -13,6 +13,7 @@ import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
import { isApiLaunch } from '../../lib/gridLaunch.js'
import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from '../../lib/launchOverrides.js'
import { sid } from '../../lib/log.js'
+import { prepareInstructionWrites } from '../../scm/scmProjects.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
export interface LaunchHelperDeps {
@@ -32,6 +33,7 @@ export function createLaunchHelpers({ prepareApiTools, savedApis, launchOverride
// An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key
// pasted since takes effect, and a removed API is refused rather than kept on its old key.
const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {
+ await prepareInstructionWrites(session.cwd)
prepareApiTools(session.cwd, session.engine)
let gridLaunch = source.gridLaunch ?? null
if (gridLaunch && isApiLaunch(gridLaunch)) {
diff --git a/cli/src/dsh/adapters.ts b/cli/src/dsh/adapters.ts
index 00e757fec..2aae1307f 100644
--- a/cli/src/dsh/adapters.ts
+++ b/cli/src/dsh/adapters.ts
@@ -48,6 +48,16 @@ export const HARNESS_ADAPTERS = {
copilot: { instructionFiles: ['AGENTS.md'] },
} satisfies Record<ProcessEngine, HarnessAdapter>
+/**
+ * Every project file Harness itself may write into: any adapter's instruction files (the session
+ * bootstrap, `runtime.ts`) and the files the saved-API notes go in (`lib/apiInstructions.ts`). Asked of
+ * the workspace's SCM before those writes (`prepareScmWrite`), for an SCM that holds tracked files
+ * read-only. Not every name exists in a given workspace.
+ */
+export const PROJECT_INSTRUCTION_FILES: readonly string[] = [...new Set([
+ ...Object.values(HARNESS_ADAPTERS).flatMap(adapter => adapter.instructionFiles), 'AGENTS.md', 'CLAUDE.md', 'GEMINI.md',
+])]
+
/** A terminal has no instruction loader or agent tools. It remains a Coding-only choice. */
export function harnessAdapter(engine: AgentEngine): HarnessAdapter {
if (engine === 'terminal') throw new Error('A harness needs an agent engine; Terminal cannot run harness instructions.')
diff --git a/cli/src/scm/instructionWrites.spec.ts b/cli/src/scm/instructionWrites.spec.ts
new file mode 100644
index 000000000..cd26209b2
--- /dev/null
+++ b/cli/src/scm/instructionWrites.spec.ts
@@ -0,0 +1,69 @@
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { PROCESS_ENGINES } from '../engines/types.js'
+import { PROJECT_INSTRUCTION_FILES } from '../dsh/adapters.js'
+import type { InstalledDsh } from '../dsh/installed.js'
+import { prepareHarnessLaunch } from '../dsh/runtime.js'
+import type { ApiConnections } from '../lib/apiConnections.js'
+import { prepareApiInstructions } from '../lib/apiInstructions.js'
+
+// `prepareScmWrite` is handed PROJECT_INSTRUCTION_FILES before Harness writes into a project's
+// instruction files (`prepareInstructionWrites`: create, fork, every relaunch in core/agents/). The
+// list is only useful if it names every file those writers actually touch, so this runs the writers
+// and compares.
+describe('the files an SCM is asked to prepare before Harness writes instructions', () => {
+ let root: string, ws: string, pkg: InstalledDsh
+ const write = (path: string, text: string) => {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, text)
+ }
+ /** The workspace's top-level files and their contents, `.harness/` (Harness's own folder) aside. */
+ const snapshot = () => new Map(readdirSync(ws).filter(name => name !== '.harness' && statSync(join(ws, name)).isFile())
+ .map(name => [name, readFileSync(join(ws, name), 'utf8')]))
+ const touched = (before: Map<string, string>) => [...snapshot()].filter(([name, text]) => before.get(name) !== text).map(([name]) => name)
+
+ beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'scm-instruction-writes-')))
+ ws = join(root, 'workspace')
+ mkdirSync(ws)
+ const dir = join(root, 'package')
+ write(join(dir, 'AGENTS.md'), '# Make a drawing\n')
+ write(join(dir, 'skills/draw/SKILL.md'), '# Draw\n')
+ pkg = { id: 'acme/draw', dir, realDir: dir, source: dir, ref: null, commit: null, linked: true, installedAt: 1,
+ manifest: { spec: 1, id: 'acme/draw', name: 'Drawing', engine: 'claude', agent: { instructions: 'AGENTS.md', skills: ['skills'] } } }
+ })
+ afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+ for (const engine of PROCESS_ENGINES) {
+ it(`${engine}: names every file the session bootstrap writes, in a fresh workspace and one with instructions of its own`, () => {
+ let before = snapshot()
+ prepareHarnessLaunch(pkg, ws, engine, `${engine}-fresh`)
+ const fresh = touched(before)
+ expect(fresh.length).toBeGreaterThan(0)
+ for (const name of fresh) expect(PROJECT_INSTRUCTION_FILES).toContain(name)
+
+ rmSync(ws, { recursive: true, force: true })
+ mkdirSync(ws)
+ write(join(ws, 'AGENTS.md'), '# Project rules\n')
+ write(join(ws, 'CLAUDE.md'), '# Project rules\n')
+ before = snapshot()
+ prepareHarnessLaunch(pkg, ws, engine, `${engine}-existing`)
+ for (const name of touched(before)) expect(PROJECT_INSTRUCTION_FILES).toContain(name)
+ })
+ }
+
+ it('names every file the saved-API notes go in', () => {
+ const store = { list: () => [{ id: 'api' }] } as unknown as ApiConnections
+ for (const engine of [...PROCESS_ENGINES, 'gemini']) {
+ rmSync(ws, { recursive: true, force: true })
+ mkdirSync(ws)
+ const before = snapshot()
+ prepareApiInstructions(store, ws, engine)
+ const written = touched(before)
+ expect(written).toHaveLength(1)
+ expect(PROJECT_INSTRUCTION_FILES).toContain(written[0])
+ }
+ })
+})
diff --git a/cli/src/scm/scmProjects.spec.ts b/cli/src/scm/scmProjects.spec.ts
index 9503204b4..e639e6fbc 100644
--- a/cli/src/scm/scmProjects.spec.ts
+++ b/cli/src/scm/scmProjects.spec.ts
@@ -3,14 +3,15 @@ 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { PROJECT_INSTRUCTION_FILES } from '../dsh/adapters.js'
import { agentProject } from '../lib/agentProject.js'
import { encryptDownFrame, encryptRpcResult } from '../lib/e2ee/applicationFrames.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,
+ describeScmProject, detectScmProject, forgetScmProject, prepareInstructionWrites, prepareScmWrite, renameScmProject, scmByKind, scmLaunchEnv, scmProjects, sweepScmProjects,
} from './scmProjects.js'
import { parseScmLaunchRecord, type ScmDetectResult, type ScmProject } from './types.js'
@@ -113,6 +114,20 @@ describe('the SCM seam, with git as its only implementation', { timeout: 30_000
expect(asked).toEqual([[repo, ['AGENTS.md', 'CLAUDE.md']]])
})
+ it('asks for the instruction files before a write, skips a missing cwd, and only logs a failure', async () => {
+ const asked: Array<[string, readonly string[]]> = []
+ const writer = { kind: 'git', prepareWrite: async (cwd: string, paths: readonly string[]) => { asked.push([cwd, paths]) } }
+ await prepareInstructionWrites(repo, [writer as unknown as ScmProject])
+ await prepareInstructionWrites(null, [writer as unknown as ScmProject])
+ expect(asked).toEqual([[repo, PROJECT_INSTRUCTION_FILES]])
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const failing = { kind: 'git', prepareWrite: async () => { throw new Error('locked') } }
+ await expect(prepareInstructionWrites(repo, [failing as unknown as ScmProject])).resolves.toBeUndefined()
+ expect(warn).toHaveBeenCalledWith('[scm] could not prepare instruction files for writing · locked')
+ } finally { warn.mockRestore() }
+ })
+
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' })
diff --git a/cli/src/scm/scmProjects.ts b/cli/src/scm/scmProjects.ts
index dd10cfe25..c311ad917 100644
--- a/cli/src/scm/scmProjects.ts
+++ b/cli/src/scm/scmProjects.ts
@@ -11,6 +11,7 @@
* The optional `scms` parameters are test seams; the daemon always uses `scmProjects`.
*/
import { basename } from 'node:path'
+import { PROJECT_INSTRUCTION_FILES } from '../dsh/adapters.js'
import { validProjectCwd } from '../lib/agentProject.js'
import { GitScmProject } from './gitScmProject.js'
import type { ScmDescription, ScmDetectOptions, ScmDetectResult, ScmKind, ScmLaunchRecord, ScmProject } from './types.js'
@@ -85,6 +86,17 @@ export async function prepareScmWrite(cwd: string, paths: readonly string[], scm
for (const scm of scms) await scm.prepareWrite?.(cwd, paths)
}
+/** Before Harness writes into a project's instruction files (a harness's session bootstrap, the
+ * saved-API notes): an SCM that holds tracked files read-only opens `PROJECT_INSTRUCTION_FILES` first.
+ * Awaited by create, fork and every relaunch (`core/agents/create.ts`, `fork.ts`, `launch.ts`). Git
+ * has no `prepareWrite`, so for a git workspace this runs nothing and touches no file. A failure here
+ * is only logged; the write that follows reports its own. */
+export async function prepareInstructionWrites(cwd: string | null | undefined, scms: readonly ScmProject[] = scmProjects): Promise<void> {
+ if (!cwd) return
+ try { await prepareScmWrite(cwd, PROJECT_INSTRUCTION_FILES, scms) }
+ catch (error) { console.warn(`[scm] could not prepare instruction files for writing · ${error instanceof Error ? error.message : error}`) }
+}
+
export function forgetScmProject(cwd: string, scms: readonly ScmProject[] = scmProjects): void {
for (const scm of scms) scm.forget?.(cwd)
}