Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix repo-sync safety gates

[._.]/ Adam Eivyc6067ab1d2db
diff --git a/server/services/getDefaultBranch.test.js b/server/services/getDefaultBranch.test.js
index 0677965f8b..9b549eab05 100644
--- a/server/services/getDefaultBranch.test.js
+++ b/server/services/getDefaultBranch.test.js
@@ -125,6 +125,24 @@ describe('getDefaultBranch', () => {
expect(result).toBe('develop');
});
+ it('returns null in strict mode instead of treating the current feature branch as default', async () => {
+ execGit.mockImplementation((args) => {
+ if (args[0] === 'symbolic-ref') {
+ return Promise.reject(new Error('not set'));
+ }
+ if (args[0] === 'branch') {
+ return Promise.resolve({ stdout: ' develop\n feature/x\n', stderr: '', exitCode: 0 });
+ }
+ if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) {
+ return Promise.resolve({ stdout: 'feature/x', stderr: '', exitCode: 0 });
+ }
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ });
+
+ const result = await getDefaultBranch('/fake/dir', { allowRemote: false, strict: true });
+ expect(result).toBeNull();
+ });
+
it('returns null when all detection methods fail', async () => {
execGit.mockImplementation((args) => {
if (args[0] === 'symbolic-ref') {
diff --git a/server/services/git.js b/server/services/git.js
index 9cadb6810e..7395076708 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -671,7 +671,7 @@ export async function suggestPRTitle(dir, baseBranch, headBranch, fallbackText)
return firstLine.trim().substring(0, 100) || 'CoS automated task';
}
-export async function getDefaultBranch(dir, { allowRemote = true } = {}) {
+export async function getDefaultBranch(dir, { allowRemote = true, strict = false } = {}) {
const symRef = await execGitSafe(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], dir);
if (symRef.stdout?.trim()) {
const branch = symRef.stdout.trim().replace(/^origin\//, '');
@@ -697,6 +697,11 @@ export async function getDefaultBranch(dir, { allowRemote = true } = {}) {
if (branches.includes('main')) return 'main';
if (branches.includes('master')) return 'master';
+ // Callers that are about to mutate a checkout need a known default branch;
+ // falling back to whichever feature branch happens to be checked out would
+ // make a remote-sync operation treat that branch as the canonical target.
+ if (strict) return null;
+
// Last resort: use the currently checked-out branch
const head = await execGitSafe(['rev-parse', '--abbrev-ref', 'HEAD'], dir);
if (head.stdout?.trim() && head.stdout.trim() !== 'HEAD') {
@@ -770,7 +775,7 @@ async function getLocalMergedBranchNames(dir, defaultBranch) {
* Get all local branches with tracking info
* @returns {Promise<Array<{name: string, current: boolean, tracking: string|null, ahead: number, behind: number, isDefault: boolean, merged: boolean, worktree: boolean}>>}
*/
-export async function getBranches(dir) {
+export async function getBranches(dir, { strict = false } = {}) {
// Get branches with verbose info (includes tracking)
const [result, { baseBranch }, worktreeBranches] = await Promise.all([
execGit(
@@ -782,6 +787,10 @@ export async function getBranches(dir) {
getWorktreeBranches(dir)
]);
+ if (strict && result.exitCode !== 0) {
+ throw new Error(result.stderr || `git branch -vv failed with exit code ${result.exitCode}`);
+ }
+
const defaultBranch = baseBranch || 'main';
const protectedSet = new Set(PROTECTED_BRANCHES);
protectedSet.add(defaultBranch);
@@ -1239,13 +1248,22 @@ async function clearSequencerState(dir, gitDirPath) {
* @param {string} dir - Repo root to check
* @returns {Promise<string|null>} - Agent id, or null
*/
-export async function findActiveAgentInWorkspace(dir) {
- const { getAgents } = await import('./cosAgentLifecycle.js').catch(() => ({ getAgents: null }));
- if (!getAgents) return null;
- const agents = await getAgents().catch(() => []);
+export async function findActiveAgentInWorkspace(dir, { includePaused = false, failClosed = false } = {}) {
+ const { getAgents } = await import('./cosAgentLifecycle.js').catch((err) => {
+ if (failClosed) throw err;
+ return { getAgents: null };
+ });
+ if (!getAgents) {
+ if (failClosed) throw new Error('could not load the CoS agent registry');
+ return null;
+ }
+ const agents = await getAgents().catch((err) => {
+ if (failClosed) throw err;
+ return [];
+ });
const target = resolve(dir);
const busy = agents.find(agent =>
- agent.status === 'running'
+ (agent.status === 'running' || (includePaused && agent.status === 'paused'))
&& agent.metadata?.workspacePath
&& resolve(agent.metadata.workspacePath) === target
);
diff --git a/server/services/repoSync.js b/server/services/repoSync.js
index 1235ba48d5..1d600d345e 100644
--- a/server/services/repoSync.js
+++ b/server/services/repoSync.js
@@ -143,6 +143,9 @@ const STASH_CLASSIFY_CONCURRENCY = 6;
*/
async function detectOperationInProgress(repoPath) {
const out = await execGitSafe(['rev-parse', '--git-dir'], repoPath, { ignoreExitCode: true });
+ if (out.exitCode !== 0) {
+ throw new Error(out.stderr || `could not inspect git operation state (exit code ${out.exitCode})`);
+ }
const raw = (out.stdout || '').trim();
if (!raw) return null;
const gitDir = isAbsolute(raw) ? raw : join(repoPath, raw);
@@ -294,7 +297,7 @@ async function collectRepoState(repoPath) {
const [operationInProgress, origin] = await Promise.all([
detectOperationInProgress(repoPath),
- getOriginInfo(repoPath).catch(() => null)
+ getOriginInfo(repoPath)
]);
const hasOrigin = Boolean(origin?.hasOrigin);
@@ -324,10 +327,10 @@ async function collectRepoState(repoPath) {
return fallback;
});
const [defaultBranch, headBranch, porcelain, branches, rawStashes, activeAgentId] = await Promise.all([
- getDefaultBranch(repoPath).then((b) => b || 'main', () => 'main'),
+ required('default branch', getDefaultBranch(repoPath, { strict: true }), null),
required('current branch', getBranch(repoPath), ''),
required('working-tree status', getStatusPorcelain(repoPath), ''),
- required('branch list', getBranches(repoPath), []),
+ required('branch list', getBranches(repoPath, { strict: true }), []),
// The planner refuses to act on a repo mid-operation, so classifying its
// stashes (2–3 git spawns each) buys nothing.
operationInProgress
@@ -342,15 +345,22 @@ async function collectRepoState(repoPath) {
}),
// A lookup failure here must NOT read as "nobody is working in this
// checkout" — that is the fact every mutating step below is gated on.
- required('active-agent lookup', findActiveAgentInWorkspace(repoPath), null)
+ required('active-agent lookup', findActiveAgentInWorkspace(repoPath, { includePaused: true, failClosed: true }), null)
]);
+ if (!defaultBranch) readFailures.push('default branch: no default branch could be determined');
+
const detached = headBranch === 'HEAD' || headBranch === '';
const currentBranch = detached ? null : headBranch;
const dirtyTracked = dirtyTrackedPaths(porcelain);
const remoteDefault = hasOrigin ? `origin/${defaultBranch}` : null;
- const remotes = await execGitSafe(['remote'], repoPath, { ignoreExitCode: true })
- .then((r) => (r.exitCode === 0 ? r.stdout.split('\n').map((l) => l.trim()).filter(Boolean) : []));
+ const remoteResult = await execGitSafe(['remote'], repoPath, { ignoreExitCode: true });
+ const remotes = remoteResult.exitCode === 0
+ ? remoteResult.stdout.split('\n').map((l) => l.trim()).filter(Boolean)
+ : [];
+ if (remoteResult.exitCode !== 0) {
+ readFailures.push(`remote list: ${remoteResult.stderr || `git exited with code ${remoteResult.exitCode}`}`);
+ }
// How the LOCAL default branch stands against origin's copy — the number that
// decides fast-forward vs "diverged, hand it to the agent". `getBranches`
@@ -358,16 +368,20 @@ async function collectRepoState(repoPath) {
// case needs no extra spawn; the `rev-list` fallback covers a default branch
// that tracks something other than `origin/<default>` (or nothing at all).
const defaultEntry = branches.find((b) => b.name === defaultBranch);
- const defaultDivergence = !remoteDefault
- ? null
- : defaultEntry?.tracking === remoteDefault
+ let defaultDivergence = null;
+ if (remoteDefault) {
+ defaultDivergence = defaultEntry?.tracking === remoteDefault
? { ahead: defaultEntry.ahead, behind: defaultEntry.behind }
: await countAheadBehind(repoPath, defaultBranch, remoteDefault);
+ if (!defaultDivergence) {
+ readFailures.push(`default branch comparison: could not compare ${defaultBranch} with ${remoteDefault}`);
+ }
+ }
// Compare stashes against origin's default when we have it (that is what the
// branch will be after the fast-forward below) and the local default
// otherwise, so an offline machine still gets a correct — just staler — answer.
- const stashTarget = remoteDefault && defaultDivergence ? remoteDefault : defaultBranch;
+ const stashTarget = remoteDefault && !fetchError ? remoteDefault : defaultBranch;
// `getBranches` derives ahead/behind from `%(upstream:track)`, which is EMPTY
// for a branch that was never pushed — so its `ahead` is 0 and the
@@ -377,8 +391,13 @@ async function collectRepoState(repoPath) {
const localOnly = branches.filter((b) => !b.tracking && b.name !== defaultBranch);
const localAheadByBranch = new Map(await mapWithConcurrency(localOnly, STASH_CLASSIFY_CONCURRENCY, async (b) => [
b.name,
- (await countAheadBehind(repoPath, b.name, defaultBranch))?.ahead ?? 0
+ (await countAheadBehind(repoPath, b.name, defaultBranch))?.ahead ?? null
]));
+ for (const branch of localOnly) {
+ if (localAheadByBranch.get(branch.name) === null) {
+ readFailures.push(`local branch comparison for ${branch.name}: could not compare with ${defaultBranch}`);
+ }
+ }
const branchesWithLocalAhead = branches.map((b) => (
localAheadByBranch.has(b.name) ? { ...b, localAhead: localAheadByBranch.get(b.name) } : b
));
@@ -405,6 +424,7 @@ async function collectRepoState(repoPath) {
return {
repoPath,
isRepo: true,
+ hasOrigin,
fetchError,
readFailures,
remotes,
@@ -478,6 +498,12 @@ export function planRepoSync(state, actions = {}) {
return { steps, escalations };
}
+ if (state.hasOrigin !== true) {
+ escalate(ESCALATION_KINDS.SCAN_FAILED,
+ 'no origin remote is configured — the repository cannot be synchronized automatically');
+ return { steps, escalations };
+ }
+
// Somebody's agent is working in this checkout right now. Pushing its branch,
// fast-forwarding under it, dropping its stashes, or reaping its worktrees all
// race live work — the switch-back gate below is NOT enough on its own.
@@ -528,6 +554,16 @@ export function planRepoSync(state, actions = {}) {
continue;
}
if (branch.ahead > 0 && actionOn(actions, 'syncPush')) {
+ // A branch checked out in another worktree may belong to a live agent or
+ // a human. Publishing it from the source checkout would race that work
+ // and could expose an unfinished branch, so leave it for judgment. The
+ // branch-reconcile pass has the worktree ownership gates needed to decide
+ // whether that tree is safe to clean up later.
+ if (branch.worktree) {
+ escalate(ESCALATION_KINDS.IN_FLIGHT_BRANCH,
+ `${branch.name} is checked out in another worktree — left untouched`);
+ continue;
+ }
// The ahead count was measured against THIS branch's configured upstream,
// so the push has to go there. `git push origin <local name>` would publish
// to a different ref whenever the upstream is on another remote or carries
@@ -726,7 +762,13 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
if (state.scanError) {
return { ...base, escalations: [{ kind: ESCALATION_KINDS.SCAN_FAILED, detail: state.scanError }] };
}
- if (!state.isRepo) return { ...base, notARepo: true };
+ if (!state.isRepo) {
+ return {
+ ...base,
+ notARepo: true,
+ escalations: [{ kind: ESCALATION_KINDS.SCAN_FAILED, detail: 'managed app path is not a git repository' }]
+ };
+ }
const { steps, escalations } = planRepoSync(state, actions);
const performed = [];
@@ -751,7 +793,9 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
// Gated on the same facts the planner refuses to act without: reconcile
// DELETES branches and worktrees, so an incomplete snapshot, a live agent, or
// an unfetched origin must keep it out exactly as they keep out the steps above.
- const reconcileSafe = !state.operationInProgress
+ const reconcileSafe = state.hasOrigin === true
+ && Boolean(state.defaultBranch && state.remoteDefault)
+ && !state.operationInProgress
&& !state.readFailures?.length
&& !state.activeAgentId
&& !state.fetchError;
diff --git a/server/services/repoSync.test.js b/server/services/repoSync.test.js
index 8cc886300c..2d78fc7d29 100644
--- a/server/services/repoSync.test.js
+++ b/server/services/repoSync.test.js
@@ -58,6 +58,7 @@ const {
const cleanState = (over = {}) => ({
repoPath: '/tmp/example-repo',
isRepo: true,
+ hasOrigin: true,
fetchError: null,
defaultBranch: 'main',
remoteDefault: 'origin/main',
@@ -152,6 +153,13 @@ describe('planRepoSync — refuses to act on an unsettled repo', () => {
expect(kinds(escalations)).toContain(ESCALATION_KINDS.SCAN_FAILED);
});
+ it('refuses to mutate a repository with no origin remote', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ hasOrigin: false, remoteDefault: null }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.SCAN_FAILED]);
+ expect(escalations[0].detail).toContain('no origin remote');
+ });
+
it('plans nothing when a snapshot read failed', () => {
// An unreadable status/branch/stash read defaults to the value that LOOKS
// safe (clean tree, no branches, no stashes) — exactly the values that unlock
@@ -190,6 +198,15 @@ describe('planRepoSync — publishing local commits', () => {
expect(steps).toEqual([{ kind: 'push', branch: 'feature/x', ahead: 2, remote: 'origin', remoteRef: 'feature/x' }]);
});
+ it('does not push a branch checked out in another worktree', () => {
+ const { steps, escalations } = planRepoSync(cleanState({
+ branches: [branch('feature/x', { ahead: 2, worktree: true })]
+ }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.IN_FLIGHT_BRANCH]);
+ expect(escalations[0].detail).toContain('another worktree');
+ });
+
it('never pushes a branch that has diverged — it escalates instead', () => {
const { steps, escalations } = planRepoSync(cleanState({ branches: [branch('feature/x', { ahead: 2, behind: 3 })] }));
expect(steps).toEqual([]);
@@ -619,7 +636,7 @@ describe('syncRepo — the argv it issues is the non-destructive form', () => {
gitMocks.isRepo.mockResolvedValueOnce(false);
const result = await syncRepo({ repoPath: process.cwd(), name: 'Not a repo' });
expect(result.notARepo).toBe(true);
- expect(result.escalations).toEqual([]);
+ expect(result.escalations[0].kind).toBe(ESCALATION_KINDS.SCAN_FAILED);
});
});