Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/design/agent-proximity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
38 changes: 31 additions & 7 deletions scripts/lib/control-pane/proximity.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ function parseDiffRanges(diff) {
const byFile = new Map();
let current = null;
for (const line of String(diff || '').split('\n')) {
if (line.startsWith('diff --git ')) {
current = null;
continue;
}
const fileMatch = line.match(/^\+\+\+ b\/(.+)$/);
if (fileMatch) {
const name = fileMatch[1].trim();
const name = fileMatch[1].replace(/\t$/, '');
current = name === '/dev/null' ? null : name;
if (current && !byFile.has(current)) byFile.set(current, []);
continue;
Expand All @@ -45,15 +49,29 @@ 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,
stdio: ['ignore', 'pipe', 'ignore']
});
}

function runGitDiff(worktreePath, base, extraArgs) {
const mergeBase = runGit(worktreePath, ['merge-base', '--', base, 'HEAD']).trim();
return runGit(worktreePath, ['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
Expand All @@ -65,6 +83,15 @@ function defaultWorkingSetFor(session) {
const base = wt.base || 'HEAD';
try {
const ranges = parseDiffRanges(runGitDiff(wt.path, base, ['--unified=0']));
Comment thread
xiehuanyi marked this conversation as resolved.
Resolved
// 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.
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for (const file of untrackedFiles(wt.path)) ranges.set(file, []);
Comment thread
xiehuanyi marked this conversation as resolved.
Resolved
Comment thread
xiehuanyi marked this conversation as resolved.
Resolved
return [...ranges.entries()].map(([path, lines]) => (lines.length > 0 ? { path, lines } : { path }));
} catch {
return [];
Expand All @@ -79,10 +106,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 [];
}
Expand Down
144 changes: 144 additions & 0 deletions tests/lib/control-pane-proximity.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '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), ['README']);
}
} 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']);
Expand Down Expand Up @@ -97,6 +229,18 @@ 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('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 =>
Expand Down