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

feat: support fork-aware managed app workflows

[._.]/ Adam Eivy1d5d968ff828
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index 45549ede34..465235cb35 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -5,7 +5,7 @@ import Modal from '../../ui/Modal';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
import { formatDateNumeric } from '../../../utils/formatters';
-import EidoverseSourcePanel from './EidoverseSourcePanel';
+import RepositorySourcePanel from './RepositorySourcePanel';
function buildReleasePrompt({ repoPath, appName, comparison, baseBranch, devBranch, hasChangelog }) {
const commitList = comparison.commits
@@ -131,7 +131,7 @@ function ConfirmModal({ open, onClose, titleId, icon, title, tone = 'accent', co
);
}
-export default function GitTab({ appId, app, appName, repoPath }) {
+export default function GitTab({ appId, appName, repoPath }) {
const [gitInfo, setGitInfo] = useState(null);
const [diff, setDiff] = useState('');
const [showDiff, setShowDiff] = useState(false);
@@ -482,12 +482,11 @@ export default function GitTab({ appId, app, appName, repoPath }) {
return (
<div className="space-y-6">
- {app?.pm2ProcessNames?.includes('eidoverse-worlds') && (
- <EidoverseSourcePanel
- appId={appId}
- onUpdated={() => loadGitData({ includeRemote: true })}
- />
- )}
+ <RepositorySourcePanel
+ appId={appId}
+ appName={appName}
+ onUpdated={() => loadGitData({ includeRemote: true })}
+ />
{/* Wraps rather than overflows: three actions no longer fit one phone row. */}
<div className="flex flex-wrap items-center justify-between gap-2">
diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsx
index 239a59255c..9dcee0b7f8 100644
--- a/client/src/components/apps/tabs/GitTab.test.jsx
+++ b/client/src/components/apps/tabs/GitTab.test.jsx
@@ -11,8 +11,8 @@ vi.mock('../../../services/api', () => ({
cleanupMergedBranches: vi.fn(),
resetToDefaultBranch: vi.fn(),
}));
-vi.mock('./EidoverseSourcePanel', () => ({
- default: ({ appId }) => <div data-testid="eidoverse-source-panel">{appId}</div>,
+vi.mock('./RepositorySourcePanel', () => ({
+ default: ({ appId }) => <div data-testid="repository-source-panel">{appId}</div>,
}));
import * as api from '../../../services/api';
@@ -49,7 +49,7 @@ afterEach(() => {
});
describe('GitTab managed repository sources', () => {
- it('shows the Eidoverse source stack only for the managed Eidoverse process', async () => {
+ it('shows repository topology for every managed app', async () => {
const { rerender } = render(
<GitTab
appId="app-eidoverse"
@@ -59,7 +59,7 @@ describe('GitTab managed repository sources', () => {
/>,
);
- expect(await screen.findByTestId('eidoverse-source-panel')).toHaveTextContent('app-eidoverse');
+ expect(await screen.findByTestId('repository-source-panel')).toHaveTextContent('app-eidoverse');
rerender(
<GitTab
@@ -69,7 +69,7 @@ describe('GitTab managed repository sources', () => {
repoPath="/repo"
/>,
);
- expect(screen.queryByTestId('eidoverse-source-panel')).toBeNull();
+ expect(screen.getByTestId('repository-source-panel')).toHaveTextContent('app-other');
});
});
diff --git a/client/src/components/apps/tabs/EidoverseSourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
similarity index 76%
rename from client/src/components/apps/tabs/EidoverseSourcePanel.jsx
rename to client/src/components/apps/tabs/RepositorySourcePanel.jsx
index c346f479eb..8311a030df 100644
--- a/client/src/components/apps/tabs/EidoverseSourcePanel.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
@@ -23,6 +23,9 @@ const statusTone = {
function sourceStatus(source) {
if (!source?.present) return { tone: 'error', label: 'Checkout missing' };
if (!source.remoteFresh) return { tone: 'unknown', label: 'Remote check unavailable' };
+ if (source.origin?.hasOrigin && source.origin.isUpstream == null) {
+ return { tone: 'unknown', label: 'Upstream check unavailable' };
+ }
if (source.origin?.isFork && source.forkVsUpstream?.available === false) {
return { tone: 'unknown', label: 'Upstream check unavailable' };
}
@@ -46,7 +49,7 @@ function sourceStatus(source) {
if ((source.localVsOrigin?.ahead || 0) > 0) {
return { tone: 'attention', label: `Checkout ${source.localVsOrigin.ahead} ahead` };
}
- if (source.origin?.hasOrigin && !source.origin.isUpstream) {
+ if (source.origin?.hasOrigin && source.origin.isUpstream === false) {
return { tone: 'attention', label: 'Custom origin' };
}
return { tone: 'current', label: 'Current' };
@@ -56,22 +59,22 @@ const countText = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
function RepositoryCard({ source }) {
const status = sourceStatus(source);
- const isWorlds = source.id === 'worlds';
+ const isPrimary = source.id === 'primary';
const originName = source.origin?.fullName || 'configured origin';
const upstreamName = source.upstream?.fullName || 'canonical upstream';
const local = source.localVsOrigin;
const fork = source.forkVsUpstream;
return (
- <section className="rounded-xl border border-port-border bg-port-bg/50 p-4" data-testid={`eidoverse-source-${source.id}`}>
+ <section className="rounded-xl border border-port-border bg-port-bg/50 p-4" data-testid={`repository-source-${source.id}`}>
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="flex items-center gap-2">
- {isWorlds ? <GitBranch size={17} className="text-port-accent" /> : <Server size={17} className="text-cyan-400" />}
+ {isPrimary ? <GitBranch size={17} className="text-port-accent" /> : <Server size={17} className="text-cyan-400" />}
<h4 className="font-medium text-white">{source.label}</h4>
</div>
<p className="mt-1 text-xs text-gray-500">
- {isWorlds ? 'World and application checkout' : 'Sidecar runtime · independent checkout · not a submodule'}
+ {isPrimary ? 'Application checkout' : 'Independent companion checkout · not a submodule'}
</p>
</div>
<span className={`rounded-full px-2 py-1 text-xs font-medium ${statusTone[status.tone]}`}>
@@ -134,7 +137,7 @@ function RepositoryCard({ source }) {
);
}
-export default function EidoverseSourcePanel({ appId, onUpdated }) {
+export default function RepositorySourcePanel({ appId, appName, onUpdated }) {
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
@@ -148,7 +151,7 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
else setRefreshing(true);
setError(null);
const result = await api.getAppRepositorySources(appId, { silent: true }).catch((reason) => {
- setError(reason.message || 'Could not inspect the Eidoverse repositories');
+ setError(reason.message || 'Could not inspect the app repositories');
return null;
});
if (result) setStatus(result);
@@ -162,37 +165,38 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
}, [load]);
const sources = status?.sources || [];
- const worlds = sources.find((source) => source.id === 'worlds') || null;
- const video = sources.find((source) => source.id === 'video') || null;
- const forkDiverged = worlds?.forkVsUpstream?.state === 'diverged';
- const forkNeedsSync = worlds?.origin?.isFork
- && (worlds.forkVsUpstream?.behind || 0) > 0
+ const primary = sources.find((source) => source.id === 'primary') || sources[0] || null;
+ const companions = sources.filter((source) => source !== primary);
+ const forkDiverged = primary?.forkVsUpstream?.state === 'diverged';
+ const forkNeedsSync = primary?.origin?.isFork
+ && (primary.forkVsUpstream?.behind || 0) > 0
&& !forkDiverged;
const remoteUnknown = sources.some((source) => (
!source.remoteFresh
+ || (source.origin?.hasOrigin && source.origin.isUpstream == null)
|| (source.origin?.isFork && source.forkVsUpstream?.available === false)
));
- const canUpdate = sources.every((source) => source.present) && status?.updatePullsBoth;
+ const canUpdate = sources.every((source) => source.present) && status?.updatePullsAll;
const shouldOfferUpdate = status?.updateAvailable || remoteUnknown;
const primaryLabel = forkNeedsSync
- ? 'Sync fork & update both'
- : worlds?.origin?.isFork ? 'Update both from fork' : 'Update both';
+ ? 'Sync fork & update app'
+ : primary?.origin?.isFork ? 'Update app from fork' : 'Update app';
const updateSummary = useMemo(() => {
if (!status) return '';
if (status.updateAvailable) return 'One managed update will bring the source stack forward.';
- if (remoteUnknown) return 'Remote freshness is unknown; a managed update can retry both repositories.';
- return 'Both checkouts are current.';
+ if (remoteUnknown) return 'Remote freshness is unknown; a managed update can retry the source checkouts.';
+ return sources.length > 1 ? 'All checkouts are current.' : 'The checkout is current.';
}, [remoteUnknown, status]);
const handleSyncOnly = async () => {
setSyncingFork(true);
const result = await api.syncAppRepositoryFork(appId, { silent: true }).catch((reason) => {
- toast.error(reason.message || 'Could not sync the Eidoverse Worlds fork');
+ toast.error(reason.message || 'Could not sync the app fork');
return null;
});
if (result) {
- toast.success(result.alreadyUpToDate ? 'Worlds fork is already current' : 'Worlds fork synced from upstream');
+ toast.success(result.alreadyUpToDate ? 'Fork is already current' : 'Fork synced from upstream');
await load();
}
setSyncingFork(false);
@@ -203,22 +207,16 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
setUpdateIntent(null);
setUpdating(true);
- let forkReady = true;
- if (intent?.syncFork) {
- forkReady = Boolean(await api.syncAppRepositoryFork(appId, { silent: true }).catch((reason) => {
- toast.error(reason.message || 'Could not sync the Eidoverse Worlds fork');
- return null;
- }));
- }
-
- const result = forkReady
- ? await api.pullAndUpdateApp(appId, { silent: true }).catch((reason) => {
- toast.error(reason.message || 'Could not update Eidoverse');
- return null;
- })
- : null;
+ const result = await api.pullAndUpdateApp(
+ appId,
+ { syncFork: intent?.syncFork === true },
+ { silent: true },
+ ).catch((reason) => {
+ toast.error(reason.message || `Could not update ${appName || 'the app'}`);
+ return null;
+ });
if (result?.success) {
- toast.success('Eidoverse Worlds and Video updated; Eidoverse restarted');
+ toast.success(`${appName || 'App'} updated${status?.updateRestartsApp ? ' and restarted' : ''}`);
await load();
onUpdated?.();
}
@@ -231,10 +229,10 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
<div className="min-w-0">
<div className="flex items-center gap-2">
<GitFork size={19} className="text-port-accent" />
- <h3 className="font-semibold text-white">Eidoverse source stack</h3>
+ <h3 className="font-semibold text-white">Repository sources</h3>
</div>
<p className="mt-1 max-w-3xl text-sm text-gray-400">
- Worlds and Video are separate Git checkouts. Video is the runtime sidecar, not a submodule; PortOS updates both together.
+ PortOS distinguishes the local checkout, its origin fork, and canonical upstream before updating.
</p>
</div>
<button
@@ -248,7 +246,7 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
</div>
{loading && !status ? (
- <div className="py-8 text-center"><BrailleSpinner text="Checking Eidoverse sources" /></div>
+ <div className="py-8 text-center"><BrailleSpinner text="Checking repository sources" /></div>
) : error && !status ? (
<div className="mt-4 rounded-lg border border-port-error/30 bg-port-error/10 p-3 text-sm text-port-error" role="alert">
{error}
@@ -261,34 +259,27 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
</div>
)}
<div className="mt-4 grid grid-cols-1 gap-3 xl:grid-cols-2">
- {worlds && <RepositoryCard source={worlds} />}
- {video && <RepositoryCard source={video} />}
+ {primary && <RepositoryCard source={primary} />}
+ {companions.map((source) => <RepositoryCard key={source.id} source={source} />)}
</div>
- {!status.updatePullsBoth && (
- <div className="mt-3 flex items-start gap-2 rounded-lg border border-port-error/30 bg-port-error/10 p-3 text-sm text-port-error" role="alert">
- <AlertTriangle size={16} className="mt-0.5 shrink-0" />
- This older app registration does not yet include Video in managed updates. Update PortOS and run its pending migrations before updating Eidoverse.
- </div>
- )}
-
<div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-port-border pt-4">
<div className="flex items-center gap-2 text-sm text-gray-400">
{!status.updateAvailable && !remoteUnknown && <CheckCircle2 size={16} className="text-port-success" />}
{updateSummary}
</div>
<div className="flex flex-wrap items-center gap-2">
- {worlds?.origin?.isFork && (
+ {primary?.origin?.isFork && (
<button
onClick={handleSyncOnly}
disabled={syncingFork || updating || forkDiverged}
title={forkDiverged
? 'Reconcile the fork commits on GitHub before syncing'
- : 'Fast-forward the GitHub fork only; does not touch the checkout or restart Eidoverse'}
+ : 'Fast-forward the GitHub fork only; does not touch the checkout or restart the app'}
className="flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"
>
<GitFork size={15} className={syncingFork ? 'animate-pulse' : ''} />
- {forkDiverged ? 'Fork needs reconciliation' : syncingFork ? 'Syncing fork...' : 'Sync fork only'}
+ {forkDiverged ? 'Fork needs reconciliation' : syncingFork ? 'Syncing fork...' : 'Sync fork'}
</button>
)}
{shouldOfferUpdate && (
@@ -298,7 +289,7 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
className="flex min-h-[40px] items-center gap-1.5 rounded-lg bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80 disabled:opacity-50"
>
<Download size={16} className={updating ? 'animate-bounce' : ''} />
- {updating ? 'Updating both...' : primaryLabel}
+ {updating ? 'Updating...' : primaryLabel}
</button>
)}
</div>
@@ -313,12 +304,12 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
align="none"
backdropClassName="bg-black/50"
panelClassName="bg-port-card border border-port-border rounded-xl overflow-hidden"
- ariaLabelledBy="eidoverse-source-update-title"
+ ariaLabelledBy="repository-source-update-title"
>
<div className="flex items-center justify-between border-b border-port-border p-4">
- <h3 id="eidoverse-source-update-title" className="flex items-center gap-2 font-medium text-white">
+ <h3 id="repository-source-update-title" className="flex items-center gap-2 font-medium text-white">
<Download size={18} className="text-port-accent" />
- Update the Eidoverse source stack?
+ Update {appName || 'this app'}?
</h3>
<button
onClick={() => setUpdateIntent(null)}
@@ -329,11 +320,11 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
<div className="space-y-3 p-4">
<p className="text-sm text-gray-300">This managed update will:</p>
<ul className="ml-4 list-disc space-y-1.5 text-sm text-gray-400">
- {updateIntent?.syncFork && <li>Fast-forward the Worlds fork from canonical upstream without forcing</li>}
- <li>Pull the Worlds checkout from its configured origin</li>
- <li>Pull the independent Eidoverse Video sidecar checkout</li>
- <li>Install frozen Bun dependencies</li>
- <li>Restart Eidoverse Worlds only; PortOS and its CoS agents keep running</li>
+ {updateIntent?.syncFork && <li>Fast-forward the origin fork from canonical upstream without forcing</li>}
+ <li>Pull the application checkout from its configured origin</li>
+ {companions.length > 0 && <li>Pull {companions.length} independent companion checkout{companions.length === 1 ? '' : 's'}</li>}
+ <li>Install dependencies and run the app&apos;s setup script when configured</li>
+ {status?.updateRestartsApp && <li>Restart the app&apos;s managed processes</li>}
</ul>
</div>
<div className="flex justify-end gap-3 border-t border-port-border p-4">
@@ -343,7 +334,7 @@ export default function EidoverseSourcePanel({ appId, onUpdated }) {
className="flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80"
>
<Download size={16} />
- {updateIntent?.syncFork ? 'Sync and update both' : 'Update both'}
+ {updateIntent?.syncFork ? 'Sync fork and update' : 'Update app'}
</button>
</div>
</Modal>
diff --git a/client/src/components/apps/tabs/EidoverseSourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
similarity index 52%
rename from client/src/components/apps/tabs/EidoverseSourcePanel.test.jsx
rename to client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
index 0460f47ef4..e6c7e76f11 100644
--- a/client/src/components/apps/tabs/EidoverseSourcePanel.test.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
@@ -8,7 +8,7 @@ vi.mock('../../../services/api', () => ({
}));
import * as api from '../../../services/api';
-import EidoverseSourcePanel from './EidoverseSourcePanel';
+import RepositorySourcePanel from './RepositorySourcePanel';
const source = ({
id,
@@ -34,7 +34,7 @@ const source = ({
...origin,
},
upstream: {
- fullName: `anima-research/${id === 'worlds' ? 'eidoverse-worlds' : 'eidoverse-video'}`,
+ fullName: `anima-research/${id === 'primary' ? 'example-app' : 'example-runtime'}`,
branch,
},
localVsOrigin,
@@ -44,30 +44,30 @@ const source = ({
});
const canonicalStatus = () => ({
- kind: 'eidoverse',
+ kind: 'managed-app',
updateAvailable: true,
- updatePullsBoth: true,
+ updatePullsAll: true,
updateRestartsApp: true,
sources: [
source({
- id: 'worlds',
- label: 'Eidoverse Worlds',
+ id: 'primary',
+ label: 'Example App',
branch: 'main',
head: '1'.repeat(40),
origin: {
- fullName: 'anima-research/eidoverse-worlds',
+ fullName: 'anima-research/example-app',
isUpstream: true,
isFork: false,
},
localVsOrigin: { ahead: 0, behind: 1, state: 'behind' },
}),
source({
- id: 'video',
- label: 'Eidoverse Video',
+ id: 'companion-1',
+ label: 'example-runtime',
branch: 'prod-serving',
head: '2'.repeat(40),
origin: {
- fullName: 'anima-research/eidoverse-video',
+ fullName: 'anima-research/example-runtime',
isUpstream: true,
isFork: false,
},
@@ -84,55 +84,55 @@ beforeEach(() => {
afterEach(() => cleanup());
-describe('Eidoverse source stack', () => {
+describe('managed app repository sources', () => {
it('explains and versions both independent checkouts', async () => {
- render(<EidoverseSourcePanel appId="app-eidoverse" />);
-
- expect(await screen.findByText('Eidoverse source stack')).toBeInTheDocument();
- expect(screen.getByText('Sidecar runtime · independent checkout · not a submodule')).toBeInTheDocument();
- expect(screen.getByTestId('eidoverse-source-worlds')).toHaveTextContent('main @ 1111111');
- expect(screen.getByTestId('eidoverse-source-worlds')).toHaveTextContent('Checkout 1 behind');
- expect(screen.getByTestId('eidoverse-source-video')).toHaveTextContent('prod-serving @ 2222222');
- expect(screen.getByTestId('eidoverse-source-video')).toHaveTextContent('Current');
- expect(screen.getByRole('button', { name: 'Update both' })).toBeInTheDocument();
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
+
+ expect(await screen.findByText('Repository sources')).toBeInTheDocument();
+ expect(screen.getByText('Independent companion checkout · not a submodule')).toBeInTheDocument();
+ expect(screen.getByTestId('repository-source-primary')).toHaveTextContent('main @ 1111111');
+ expect(screen.getByTestId('repository-source-primary')).toHaveTextContent('Checkout 1 behind');
+ expect(screen.getByTestId('repository-source-companion-1')).toHaveTextContent('prod-serving @ 2222222');
+ expect(screen.getByTestId('repository-source-companion-1')).toHaveTextContent('Current');
+ expect(screen.getByRole('button', { name: 'Update app' })).toBeInTheDocument();
});
it('shows local, fork, and upstream as separate version hops and can sync only the fork', async () => {
const status = canonicalStatus();
status.sources[0] = source({
- id: 'worlds',
- label: 'Eidoverse Worlds',
+ id: 'primary',
+ label: 'Example App',
branch: 'main',
head: '1'.repeat(40),
origin: {
- fullName: 'example-owner/eidoverse-worlds',
+ fullName: 'example-owner/example-app',
isUpstream: false,
isFork: true,
},
forkVsUpstream: { available: true, ahead: 0, behind: 2, state: 'behind', error: null },
});
api.getAppRepositorySources.mockResolvedValue(status);
- render(<EidoverseSourcePanel appId="app-eidoverse" />);
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
- const worlds = await screen.findByTestId('eidoverse-source-worlds');
- expect(worlds).toHaveTextContent('example-owner/eidoverse-worlds (fork)');
- expect(worlds).toHaveTextContent('anima-research/eidoverse-worlds (upstream)');
- expect(screen.getByRole('button', { name: 'Sync fork & update both' })).toBeInTheDocument();
+ const primary = await screen.findByTestId('repository-source-primary');
+ expect(primary).toHaveTextContent('example-owner/example-app (fork)');
+ expect(primary).toHaveTextContent('anima-research/example-app (upstream)');
+ expect(screen.getByRole('button', { name: 'Sync fork & update app' })).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Sync fork only' }));
- await waitFor(() => expect(api.syncAppRepositoryFork).toHaveBeenCalledWith('app-eidoverse', { silent: true }));
+ fireEvent.click(screen.getByRole('button', { name: 'Sync fork' }));
+ await waitFor(() => expect(api.syncAppRepositoryFork).toHaveBeenCalledWith('app-example', { silent: true }));
expect(api.pullAndUpdateApp).not.toHaveBeenCalled();
});
- it('confirms that a combined update syncs the fork, pulls both repos, and restarts only Eidoverse', async () => {
+ it('confirms that one managed update syncs the fork and updates every checkout', async () => {
const status = canonicalStatus();
status.sources[0] = source({
- id: 'worlds',
- label: 'Eidoverse Worlds',
+ id: 'primary',
+ label: 'Example App',
branch: 'main',
head: '1'.repeat(40),
origin: {
- fullName: 'example-owner/eidoverse-worlds',
+ fullName: 'example-owner/example-app',
isUpstream: false,
isFork: true,
},
@@ -140,41 +140,43 @@ describe('Eidoverse source stack', () => {
});
api.getAppRepositorySources.mockResolvedValue(status);
const onUpdated = vi.fn();
- render(<EidoverseSourcePanel appId="app-eidoverse" onUpdated={onUpdated} />);
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" onUpdated={onUpdated} />);
- fireEvent.click(await screen.findByRole('button', { name: 'Sync fork & update both' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Sync fork & update app' }));
const dialog = await screen.findByRole('dialog');
- expect(dialog).toHaveTextContent('Pull the independent Eidoverse Video sidecar checkout');
- expect(dialog).toHaveTextContent('Restart Eidoverse Worlds only; PortOS and its CoS agents keep running');
-
- fireEvent.click(screen.getByRole('button', { name: 'Sync and update both' }));
- await waitFor(() => expect(api.pullAndUpdateApp).toHaveBeenCalledWith('app-eidoverse', { silent: true }));
- expect(api.syncAppRepositoryFork).toHaveBeenCalledWith('app-eidoverse', { silent: true });
- expect(api.syncAppRepositoryFork.mock.invocationCallOrder[0])
- .toBeLessThan(api.pullAndUpdateApp.mock.invocationCallOrder[0]);
+ expect(dialog).toHaveTextContent('Pull 1 independent companion checkout');
+ expect(dialog).toHaveTextContent('Restart the app\'s managed processes');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sync fork and update' }));
+ await waitFor(() => expect(api.pullAndUpdateApp).toHaveBeenCalledWith(
+ 'app-example',
+ { syncFork: true },
+ { silent: true },
+ ));
+ expect(api.syncAppRepositoryFork).not.toHaveBeenCalled();
await waitFor(() => expect(onUpdated).toHaveBeenCalledOnce());
});
it('refuses automatic fork sync after divergence but still permits updating from the fork as-is', async () => {
const status = canonicalStatus();
status.sources[0] = source({
- id: 'worlds',
- label: 'Eidoverse Worlds',
+ id: 'primary',
+ label: 'Example App',
branch: 'main',
head: '1'.repeat(40),
origin: {
- fullName: 'example-owner/eidoverse-worlds',
+ fullName: 'example-owner/example-app',
isUpstream: false,
isFork: true,
},
forkVsUpstream: { available: true, ahead: 1, behind: 2, state: 'diverged', error: null },
});
api.getAppRepositorySources.mockResolvedValue(status);
- render(<EidoverseSourcePanel appId="app-eidoverse" />);
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
expect(await screen.findByRole('button', { name: 'Fork needs reconciliation' })).toBeDisabled();
- fireEvent.click(screen.getByRole('button', { name: 'Update both from fork' }));
- fireEvent.click(await screen.findByRole('button', { name: 'Update both' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Update app from fork' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Update app' }));
await waitFor(() => expect(api.pullAndUpdateApp).toHaveBeenCalledOnce());
expect(api.syncAppRepositoryFork).not.toHaveBeenCalled();
@@ -184,12 +186,12 @@ describe('Eidoverse source stack', () => {
const status = canonicalStatus();
status.updateAvailable = false;
status.sources[0] = source({
- id: 'worlds',
- label: 'Eidoverse Worlds',
+ id: 'primary',
+ label: 'Example App',
branch: 'main',
head: '1'.repeat(40),
origin: {
- fullName: 'example-owner/eidoverse-worlds',
+ fullName: 'example-owner/example-app',
isUpstream: false,
isFork: true,
},
@@ -202,11 +204,34 @@ describe('Eidoverse source stack', () => {
},
});
api.getAppRepositorySources.mockResolvedValue(status);
- render(<EidoverseSourcePanel appId="app-eidoverse" />);
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
+
+ const primary = await screen.findByTestId('repository-source-primary');
+ expect(primary).toHaveTextContent('Upstream check unavailable');
+ expect(primary).toHaveTextContent('fork freshness is unknown');
+ expect(screen.getByText('Remote freshness is unknown; a managed update can retry the source checkouts.')).toBeInTheDocument();
+ });
+
+ it('does not mislabel an undiscovered repository topology as a custom origin', async () => {
+ const status = canonicalStatus();
+ status.updateAvailable = false;
+ status.sources = [source({
+ id: 'primary',
+ label: 'Example App',
+ branch: 'main',
+ head: '1'.repeat(40),
+ origin: {
+ fullName: 'example-owner/example-app',
+ isUpstream: null,
+ isFork: false,
+ },
+ })];
+ api.getAppRepositorySources.mockResolvedValue(status);
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
- const worlds = await screen.findByTestId('eidoverse-source-worlds');
- expect(worlds).toHaveTextContent('Upstream check unavailable');
- expect(worlds).toHaveTextContent('fork freshness is unknown');
- expect(screen.getByText('Remote freshness is unknown; a managed update can retry both repositories.')).toBeInTheDocument();
+ const primary = await screen.findByTestId('repository-source-primary');
+ expect(primary).toHaveTextContent('Upstream check unavailable');
+ expect(primary).not.toHaveTextContent('Custom origin');
+ expect(screen.getByRole('button', { name: 'Update app' })).toBeInTheDocument();
});
});
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 648a218816..0da3c3faa3 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -57,6 +57,8 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [openPR, setOpenPR] = useState(true);
const [simplify, setSimplify] = useState(true);
const [planOnly, setPlanOnly] = useState(false);
+ const [issueTarget, setIssueTarget] = useState('upstream');
+ const [issueTargets, setIssueTargets] = useState({ appId: null, value: null });
// Hidden run-shape state, never a user-facing toggle: the slashdo catalog's
// deliverable posture (#3636/#3651). `undefined` = the form pins no opinion,
// so the server keeps its own default. Only a slashdo-backed template sets it.
@@ -225,6 +227,30 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
}, [resolvedWorkTracker, selectedApp]);
const planOnlySupported = planOnlyTrackerStatus === 'supported';
+ // A fork has two legitimate issue destinations. Default to canonical
+ // upstream, but make the origin an explicit per-task choice rather than
+ // silently inheriting whichever remote the checkout calls `origin`.
+ useEffect(() => {
+ const appId = selectedApp?.id || PORTOS_APP_ID;
+ if (!planOnly || !planOnlySupported) {
+ setIssueTargets({ appId, value: null });
+ return undefined;
+ }
+ let cancelled = false;
+ setIssueTargets({ appId, value: null });
+ Promise.resolve(api.getAppRepositorySources(appId, { silent: true }))
+ .then((status) => {
+ if (cancelled) return;
+ const value = status?.issueTargets || null;
+ setIssueTargets({ appId, value });
+ setIssueTarget(value?.default || 'upstream');
+ })
+ .catch(() => {
+ if (!cancelled) setIssueTargets({ appId, value: null });
+ });
+ return () => { cancelled = true; };
+ }, [planOnly, planOnlySupported, selectedApp?.id]);
+
// Clear a template or an already-selected mode when an app resolves to a
// tracker that cannot receive the issue-only plan-task workflow.
useEffect(() => {
@@ -517,6 +543,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
app: newTask.app || undefined,
targetInstanceId: targetInstanceId || undefined,
planOnly,
+ issueTarget: planOnly ? issueTarget : undefined,
slashdoCommand: planOnly ? 'plan-task' : (slashdoCommand || undefined),
slashdoArgs: planOnly ? '--yes' : undefined,
createJiraTicket: planOnly ? false : createJiraTicket,
@@ -774,9 +801,26 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
</p>
)}
{planOnly && (
- <p className="basis-full text-xs text-gray-500">
- Read-only planning: file the issue without code changes, a worktree, PR, simplify pass, or review.
- </p>
+ <div className="basis-full space-y-2">
+ <p className="text-xs text-gray-500">
+ Read-only planning: file the issue without code changes, a worktree, PR, simplify pass, or review.
+ </p>
+ {issueTargets.appId === (selectedApp?.id || PORTOS_APP_ID) && issueTargets.value?.canChoose && (
+ <div className="max-w-md">
+ <label htmlFor="task-issue-target" className="mb-1 block text-xs text-gray-400">File issue on</label>
+ <select
+ id="task-issue-target"
+ value={issueTarget}
+ onChange={(event) => setIssueTarget(event.target.value)}
+ className="w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white"
+ >
+ <option value="upstream">Upstream · {issueTargets.value.upstream?.fullName}</option>
+ <option value="origin">Origin fork · {issueTargets.value.origin?.fullName}</option>
+ </select>
+ <p className="mt-1 text-xs text-gray-500">Upstream is the default so project work is not stranded on a personal fork.</p>
+ </div>
+ )}
+ </div>
)}
{!planOnly && (
<>
diff --git a/client/src/components/cos/TaskAddForm.test.jsx b/client/src/components/cos/TaskAddForm.test.jsx
index 8c1d8ea303..0bf1bb777d 100644
--- a/client/src/components/cos/TaskAddForm.test.jsx
+++ b/client/src/components/cos/TaskAddForm.test.jsx
@@ -10,6 +10,7 @@ const api = vi.hoisted(() => ({
getLocalLlmStatus: vi.fn(),
getProviders: vi.fn(),
getAppWorkTracker: vi.fn(),
+ getAppRepositorySources: vi.fn(),
applyCosTaskTemplate: vi.fn(),
addCosTask: vi.fn()
}));
@@ -40,6 +41,14 @@ describe('TaskAddForm responsive layout', () => {
api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
api.getProviders.mockResolvedValue({ providers: [] });
api.getAppWorkTracker.mockResolvedValue({ resolved: 'github' });
+ api.getAppRepositorySources.mockResolvedValue({
+ issueTargets: {
+ default: 'origin',
+ canChoose: false,
+ origin: { fullName: 'example-org/example-app' },
+ upstream: { fullName: 'example-org/example-app' },
+ },
+ });
api.applyCosTaskTemplate.mockResolvedValue({ success: true });
apiSystem.getAssignableInstances.mockResolvedValue({ instances: [] });
});
@@ -203,6 +212,38 @@ describe('TaskAddForm responsive layout', () => {
});
});
+ it('defaults a forked app plan to upstream and permits an explicit origin target', async () => {
+ const user = userEvent.setup();
+ api.addCosTask.mockResolvedValue({ success: true });
+ api.getAppRepositorySources.mockResolvedValue({
+ issueTargets: {
+ default: 'upstream',
+ canChoose: true,
+ origin: { fullName: 'example-owner/example-app' },
+ upstream: { fullName: 'example-org/example-app' },
+ },
+ });
+ render(<TaskAddForm
+ providers={[]}
+ apps={[{ id: 'example-app', name: 'Example App', repoPath: '/example/app' }]}
+ defaultApp="example-app"
+ onTaskAdded={vi.fn()}
+ />);
+
+ await user.type(screen.getByPlaceholderText('Task description *'), 'Plan a feature');
+ await user.click(await screen.findByLabelText(/Plan & file issue/i));
+ const target = await screen.findByLabelText('File issue on');
+ expect(target).toHaveValue('upstream');
+ expect(target).toHaveTextContent('Upstream · example-org/example-app');
+ await user.selectOptions(target, 'origin');
+ await user.click(screen.getByRole('button', { name: 'Plan & File Issue' }));
+
+ await waitFor(() => expect(api.addCosTask).toHaveBeenCalledWith(
+ expect.objectContaining({ planOnly: true, issueTarget: 'origin' }),
+ { silent: true },
+ ));
+ });
+
it('offers and submits the non-worktree completion choice', async () => {
const user = userEvent.setup();
api.addCosTask.mockResolvedValue({ success: true });
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 752f1d7efa..6dad97f530 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -4,11 +4,11 @@ import { request, API_BASE } from './apiCore.js';
// Apps
export const getApps = (options) => request('/apps', options);
export const getApp = (id, options) => request(`/apps/${id}`, options);
-// Multi-checkout managed integrations (currently Eidoverse): returns sanitized
-// local/fork/upstream revision state without exposing machine-local repo paths.
+// Managed checkout topology: returns sanitized local/fork/upstream revision
+// state without exposing machine-local repo paths.
export const getAppRepositorySources = (id, options = {}) =>
request(`/apps/${id}/repository-sources`, { silent: true, ...options });
-// Fast-forward the integration's configured GitHub fork from canonical
+// Fast-forward the app's configured GitHub fork from canonical
// upstream. The server deliberately refuses divergence and never forces.
export const syncAppRepositoryFork = (id, options = {}) =>
request(`/apps/${id}/repository-sources/sync-fork`, {
@@ -134,8 +134,9 @@ export const openAppFolder = (id) => request(`/apps/${id}/open-folder`, { method
// comes back as a real error instead of a silent `xcode://` no-op.
export const openAppInXcode = (id) => request(`/apps/${id}/open-xcode`, { method: 'POST' });
export const refreshAppConfig = (id) => request(`/apps/${id}/refresh-config`, { method: 'POST' });
-export const pullAndUpdateApp = (id, options = {}) => request(`/apps/${id}/update`, {
+export const pullAndUpdateApp = (id, body = {}, options = {}) => request(`/apps/${id}/update`, {
method: 'POST',
+ body: JSON.stringify(body),
...options,
});
// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`
diff --git a/server/lib/README.md b/server/lib/README.md
index e3f64fc22d..cf8c4f5dc3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -273,7 +273,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
-| `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely classifies a checkout's `origin` against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |
+| `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |
| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index a7b969da59..0e7a4ad104 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1270,6 +1270,10 @@ export const createCosTaskSchema = z.object({
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
),
+ // Plan-only issue destination when the selected app is a fork. The server
+ // resolves this role to a validated forge repository; callers never provide
+ // an arbitrary owner/repo string.
+ issueTarget: z.enum(['upstream', 'origin']).optional(),
openPR: z.preprocess(
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
@@ -1836,7 +1840,7 @@ export const slashdoTaskSchema = createCosTaskSchema
.pick({
model: true, provider: true, effort: true, simplify: true,
reviewers: true, usernames: true, optionalReviewers: true, reviewerMaxRounds: true,
- reviewerModels: true, reviewerEfforts: true
+ reviewerModels: true, reviewerEfforts: true, issueTarget: true
})
.extend({
command: z.string().min(1),
diff --git a/server/lib/gitRemote.js b/server/lib/gitRemote.js
index 65bd1cd7d5..cf4cd07b79 100644
--- a/server/lib/gitRemote.js
+++ b/server/lib/gitRemote.js
@@ -73,7 +73,13 @@ export function parseGitRemoteUrl(url) {
* isn't a git repo or has no `origin` remote (rare, e.g. a tarball install).
*/
export async function readOriginRemoteUrl(cwd = PATHS.root) {
- const result = await execGit(['remote', 'get-url', 'origin'], cwd, { ignoreExitCode: true });
+ return readRemoteUrl('origin', cwd);
+}
+
+/** Read a named git remote without exposing it to a shell. */
+export async function readRemoteUrl(remote, cwd = PATHS.root) {
+ if (typeof remote !== 'string' || !/^[A-Za-z0-9._-]+$/.test(remote)) return null;
+ const result = await execGit(['remote', 'get-url', remote], cwd, { ignoreExitCode: true });
if (result.exitCode !== 0) return null;
const url = result.stdout.trim();
return url || null;
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c20c2ded97..eb2205df6c 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -353,6 +353,10 @@ export const referenceRepoUpdateSchema = z.object({
// either — all ref CRUD goes through /api/apps/:appId/reference-repos.
export const appUpdateSchema = partialWithoutDefaults(appSchema);
+export const managedAppUpdateSchema = z.object({
+ syncFork: z.boolean().optional(),
+}).strict();
+
const standardizePlanFileSchema = z.string().trim().min(1).max(500)
.refine((file) => {
const segments = file.split(/[/\\]/);
diff --git a/server/routes/apps/index.js b/server/routes/apps/index.js
index 8cb0bede21..64ad5ad7c4 100644
--- a/server/routes/apps/index.js
+++ b/server/routes/apps/index.js
@@ -16,7 +16,7 @@
* launch — open-editor, open-claude, open-folder, open-xcode
* documents — planning-doc read/list/commit
* agents — recent CoS agent history
- * repositorySources — multi-checkout version and upstream management
+ * repositorySources — checkout origin/upstream status and fork synchronization
*
* Route ordering is safe across sub-routers: every param route is either the
* single-segment `/:id` or a deeper `/:id/...`, and the static routes
diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.js
index 5709cbaf20..a7b8f56676 100644
--- a/server/routes/apps/lifecycle.js
+++ b/server/routes/apps/lifecycle.js
@@ -24,6 +24,7 @@ import * as appUpdater from '../../services/appUpdater.js';
import * as appBuilder from '../../services/appBuilder.js';
import { logAction } from '../../services/history.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+import { managedAppUpdateSchema, validateRequest } from '../../lib/validation.js';
import { parseEcosystemFromPath, usesPm2, isDesktopType } from '../../services/streamingDetect.js';
import { detectAppIcon, isUsableSvg } from '../../services/appIconDetect.js';
import { loadApp, pathExists, deriveUiPort } from './shared.js';
@@ -238,6 +239,7 @@ router.post('/:id/restart', loadApp, asyncHandler(async (req, res) => {
// POST /api/apps/:id/update - Pull, install deps, setup, restart
router.post('/:id/update', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
+ const options = validateRequest(managedAppUpdateSchema, req.body || {});
if (!app.repoPath || !await pathExists(app.repoPath)) {
throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
@@ -249,7 +251,7 @@ router.post('/:id/update', loadApp, asyncHandler(async (req, res) => {
progressSteps.push({ step, status, message, timestamp: Date.now() });
};
- const result = await appUpdater.updateApp(app, emit);
+ const result = await appUpdater.updateApp(app, emit, options);
const success = result.success;
await logAction('update', app.id, app.name, { steps: result.steps }, success);
notifyAppsChanged('update');
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 011f0c34a8..47852b425c 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -53,6 +53,7 @@ vi.mock('../../services/appIconDetect.js', () => ({
import * as appsService from '../../services/apps.js';
import * as pm2Service from '../../services/pm2.js';
import * as history from '../../services/history.js';
+import * as appUpdater from '../../services/appUpdater.js';
describe('Apps Lifecycle Routes', () => {
let app;
@@ -397,6 +398,43 @@ describe('Apps Lifecycle Routes', () => {
});
});
+ describe('POST /api/apps/:id/update', () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ repoPath: REAL_DIR,
+ pm2ProcessNames: ['test-app'],
+ };
+
+ it('passes the validated fork-sync request to the managed updater', async () => {
+ appsService.getAppById.mockResolvedValue(mockApp);
+ appUpdater.updateApp.mockResolvedValue({ success: true, steps: [] });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app)
+ .post('/api/apps/app-001/update')
+ .send({ syncFork: true });
+
+ expect(response.status).toBe(200);
+ expect(appUpdater.updateApp).toHaveBeenCalledWith(
+ mockApp,
+ expect.any(Function),
+ { syncFork: true },
+ );
+ });
+
+ it('rejects a non-boolean fork-sync request before updating', async () => {
+ appsService.getAppById.mockResolvedValue(mockApp);
+
+ const response = await request(app)
+ .post('/api/apps/app-001/update')
+ .send({ syncFork: 'yes' });
+
+ expect(response.status).toBe(400);
+ expect(appUpdater.updateApp).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/apps/:id/build', () => {
it('should return 404 if app not found', async () => {
appsService.getAppById.mockResolvedValue(null);
diff --git a/server/routes/apps/repositorySources.js b/server/routes/apps/repositorySources.js
index 3a2d651c8a..821a1298ba 100644
--- a/server/routes/apps/repositorySources.js
+++ b/server/routes/apps/repositorySources.js
@@ -1,31 +1,26 @@
/**
- * Managed repository topology and upstream actions for integrations composed
- * from more than one checkout.
+ * Managed repository topology and upstream actions for every registered app.
*
* GET /:id/repository-sources → versions and origin/upstream state
- * POST /:id/repository-sources/sync-fork → fast-forward the Worlds fork only
- *
- * The first integration is Eidoverse. Keeping this on the app-management
- * surface makes the companion runtime visible without pretending it is a git
- * submodule or exposing machine-local checkout paths to the browser.
+ * POST /:id/repository-sources/sync-fork → fast-forward the primary fork
*/
import { Router } from 'express';
import { asyncHandler } from '../../lib/errorHandler.js';
import {
- getEidoverseRepositorySources,
- syncEidoverseWorldsFork,
-} from '../../services/eidoverseRepositories.js';
+ getManagedAppRepositorySources,
+ syncManagedAppFork,
+} from '../../services/managedAppRepositories.js';
import { loadApp } from './shared.js';
const router = Router();
router.get('/:id/repository-sources', loadApp, asyncHandler(async (req, res) => {
- res.json(await getEidoverseRepositorySources(req.loadedApp));
+ res.json(await getManagedAppRepositorySources(req.loadedApp));
}));
router.post('/:id/repository-sources/sync-fork', loadApp, asyncHandler(async (req, res) => {
- res.json(await syncEidoverseWorldsFork(req.loadedApp));
+ res.json(await syncManagedAppFork(req.loadedApp));
}));
export default router;
diff --git a/server/routes/apps/repositorySources.test.js b/server/routes/apps/repositorySources.test.js
index 6220e85c6e..b479e9e98d 100644
--- a/server/routes/apps/repositorySources.test.js
+++ b/server/routes/apps/repositorySources.test.js
@@ -6,16 +6,16 @@ import repositorySourceRoutes from './repositorySources.js';
vi.mock('../../services/apps.js', () => ({
getAppById: vi.fn(),
}));
-vi.mock('../../services/eidoverseRepositories.js', () => ({
- getEidoverseRepositorySources: vi.fn(),
- syncEidoverseWorldsFork: vi.fn(),
+vi.mock('../../services/managedAppRepositories.js', () => ({
+ getManagedAppRepositorySources: vi.fn(),
+ syncManagedAppFork: vi.fn(),
}));
import * as appsService from '../../services/apps.js';
import {
- getEidoverseRepositorySources,
- syncEidoverseWorldsFork,
-} from '../../services/eidoverseRepositories.js';
+ getManagedAppRepositorySources,
+ syncManagedAppFork,
+} from '../../services/managedAppRepositories.js';
describe('managed app repository sources routes', () => {
let app;
@@ -35,21 +35,21 @@ describe('managed app repository sources routes', () => {
});
it('returns the repository topology for the loaded app', async () => {
- getEidoverseRepositorySources.mockResolvedValue({
- kind: 'eidoverse',
- updatePullsBoth: true,
- sources: [{ id: 'worlds' }, { id: 'video' }],
+ getManagedAppRepositorySources.mockResolvedValue({
+ kind: 'managed-app',
+ updatePullsAll: true,
+ sources: [{ id: 'primary' }, { id: 'companion-1' }],
});
const response = await request(app).get('/api/apps/app-eidoverse/repository-sources');
expect(response.status).toBe(200);
- expect(getEidoverseRepositorySources).toHaveBeenCalledWith(managed);
+ expect(getManagedAppRepositorySources).toHaveBeenCalledWith(managed);
expect(response.body.sources).toHaveLength(2);
});
- it('syncs only the configured Worlds fork', async () => {
- syncEidoverseWorldsFork.mockResolvedValue({
+ it('syncs only the app primary checkout fork', async () => {
+ syncManagedAppFork.mockResolvedValue({
synced: true,
fullName: 'example-owner/eidoverse-worlds',
source: 'anima-research/eidoverse-worlds',
@@ -60,7 +60,7 @@ describe('managed app repository sources routes', () => {
.post('/api/apps/app-eidoverse/repository-sources/sync-fork');
expect(response.status).toBe(200);
- expect(syncEidoverseWorldsFork).toHaveBeenCalledWith(managed);
+ expect(syncManagedAppFork).toHaveBeenCalledWith(managed);
expect(response.body).toMatchObject({ synced: true, branch: 'main' });
});
@@ -70,6 +70,6 @@ describe('managed app repository sources routes', () => {
const response = await request(app).get('/api/apps/missing/repository-sources');
expect(response.status).toBe(404);
- expect(getEidoverseRepositorySources).not.toHaveBeenCalled();
+ expect(getManagedAppRepositorySources).not.toHaveBeenCalled();
});
});
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 8dee1f9f01..2a4029ca8c 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -10,6 +10,7 @@ import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import { buildClaimWorkTask, buildJiraTicketTask } from '../services/cosTaskGenerator.js';
import { getAppById, getAppWorkTracker, PORTOS_APP_ID } from '../services/apps.js';
import { getAssignableInstances } from '../services/instances.js';
+import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';
import { workTrackerLabel } from '../lib/workTracker.js';
import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';
import { NON_PM2_TYPES } from '../services/streamingDetect.js';
@@ -50,17 +51,37 @@ async function assertAssignableInstance(instanceId) {
const ISSUE_TRACKERS = new Set(['github', 'gitlab']);
-// The bundled plan-task workflow files an issue; it cannot target PLAN.md or
-// JIRA. Keep the API contract aligned with the quick-task form so direct
-// callers cannot bypass the tracker gate.
-async function assertPlanOnlyTracker(taskData) {
- if (taskData.planOnly !== true && taskData.slashdoCommand !== 'plan-task') return;
- const trackerInfo = await getAppWorkTracker(taskData.app || PORTOS_APP_ID);
- if (!trackerInfo || ISSUE_TRACKERS.has(trackerInfo.resolved)) return;
- throw new ServerError(
- `Plan-and-file tasks require a GitHub or GitLab issue tracker (resolved to ${trackerInfo.resolved})`,
- { status: 400, code: 'UNSUPPORTED_PLAN_ONLY_TRACKER' }
- );
+function issueTargetInstructions(target, tracker) {
+ if (!target?.fullName) {
+ return '## Issue repository\n\nBefore filing, inspect whether the checkout origin is a fork. If it is, file on the canonical upstream repository rather than the origin fork. Do not rely on the working directory\'s implicit forge target.';
+ }
+ const role = target.role === 'upstream' ? 'canonical upstream' : 'configured origin';
+ const repoFlag = tracker === 'github' ? (target.repoSpec || target.fullName) : target.fullName;
+ const cli = tracker === 'github' ? 'gh' : 'glab';
+ return `## Issue repository\n\nFile this issue on the ${role} repository \`${target.fullName}\`. Pass \`--repo ${repoFlag}\` to every \`${cli} issue\`, label, and related repository command; do not let \`${cli}\` infer the origin fork from the working directory.`;
+}
+
+// The bundled plan-task workflow files an issue; resolve the app's canonical
+// destination before queueing so a checkout whose origin is a fork does not
+// silently file project work on that fork. The form may deliberately choose the
+// origin; upstream is the unattended/default posture.
+async function preparePlanOnlyTask(taskData, knownApp = null) {
+ if (taskData.planOnly !== true && taskData.slashdoCommand !== 'plan-task') return taskData;
+ const appId = taskData.app || PORTOS_APP_ID;
+ const [trackerInfo, app] = await Promise.all([
+ getAppWorkTracker(appId),
+ knownApp ? Promise.resolve(knownApp) : getAppById(appId),
+ ]);
+ if (trackerInfo && !ISSUE_TRACKERS.has(trackerInfo.resolved)) {
+ throw new ServerError(
+ `Plan-and-file tasks require a GitHub or GitLab issue tracker (resolved to ${trackerInfo.resolved})`,
+ { status: 400, code: 'UNSUPPORTED_PLAN_ONLY_TRACKER' }
+ );
+ }
+ if (!app || !trackerInfo) return taskData;
+ const target = await resolveManagedAppIssueTarget(app, taskData.issueTarget || 'upstream').catch(() => null);
+ const targetPrompt = issueTargetInstructions(target, target?.forge || trackerInfo.resolved);
+ return { ...taskData, prompt: [taskData.prompt, targetPrompt].filter(Boolean).join('\n\n') };
}
const router = Router();
@@ -151,7 +172,7 @@ router.post('/tasks/enhance', asyncHandler(async (req, res) => {
// source, so the two surfaces can't drift.
router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
const {
- command, app, provider, model, effort, simplify,
+ command, app, provider, model, effort, simplify, issueTarget,
target, issueContext, overrideContext, issueAuthorFilter, reviewers, usernames, optionalReviewers,
reviewerMaxRounds, reviewerModels, reviewerEfforts
} = validateRequest(slashdoTaskSchema, req.body);
@@ -169,10 +190,11 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
throw new ServerError(`App not found: ${app}`, { status: 404, code: 'APP_NOT_FOUND' });
}
- // `plan-task` is also a plan-only quick action, so it must use the same
- // forge-only gate as the general task endpoint rather than reaching
- // `cos.addTask` through this separate route.
- if (command === 'plan-task') await assertPlanOnlyTracker({ app, slashdoCommand: command });
+ // `plan-task` is also a plan-only quick action, so resolve its forge target
+ // before it reaches the store through this separate route.
+ const planTask = command === 'plan-task'
+ ? await preparePlanOnlyTask({ app, slashdoCommand: command, issueTarget }, appObj)
+ : null;
// Enforce the catalog's stack gate server-side. The Agent Operations panel only
// offers the applicable one of `better` / `better-swift`, but the API must not
@@ -272,7 +294,7 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
simplify: simplify === true,
reviewLoop: false
};
- const result = await cos.addTask(taskData, 'user');
+ const result = await cos.addTask(planTask ? { ...taskData, prompt: planTask.prompt } : taskData, 'user');
if (result?.duplicate) {
throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });
@@ -325,8 +347,8 @@ router.post('/tasks', asyncHandler(async (req, res) => {
if (!parsed.success) failValidation(parsed);
const { type, ...taskData } = parsed.data;
if (taskData.targetInstanceId) await assertAssignableInstance(taskData.targetInstanceId);
- await assertPlanOnlyTracker(taskData);
- const result = await cos.addTask(taskData, type);
+ const preparedTask = await preparePlanOnlyTask(taskData);
+ const result = await cos.addTask(preparedTask, type);
if (result?.duplicate) {
throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index 1ad55dccf8..67ea396afb 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -36,10 +36,12 @@ vi.mock('../services/cosTaskGenerator.js', () => ({
vi.mock('../services/apps.js', () => ({ getAppById: vi.fn(), getAppWorkTracker: vi.fn(), PORTOS_APP_ID: 'portos-default' }));
vi.mock('../services/streamingDetect.js', () => ({ NON_PM2_TYPES: new Set() }));
vi.mock('../services/instances.js', () => ({ getAssignableInstances: vi.fn() }));
+vi.mock('../services/managedAppRepositories.js', () => ({ resolveManagedAppIssueTarget: vi.fn() }));
import * as cos from '../services/cos.js';
import { getAssignableInstances } from '../services/instances.js';
-import { getAppWorkTracker } from '../services/apps.js';
+import { getAppById, getAppWorkTracker } from '../services/apps.js';
+import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';
import cosTaskRoutes from './cosTaskRoutes.js';
const SELF = 'self-instance-id';
@@ -61,6 +63,13 @@ beforeEach(() => {
]);
cos.addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));
cos.updateTask.mockResolvedValue({ id: 'task-1' });
+ getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', repoPath: '/example/portos' });
+ resolveManagedAppIssueTarget.mockResolvedValue({
+ role: 'upstream',
+ forge: 'github',
+ fullName: 'example-org/example-app',
+ repoSpec: 'github.com/example-org/example-app',
+ });
});
describe('POST /api/cos/tasks — targetInstanceId (#4520)', () => {
@@ -111,6 +120,37 @@ describe('POST /api/cos/tasks — plan-only tracker gate', () => {
expect(res.status).toBe(200);
expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({ planOnly: true }), 'user');
});
+
+ it('pins plan-only GitHub commands to the detected upstream repository', async () => {
+ getAppWorkTracker.mockResolvedValue({ resolved: 'github' });
+
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: 'plan the change', app: 'forked-app', planOnly: true });
+
+ expect(res.status).toBe(200);
+ expect(resolveManagedAppIssueTarget).toHaveBeenCalledWith(
+ expect.objectContaining({ repoPath: '/example/portos' }),
+ 'upstream',
+ );
+ expect(cos.addTask.mock.calls[0][0].prompt).toContain('github.com/example-org/example-app');
+ expect(cos.addTask.mock.calls[0][0].prompt).toContain('canonical upstream');
+ });
+
+ it('honors a deliberate origin target for a plan-only task', async () => {
+ getAppWorkTracker.mockResolvedValue({ resolved: 'github' });
+ resolveManagedAppIssueTarget.mockResolvedValue({
+ role: 'origin', fullName: 'example-owner/example-app', repoSpec: 'github.com/example-owner/example-app',
+ });
+
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: 'plan the change', app: 'forked-app', planOnly: true, issueTarget: 'origin' });
+
+ expect(res.status).toBe(200);
+ expect(resolveManagedAppIssueTarget).toHaveBeenCalledWith(expect.anything(), 'origin');
+ expect(cos.addTask.mock.calls[0][0].prompt).toContain('configured origin');
+ });
});
describe('PUT /api/cos/tasks/:id — targetInstanceId (#4520)', () => {
diff --git a/server/services/appUpdater.js b/server/services/appUpdater.js
index 5e8c1ebe75..dba19758ed 100644
--- a/server/services/appUpdater.js
+++ b/server/services/appUpdater.js
@@ -5,6 +5,7 @@ import * as gitService from './git.js';
import * as pm2Service from './pm2.js';
import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';
import { parseCommandArgs } from '../lib/commandSecurity.js';
+import { syncManagedAppFork } from './managedAppRepositories.js';
const CMD_TIMEOUT_MS = 5 * 60 * 1000;
@@ -30,9 +31,10 @@ const updatingApps = new Set();
*
* @param {object} app - The app object (must have repoPath, pm2ProcessNames, pm2Home)
* @param {function} emit - Callback (step, status, message) for progress updates
+ * @param {{syncFork?: boolean}} options
* @returns {Promise<{success: boolean, steps: object[]}>}
*/
-export async function updateApp(app, emit) {
+export async function updateApp(app, emit, { syncFork = false } = {}) {
const dir = app.repoPath;
if (updatingApps.has(dir)) {
return { success: false, steps: [{ step: 'lock', success: false, message: 'Update already in progress' }] };
@@ -40,13 +42,13 @@ export async function updateApp(app, emit) {
updatingApps.add(dir);
try {
- return await _doUpdate(app, emit);
+ return await _doUpdate(app, emit, { syncFork });
} finally {
updatingApps.delete(dir);
}
}
-async function _doUpdate(app, emit) {
+async function _doUpdate(app, emit, { syncFork }) {
const dir = app.repoPath;
const steps = [];
const packageManager = app.type === 'bun' ? 'bun' : 'npm';
@@ -56,6 +58,16 @@ async function _doUpdate(app, emit) {
: packageManager;
const installArgs = packageManager === 'bun' ? ['install', '--frozen-lockfile'] : ['install'];
+ if (syncFork) {
+ emit('git-sync-fork', 'running', 'Syncing the origin fork from canonical upstream...');
+ const sync = await syncManagedAppFork(app);
+ const syncMessage = sync.alreadyUpToDate
+ ? `${sync.fullName} is already current`
+ : `Synced ${sync.fullName} from ${sync.source}`;
+ emit('git-sync-fork', 'done', syncMessage);
+ steps.push({ step: 'git-sync-fork', success: true, message: syncMessage });
+ }
+
emit('git-pull', 'running', 'Pulling latest changes...');
const pullResult = await gitService.pull(dir);
const pullMsg = pullResult.output?.trim() || 'Up to date';
diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.js
index 4e0e787c04..85df92f973 100644
--- a/server/services/appUpdater.test.js
+++ b/server/services/appUpdater.test.js
@@ -7,11 +7,13 @@ const mock = vi.hoisted(() => ({
pull: vi.fn(),
spawn: vi.fn(),
restart: vi.fn(),
+ syncFork: vi.fn(),
}));
vi.mock('./git.js', () => ({ pull: mock.pull }));
vi.mock('./pm2.js', () => ({ restartApp: mock.restart }));
vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawnOrThrow: mock.spawn }));
+vi.mock('./managedAppRepositories.js', () => ({ syncManagedAppFork: mock.syncFork }));
import { updateApp } from './appUpdater.js';
@@ -27,6 +29,11 @@ describe('managed app updates', () => {
mock.pull.mockResolvedValue({ output: 'Already up to date' });
mock.spawn.mockResolvedValue({ stdout: '', stderr: '' });
mock.restart.mockResolvedValue({ success: true });
+ mock.syncFork.mockResolvedValue({
+ alreadyUpToDate: false,
+ fullName: 'example-owner/example-app',
+ source: 'example-org/example-app',
+ });
});
afterEach(async () => {
@@ -56,4 +63,19 @@ describe('managed app updates', () => {
expect(emit).toHaveBeenCalledWith('git-pull:companion-1', 'done', 'Already up to date');
expect(emit).toHaveBeenCalledWith('bun-install:root', 'done', 'root dependencies installed');
});
+
+ it('syncs a detected fork before pulling when the managed update requests it', async () => {
+ const emit = vi.fn();
+ const managed = { name: 'Example App', type: 'express', repoPath: repo, pm2ProcessNames: [] };
+
+ await updateApp(managed, emit, { syncFork: true });
+
+ expect(mock.syncFork).toHaveBeenCalledWith(managed);
+ expect(mock.syncFork.mock.invocationCallOrder[0]).toBeLessThan(mock.pull.mock.invocationCallOrder[0]);
+ expect(emit).toHaveBeenCalledWith(
+ 'git-sync-fork',
+ 'done',
+ 'Synced example-owner/example-app from example-org/example-app',
+ );
+ });
});
diff --git a/server/services/eidoverseRepositories.js b/server/services/eidoverseRepositories.js
deleted file mode 100644
index 7ac4699e48..0000000000
--- a/server/services/eidoverseRepositories.js
+++ /dev/null
@@ -1,287 +0,0 @@
-import { join } from 'path';
-import { ServerError } from '../lib/errorHandler.js';
-import { pathExists, safeJSONParse } from '../lib/fileUtils.js';
-import { getOriginInfo } from '../lib/gitRemote.js';
-import { parseGitHubUrl } from '../lib/githubRepoUrl.js';
-import {
- DEFAULT_EIDOVERSE_WORLDS_REPO,
- EIDOVERSE_PROCESS_NAME,
- EIDOVERSE_VIDEO_REPO,
- getEidoversePaths,
-} from './eidoverse.js';
-import { execGitSafe, fetchOrigin, resolveForgeForRepo } from './git.js';
-import { execGh } from './github.js';
-
-const WORLDS_UPSTREAM_BRANCH = 'main';
-const GH_TIMEOUT_MS = 60_000;
-
-const repoIdentity = (url) => {
- const parsed = parseGitHubUrl(url);
- return {
- owner: parsed.owner,
- repo: parsed.repo,
- fullName: `${parsed.owner}/${parsed.repo}`,
- };
-};
-
-const WORLDS_UPSTREAM = repoIdentity(DEFAULT_EIDOVERSE_WORLDS_REPO);
-const VIDEO_UPSTREAM = repoIdentity(EIDOVERSE_VIDEO_REPO);
-
-const isEidoverseApp = (app) => Boolean(app?.pm2ProcessNames?.includes(EIDOVERSE_PROCESS_NAME));
-
-function assertEidoverseApp(app) {
- if (isEidoverseApp(app)) return;
- throw new ServerError('Repository source management is available only for the managed Eidoverse Worlds app.', {
- status: 400,
- code: 'EIDOVERSE_APP_REQUIRED',
- });
-}
-
-const comparisonState = (ahead, behind) => {
- if (ahead > 0 && behind > 0) return 'diverged';
- if (behind > 0) return 'behind';
- if (ahead > 0) return 'ahead';
- return 'current';
-};
-
-function parseRevisionCounts(result) {
- if (result.exitCode !== 0) return null;
- const [aheadText, behindText] = result.stdout.trim().split(/\s+/);
- const ahead = Number.parseInt(aheadText, 10);
- const behind = Number.parseInt(behindText, 10);
- if (!Number.isInteger(ahead) || !Number.isInteger(behind)) return null;
- return { ahead, behind, state: comparisonState(ahead, behind) };
-}
-
-async function inspectCheckout({ id, label, repoPath, upstream, upstreamBranch }) {
- const present = typeof repoPath === 'string'
- && repoPath.trim().length > 0
- && await pathExists(join(repoPath, '.git'));
- if (!present) {
- return {
- id,
- label,
- present: false,
- branch: null,
- head: null,
- shortHead: null,
- clean: null,
- origin: null,
- upstream: { fullName: upstream.fullName, branch: upstreamBranch || null },
- localVsOrigin: null,
- remoteFresh: false,
- remoteError: 'Checkout not found',
- };
- }
-
- const [branchResult, headResult, worktreeResult, origin] = await Promise.all([
- execGitSafe(['rev-parse', '--abbrev-ref', 'HEAD'], repoPath, { ignoreExitCode: true }),
- execGitSafe(['rev-parse', 'HEAD'], repoPath, { ignoreExitCode: true }),
- execGitSafe(['status', '--porcelain'], repoPath, { ignoreExitCode: true }),
- getOriginInfo(repoPath, { upstreamOwner: upstream.owner, upstreamRepo: upstream.repo }),
- ]);
- const branchName = branchResult.exitCode === 0 ? branchResult.stdout.trim() : null;
- const branch = branchName && branchName !== 'HEAD' ? branchName : null;
- const head = headResult.exitCode === 0 ? headResult.stdout.trim() : null;
- const clean = worktreeResult.exitCode === 0 ? worktreeResult.stdout.trim().length === 0 : null;
-
- const fetchResult = origin.hasOrigin
- ? await fetchOrigin(repoPath).then(
- () => ({ fresh: true, error: null }),
- () => ({ fresh: false, error: 'Could not refresh the remote repository' }),
- )
- : { fresh: false, error: 'No origin remote configured' };
-
- const originRef = branch ? `refs/remotes/origin/${branch}` : null;
- const [originHeadResult, countsResult] = originRef
- ? await Promise.all([
- execGitSafe(['rev-parse', '--verify', originRef], repoPath, { ignoreExitCode: true }),
- execGitSafe(['rev-list', '--left-right', '--count', `HEAD...${originRef}`], repoPath, { ignoreExitCode: true }),
- ])
- : [null, null];
- const originHead = originHeadResult?.exitCode === 0 ? originHeadResult.stdout.trim() : null;
- const localVsOrigin = countsResult ? parseRevisionCounts(countsResult) : null;
-
- return {
- id,
- label,
- present: true,
- branch,
- head,
- shortHead: head?.slice(0, 7) || null,
- clean,
- origin: {
- hasOrigin: origin.hasOrigin,
- fullName: origin.fullName,
- url: origin.originUrl,
- isGithub: origin.isGithub,
- isUpstream: origin.isUpstream,
- isFork: origin.isFork,
- head: originHead,
- shortHead: originHead?.slice(0, 7) || null,
- },
- upstream: {
- fullName: upstream.fullName,
- branch: upstreamBranch || branch,
- },
- localVsOrigin,
- remoteFresh: fetchResult.fresh,
- remoteError: fetchResult.error,
- };
-}
-
-async function compareForkWithUpstream(checkout) {
- if (!checkout?.origin?.isFork || !checkout.origin.fullName) return null;
- const branch = checkout.upstream.branch || WORLDS_UPSTREAM_BRANCH;
- const basehead = encodeURIComponent(
- `${WORLDS_UPSTREAM.owner}:${branch}...${checkout.origin.fullName.split('/')[0]}:${branch}`,
- );
- const forge = await resolveForgeForRepo(checkout.repoPath).catch(() => null);
- const raw = await execGh([
- 'api',
- `repos/${WORLDS_UPSTREAM.fullName}/compare/${basehead}`,
- '--jq',
- '{status: .status, ahead: .ahead_by, behind: .behind_by}',
- ], GH_TIMEOUT_MS, {
- cwd: checkout.repoPath,
- env: forge?.env || process.env,
- }).catch(() => null);
- const parsed = safeJSONParse(raw, null);
- if (!parsed
- || !Number.isInteger(parsed.ahead)
- || !Number.isInteger(parsed.behind)) {
- return {
- available: false,
- ahead: null,
- behind: null,
- state: 'unknown',
- error: 'Could not compare the fork with canonical upstream',
- };
- }
- return {
- available: true,
- ahead: parsed.ahead,
- behind: parsed.behind,
- state: comparisonState(parsed.ahead, parsed.behind),
- error: null,
- };
-}
-
-/**
- * Report the two checkouts that make up one Eidoverse installation. No local
- * paths are returned: the app-management UI needs versions and topology, not
- * machine identity. Network failures stay distinct from a confirmed current
- * repository so a stale ref is never presented as "up to date".
- */
-export async function getEidoverseRepositorySources(app) {
- assertEidoverseApp(app);
- const registeredCompanions = Array.isArray(app.companionRepoPaths)
- ? app.companionRepoPaths.filter((path) => typeof path === 'string' && path.trim())
- : [];
- const videoPath = getEidoversePaths().video;
-
- const [worldsBase, video] = await Promise.all([
- inspectCheckout({
- id: 'worlds',
- label: 'Eidoverse Worlds',
- repoPath: app.repoPath,
- upstream: WORLDS_UPSTREAM,
- upstreamBranch: WORLDS_UPSTREAM_BRANCH,
- }),
- inspectCheckout({
- id: 'video',
- label: 'Eidoverse Video',
- repoPath: videoPath,
- upstream: VIDEO_UPSTREAM,
- upstreamBranch: null,
- }),
- ]);
- // Kept server-only above; callers receive no absolute checkout path.
- const worlds = {
- ...worldsBase,
- forkVsUpstream: await compareForkWithUpstream({ ...worldsBase, repoPath: app.repoPath }),
- };
-
- const updateAvailable = [worlds, video].some((source) => source.localVsOrigin?.behind > 0)
- || (worlds.forkVsUpstream?.behind || 0) > 0;
-
- return {
- kind: 'eidoverse',
- checkedAt: new Date().toISOString(),
- updateAvailable,
- updatePullsBoth: registeredCompanions.includes(videoPath),
- updateRestartsApp: true,
- sources: [worlds, video],
- };
-}
-
-/**
- * Fast-forward the configured Worlds fork from canonical upstream. This is a
- * remote-only action: it never touches the checkout and deliberately omits
- * `--force`, so GitHub refuses instead of discarding fork commits.
- */
-export async function syncEidoverseWorldsFork(app) {
- assertEidoverseApp(app);
- const origin = await getOriginInfo(app.repoPath, {
- upstreamOwner: WORLDS_UPSTREAM.owner,
- upstreamRepo: WORLDS_UPSTREAM.repo,
- });
- if (!origin.hasOrigin) {
- throw new ServerError('The Eidoverse Worlds checkout has no Git origin.', {
- status: 400,
- code: 'NO_ORIGIN',
- });
- }
- if (!origin.isGithub) {
- throw new ServerError('Eidoverse fork sync is available only for GitHub origins.', {
- status: 400,
- code: 'NOT_GITHUB',
- });
- }
- if (origin.isUpstream) {
- throw new ServerError(`The Worlds origin is already ${WORLDS_UPSTREAM.fullName}.`, {
- status: 400,
- code: 'ALREADY_UPSTREAM',
- });
- }
- if (!origin.isFork) {
- throw new ServerError(
- `The Worlds origin is not a same-name fork of ${WORLDS_UPSTREAM.fullName}.`,
- { status: 400, code: 'NOT_A_FORK' },
- );
- }
-
- const forge = await resolveForgeForRepo(app.repoPath).catch(() => null);
- const output = await execGh([
- 'repo',
- 'sync',
- origin.fullName,
- '--source',
- WORLDS_UPSTREAM.fullName,
- '--branch',
- WORLDS_UPSTREAM_BRANCH,
- ], GH_TIMEOUT_MS, {
- cwd: app.repoPath,
- env: forge?.env || process.env,
- }).catch((error) => {
- if (/fast forward|diverge|non-fast/i.test(error.message || '')) {
- throw new ServerError(
- `The ${origin.fullName} fork has commits that cannot be fast-forwarded from ${WORLDS_UPSTREAM.fullName}. Reconcile those commits on GitHub before syncing.`,
- { status: 409, code: 'FORK_DIVERGED' },
- );
- }
- throw new ServerError(`Could not sync the Eidoverse Worlds fork: ${error.message}`, {
- status: 502,
- code: 'FORK_SYNC_FAILED',
- });
- });
-
- return {
- synced: true,
- alreadyUpToDate: /up to date/i.test(output),
- fullName: origin.fullName,
- source: WORLDS_UPSTREAM.fullName,
- branch: WORLDS_UPSTREAM_BRANCH,
- message: output.trim(),
- };
-}
diff --git a/server/services/eidoverseRepositories.test.js b/server/services/eidoverseRepositories.test.js
deleted file mode 100644
index 52e7e10f73..0000000000
--- a/server/services/eidoverseRepositories.test.js
+++ /dev/null
@@ -1,252 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mock = vi.hoisted(() => ({
- pathExists: vi.fn(),
- execGit: vi.fn(),
- getOriginInfo: vi.fn(),
- fetchOrigin: vi.fn(),
- resolveForgeForRepo: vi.fn(),
- execGh: vi.fn(),
-}));
-
-vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
- ...(await importOriginal()),
- pathExists: mock.pathExists,
-}));
-vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: mock.getOriginInfo }));
-vi.mock('./git.js', () => ({
- execGitSafe: mock.execGit,
- fetchOrigin: mock.fetchOrigin,
- resolveForgeForRepo: mock.resolveForgeForRepo,
-}));
-vi.mock('./github.js', () => ({ execGh: mock.execGh }));
-vi.mock('./eidoverse.js', () => ({
- DEFAULT_EIDOVERSE_WORLDS_REPO: 'https://github.com/anima-research/eidoverse-worlds',
- EIDOVERSE_PROCESS_NAME: 'eidoverse-worlds',
- EIDOVERSE_VIDEO_REPO: 'https://github.com/anima-research/eidoverse-video',
- getEidoversePaths: () => ({ video: '/example/video' }),
-}));
-
-import {
- getEidoverseRepositorySources,
- syncEidoverseWorldsFork,
-} from './eidoverseRepositories.js';
-
-const WORLDS = '/example/worlds';
-const VIDEO = '/example/video';
-const managedApp = {
- id: 'app-eidoverse',
- name: 'Eidoverse Worlds',
- repoPath: WORLDS,
- companionRepoPaths: [VIDEO],
- pm2ProcessNames: ['eidoverse-worlds'],
-};
-const HEADS = {
- [WORLDS]: '1'.repeat(40),
- [VIDEO]: '2'.repeat(40),
-};
-const BRANCHES = {
- [WORLDS]: 'main',
- [VIDEO]: 'prod-serving',
-};
-
-const canonicalOrigin = (repo) => ({
- hasOrigin: true,
- originUrl: `https://github.com/anima-research/${repo}.git`,
- fullName: `anima-research/${repo}`,
- isGithub: true,
- isUpstream: true,
- isFork: false,
-});
-
-describe('Eidoverse repository source management', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mock.pathExists.mockResolvedValue(true);
- mock.fetchOrigin.mockResolvedValue(true);
- mock.resolveForgeForRepo.mockResolvedValue({ env: { GH_TOKEN: 'test-token' } });
- mock.getOriginInfo.mockImplementation(async (repoPath) => (
- repoPath === WORLDS
- ? canonicalOrigin('eidoverse-worlds')
- : canonicalOrigin('eidoverse-video')
- ));
- mock.execGit.mockImplementation(async (args, repoPath) => {
- if (args[0] === 'status') return { stdout: '', stderr: '', exitCode: 0 };
- if (args[0] === 'rev-list') {
- return {
- stdout: repoPath === WORLDS ? '0\t1\n' : '0\t0\n',
- stderr: '',
- exitCode: 0,
- };
- }
- if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {
- return { stdout: `${BRANCHES[repoPath]}\n`, stderr: '', exitCode: 0 };
- }
- if (args[0] === 'rev-parse' && args[1] === '--verify') {
- return { stdout: `${repoPath === WORLDS ? '3'.repeat(40) : HEADS[repoPath]}\n`, stderr: '', exitCode: 0 };
- }
- if (args[0] === 'rev-parse' && args[1] === 'HEAD') {
- return { stdout: `${HEADS[repoPath]}\n`, stderr: '', exitCode: 0 };
- }
- return { stdout: '', stderr: '', exitCode: 1 };
- });
- });
-
- it('reports Worlds and the independently versioned Video companion without leaking checkout paths', async () => {
- const result = await getEidoverseRepositorySources(managedApp);
-
- expect(result).toMatchObject({
- kind: 'eidoverse',
- updateAvailable: true,
- updatePullsBoth: true,
- updateRestartsApp: true,
- sources: [
- {
- id: 'worlds',
- branch: 'main',
- shortHead: '1111111',
- localVsOrigin: { ahead: 0, behind: 1, state: 'behind' },
- origin: { fullName: 'anima-research/eidoverse-worlds', isUpstream: true },
- },
- {
- id: 'video',
- branch: 'prod-serving',
- shortHead: '2222222',
- localVsOrigin: { ahead: 0, behind: 0, state: 'current' },
- origin: { fullName: 'anima-research/eidoverse-video', isUpstream: true },
- },
- ],
- });
- expect(JSON.stringify(result)).not.toContain('/example/');
- });
-
- it('uses the canonical Video path even when another companion is registered first', async () => {
- const result = await getEidoverseRepositorySources({
- ...managedApp,
- companionRepoPaths: ['/example/other-helper', VIDEO],
- });
-
- expect(mock.execGit).toHaveBeenCalledWith(
- ['rev-parse', '--abbrev-ref', 'HEAD'],
- VIDEO,
- { ignoreExitCode: true },
- );
- expect(result.updatePullsBoth).toBe(true);
- expect(result.sources[1]).toMatchObject({ id: 'video', shortHead: '2222222' });
- });
-
- it('reports a detached checkout without comparing it to origin/HEAD', async () => {
- const normalExecGit = mock.execGit.getMockImplementation();
- mock.execGit.mockImplementation((args, repoPath) => {
- if (repoPath === WORLDS && args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {
- return Promise.resolve({ stdout: 'HEAD\n', stderr: '', exitCode: 0 });
- }
- return normalExecGit(args, repoPath);
- });
-
- const result = await getEidoverseRepositorySources(managedApp);
-
- expect(result.sources[0]).toMatchObject({ branch: null, localVsOrigin: null });
- expect(mock.execGit).not.toHaveBeenCalledWith(
- ['rev-parse', '--verify', 'refs/remotes/origin/HEAD'],
- WORLDS,
- { ignoreExitCode: true },
- );
- });
-
- it('distinguishes the local-to-fork gap from the fork-to-upstream gap', async () => {
- mock.getOriginInfo.mockImplementation(async (repoPath) => (
- repoPath === WORLDS
- ? {
- hasOrigin: true,
- originUrl: '[email protected]:example-owner/eidoverse-worlds.git',
- fullName: 'example-owner/eidoverse-worlds',
- isGithub: true,
- isUpstream: false,
- isFork: true,
- }
- : canonicalOrigin('eidoverse-video')
- ));
- mock.execGh.mockResolvedValue('{"status":"diverged","ahead":2,"behind":3}');
-
- const result = await getEidoverseRepositorySources(managedApp);
- const worlds = result.sources[0];
-
- expect(worlds.localVsOrigin).toMatchObject({ ahead: 0, behind: 1 });
- expect(worlds.forkVsUpstream).toEqual({
- available: true,
- ahead: 2,
- behind: 3,
- state: 'diverged',
- error: null,
- });
- expect(mock.execGh).toHaveBeenCalledWith(
- expect.arrayContaining([
- 'repos/anima-research/eidoverse-worlds/compare/anima-research%3Amain...example-owner%3Amain',
- ]),
- 60000,
- expect.objectContaining({ cwd: WORLDS }),
- );
- });
-
- it('keeps a failed remote refresh distinct from a confirmed current checkout', async () => {
- mock.fetchOrigin.mockRejectedValue(new Error('offline'));
-
- const result = await getEidoverseRepositorySources(managedApp);
-
- expect(result.sources[0]).toMatchObject({
- remoteFresh: false,
- remoteError: 'Could not refresh the remote repository',
- });
- });
-
- it('fast-forwards the Worlds fork without ever passing --force', async () => {
- mock.getOriginInfo.mockResolvedValue({
- hasOrigin: true,
- fullName: 'example-owner/eidoverse-worlds',
- isGithub: true,
- isUpstream: false,
- isFork: true,
- });
- mock.execGh.mockResolvedValue('Synced the main branch');
-
- const result = await syncEidoverseWorldsFork(managedApp);
-
- const args = mock.execGh.mock.calls[0][0];
- expect(args).toEqual([
- 'repo', 'sync', 'example-owner/eidoverse-worlds',
- '--source', 'anima-research/eidoverse-worlds',
- '--branch', 'main',
- ]);
- expect(args).not.toContain('--force');
- expect(result).toMatchObject({
- synced: true,
- fullName: 'example-owner/eidoverse-worlds',
- source: 'anima-research/eidoverse-worlds',
- });
- });
-
- it('fails closed when GitHub says the fork cannot be fast-forwarded', async () => {
- mock.getOriginInfo.mockResolvedValue({
- hasOrigin: true,
- fullName: 'example-owner/eidoverse-worlds',
- isGithub: true,
- isUpstream: false,
- isFork: true,
- });
- mock.execGh.mockRejectedValue(new Error('destination would not be a fast forward'));
-
- await expect(syncEidoverseWorldsFork(managedApp)).rejects.toMatchObject({
- status: 409,
- code: 'FORK_DIVERGED',
- });
- });
-
- it('refuses the Eidoverse-only contract for an unrelated managed app', async () => {
- await expect(getEidoverseRepositorySources({
- ...managedApp,
- pm2ProcessNames: ['example-app'],
- })).rejects.toMatchObject({ status: 400, code: 'EIDOVERSE_APP_REQUIRED' });
- expect(mock.fetchOrigin).not.toHaveBeenCalled();
- });
-});
diff --git a/server/services/managedAppRepositories.js b/server/services/managedAppRepositories.js
new file mode 100644
index 0000000000..439898953c
--- /dev/null
+++ b/server/services/managedAppRepositories.js
@@ -0,0 +1,298 @@
+import { basename, join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { pathExists, safeJSONParse } from '../lib/fileUtils.js';
+import { getOriginInfo, parseGitRemoteUrl, readRemoteUrl } from '../lib/gitRemote.js';
+import { githubApiHost, hostToWorkTracker, isGithubHost } from '../lib/workTracker.js';
+import { execGitSafe, fetchOrigin, resolveForgeForRepo } from './git.js';
+import { execGh } from './github.js';
+
+const GH_TIMEOUT_MS = 60_000;
+
+const comparisonState = (ahead, behind) => {
+ if (ahead > 0 && behind > 0) return 'diverged';
+ if (behind > 0) return 'behind';
+ if (ahead > 0) return 'ahead';
+ return 'current';
+};
+
+function parseRevisionCounts(result) {
+ if (result?.exitCode !== 0) return null;
+ const [aheadText, behindText] = result.stdout.trim().split(/\s+/);
+ const ahead = Number.parseInt(aheadText, 10);
+ const behind = Number.parseInt(behindText, 10);
+ if (!Number.isInteger(ahead) || !Number.isInteger(behind)) return null;
+ return { ahead, behind, state: comparisonState(ahead, behind) };
+}
+
+const repositoryIdentity = (fullName, host = 'github.com') => {
+ if (typeof fullName !== 'string' || !fullName.trim()) return null;
+ const parts = fullName.trim().split('/');
+ if (parts.length !== 2 || parts.some((part) => !part)) return null;
+ return {
+ host: githubApiHost(host),
+ owner: parts[0],
+ repo: parts[1],
+ fullName: `${parts[0]}/${parts[1]}`,
+ };
+};
+
+function remoteIdentity(url) {
+ const parsed = parseGitRemoteUrl(url);
+ if (!parsed) return null;
+ return {
+ host: githubApiHost(parsed.host),
+ owner: parsed.owner,
+ repo: parsed.repo,
+ fullName: `${parsed.owner}/${parsed.repo}`,
+ };
+}
+
+async function githubRepositoryMetadata(repoPath, origin) {
+ if (!origin?.fullName || !isGithubHost(origin.host)) return null;
+ const forge = await resolveForgeForRepo(repoPath).catch(() => null);
+ const host = githubApiHost(origin.host);
+ const raw = await execGh([
+ 'api', ...(host === 'github.com' ? [] : ['--hostname', host]),
+ `repos/${origin.fullName}`, '--jq',
+ '{fullName: .full_name, defaultBranch: .default_branch, isFork: .fork, '
+ + 'parentFullName: .parent.full_name, parentDefaultBranch: .parent.default_branch, '
+ + 'sourceFullName: .source.full_name, sourceDefaultBranch: .source.default_branch}',
+ ], GH_TIMEOUT_MS, {
+ cwd: repoPath,
+ env: forge?.env || process.env,
+ }).catch(() => null);
+ const parsed = safeJSONParse(raw, null);
+ return parsed && typeof parsed.fullName === 'string' ? parsed : null;
+}
+
+/**
+ * Resolve one checkout's origin → canonical-upstream topology. GitHub's own
+ * fork metadata is authoritative, so renamed forks work too. An explicit
+ * `upstream` remote is the offline/cross-forge fallback; otherwise a repository
+ * that GitHub confirms is not a fork is its own canonical source.
+ */
+export async function resolveRepositoryTopology(repoPath) {
+ const origin = await getOriginInfo(repoPath);
+ if (!origin.hasOrigin) {
+ return { origin, upstream: null, isFork: false, available: false, error: 'No origin remote configured' };
+ }
+
+ const [metadata, upstreamUrl] = await Promise.all([
+ githubRepositoryMetadata(repoPath, origin),
+ readRemoteUrl('upstream', repoPath).catch(() => null),
+ ]);
+
+ const apiUpstream = repositoryIdentity(
+ metadata?.sourceFullName || metadata?.parentFullName,
+ origin.host,
+ );
+ const explicitUpstream = remoteIdentity(upstreamUrl);
+ const upstream = metadata
+ ? apiUpstream || repositoryIdentity(origin.fullName, origin.host)
+ : explicitUpstream;
+ const isFork = Boolean(upstream && origin.fullName
+ && upstream.fullName.toLowerCase() !== origin.fullName.toLowerCase());
+ const defaultBranch = apiUpstream
+ ? (metadata.sourceDefaultBranch || metadata.parentDefaultBranch || metadata.defaultBranch || 'main')
+ : metadata?.defaultBranch || null;
+
+ return {
+ origin: { ...origin, isFork, isUpstream: upstream ? !isFork : null },
+ upstream: upstream ? { ...upstream, branch: defaultBranch } : null,
+ isFork,
+ available: Boolean(upstream),
+ error: upstream ? null : 'Could not determine the canonical upstream repository',
+ };
+}
+
+async function compareForkWithUpstream(checkout, repoPath) {
+ if (!checkout?.origin?.isFork || !checkout.origin.fullName || !checkout.upstream?.fullName) return null;
+ if (!isGithubHost(checkout.origin.host) || checkout.origin.host !== checkout.upstream.host) return null;
+ const branch = checkout.upstream.branch || checkout.branch || 'main';
+ const upstreamOwner = checkout.upstream.owner;
+ const originOwner = checkout.origin.owner;
+ const basehead = encodeURIComponent(`${upstreamOwner}:${branch}...${originOwner}:${branch}`);
+ const forge = await resolveForgeForRepo(repoPath).catch(() => null);
+ const host = githubApiHost(checkout.origin.host);
+ const raw = await execGh([
+ 'api', ...(host === 'github.com' ? [] : ['--hostname', host]),
+ `repos/${checkout.upstream.fullName}/compare/${basehead}`, '--jq',
+ '{status: .status, ahead: .ahead_by, behind: .behind_by}',
+ ], GH_TIMEOUT_MS, {
+ cwd: repoPath,
+ env: { ...(forge?.env || process.env), GH_HOST: host },
+ }).catch(() => null);
+ const parsed = safeJSONParse(raw, null);
+ if (!parsed || !Number.isInteger(parsed.ahead) || !Number.isInteger(parsed.behind)) {
+ return { available: false, ahead: null, behind: null, state: 'unknown', error: 'Could not compare the fork with canonical upstream' };
+ }
+ return {
+ available: true,
+ ahead: parsed.ahead,
+ behind: parsed.behind,
+ state: comparisonState(parsed.ahead, parsed.behind),
+ error: null,
+ };
+}
+
+async function inspectCheckout({ id, label, repoPath }) {
+ const present = typeof repoPath === 'string' && repoPath.trim().length > 0
+ && await pathExists(join(repoPath, '.git'));
+ if (!present) {
+ return {
+ id, label, present: false, branch: null, head: null, shortHead: null, clean: null,
+ origin: null, upstream: null, localVsOrigin: null, forkVsUpstream: null,
+ remoteFresh: false, remoteError: 'Checkout not found',
+ };
+ }
+
+ const [branchResult, headResult, worktreeResult, topology] = await Promise.all([
+ execGitSafe(['rev-parse', '--abbrev-ref', 'HEAD'], repoPath, { ignoreExitCode: true }),
+ execGitSafe(['rev-parse', 'HEAD'], repoPath, { ignoreExitCode: true }),
+ execGitSafe(['status', '--porcelain'], repoPath, { ignoreExitCode: true }),
+ resolveRepositoryTopology(repoPath),
+ ]);
+ const branchName = branchResult.exitCode === 0 ? branchResult.stdout.trim() : null;
+ const branch = branchName && branchName !== 'HEAD' ? branchName : null;
+ const head = headResult.exitCode === 0 ? headResult.stdout.trim() : null;
+ const clean = worktreeResult.exitCode === 0 ? worktreeResult.stdout.trim().length === 0 : null;
+ const fetchResult = topology.origin.hasOrigin
+ ? await fetchOrigin(repoPath).then(
+ () => ({ fresh: true, error: topology.error }),
+ () => ({ fresh: false, error: 'Could not refresh the origin repository' }),
+ )
+ : { fresh: false, error: topology.error };
+
+ const originRef = branch ? `refs/remotes/origin/${branch}` : null;
+ const [originHeadResult, countsResult] = originRef
+ ? await Promise.all([
+ execGitSafe(['rev-parse', '--verify', originRef], repoPath, { ignoreExitCode: true }),
+ execGitSafe(['rev-list', '--left-right', '--count', `HEAD...${originRef}`], repoPath, { ignoreExitCode: true }),
+ ])
+ : [null, null];
+ const originHead = originHeadResult?.exitCode === 0 ? originHeadResult.stdout.trim() : null;
+ const checkout = {
+ id,
+ label,
+ present: true,
+ branch,
+ head,
+ shortHead: head?.slice(0, 7) || null,
+ clean,
+ origin: {
+ ...topology.origin,
+ url: topology.origin.originUrl,
+ head: originHead,
+ shortHead: originHead?.slice(0, 7) || null,
+ },
+ upstream: topology.upstream
+ ? { fullName: topology.upstream.fullName, branch: topology.upstream.branch, host: topology.upstream.host }
+ : null,
+ localVsOrigin: countsResult ? parseRevisionCounts(countsResult) : null,
+ remoteFresh: fetchResult.fresh,
+ remoteError: fetchResult.error,
+ };
+ return { ...checkout, forkVsUpstream: await compareForkWithUpstream(checkout, repoPath) };
+}
+
+function sourceDescriptors(app) {
+ const companions = Array.isArray(app?.companionRepoPaths)
+ ? [...new Set(app.companionRepoPaths)].filter((path) => path && path !== app.repoPath)
+ : [];
+ return [
+ { id: 'primary', label: app.name || 'Application', repoPath: app.repoPath },
+ ...companions.map((repoPath, index) => ({
+ id: `companion-${index + 1}`,
+ label: basename(repoPath) || `Companion repository ${index + 1}`,
+ repoPath,
+ })),
+ ];
+}
+
+function publicTarget(repository, role) {
+ if (!repository?.fullName) return null;
+ const host = repository.host || 'github.com';
+ const forge = hostToWorkTracker(host);
+ return {
+ role,
+ forge,
+ fullName: repository.fullName,
+ repoSpec: isGithubHost(host) ? `${githubApiHost(host)}/${repository.fullName}` : null,
+ };
+}
+
+export async function getManagedAppRepositorySources(app) {
+ const descriptors = sourceDescriptors(app);
+ const sources = await Promise.all(descriptors.map(inspectCheckout));
+ const primary = sources[0] || null;
+ const originTarget = publicTarget(primary?.origin, 'origin');
+ const upstreamTarget = publicTarget(primary?.upstream, 'upstream');
+ const canChoose = Boolean(primary?.origin?.isFork && originTarget && upstreamTarget);
+ return {
+ kind: 'managed-app',
+ checkedAt: new Date().toISOString(),
+ updateAvailable: sources.some((source) => source.localVsOrigin?.behind > 0
+ || (source.forkVsUpstream?.behind || 0) > 0),
+ updatePullsAll: true,
+ updateRestartsApp: Array.isArray(app?.pm2ProcessNames) && app.pm2ProcessNames.length > 0,
+ issueTargets: {
+ default: canChoose || primary?.origin?.isUpstream == null ? 'upstream' : 'origin',
+ canChoose,
+ origin: originTarget,
+ upstream: upstreamTarget,
+ },
+ sources,
+ };
+}
+
+export async function resolveManagedAppIssueTarget(app, preference = 'upstream') {
+ const topology = await resolveRepositoryTopology(app.repoPath);
+ const origin = publicTarget(topology.origin, 'origin');
+ if (preference === 'origin') return origin;
+ if (!topology.available) return null;
+ const upstream = publicTarget(topology.upstream, 'upstream');
+ if (!topology.isFork || !upstream) return origin;
+ return upstream;
+}
+
+/** Fast-forward the primary checkout's GitHub fork without touching local files. */
+export async function syncManagedAppFork(app) {
+ const topology = await resolveRepositoryTopology(app.repoPath);
+ const { origin, upstream } = topology;
+ if (!origin?.hasOrigin) {
+ throw new ServerError('The app checkout has no Git origin.', { status: 400, code: 'NO_ORIGIN' });
+ }
+ if (!isGithubHost(origin.host)) {
+ throw new ServerError('Fork sync is available only for GitHub origins.', { status: 400, code: 'NOT_GITHUB' });
+ }
+ if (!topology.available) {
+ throw new ServerError('Could not determine the canonical upstream repository.', { status: 502, code: 'UPSTREAM_UNAVAILABLE' });
+ }
+ if (!topology.isFork) {
+ throw new ServerError(`The origin is already the canonical ${origin.fullName} repository.`, { status: 400, code: 'ALREADY_UPSTREAM' });
+ }
+ const branch = upstream.branch || null;
+ const forge = await resolveForgeForRepo(app.repoPath).catch(() => null);
+ const args = ['repo', 'sync', origin.fullName, '--source', upstream.fullName];
+ if (branch) args.push('--branch', branch);
+ const output = await execGh(args, GH_TIMEOUT_MS, {
+ cwd: app.repoPath,
+ env: { ...(forge?.env || process.env), GH_HOST: githubApiHost(origin.host) },
+ }).catch((error) => {
+ if (/fast forward|diverge|non-fast/i.test(error.message || '')) {
+ throw new ServerError(
+ `The ${origin.fullName} fork has commits that cannot be fast-forwarded from ${upstream.fullName}. Reconcile those commits on GitHub before syncing.`,
+ { status: 409, code: 'FORK_DIVERGED' },
+ );
+ }
+ throw new ServerError(`Could not sync the app fork: ${error.message}`, { status: 502, code: 'FORK_SYNC_FAILED' });
+ });
+ return {
+ synced: true,
+ alreadyUpToDate: /up to date/i.test(output),
+ fullName: origin.fullName,
+ source: upstream.fullName,
+ branch,
+ message: output.trim(),
+ };
+}
diff --git a/server/services/managedAppRepositories.test.js b/server/services/managedAppRepositories.test.js
new file mode 100644
index 0000000000..cd2c24de06
--- /dev/null
+++ b/server/services/managedAppRepositories.test.js
@@ -0,0 +1,219 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({
+ pathExists: vi.fn(),
+ getOriginInfo: vi.fn(),
+ readRemoteUrl: vi.fn(),
+ execGit: vi.fn(),
+ fetchOrigin: vi.fn(),
+ resolveForgeForRepo: vi.fn(),
+ execGh: vi.fn(),
+}));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ pathExists: mock.pathExists,
+}));
+vi.mock('../lib/gitRemote.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getOriginInfo: mock.getOriginInfo,
+ readRemoteUrl: mock.readRemoteUrl,
+}));
+vi.mock('./git.js', () => ({
+ execGitSafe: mock.execGit,
+ fetchOrigin: mock.fetchOrigin,
+ resolveForgeForRepo: mock.resolveForgeForRepo,
+}));
+vi.mock('./github.js', () => ({ execGh: mock.execGh }));
+
+import {
+ getManagedAppRepositorySources,
+ resolveManagedAppIssueTarget,
+ resolveRepositoryTopology,
+ syncManagedAppFork,
+} from './managedAppRepositories.js';
+
+const REPO = '/example/app';
+const app = { id: 'app-example', name: 'Example App', repoPath: REPO, pm2ProcessNames: ['example-app'] };
+const forkOrigin = {
+ hasOrigin: true,
+ originUrl: '[email protected]:example-owner/example-app.git',
+ host: 'github.com',
+ owner: 'example-owner',
+ repo: 'example-app',
+ fullName: 'example-owner/example-app',
+ isGithub: true,
+ isFork: false,
+ isUpstream: false,
+};
+
+describe('managed app repository topology', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mock.pathExists.mockResolvedValue(true);
+ mock.getOriginInfo.mockResolvedValue(forkOrigin);
+ mock.readRemoteUrl.mockResolvedValue(null);
+ mock.fetchOrigin.mockResolvedValue(true);
+ mock.resolveForgeForRepo.mockResolvedValue({ env: { GH_TOKEN: 'test-token' } });
+ mock.execGh.mockImplementation(async (args) => {
+ if (args[1] === 'repos/example-owner/example-app') {
+ return JSON.stringify({
+ fullName: 'example-owner/example-app',
+ defaultBranch: 'main',
+ isFork: true,
+ parentFullName: 'example-org/example-app',
+ parentDefaultBranch: 'main',
+ sourceFullName: 'example-org/example-app',
+ sourceDefaultBranch: 'main',
+ });
+ }
+ if (String(args[1]).includes('/compare/')) {
+ return JSON.stringify({ status: 'behind', ahead: 0, behind: 2 });
+ }
+ return 'Synced the main branch';
+ });
+ mock.execGit.mockImplementation(async (args) => {
+ if (args[0] === 'status') return { stdout: '', stderr: '', exitCode: 0 };
+ if (args[0] === 'rev-list') return { stdout: '0\t1\n', stderr: '', exitCode: 0 };
+ if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return { stdout: 'main\n', stderr: '', exitCode: 0 };
+ if (args[0] === 'rev-parse' && args[1] === '--verify') return { stdout: `${'2'.repeat(40)}\n`, stderr: '', exitCode: 0 };
+ if (args[0] === 'rev-parse' && args[1] === 'HEAD') return { stdout: `${'1'.repeat(40)}\n`, stderr: '', exitCode: 0 };
+ return { stdout: '', stderr: '', exitCode: 1 };
+ });
+ });
+
+ it('discovers a canonical upstream from GitHub fork metadata without app-specific constants', async () => {
+ const topology = await resolveRepositoryTopology(REPO);
+
+ expect(topology).toMatchObject({
+ isFork: true,
+ origin: { fullName: 'example-owner/example-app', isFork: true, isUpstream: false },
+ upstream: { fullName: 'example-org/example-app', branch: 'main' },
+ });
+ expect(mock.execGh).toHaveBeenCalledWith(
+ expect.arrayContaining(['api', 'repos/example-owner/example-app']),
+ 60000,
+ expect.objectContaining({ cwd: REPO }),
+ );
+ });
+
+ it('reports sanitized source state and defaults issue filing to upstream', async () => {
+ const result = await getManagedAppRepositorySources(app);
+
+ expect(result).toMatchObject({
+ kind: 'managed-app',
+ updateAvailable: true,
+ updatePullsAll: true,
+ issueTargets: {
+ default: 'upstream',
+ canChoose: true,
+ origin: { fullName: 'example-owner/example-app', role: 'origin' },
+ upstream: { fullName: 'example-org/example-app', role: 'upstream' },
+ },
+ sources: [{
+ id: 'primary',
+ branch: 'main',
+ localVsOrigin: { ahead: 0, behind: 1, state: 'behind' },
+ forkVsUpstream: { ahead: 0, behind: 2, state: 'behind' },
+ }],
+ });
+ expect(JSON.stringify(result)).not.toContain(REPO);
+ });
+
+ it('resolves upstream by default while honoring an explicit origin choice', async () => {
+ await expect(resolveManagedAppIssueTarget(app)).resolves.toMatchObject({
+ role: 'upstream',
+ repoSpec: 'github.com/example-org/example-app',
+ });
+ await expect(resolveManagedAppIssueTarget(app, 'origin')).resolves.toMatchObject({
+ role: 'origin',
+ repoSpec: 'github.com/example-owner/example-app',
+ });
+ });
+
+ it('syncs a fork from its detected upstream without force', async () => {
+ const result = await syncManagedAppFork(app);
+ const syncArgs = mock.execGh.mock.calls.at(-1)[0];
+
+ expect(syncArgs).toEqual([
+ 'repo', 'sync', 'example-owner/example-app',
+ '--source', 'example-org/example-app', '--branch', 'main',
+ ]);
+ expect(syncArgs).not.toContain('--force');
+ expect(result).toMatchObject({ fullName: 'example-owner/example-app', source: 'example-org/example-app' });
+ });
+
+ it('uses an explicit upstream remote when forge metadata is unavailable', async () => {
+ mock.execGh.mockResolvedValue(null);
+ mock.readRemoteUrl.mockResolvedValue('[email protected]:example-org/example-app.git');
+
+ await expect(resolveRepositoryTopology(REPO)).resolves.toMatchObject({
+ isFork: true,
+ upstream: { fullName: 'example-org/example-app' },
+ });
+ });
+
+ it('keeps successful forge metadata authoritative over an unrelated upstream remote', async () => {
+ mock.readRemoteUrl.mockResolvedValue('[email protected]:example-org/example-app.git');
+ mock.execGh.mockResolvedValue(JSON.stringify({
+ fullName: 'example-owner/example-app',
+ defaultBranch: 'trunk',
+ isFork: false,
+ parentFullName: null,
+ sourceFullName: null,
+ }));
+
+ await expect(resolveRepositoryTopology(REPO)).resolves.toMatchObject({
+ isFork: false,
+ origin: { isUpstream: true },
+ upstream: { fullName: 'example-owner/example-app', branch: 'trunk' },
+ });
+ });
+
+ it('targets the origin GitHub host when syncing an enterprise fork', async () => {
+ mock.getOriginInfo.mockResolvedValue({
+ ...forkOrigin,
+ originUrl: '[email protected]:example-owner/example-app.git',
+ host: 'github.example.com',
+ });
+ mock.execGh.mockImplementation(async (args) => {
+ if (args.includes('repos/example-owner/example-app')) {
+ return JSON.stringify({
+ fullName: 'example-owner/example-app',
+ defaultBranch: 'main',
+ isFork: true,
+ parentFullName: 'example-org/example-app',
+ parentDefaultBranch: 'main',
+ sourceFullName: 'example-org/example-app',
+ sourceDefaultBranch: 'main',
+ });
+ }
+ return 'Synced the main branch';
+ });
+
+ await syncManagedAppFork(app);
+
+ expect(mock.execGh.mock.calls[0][0]).toEqual(expect.arrayContaining([
+ 'api', '--hostname', 'github.example.com', 'repos/example-owner/example-app',
+ ]));
+ expect(mock.execGh.mock.calls.at(-1)[2].env).toMatchObject({ GH_HOST: 'github.example.com' });
+ });
+
+ it('preserves upstream intent when canonical discovery is temporarily unavailable', async () => {
+ mock.execGh.mockResolvedValue(null);
+ mock.readRemoteUrl.mockResolvedValue(null);
+
+ const result = await getManagedAppRepositorySources(app);
+
+ expect(result.issueTargets).toMatchObject({ default: 'upstream', canChoose: false });
+ await expect(resolveManagedAppIssueTarget(app)).resolves.toBeNull();
+ await expect(resolveManagedAppIssueTarget(app, 'origin')).resolves.toMatchObject({
+ role: 'origin',
+ fullName: 'example-owner/example-app',
+ });
+ await expect(syncManagedAppFork(app)).rejects.toMatchObject({
+ status: 502,
+ code: 'UPSTREAM_UNAVAILABLE',
+ });
+ });
+});