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: complete clone recovery lifecycle (#5463)
[._.]/ Adam Eivy674f7110beaa
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex ea4b4860ef..d8dac4df3a 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -445,7 +445,10 @@ export const linkRecordSchema = z.object({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(),+ cloneInstanceId: z.string().nullable().optional(),+ // True only when boot recovery observed an interrupted attempt. Retry uses+ // this to replace a legacy direct-to-destination partial checkout safely.+ cloneInterrupted: z.boolean().optional().default(false),malwareScan: z.object({reportId: z.string().uuid(),taskId: z.string().optional(),diff --git a/server/services/brain.js b/server/services/brain.jsindex b1a5f2c129..f79b78f3bc 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -844,6 +844,8 @@ export async function recoverStuckClassifications() {* can keep writing its private staging directory without racing a retry.*/export async function recoverInterruptedRepoClones() {+ await githubCloner.reapStaleCloneStaging()+ .catch(err => console.error(`❌ Clone staging recovery failed: ${err.message}`));const instanceId = await getInstanceId();const links = await storage.getLinks({ cloneStatus: 'cloning' });let recovered = 0;@@ -853,11 +855,19 @@ export async function recoverInterruptedRepoClones() {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;+ if (link.cloneInstanceId && link.cloneInstanceId !== instanceId) continue;+ // Old peers did not stamp cloneInstanceId. Preserve a recent peer-origin+ // attempt, but recover it once it is older than the client stall window so+ // a mixed-version crash cannot strand the link forever.+ if (!link.cloneInstanceId && link.originInstanceId && link.originInstanceId !== instanceId) {+ const updatedAt = Date.parse(link.updatedAt);+ if (!Number.isFinite(updatedAt) || Date.now() - updatedAt < 10 * 60 * 1000) continue;+ }await storage.updateLink(link.id, {cloneStatus: 'failed',- cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.'+ cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.',+ cloneInstanceId: null,+ cloneInterrupted: true});recovered++;}@@ -989,15 +999,22 @@ function hostnameFromUrl(url) {* queue an agent against a path that doesn't exist.*/export async function cloneRepoInBackground(linkId, url) {+ const previous = await storage.getLinkById(linkId);const cloneInstanceId = await getInstanceId();- await storage.updateLink(linkId, { cloneStatus: 'cloning', cloneInstanceId });+ await storage.updateLink(linkId, {+ cloneStatus: 'cloning',+ cloneInstanceId,+ cloneInterrupted: false+ });- githubCloner.cloneRepo(url)+ githubCloner.cloneRepo(url, { replaceIncomplete: previous?.cloneInterrupted === true }).then(async (result) => {const link = await storage.updateLink(linkId, {localPath: result.localPath,cloneStatus: 'cloned',- cloneError: null+ cloneError: null,+ cloneInstanceId: null,+ cloneInterrupted: false});console.log(`✅ Background clone complete: ${linkId}`);// `link` is null when the user deleted the bookmark mid-clone — nothing@@ -1019,7 +1036,9 @@ export async function cloneRepoInBackground(linkId, url) {.catch(async (err) => {await storage.updateLink(linkId, {cloneStatus: 'failed',- cloneError: err.message+ cloneError: err.message,+ cloneInstanceId: null,+ cloneInterrupted: false});console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);});diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 5a663ca192..7d6bb92cb7 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -68,7 +68,8 @@ vi.mock('./brainStorage.js', () => {// kick off a background clone; stub it so no test ever shells out to git.vi.mock('./githubCloner.js', () => ({parseGitHubUrl: vi.fn(() => null),- cloneRepo: vi.fn()+ cloneRepo: vi.fn(),+ reapStaleCloneStaging: vi.fn(() => Promise.resolve(0))}));// Mock chatgptImport — brain.js's deleteMemoryEntry wrapper delegates the@@ -312,7 +313,8 @@ describe('brain service', () => {}));expect(storage.updateLink).toHaveBeenCalledWith('link-001', {cloneStatus: 'cloning',- cloneInstanceId: 'local-instance'+ cloneInstanceId: 'local-instance',+ cloneInterrupted: false});});@@ -979,6 +981,9 @@ describe('brain service', () => {{ id: 'pending', cloneStatus: 'pending' },{ id: 'cloning', cloneStatus: 'cloning', cloneInstanceId: 'local-instance' },{ id: 'peer-cloning', cloneStatus: 'cloning', cloneInstanceId: 'peer-x' },+ { id: 'old-peer-recent', cloneStatus: 'cloning', originInstanceId: 'peer-x', updatedAt: new Date().toISOString() },+ { id: 'old-peer-stale', cloneStatus: 'cloning', originInstanceId: 'peer-x', updatedAt: '2020-01-01T00:00:00.000Z' },+ { id: 'legacy-local', cloneStatus: 'cloning' },{ id: 'cloned', cloneStatus: 'cloned' },{ id: 'failed', cloneStatus: 'failed' },{ id: 'none', cloneStatus: 'none' },@@ -988,12 +993,23 @@ describe('brain service', () => {await recoverInterruptedRepoClones();expect(storage.getLinks).toHaveBeenCalledWith({ cloneStatus: 'cloning' });- expect(storage.updateLink).toHaveBeenCalledTimes(1);+ expect(storage.updateLink).toHaveBeenCalledTimes(3);expect(storage.updateLink).toHaveBeenCalledWith('cloning', {cloneStatus: 'failed',cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.',+ cloneInstanceId: null,+ cloneInterrupted: true,});expect(storage.updateLink).not.toHaveBeenCalledWith('peer-cloning', expect.anything());+ expect(storage.updateLink).not.toHaveBeenCalledWith('old-peer-recent', expect.anything());+ expect(storage.updateLink).toHaveBeenCalledWith('old-peer-stale', expect.objectContaining({+ cloneStatus: 'failed',+ cloneInstanceId: null,+ }));+ expect(storage.updateLink).toHaveBeenCalledWith('legacy-local', expect.objectContaining({+ cloneStatus: 'failed',+ cloneInstanceId: null,+ }));});});diff --git a/server/services/githubCloner.js b/server/services/githubCloner.jsindex c6e836e720..1579804d33 100644--- a/server/services/githubCloner.js+++ b/server/services/githubCloner.js@@ -7,13 +7,16 @@import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';-import { mkdtemp, rename, rm } from 'fs/promises';+import { mkdtemp, readdir, rename, rm } from 'fs/promises';import { join } from 'path';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { parseGitHubUrl, isGitHubRepoUrl } from '../lib/githubRepoUrl.js';// Default directory for cloned repos (can be configured in settings)const DEFAULT_CLONE_DIR = PATHS.repos;+const CLONE_STAGING_PREFIX = '.portos-clone-';+const CLONE_STAGING_MAX_AGE_MS = 10 * 60 * 1000;+const CLONE_STAGING_RE = /^\.portos-clone-(\d{13})-[A-Za-z0-9]+$/;// The owner/repo parse rule lives in lib/ so the client can mirror it — the// Brain capture boxes have to predict "this URL will be cloned" before submit.@@ -53,6 +56,13 @@ export async function cloneRepo(url, options = {}) {const cloneDir = await ensureCloneDir(options.cloneDir);const localPath = join(cloneDir, owner, repo);+ // Boot recovery marks only a known interrupted attempt. Old PortOS versions+ // cloned straight into localPath, so their partial checkout must be replaced+ // before the normal already-cloned compatibility check can trust `.git`.+ if (options.replaceIncomplete === true) {+ await rm(localPath, { recursive: true, force: true });+ }+// Check if already clonedif (existsSync(join(localPath, '.git'))) {console.log(`📦 Repo already cloned: ${owner}/${repo}`);@@ -73,7 +83,7 @@ export async function cloneRepo(url, options = {}) {// 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 stagingRoot = await mkdtemp(join(ownerDir, `${CLONE_STAGING_PREFIX}${Date.now()}-`));const stagingPath = join(stagingRoot, repo);// Build clone command with shallow clone for space efficiency@@ -142,6 +152,31 @@ export async function cloneRepo(url, options = {}) {});}+/**+ * Remove only PortOS-owned clone staging directories older than twice the git+ * timeout. A freshly orphaned child may still be writing; the age gate leaves+ * it alone while bounding disk retained across repeated interrupted attempts.+ */+export async function reapStaleCloneStaging({ cloneDir = DEFAULT_CLONE_DIR, now = Date.now() } = {}) {+ const owners = await readdir(cloneDir, { withFileTypes: true })+ .catch(err => err.code === 'ENOENT' ? [] : Promise.reject(err));+ let reaped = 0;+ for (const owner of owners) {+ if (!owner.isDirectory()) continue;+ const ownerDir = join(cloneDir, owner.name);+ const entries = await readdir(ownerDir, { withFileTypes: true });+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const match = entry.name.match(CLONE_STAGING_RE);+ if (!match || now - Number(match[1]) < CLONE_STAGING_MAX_AGE_MS) continue;+ await rm(join(ownerDir, entry.name), { recursive: true, force: true });+ reaped++;+ }+ }+ if (reaped > 0) console.log(`🧹 Reaped ${reaped} stale repository clone staging director${reaped === 1 ? 'y' : 'ies'}`);+ return reaped;+}+/*** Pull latest changes for an existing repo*/diff --git a/server/services/githubCloner.test.js b/server/services/githubCloner.test.jsindex 7979eaf478..cfc736d138 100644--- a/server/services/githubCloner.test.js+++ b/server/services/githubCloner.test.js@@ -4,6 +4,7 @@ import EventEmitter from 'node:events';vi.mock('fs', () => ({ existsSync: vi.fn() }));vi.mock('fs/promises', () => ({mkdtemp: vi.fn(),+ readdir: vi.fn(),rename: vi.fn(),rm: vi.fn(),}));@@ -14,9 +15,9 @@ vi.mock('../lib/fileUtils.js', () => ({}));import { existsSync } from 'fs';-import { mkdtemp, rename, rm } from 'fs/promises';+import { mkdtemp, readdir, rename, rm } from 'fs/promises';import { spawn } from '../lib/childProcess.js';-import { cloneRepo } from './githubCloner.js';+import { cloneRepo, reapStaleCloneStaging } from './githubCloner.js';const createChild = () => {const child = new EventEmitter();@@ -30,6 +31,7 @@ describe('cloneRepo', () => {vi.clearAllMocks();existsSync.mockImplementation(path => !String(path).endsWith('.git'));mkdtemp.mockResolvedValue('/repos/acme/.widgets-cloning-attempt');+ readdir.mockResolvedValue([]);rename.mockResolvedValue();rm.mockResolvedValue();});@@ -63,4 +65,38 @@ describe('cloneRepo', () => {{ recursive: true, force: true });});++ it('removes a legacy partial destination only for a recovered attempt', async () => {+ const child = createChild();+ spawn.mockReturnValue(child);++ const resultPromise = cloneRepo('https://github.com/acme/widgets', { replaceIncomplete: true });+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());++ expect(rm).toHaveBeenCalledWith('/repos/acme/widgets', { recursive: true, force: true });+ child.emit('close', 0);+ await resultPromise;+ });++ it('reaps only expired PortOS clone staging directories', async () => {+ const directory = name => ({ name, isDirectory: () => true });+ readdir+ .mockResolvedValueOnce([directory('acme')])+ .mockResolvedValueOnce([+ directory('.portos-clone-1000000000000-old123'),+ directory('.portos-clone-1999999999999-new123'),+ directory('.unrelated'),+ ]);++ await expect(reapStaleCloneStaging({+ cloneDir: '/repos',+ now: 2000000000000+ })).resolves.toBe(1);++ expect(rm).toHaveBeenCalledTimes(1);+ expect(rm).toHaveBeenCalledWith(+ '/repos/acme/.portos-clone-1000000000000-old123',+ { recursive: true, force: true }+ );+ });});