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: close the remaining ways an interrupted clone stays stranded (#5463)

[._.]/ Adam Eivy079dfbcd41bf
diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.js
index ce37252e2a..13bb270a57 100644
--- a/server/routes/brainLinks.js
+++ b/server/routes/brainLinks.js
@@ -182,8 +182,13 @@ router.post('/links/:id/clone', asyncHandler(async (req, res) => {
});
}
- // Start clone in background
- brainService.cloneRepoInBackground(link.id, link.url);
+ // Start clone in background. Deliberately not awaited, so it needs its own
+ // catch: the setup steps before the clone's own handlers are armed (identity
+ // resolve, the `cloning` stamp) run outside the request lifecycle, and an
+ // unhandled rejection there would crash the process instead of logging.
+ brainService.cloneRepoInBackground(link.id, link.url).catch(err => {
+ console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);
+ });
res.json({ message: 'Clone started', linkId: link.id });
}));
diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.js
index c74c4fbc72..b8566ae32a 100644
--- a/server/routes/brainLinks.test.js
+++ b/server/routes/brainLinks.test.js
@@ -162,13 +162,16 @@ describe('POST /api/brain/links/reorder', () => {
});
describe('POST /api/brain/links/:id/clone', () => {
- it('starts a new clone for a link recovered to failed', async () => {
- brainService.getLinkById.mockResolvedValue({
- id: 'repo-link',
- url: 'https://github.com/acme/widgets',
- isGitHubRepo: true,
- cloneStatus: 'failed',
- });
+ const repoLink = (cloneStatus) => ({
+ id: 'repo-link',
+ url: 'https://github.com/acme/widgets',
+ isGitHubRepo: true,
+ cloneStatus,
+ });
+
+ it('starts a new clone for a link boot recovery reset to failed', async () => {
+ brainService.getLinkById.mockResolvedValue(repoLink('failed'));
+ brainService.cloneRepoInBackground.mockResolvedValue();
const res = await request(app).post('/api/brain/links/repo-link/clone');
@@ -178,4 +181,19 @@ describe('POST /api/brain/links/:id/clone', () => {
'https://github.com/acme/widgets',
);
});
+
+ it('logs rather than crashing when the un-awaited clone kickoff rejects', async () => {
+ // The kickoff runs outside the request lifecycle, so its pre-clone steps
+ // (identity resolve, the `cloning` stamp) have no `next(err)` to bubble to.
+ brainService.getLinkById.mockResolvedValue(repoLink('none'));
+ brainService.cloneRepoInBackground.mockRejectedValue(new Error('identity unavailable'));
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const res = await request(app).post('/api/brain/links/repo-link/clone');
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(res.status).toBe(200);
+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('identity unavailable'));
+ logged.mockRestore();
+ });
});
diff --git a/server/services/brain.js b/server/services/brain.js
index f79b78f3bc..4a7b77cd89 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -10,7 +10,7 @@
import * as storage from './brainStorage.js';
import { brainEvents } from './brainStorage.js';
-import { getInstanceId } from './instances.js';
+import { getInstanceId, ensureInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { validate } from '../lib/validation.js';
@@ -838,31 +838,44 @@ export async function recoverStuckClassifications() {
}
}
+// Matches the client's clone stall window (#5442). Past it, a `cloning` record
+// this install cannot attribute to itself is treated as orphaned rather than
+// left in place — see `shouldRecoverInterruptedClone`.
+const CLONE_STALE_MS = 10 * 60 * 1000;
+
+/**
+ * Whether THIS install should reset `link` out of `cloning` at boot.
+ *
+ * Ours, or unattributed (pre-#5463 records carry no `cloneInstanceId`) — always,
+ * because no in-process clone survives a restart. A clone another instance owns
+ * is left alone while it could still be running, but ages out of that
+ * protection: a peer that crashed mid-clone and never comes back must not
+ * strand the link at `cloning` forever, which is the whole bug (#5463).
+ */
+const shouldRecoverInterruptedClone = (link, instanceId) => {
+ const owner = link.cloneInstanceId ?? link.originInstanceId ?? null;
+ if (!owner || owner === instanceId) return true;
+ const updatedAt = Date.parse(link.updatedAt);
+ return Number.isFinite(updatedAt) && Date.now() - updatedAt >= CLONE_STALE_MS;
+};
+
/**
* Recover repository clones interrupted by a previous server shutdown.
* 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() {
- await githubCloner.reapStaleCloneStaging()
- .catch(err => console.error(`❌ Clone staging recovery failed: ${err.message}`));
- const instanceId = await getInstanceId();
+ // `ensureInstanceId`, not `getInstanceId`: this comparison decides a durable
+ // record mutation, and the sentinel would match every other uninitialized
+ // install's records while missing our own.
+ const instanceId = await ensureInstanceId();
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.
- 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;
- }
+ if (!shouldRecoverInterruptedClone(link, instanceId)) continue;
await storage.updateLink(link.id, {
cloneStatus: 'failed',
cloneError: 'Clone interrupted by a server restart. Retry to clone the repository again.',
@@ -874,6 +887,11 @@ export async function recoverInterruptedRepoClones() {
if (recovered > 0) {
console.log(`🧠 Recovered ${recovered} interrupted repository clone(s)`);
}
+ // Detached on purpose: boot AWAITS this function so the first links request
+ // can't see an orphaned `cloning` badge, and a recursive scan plus `rm -rf` of
+ // abandoned partial checkouts must not sit in front of `startListening()`.
+ githubCloner.reapStaleCloneStaging()
+ .catch(err => console.error(`❌ Clone staging recovery failed: ${err.message}`));
}
// Re-export storage functions for convenience
@@ -1000,9 +1018,18 @@ function hostnameFromUrl(url) {
*/
export async function cloneRepoInBackground(linkId, url) {
const previous = await storage.getLinkById(linkId);
- const cloneInstanceId = await getInstanceId();
+ // `ensureInstanceId`, and null rather than the sentinel: `cloneInstanceId`
+ // lands on a durable, federated record, and a stamped 'unknown' would read as
+ // "some other install owns this" at boot on every machine — re-stranding the
+ // exact record this recovery exists to free.
+ const resolvedInstanceId = await ensureInstanceId();
+ const cloneInstanceId = resolvedInstanceId === UNKNOWN_INSTANCE_ID ? null : resolvedInstanceId;
await storage.updateLink(linkId, {
cloneStatus: 'cloning',
+ // The Links tab renders `cloneError` whenever it is set, independent of
+ // status — leaving the previous attempt's message would show the failure
+ // text beside the new attempt's spinner.
+ cloneError: null,
cloneInstanceId,
cloneInterrupted: false
});
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index 7d6bb92cb7..8d4de2c3f0 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -113,6 +113,8 @@ tryReadFile: vi.fn().mockResolvedValue(null),
// entries; stub it to a stable id.
vi.mock('./instances.js', () => ({
getInstanceId: () => Promise.resolve('local-instance'),
+ ensureInstanceId: () => Promise.resolve('local-instance'),
+ UNKNOWN_INSTANCE_ID: 'unknown',
}));
// Mock the central LLM handler — brain.js used to spawn child_process
@@ -313,6 +315,9 @@ describe('brain service', () => {
}));
expect(storage.updateLink).toHaveBeenCalledWith('link-001', {
cloneStatus: 'cloning',
+ // Cleared, so a recovered link's "interrupted by a server restart"
+ // message doesn't sit beside the retry's spinner.
+ cloneError: null,
cloneInstanceId: 'local-instance',
cloneInterrupted: false
});
@@ -1011,6 +1016,37 @@ describe('brain service', () => {
cloneInstanceId: null,
}));
});
+
+ it('ages a stale peer-owned attempt out so a dead peer cannot strand the link', async () => {
+ // The peer that owned this clone crashed and never came back. Skipping it
+ // forever on ownership alone is the original #5463 bug, one hop removed.
+ storage.getLinks.mockResolvedValue([
+ { id: 'peer-dead', cloneStatus: 'cloning', cloneInstanceId: 'peer-x', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ]);
+ storage.updateLink.mockResolvedValue({});
+
+ await recoverInterruptedRepoClones();
+
+ expect(storage.updateLink).toHaveBeenCalledWith('peer-dead', expect.objectContaining({
+ cloneStatus: 'failed',
+ cloneInterrupted: true,
+ }));
+ });
+
+ it('does not block on the staging sweep', async () => {
+ // Boot awaits this function before it starts listening, so an `rm -rf` of
+ // abandoned partial checkouts must not gate the server accepting requests.
+ // `Once`, so the never-settling promise can't leak into a later test —
+ // mockReturnValue survives clearAllMocks.
+ let released;
+ githubCloner.reapStaleCloneStaging.mockReturnValueOnce(new Promise(resolve => { released = resolve; }));
+ storage.getLinks.mockResolvedValue([]);
+
+ await recoverInterruptedRepoClones();
+
+ expect(githubCloner.reapStaleCloneStaging).toHaveBeenCalled();
+ released(0);
+ });
});
// ===========================================================================
diff --git a/server/services/githubCloner.js b/server/services/githubCloner.js
index 1579804d33..0537f7ab5c 100644
--- a/server/services/githubCloner.js
+++ b/server/services/githubCloner.js
@@ -164,7 +164,13 @@ export async function reapStaleCloneStaging({ cloneDir = DEFAULT_CLONE_DIR, now
for (const owner of owners) {
if (!owner.isDirectory()) continue;
const ownerDir = join(cloneDir, owner.name);
- const entries = await readdir(ownerDir, { withFileTypes: true });
+ // One unreadable owner directory (removed mid-sweep, or not ours to read)
+ // must not abort the sweep and leave every later owner's staging behind.
+ const entries = await readdir(ownerDir, { withFileTypes: true })
+ .catch(err => {
+ console.error(`⚠️ Skipped clone staging sweep for ${owner.name}: ${err.message}`);
+ return [];
+ });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const match = entry.name.match(CLONE_STAGING_RE);
diff --git a/server/services/githubCloner.test.js b/server/services/githubCloner.test.js
index cfc736d138..7b4037d329 100644
--- a/server/services/githubCloner.test.js
+++ b/server/services/githubCloner.test.js
@@ -78,8 +78,67 @@ describe('cloneRepo', () => {
await resultPromise;
});
+ it('never removes the destination for an ordinary clone', async () => {
+ // `replaceIncomplete` is the ONLY thing licensed to delete a checkout the
+ // user may already be using; a plain clone must stage and rename instead.
+ const child = createChild();
+ spawn.mockReturnValue(child);
+
+ const resultPromise = cloneRepo('https://github.com/acme/widgets');
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ child.emit('close', 0);
+ await resultPromise;
+
+ expect(rm).not.toHaveBeenCalledWith('/repos/acme/widgets', expect.anything());
+ });
+
+ it('discards staging and surfaces the git error when the clone fails', async () => {
+ const child = createChild();
+ spawn.mockReturnValue(child);
+
+ const resultPromise = cloneRepo('https://github.com/acme/widgets');
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ child.stderr.emit('data', Buffer.from('fatal: repository not found'));
+ child.emit('close', 128);
+
+ await expect(resultPromise).rejects.toThrow('fatal: repository not found');
+ // Nothing published, and the abandoned partial checkout is gone rather than
+ // left for the boot-time reaper.
+ expect(rename).not.toHaveBeenCalled();
+ expect(rm).toHaveBeenCalledWith(
+ '/repos/acme/.widgets-cloning-attempt',
+ { recursive: true, force: true }
+ );
+ });
+
+ it('keeps a checkout a concurrent attempt already published', async () => {
+ const child = createChild();
+ spawn.mockReturnValue(child);
+
+ const resultPromise = cloneRepo('https://github.com/acme/widgets');
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ // The rival attempt won while git was running.
+ existsSync.mockReturnValue(true);
+ child.emit('close', 0);
+
+ await expect(resultPromise).resolves.toMatchObject({
+ localPath: '/repos/acme/widgets',
+ alreadyCloned: true
+ });
+ expect(rename).not.toHaveBeenCalled();
+ });
+});
+
+describe('reapStaleCloneStaging', () => {
+ const directory = name => ({ name, isDirectory: () => true });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ rm.mockResolvedValue();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
it('reaps only expired PortOS clone staging directories', async () => {
- const directory = name => ({ name, isDirectory: () => true });
readdir
.mockResolvedValueOnce([directory('acme')])
.mockResolvedValueOnce([
@@ -99,4 +158,28 @@ describe('cloneRepo', () => {
{ recursive: true, force: true }
);
});
+
+ it('reports an empty repos directory rather than throwing', async () => {
+ readdir.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: 'ENOENT' }));
+
+ await expect(reapStaleCloneStaging({ cloneDir: '/repos' })).resolves.toBe(0);
+ expect(rm).not.toHaveBeenCalled();
+ });
+
+ it('keeps sweeping after an unreadable owner directory', async () => {
+ readdir
+ .mockResolvedValueOnce([directory('locked'), directory('acme')])
+ .mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }))
+ .mockResolvedValueOnce([directory('.portos-clone-1000000000000-old123')]);
+
+ await expect(reapStaleCloneStaging({
+ cloneDir: '/repos',
+ now: 2000000000000
+ })).resolves.toBe(1);
+
+ expect(rm).toHaveBeenCalledWith(
+ '/repos/acme/.portos-clone-1000000000000-old123',
+ { recursive: true, force: true }
+ );
+ });
});