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: harden interrupted clone recovery (#5463)
[._.]/ Adam Eivy010093655ed0
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 75184bc8d0..ea4b4860ef 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -443,6 +443,9 @@ export const linkRecordSchema = z.object({localPath: z.string().max(500).optional(),cloneStatus: z.enum(['pending', 'cloning', 'cloned', 'failed', 'none']).default('none'),cloneError: z.string().max(500).optional(),+ // The instance currently responsible for an in-flight clone. This differs+ // from immutable originInstanceId when a peer retries a shared link.+ cloneInstanceId: z.string().optional(),malwareScan: z.object({reportId: z.string().uuid(),taskId: z.string().optional(),diff --git a/server/services/brain.js b/server/services/brain.jsindex 9c614b40f0..b1a5f2c129 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -840,16 +840,21 @@ export async function recoverStuckClassifications() {/*** Recover repository clones interrupted by a previous server shutdown.- * A clone process cannot survive the PortOS process that started it, so every- * persisted `cloning` state observed during boot is orphaned and retryable.+ * Clone work is published only after git exits successfully; an orphaned child+ * can keep writing its private staging directory without racing a retry.*/export async function recoverInterruptedRepoClones() {+ const instanceId = await getInstanceId();const links = await storage.getLinks({ cloneStatus: 'cloning' });let recovered = 0;for (const link of links) {// Keep the state guard even though storage applies the filter so a future// storage implementation cannot broaden this boot-time mutation by accident.if (link.cloneStatus !== 'cloning') continue;+ // New records name the instance that started this attempt. For older+ // records, originInstanceId is the safest compatibility fallback.+ const cloneOwner = link.cloneInstanceId ?? link.originInstanceId;+ if (cloneOwner && cloneOwner !== instanceId) continue;await storage.updateLink(link.id, {cloneStatus: 'failed',cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.'@@ -984,7 +989,8 @@ function hostnameFromUrl(url) {* queue an agent against a path that doesn't exist.*/export async function cloneRepoInBackground(linkId, url) {- await storage.updateLink(linkId, { cloneStatus: 'cloning' });+ const cloneInstanceId = await getInstanceId();+ await storage.updateLink(linkId, { cloneStatus: 'cloning', cloneInstanceId });githubCloner.cloneRepo(url).then(async (result) => {diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 99f5b970d3..5a663ca192 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -310,7 +310,10 @@ describe('brain service', () => {isGitHubRepo: true,cloneStatus: 'pending'}));- expect(storage.updateLink).toHaveBeenCalledWith('link-001', { cloneStatus: 'cloning' });+ expect(storage.updateLink).toHaveBeenCalledWith('link-001', {+ cloneStatus: 'cloning',+ cloneInstanceId: 'local-instance'+ });});it('files a URL to Links even when the creative flag is set', async () => {@@ -974,7 +977,8 @@ describe('brain service', () => {it('marks only interrupted clones as failed so they can be retried', async () => {storage.getLinks.mockResolvedValue([{ id: 'pending', cloneStatus: 'pending' },- { id: 'cloning', cloneStatus: 'cloning' },+ { id: 'cloning', cloneStatus: 'cloning', cloneInstanceId: 'local-instance' },+ { id: 'peer-cloning', cloneStatus: 'cloning', cloneInstanceId: 'peer-x' },{ id: 'cloned', cloneStatus: 'cloned' },{ id: 'failed', cloneStatus: 'failed' },{ id: 'none', cloneStatus: 'none' },@@ -989,6 +993,7 @@ describe('brain service', () => {cloneStatus: 'failed',cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.',});+ expect(storage.updateLink).not.toHaveBeenCalledWith('peer-cloning', expect.anything());});});diff --git a/server/services/githubCloner.js b/server/services/githubCloner.jsindex e58df834ad..c6e836e720 100644--- a/server/services/githubCloner.js+++ b/server/services/githubCloner.js@@ -7,6 +7,7 @@import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';+import { mkdtemp, rename, rm } from 'fs/promises';import { join } from 'path';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { parseGitHubUrl, isGitHubRepoUrl } from '../lib/githubRepoUrl.js';@@ -69,6 +70,12 @@ export async function cloneRepo(url, options = {}) {await ensureDir(ownerDir);}+ // Clone into attempt-specific staging, then publish it only after git exits.+ // An abruptly orphaned git child can keep writing its private directory, but+ // a retry gets a different directory and cannot race the live checkout.+ const stagingRoot = await mkdtemp(join(ownerDir, `.${repo}-cloning-`));+ const stagingPath = join(stagingRoot, repo);+// Build clone command with shallow clone for space efficiencyconst httpsUrl = `https://github.com/${owner}/${repo}.git`;const args = [@@ -76,12 +83,12 @@ export async function cloneRepo(url, options = {}) {'--depth', '1','--single-branch',httpsUrl,- localPath+ stagingPath];console.log(`📥 Cloning ${owner}/${repo}...`);- return new Promise((resolve, reject) => {+ const clone = new Promise((resolve, reject) => {const child = spawn('git', args, {env: process.env,shell: false@@ -93,15 +100,15 @@ export async function cloneRepo(url, options = {}) {stderr += data.toString();});+ const timeout = setTimeout(() => {+ child.kill();+ reject(new Error('Clone timed out after 5 minutes'));+ }, 300000);+child.on('close', (code) => {+ clearTimeout(timeout);if (code === 0) {- console.log(`✅ Cloned ${owner}/${repo} to ${localPath}`);- resolve({- localPath,- owner,- repo,- alreadyCloned: false- });+ resolve();} else {console.error(`❌ Failed to clone ${owner}/${repo}: ${stderr}`);reject(new Error(`Git clone failed: ${stderr || `exit code ${code}`}`));@@ -109,15 +116,29 @@ export async function cloneRepo(url, options = {}) {});child.on('error', (err) => {+ clearTimeout(timeout);console.error(`❌ Git clone error: ${err.message}`);reject(err);});+ });- // Timeout after 5 minutes- setTimeout(() => {- child.kill();- reject(new Error('Clone timed out after 5 minutes'));- }, 300000);+ const cleanupStaging = () => rm(stagingRoot, { recursive: true, force: true })+ .catch(err => console.error(`❌ Failed to clean clone staging directory: ${err.message}`));++ return clone.then(async () => {+ // A concurrent attempt may have won while this one was cloning. Keep the+ // completed checkout and discard only this attempt's private staging dir.+ if (existsSync(join(localPath, '.git'))) {+ await cleanupStaging();+ return { localPath, owner, repo, alreadyCloned: true };+ }+ await rename(stagingPath, localPath);+ await cleanupStaging();+ console.log(`✅ Cloned ${owner}/${repo} to ${localPath}`);+ return { localPath, owner, repo, alreadyCloned: false };+ }).catch(async (err) => {+ await cleanupStaging();+ throw err;});}diff --git a/server/services/githubCloner.test.js b/server/services/githubCloner.test.jsnew file mode 100644index 0000000000..7979eaf478--- /dev/null+++ b/server/services/githubCloner.test.js@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import EventEmitter from 'node:events';++vi.mock('fs', () => ({ existsSync: vi.fn() }));+vi.mock('fs/promises', () => ({+ mkdtemp: vi.fn(),+ rename: vi.fn(),+ rm: vi.fn(),+}));+vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));+vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn(),+ PATHS: { repos: '/repos' },+}));++import { existsSync } from 'fs';+import { mkdtemp, rename, rm } from 'fs/promises';+import { spawn } from '../lib/childProcess.js';+import { cloneRepo } from './githubCloner.js';++const createChild = () => {+ const child = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++describe('cloneRepo', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ existsSync.mockImplementation(path => !String(path).endsWith('.git'));+ mkdtemp.mockResolvedValue('/repos/acme/.widgets-cloning-attempt');+ rename.mockResolvedValue();+ rm.mockResolvedValue();+ });++ it('publishes a clone only after git completes in attempt-specific staging', async () => {+ const child = createChild();+ spawn.mockReturnValue(child);++ const resultPromise = cloneRepo('https://github.com/acme/widgets');+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());++ expect(spawn).toHaveBeenCalledWith('git', [+ 'clone', '--depth', '1', '--single-branch',+ 'https://github.com/acme/widgets.git',+ '/repos/acme/.widgets-cloning-attempt/widgets'+ ], expect.objectContaining({ shell: false }));+ expect(rename).not.toHaveBeenCalled();++ child.emit('close', 0);++ await expect(resultPromise).resolves.toMatchObject({+ localPath: '/repos/acme/widgets',+ alreadyCloned: false+ });+ expect(rename).toHaveBeenCalledWith(+ '/repos/acme/.widgets-cloning-attempt/widgets',+ '/repos/acme/widgets'+ );+ expect(rm).toHaveBeenCalledWith(+ '/repos/acme/.widgets-cloning-attempt',+ { recursive: true, force: true }+ );+ });+});