diff --git a/docs/design/agent-proximity.md b/docs/design/agent-proximity.md index c9d3e2b9678..6aed3faaddb 100644 --- a/docs/design/agent-proximity.md +++ b/docs/design/agent-proximity.md @@ -149,3 +149,8 @@ the renderer draws), and pairwise `links` with risk (the edges to color). escalation wired to live session diffs. - v2: cross-machine airspace over Tailscale (teammate agents enter the same space); the recorded "N agents, M humans, zero merge conflicts" demo. + +The control pane compares each worktree against the merge base of its declared base +and HEAD. Committed, staged, and unstaged tracked edits carry changed line ranges. +Untracked files that Git does not ignore participate as whole-file working sets. +Changes made only on the base branch after the worktree diverged do not participate. diff --git a/scripts/lib/control-pane/proximity.js b/scripts/lib/control-pane/proximity.js index a958ef36f3d..a4525f41e06 100644 --- a/scripts/lib/control-pane/proximity.js +++ b/scripts/lib/control-pane/proximity.js @@ -15,6 +15,34 @@ const { execFileSync } = require('child_process'); const { scanAirspace, buildProximityTriggers } = require('../agent-proximity'); const { buildDependencyGraph } = require('../agent-proximity/graph'); +/** Decode Git C-style path escapes as bytes before UTF-8 decoding. */ +function decodeGitPath(header) { + const value = header.replace(/\t$/, ''); + if (!value.startsWith('"')) return value; + if (!value.endsWith('"')) return null; + const parts = []; + let literal = ''; + const escaped = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }; + for (let i = 1; i < value.length - 1; i += 1) { + const character = value[i]; + if (character !== '\\') { literal += character; continue; } + if (literal) { parts.push(Buffer.from(literal, 'utf8')); literal = ''; } + const next = value[++i]; + if (/[0-7]/.test(next || '')) { + let octal = next; + while (octal.length < 3 && /[0-7]/.test(value[i + 1] || '')) octal += value[++i]; + const byte = parseInt(octal, 8); + if (byte > 255) return null; + parts.push(Buffer.from([byte])); + } else { + if (!Object.prototype.hasOwnProperty.call(escaped, next)) return null; + parts.push(Buffer.from([escaped[next]])); + } + } + if (literal) parts.push(Buffer.from(literal, 'utf8')); + return Buffer.concat(parts).toString('utf8'); +} + /** * Parse `git diff --unified=0` output into per-file NEW-side line ranges. Hunk * headers look like `@@ -a,b +c,d @@`; we keep the +c,d (new) side so the overlap @@ -28,10 +56,13 @@ function parseDiffRanges(diff) { const byFile = new Map(); let current = null; for (const line of String(diff || '').split('\n')) { - const fileMatch = line.match(/^\+\+\+ b\/(.+)$/); - if (fileMatch) { - const name = fileMatch[1].trim(); - current = name === '/dev/null' ? null : name; + if (line.startsWith('diff --git ')) { + current = null; + continue; + } + if (line.startsWith('+++ ')) { + const gitPath = decodeGitPath(line.slice(4)); + current = gitPath && gitPath.startsWith('b/') ? gitPath.slice(2) : null; if (current && !byFile.has(current)) byFile.set(current, []); continue; } @@ -45,8 +76,8 @@ function parseDiffRanges(diff) { return byFile; } -function runGitDiff(worktreePath, base, extraArgs) { - return execFileSync('git', ['-C', worktreePath, 'diff', ...extraArgs, `${base}...HEAD`], { +function runGit(worktreePath, args) { + return execFileSync('git', ['-C', worktreePath, ...args], { encoding: 'utf8', timeout: 5000, maxBuffer: 8 * 1024 * 1024, @@ -54,6 +85,20 @@ function runGitDiff(worktreePath, base, extraArgs) { }); } +function runGitDiff(worktreePath, base, extraArgs) { + const mergeBase = runGit(worktreePath, ['merge-base', '--', base, 'HEAD']).trim(); + return runGit(worktreePath, ['-c', 'core.quotePath=false', 'diff', ...extraArgs, mergeBase, '--']); +} + +function untrackedFiles(worktreePath) { + try { + return runGit(worktreePath, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean); + } catch { + // Keep successful tracked-file diffs when this optional probe is unavailable. + return []; + } +} + /** * Default working-set source: a session's worktree diff against its base, with * per-file changed line ranges. Returns [{ path, lines? }], or [] on failure so @@ -65,6 +110,15 @@ function defaultWorkingSetFor(session) { const base = wt.base || 'HEAD'; try { const ranges = parseDiffRanges(runGitDiff(wt.path, base, ['--unified=0'])); + // Deletions, binary changes and quoted paths have no usable new-side hunks. + try { + for (const file of runGitDiff(wt.path, base, ['--name-only', '-z']).split('\0').filter(Boolean)) { + if (!ranges.has(file)) ranges.set(file, []); + } + } catch { + // Preserve ranges already read if the supplementary filename probe fails. + } + for (const file of untrackedFiles(wt.path)) ranges.set(file, []); return [...ranges.entries()].map(([path, lines]) => (lines.length > 0 ? { path, lines } : { path })); } catch { return []; @@ -79,10 +133,7 @@ function defaultChangedFilesFor(session) { if (!wt || !wt.path) return []; const base = wt.base || 'HEAD'; try { - return runGitDiff(wt.path, base, ['--name-only']) - .split('\n') - .map(s => s.trim()) - .filter(Boolean); + return [...new Set([...runGitDiff(wt.path, base, ['--name-only', '-z']).split('\0').filter(Boolean), ...untrackedFiles(wt.path)])]; } catch { return []; } diff --git a/tests/lib/control-pane-proximity.test.js b/tests/lib/control-pane-proximity.test.js index c91603f468e..1104214bc34 100644 --- a/tests/lib/control-pane-proximity.test.js +++ b/tests/lib/control-pane-proximity.test.js @@ -54,6 +54,138 @@ const changedFilesFor = session => 'no-worktree': [] })[session.id] || []; +test('real worktrees expose committed, staged, unstaged and untracked work before commit', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { execFileSync } = require('child_process'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-proximity-worktree-')); + const repo = path.join(dir, 'repo'); + const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], { stdio: 'pipe' }); + try { + fs.mkdirSync(repo); + git(repo, 'init', '-q', '-b', 'main'); + git(repo, 'config', 'user.name', 'proximity-test'); + git(repo, 'config', 'user.email', 'proximity-test@example.com'); + fs.writeFileSync(path.join(repo, 'shared.js'), 'const value = 1;\n'); + fs.writeFileSync(path.join(repo, '.gitignore'), 'ignored.js\n'); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'base'); + const worktrees = ['a', 'b'].map(name => { + const wt = path.join(dir, name); + git(repo, 'worktree', 'add', '-q', '-b', name, wt, 'main'); + fs.writeFileSync(path.join(wt, 'shared.js'), `const value = '${name}';\n`); + fs.writeFileSync(path.join(wt, 'new.js'), `export const name = '${name}';\n`); + fs.writeFileSync(path.join(wt, 'ignored.js'), 'ignored\n'); + return { id: name, worktree: { path: wt, base: 'main' } }; + }); + git(worktrees[0].worktree.path, 'add', 'shared.js'); + fs.writeFileSync(path.join(repo, 'upstream.js'), 'upstream only\n'); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'advance base'); + const assertWorkingSets = () => { + const agents = sessionsToAgents(worktrees); + assert.strictEqual(agents.length, 2); + for (const agent of agents) { + assert.deepStrictEqual(agent.files.map(f => f.path).sort(), ['new.js', 'shared.js']); + assert.deepStrictEqual(agent.files.find(f => f.path === 'shared.js').lines, [[1, 1]]); + assert.strictEqual(agent.files.find(f => f.path === 'new.js').lines, undefined); + } + const snapshot = buildProximitySnapshot(worktrees, { repoRoot: repo, graph: { adjacency: {} } }); + assert.strictEqual(snapshot.counts.agents, 2); + assert.ok(snapshot.advisories.some(a => a.level === 'resolution')); + }; + assertWorkingSets(); + git(worktrees[0].worktree.path, 'commit', '-qm', 'commit staged edit'); + assertWorkingSets(); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('real Git working sets retain tracked deletions and binary changes', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { execFileSync } = require('child_process'); + const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-proximity-delete-')); + const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: 'pipe' }); + try { + git('init', '-q', '-b', 'main'); + git('config', 'user.name', 'proximity-test'); + git('config', 'user.email', 'proximity-test@example.com'); + fs.writeFileSync(path.join(repo, 'deleted.js'), 'export const value = 1;\n'); + fs.writeFileSync(path.join(repo, 'binary.bin'), Buffer.from([0, 1, 2])); + git('add', '.'); + git('commit', '-qm', 'base'); + fs.unlinkSync(path.join(repo, 'deleted.js')); + fs.writeFileSync(path.join(repo, 'binary.bin'), Buffer.from([0, 3, 4])); + const [agent] = sessionsToAgents([{ id: 'delete', worktree: { path: repo, base: 'main' } }]); + assert.ok(agent, 'an agent with only non-text tracked changes still participates'); + assert.deepStrictEqual(agent.files.map(f => f.path).sort(), ['binary.bin', 'deleted.js']); + assert.ok(agent.files.every(f => f.lines === undefined)); + } finally { + fs.rmSync(repo, { recursive: true, force: true }); + } +}); + +test('quoted staged paths and untracked paths share identity, and untracked failures keep tracked edits', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const childProcess = require('child_process'); + const originalExec = childProcess.execFileSync; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-proximity-quoted-')); + const repo = path.join(dir, 'repo'); + const git = (cwd, ...args) => originalExec('git', ['-C', cwd, ...args], { stdio: 'pipe' }); + const modulePath = require.resolve('../../scripts/lib/control-pane/proximity'); + const cachedModule = require.cache[modulePath]; + try { + fs.mkdirSync(repo); + git(repo, 'init', '-q', '-b', 'main'); + git(repo, 'config', 'user.name', 'proximity-test'); + git(repo, 'config', 'user.email', 'proximity-test@example.com'); + fs.writeFileSync(path.join(repo, 'README'), 'base\n'); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'base'); + const file = process.platform === 'win32' ? 'café-résumé.js' : 'café"résumé.js'; + const worktrees = ['a', 'b'].map(name => { + const wt = path.join(dir, name); + git(repo, 'worktree', 'add', '-q', '-b', name, wt, 'main'); + fs.writeFileSync(path.join(wt, file), `export const value = '${name}';\n`); + if (name === 'a') fs.writeFileSync(path.join(wt, 'README'), 'changed\n'); + return { id: name, worktree: { path: wt, base: 'main' } }; + }); + git(worktrees[0].worktree.path, 'add', file); + const snapshot = buildProximitySnapshot(worktrees, { repoRoot: repo, graph: { adjacency: {} } }); + assert.strictEqual(snapshot.counts.agents, 2); + assert.ok(snapshot.advisories.some(advisory => advisory.level === 'resolution')); + assert.ok(snapshot.agents.every(agent => agent.files.includes(file))); + for (const code of ['EACCES', 'ETIMEDOUT', 'ENOBUFS']) { + childProcess.execFileSync = (command, args, options) => { + if (args.includes('ls-files')) throw Object.assign(new Error('untracked probe unavailable'), { code }); + return originalExec(command, args, options); + }; + delete require.cache[modulePath]; + const fresh = require(modulePath); + const [tracked] = fresh.sessionsToAgents([worktrees[0]]); + assert.ok(tracked, `${code}: tracked changes must survive`); + assert.deepStrictEqual(tracked.files.map(entry => entry.path).sort(), ['README', file].sort()); + childProcess.execFileSync = (command, args, options) => { + if (args.includes('--name-only')) throw Object.assign(new Error('tracked names unavailable'), { code }); + return originalExec(command, args, options); + }; + delete require.cache[modulePath]; + const partial = require(modulePath).sessionsToAgents([worktrees[0]]); + assert.deepStrictEqual(partial[0].files.map(entry => entry.path).sort(), ['README', file].sort()); + } + } finally { + childProcess.execFileSync = originalExec; + require.cache[modulePath] = cachedModule; + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + test('sessionsToAgents: only worktree sessions with edits participate', () => { const agents = sessionsToAgents(sessions, { changedFilesFor }); assert.deepStrictEqual(agents.map(a => a.agentId).sort(), ['docs-bot', 'lead-hermes', 'worker-kb']); @@ -97,6 +229,60 @@ test('parseDiffRanges: extracts new-side line ranges per file', () => { ]); }); +test('diff headers isolate quoted/deleted hunks and preserve trailing-space paths', () => { + const ranges = parseDiffRanges([ + 'diff --git a/first.js b/first.js', '+++ b/first.js', '@@ -1 +1 @@', + 'diff --git "a/café.js" "b/café.js"', '+++ "b/café.js"', '@@ -20 +20 @@', + 'diff --git a/deleted.js b/deleted.js', '+++ /dev/null', '@@ -30 +0,0 @@', + 'diff --git a/trailing b/trailing', '+++ b/trailing ', '@@ -40 +40 @@', + ].join('\n')); + assert.deepStrictEqual(ranges.get('first.js'), [[1, 1]]); + assert.deepStrictEqual(ranges.get('trailing '), [[40, 40]]); + assert.strictEqual(ranges.has('trailing'), false); +}); + +test('quoted Git headers decode UTF-8 octal bytes, quotes and control escapes into exact paths', () => { + const ranges = parseDiffRanges([ + 'diff --git "a/café.js" "b/café.js"', + '+++ "b/caf\\303\\251\\"r\\303\\251sum\\303\\251\\tname.js"', '@@ -4,2 +4,2 @@', + 'diff --git a/other.js b/other.js', '+++ b/other.js', '@@ -8 +8 @@', + ].join('\n')); + assert.deepStrictEqual(ranges.get('café"résumé\tname.js'), [[4, 5]]); + assert.deepStrictEqual(ranges.get('other.js'), [[8, 8]]); +}); + +test('real quoted filenames retain disjoint hunk ranges rather than whole-file collisions', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { execFileSync } = require('child_process'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-proximity-quoted-lines-')); + const repo = path.join(dir, 'repo'); + const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], { stdio: 'pipe' }); + const file = process.platform === 'win32' ? 'café-résumé.js' : 'café"résumé\tname.js'; + try { + fs.mkdirSync(repo); + git(repo, 'init', '-q', '-b', 'main'); + git(repo, 'config', 'user.name', 'proximity-test'); + git(repo, 'config', 'user.email', 'proximity-test@example.com'); + const original = Array.from({ length: 40 }, (_, i) => `const line${i} = ${i};`); + fs.writeFileSync(path.join(repo, file), `${original.join('\n')}\n`); + git(repo, 'add', '.'); git(repo, 'commit', '-qm', 'base'); + const sessions = ['a', 'b'].map((name, index) => { + const wt = path.join(dir, name); + git(repo, 'worktree', 'add', '-q', '-b', name, wt, 'main'); + const lines = original.map((line, i) => i === index * 39 ? `${line} // edit` : line); + fs.writeFileSync(path.join(wt, file), `${lines.join('\n')}\n`); + return { id: name, worktree: { path: wt, base: 'main' } }; + }); + const agents = sessionsToAgents(sessions); + assert.deepStrictEqual(agents[0].files, [{ weight: 1, path: file, lines: [[1, 1]] }]); + assert.deepStrictEqual(agents[1].files, [{ weight: 1, path: file, lines: [[40, 40]] }]); + const snapshot = buildProximitySnapshot(sessions, { repoRoot: repo, graph: { adjacency: {} } }); + assert.ok(!snapshot.advisories.some(advisory => advisory.level === 'resolution')); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +}); + test('line-range channel: same file but disjoint ranges ⇒ no resolution', () => { // Two agents in the same file, far-apart functions. workingSetFor provides ranges. const workingSetFor = s =>