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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: avoid false GitHub backoff and branch errors during shutdown (#6992)
[._.]/ Adam Eivya38a476e3e18
diff --git a/server/lib/execGit.js b/server/lib/execGit.jsindex 962886fa5f..5216ade21f 100644--- a/server/lib/execGit.js+++ b/server/lib/execGit.js@@ -14,7 +14,7 @@ import { spawn } from './childProcess.js';* @param {number} [options.maxBuffer] - Max output buffer size in bytes (default 10 MB)* @param {number} [options.timeout] - Timeout in ms (default 30s)* @param {boolean} [options.ignoreExitCode] - Resolve instead of reject on non-zero exit- * @returns {Promise<{stdout: string, stderr: string, exitCode: number}>}+ * @returns {Promise<{stdout: string, stderr: string, exitCode: number|null, signal?: string, terminated?: boolean}>}*/export function execGit(args, cwd, options = {}) {return new Promise((resolve, reject) => {@@ -69,10 +69,18 @@ export function execGit(args, cwd, options = {}) {guardOverflow();});- child.on('close', (code) => {+ child.on('close', (code, signal) => {clearTimeout(timer);if (killed) return;- if (code !== 0 && !options.ignoreExitCode) {+ if (code === null && signal) {+ if (options.ignoreExitCode) {+ resolve({ stdout, stderr, exitCode: null, signal, terminated: true });+ } else {+ reject(Object.assign(new Error(`git command cancelled by ${signal}`), {+ name: 'AbortError', signal, terminated: true+ }));+ }+ } else if (code !== 0 && !options.ignoreExitCode) {reject(new Error(stderr || `git exited with code ${code}`));} else {resolve({ stdout, stderr, exitCode: code });diff --git a/server/lib/execGit.test.js b/server/lib/execGit.test.jsindex 5e2b75a0ab..3db126650e 100644--- a/server/lib/execGit.test.js+++ b/server/lib/execGit.test.js@@ -74,6 +74,28 @@ describe('execGit', () => {});});+ it('preserves signal termination and partial output when ignoring exit codes', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['ls-remote'], '/repo', { ignoreExitCode: true });+ child.stdout.emit('data', 'partial');+ child.emit('close', null, 'SIGTERM');+ await expect(promise).resolves.toEqual({+ stdout: 'partial', stderr: '', exitCode: null, signal: 'SIGTERM', terminated: true+ });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('rejects a signal exit with cancellation metadata', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['fetch'], '/repo');+ child.emit('close', null, 'SIGTERM');+ await expect(promise).rejects.toMatchObject({+ name: 'AbortError', message: 'git command cancelled by SIGTERM', signal: 'SIGTERM', terminated: true+ });+ });+it('rejects with a timeout error and kills the child after the timeout', async () => {const child = makeChild();spawn.mockReturnValue(child);diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex a2ed0381a6..36e41385e7 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -23,6 +23,7 @@*/import { stat } from 'node:fs/promises';+import { isHostShuttingDown } from '../lib/hostShutdown.js';import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';import { execGit } from '../lib/execGit.js';import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';@@ -248,7 +249,9 @@ async function getOpenPrsByHead(repoPath, providedOrigin) {'--limit', String(PR_LIST_LIMIT),'--json', 'number,headRefName,mergeable,isDraft,url'], undefined, { backoffKey: repoSpec }).catch((err) => {- console.error(`❌ branch-reconcile: gh pr list failed for ${repoSpec}: ${err.message}`);+ if (!isHostShuttingDown() && err.name !== 'AbortError') {+ console.error(`❌ branch-reconcile: gh pr list failed for ${repoSpec}: ${err.message}`);+ }return null;});if (raw === null) return null;@@ -557,13 +560,14 @@ export function parseRemoteHeads(stdout) {*/export async function listRemoteHeads(repoPath) {const res = await execGit(['ls-remote', '--heads', RECONCILED_REMOTE], repoPath, { ignoreExitCode: true })- .catch((err) => ({ error: err.message }));+ .catch((err) => ({ error: err.message, signal: err.signal }));if (!res || res.exitCode !== 0) {+ if (isHostShuttingDown() || res?.signal === 'SIGTERM') return null;// One log line serves every caller across every managed app, so it has to// name the repo that went unread and git's own reason — without both, a// network blip, an unauthenticated remote and a repo with no `origin` at// all are one indistinguishable line and the operator has nothing to act on.- const why = (res?.error || res?.stderr || '').trim().split('\n')[0] || `exit ${res?.exitCode}`;+ const why = (res?.error || res?.stderr || '').trim().split('\n')[0] || (res?.signal ? `signal ${res.signal}` : `exit ${res?.exitCode}`);console.error(`❌ branch-reconcile: git ls-remote ${RECONCILED_REMOTE} failed in ${repoPath} (${why}) — remote branch state unknown this cycle`);return null;}diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex ee0613830d..9ab8797015 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -8,7 +8,7 @@* inFlight / wip correctly).*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';vi.mock('./git.js', () => ({getBranches: vi.fn(),@@ -94,12 +94,13 @@ import {limitBranchesForAgent,branchPriorityRank, prioritizeBranches, worktreeProtectionExpiresAt, describeIdleReconcilePark,SHIPPED_CLAIM_IDLE_MS, STALE_CLAIM_IDLE_MS,- upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes+ listRemoteHeads, upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes} from './branchReconcile.js';import * as git from './git.js';import * as wt from './worktreeManager.js';import { execGit } from '../lib/execGit.js';import { execGh } from './github.js';+import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';import { getOriginInfo } from '../lib/gitRemote.js';beforeEach(() => {@@ -2100,3 +2101,42 @@ describe('describeIdleReconcilePark', () => {expect(out.notLaterThan).toBeNull();});});++describe('shutdown interruption (#6992)', () => {+ afterEach(() => {+ resetHostShutdownFlagForTests();+ vi.restoreAllMocks();+ });++ it('keeps PR state unknown without reporting a cancellation as a forge error', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ git.getBranches.mockResolvedValue([+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }+ ]);+ wt.listWorktrees.mockResolvedValue([]);+ execGh.mockRejectedValue(Object.assign(new Error('gh command cancelled by SIGTERM'), { name: 'AbortError', signal: 'SIGTERM' }));+ git.hasBranchMergeEvidence.mockResolvedValue(false);+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });+ expect(inputs[0].prStateUnavailable).toBe(true);+ expect(classifyBranches(inputs)[0].state).toBe('WIP');+ expect(error).not.toHaveBeenCalled();+ });++ it('never treats interrupted partial remote output as an answered branch list', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ execGit.mockResolvedValue({ stdout: 'abc\trefs/heads/main', stderr: '', exitCode: null, signal: 'SIGTERM', terminated: true });+ await expect(listRemoteHeads('/repo')).resolves.toBeNull();+ expect(error).not.toHaveBeenCalled();+ markHostShuttingDown();+ execGit.mockRejectedValue(new Error('child gone'));+ await expect(listRemoteHeads('/repo')).resolves.toBeNull();+ expect(error).not.toHaveBeenCalled();+ });++ it('still reports unexpected signals outside shutdown with their signal name', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ execGit.mockResolvedValue({ stdout: '', stderr: '', exitCode: null, signal: 'SIGSEGV', terminated: true });+ await expect(listRemoteHeads('/repo')).resolves.toBeNull();+ expect(error).toHaveBeenCalledWith(expect.stringContaining('signal SIGSEGV'));+ });+});diff --git a/server/services/github.js b/server/services/github.jsindex e469177785..edfa0379e7 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -1,4 +1,5 @@import { spawn } from '../lib/childProcess.js';+import { isHostShuttingDown } from '../lib/hostShutdown.js';import { join } from 'path';import { atomicWrite, readJSONFile, PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';@@ -146,7 +147,7 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nulconst settle = (ok) => {if (settled) return;settled = true;- if (backoffKey !== null) recordGhCallOutcome(backoffKey, ok, backoffMaxMs);+ if (backoffKey !== null && ok !== null) recordGhCallOutcome(backoffKey, ok, backoffMaxMs);};const timer = setTimeout(() => {timedOut = true;@@ -158,12 +159,18 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul}, timeoutMs);child.stdout.on('data', (d) => { stdout += d.toString(); });child.stderr.on('data', (d) => { stderr += d.toString(); });- child.on('close', (code) => {- if (timedOut) return;+ child.on('close', (code, signal) => {+ if (timedOut || settled) return;clearTimeout(timer);- if (code !== 0) {+ if (signal === 'SIGTERM' || isHostShuttingDown()) {+ // Cancellation says nothing about forge health; preserve prior backoff.+ settle(null);+ reject(Object.assign(new Error(signal ? `gh command cancelled by ${signal}` : 'gh command cancelled during host shutdown'), {+ name: 'AbortError', signal, terminated: Boolean(signal)+ }));+ } else if (code !== 0) {settle(false);- const error = new Error(stderr.trim() || `gh exited with code ${code}`);+ const error = new Error(stderr.trim() || `gh exited with ${signal ? `signal ${signal}` : `code ${code}`}`);error.ghExitCode = code;error.ghStderr = stderr.trim();reject(error);diff --git a/server/services/github.test.js b/server/services/github.test.jsindex dcc5f4cd5b..e58601daff 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -32,6 +32,7 @@ vi.mock('./settings.js', () => {});import { spawn } from '../lib/childProcess.js';+import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';import {__resetGitHubDataCache,__resetGhCallBackoff,@@ -205,6 +206,37 @@ describe('execGh backoffKey', () => {expect(spawn).toHaveBeenCalledTimes(1);});+ it.each([+ [null, 'SIGTERM', false],+ [null, 'SIGKILL', true],+ [1, null, true]+ ])('does not back off cancellation (code %s, signal %s, shutdown %s)', async (code, signal, shutdown) => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const pending = execGh(['pr', 'list'], 5000, { backoffKey: 'cancelled-repo' });+ if (shutdown) markHostShuttingDown();+ child.emit('close', code, signal);+ resetHostShutdownFlagForTests();+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });+ expect(vi.getTimerCount()).toBe(0);++ const retryChild = makeChild();+ spawn.mockReturnValue(retryChild);+ const retry = execGh(['pr', 'list'], 5000, { backoffKey: 'cancelled-repo' });+ retryChild.emit('close', 0);+ await expect(retry).resolves.toBe('');+ expect(spawn).toHaveBeenCalledTimes(2);+ });++ it('keeps unexpected signal failures visible and subject to backoff', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const pending = execGh(['pr', 'list'], 5000, { backoffKey: 'crashed-repo' });+ child.emit('close', null, 'SIGSEGV');+ await expect(pending).rejects.toThrow('signal SIGSEGV');+ await expect(execGh(['pr', 'list'], 5000, { backoffKey: 'crashed-repo' })).rejects.toThrow('backing off');+ });+it('spawns again once the backoff window elapses', async () => {const failing = makeChild();spawn.mockReturnValueOnce(failing);