/** * @module core-clone-cmd * * Isomorphic engine implementation for `vcs clone` and `vcs fork`. * Supports two-phase WebSocket pull: * Phase 1: Pull remote CosmosIbGib_V1 and member galaxy manifests into localSpace. * Phase 2: Pull selected member galaxy branch spaces (DAG, snapshots, binaries). * Phase 3: Project snapshot item trees onto the local filesystem. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { putInSpace } from '../../../witness/space/space-helper.mjs'; import { getIbGibFromSpace, parseSpaceQualifiedIbGibAddr } from '../../../common/other/ibgib-helper.mjs'; import { SyncPeerWebSocketSender_V1 } from '../../../sync/sync-peer/sync-peer-websocket/sync-peer-websocket-sender/sync-peer-websocket-sender-v1.mjs'; import { SyncSagaCoordinator } from '../../../sync/sync-saga-coordinator.mjs'; import { getFullSyncSagaHistory, getTransferredPayloadAddressesFromHistory } from '../../../sync/sync-helpers.mjs'; import { SyncMode } from '../../../sync/sync-types.mjs'; import { COSMOS_ATOM, COSMOS_REL8N_NAME } from '../../cosmos/cosmos-constants.mjs'; import { CosmosIbGib_V1, CosmosRemoteInfo } from '../../cosmos/cosmos-types.mjs'; import { getCosmosByName, getAllCosmoses, createCosmosIbGib, getGalaxiesFromCosmos, getOwnerKeystoneTjp, } from '../../cosmos/cosmos-helpers.mjs'; import { resolveRemoteCosmosUrl, buildCloneWsUrl } from '../../workspace/cosmos-url-helper.mjs'; import { getBranchInfoFromGalaxy, getOrCreateBranchSpace } from '../branch/branch-helpers.mjs'; import { getLatestBranchSnapshot } from '../snapshot/snapshot-helpers.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { B2TFS_GALAXY_ATOM, B2TFS_GALAXY_REL8N_NAME, B2tFSGalaxyIbGib_V1 } from '../b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { getB2tFSGalaxyIbGib, updateB2tFSGalaxyIbGib } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { getSpaceQualifiedIbGibAddr } from '../../../common/other/ibgib-helper.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { VCS_DEFAULT_FOLDER_NAME } from '../branching-constants.mjs'; import { VcsCloneOpts, VcsCloneResult, VcsForkOpts, VcsForkResult, } from './command-types.mjs'; import { BinIbGib_V1 } from '../../../common/bin/bin-types.mjs'; const lcFile = `[core-clone-cmd]`; const logalot = GLOBAL_LOG_A_LOT; /** * Polyfill WebSocket in Node.js environment if not natively present. */ async function ensureWebSocketSupport(): Promise { if (typeof (globalThis as any).WebSocket === 'undefined') { try { const wsModule = await import('ws'); (globalThis as any).WebSocket = wsModule.default || wsModule; } catch { // Already present or in browser } } } /** * Dynamically resolves Node.js 'node:fs' module in Node environments. * Prevents static browser bundlers (esbuild) from failing when building isomorphic packages. */ async function getNodeFs(): Promise { if (typeof process !== 'undefined' && (process as any).versions?.node) { try { const fsMod = 'node:fs'; const mod = await import(fsMod); return mod.default || mod; } catch { return undefined; } } return undefined; } /** * Dynamically resolves Node.js 'node:path' module in Node environments. */ async function getNodePath(): Promise { if (typeof process !== 'undefined' && (process as any).versions?.node) { try { const pathMod = 'node:path'; const mod = await import(pathMod); return mod.default || mod; } catch { return undefined; } } return undefined; } /** * Traverses upward from startDir to locate the polycosmos root (where .vcsgib exists). */ export async function findPolycosmosRoot(startDir: string, vcsFolderName = VCS_DEFAULT_FOLDER_NAME): Promise { const fs = await getNodeFs(); const path = await getNodePath(); if (!fs || !path) { return undefined; } let current = path.resolve(startDir); while (true) { const vcsPath = path.join(current, vcsFolderName); if (fs.existsSync(vcsPath)) { return current; } const parent = path.dirname(current); if (parent === current) { return undefined; } current = parent; } } /** * Executes isomorphic VCS clone operation. */ export async function executeVcsClone({ metaspace, localSpace, remoteUrl, targetCosmosName, cwd, galaxy, vcsFolderName, senderIdentityInfo, fnSenderSecret, conflictStrategy, onProgress, }: VcsCloneOpts): Promise { const lc = `${lcFile}[${executeVcsClone.name}]`; let senderPeerCosmos: SyncPeerWebSocketSender_V1 | undefined; try { if (logalot) { console.log(`${lc} starting clone from ${remoteUrl}...`); } await ensureWebSocketSupport(); const fs = await getNodeFs(); const path = await getNodePath(); // 1. Verify polycosmos root (fail-fast: no targetDir allowed, must run inside an existing polycosmos) const workingDir = cwd ? (path ? path.resolve(cwd) : cwd) : (typeof process !== 'undefined' && process.cwd ? process.cwd() : '.'); const folderName = vcsFolderName || VCS_DEFAULT_FOLDER_NAME; const polycosmosRoot = await findPolycosmosRoot(workingDir, folderName); if (!polycosmosRoot) { throw new Error(`fatal: not an ibgib polycosmos (or any of the parent directories): ${VCS_DEFAULT_FOLDER_NAME}`); } // 2. Resolve remote URL & endpoints onProgress?.({ stage: 'resolving', message: `Resolving remote URL ${remoteUrl}...` }); const senderDomainAddr = senderIdentityInfo?.senderDomainAddr || (senderIdentityInfo?.primaryKeystone ? getIbGibAddr({ ibGib: senderIdentityInfo.primaryKeystone }) : undefined); const resolved = await resolveRemoteCosmosUrl({ remoteUrl, senderDomainAddr }); const remoteCosmosName = resolved.cosmosName; const cosmosName = targetCosmosName?.trim() || remoteCosmosName; // In Node development against localhost, tolerate self-signed certs if (typeof process !== 'undefined' && process.env && (resolved.baseUrl.includes('localhost') || resolved.baseUrl.includes('127.0.0.1'))) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; } // 3. Pre-flight checks: cosmos name uniqueness in graph and filesystem const existingCosmos = await getCosmosByName({ metaspace, space: localSpace, cosmosName }); if (existingCosmos) { throw new Error(`fatal: cosmos '${cosmosName}' already exists in local polycosmos.`); } const targetPath = path.join(polycosmosRoot, cosmosName); if (fs.existsSync(targetPath)) { const entries = fs.readdirSync(targetPath); if (entries.length > 0) { throw new Error(`fatal: destination path '${cosmosName}' already exists and is not an empty directory.`); } } // Ensure identity stones exist in localSpace if provided if (senderIdentityInfo?.primaryKeystone) { await putInSpace({ ibGib: senderIdentityInfo.primaryKeystone, space: localSpace }); } if (senderIdentityInfo?.senderIdentity) { await putInSpace({ ibGib: senderIdentityInfo.senderIdentity, space: localSpace }); } // Determine sender evolve URL: must point to sender's domain keystone so server validates // the sender's session delegate against sender's registered identity. const senderHttpEvolveUrl = senderDomainAddr ? `${resolved.baseUrl}/api/keystone/evolve/${encodeURIComponent(senderDomainAddr)}` : resolved.httpEvolveUrl; // 4. Phase 1: Pull CosmosIbGib and member galaxy manifests into localSpace onProgress?.({ stage: 'syncing_cosmos', message: `Pulling cosmos '${cosmosName}' manifest from remote...` }); const cosmosWsUrl = (senderDomainAddr && resolved.cloneWsUrl) ? resolved.cloneWsUrl : resolved.cosmosWsUrl; if (logalot) { console.log(`${lc} Phase 1 wsUrl: ${cosmosWsUrl} (senderDomainAddr: ${senderDomainAddr ?? '[undefined]'}, resolved.cloneWsUrl: ${resolved.cloneWsUrl ?? '[undefined]'}) (I: 022ad84a5dbd597be865df48a5275826)`); } senderPeerCosmos = new SyncPeerWebSocketSender_V1({ classname: 'SyncPeerWebSocketSender_V1', httpEvolveUrl: senderHttpEvolveUrl, wsUrl: cosmosWsUrl, }); const sagaIdPhase1 = await getUUID(); await senderPeerCosmos.initializeOpts({ localMetaspace: metaspace, controlSpace: localSpace, domainSpace: localSpace, senderIdentity: senderIdentityInfo?.senderIdentity, fnSenderSecret, sagaId: sagaIdPhase1, }); const coordinatorPhase1 = new SyncSagaCoordinator(); const syncSagaPhase1 = await coordinatorPhase1.sync({ peer: senderPeerCosmos, mode: SyncMode.pull, domainIbGibs: [], senderIdentityInfo, fnSenderSecret, controlSpace: localSpace, domainSpace: localSpace, metaspace, targetSpaceInfo: { cosmosName, url: cosmosWsUrl, }, }); await syncSagaPhase1.done; if (senderPeerCosmos.currentSenderIdentity && senderIdentityInfo) { senderIdentityInfo.senderIdentity = senderPeerCosmos.currentSenderIdentity; } senderPeerCosmos.disconnect(); senderPeerCosmos = undefined; // Retrieve the newly synced CosmosIbGib from localSpace using the Phase 1 sync saga history let cosmos: CosmosIbGib_V1 | undefined; if (coordinatorPhase1.latestSagaFrame) { try { const sagaHistory = await getFullSyncSagaHistory({ sagaIbGib: coordinatorPhase1.latestSagaFrame, controlSpace: localSpace, }); const transferredAddrs = getTransferredPayloadAddressesFromHistory({ sagaHistory }); for (const addr of transferredAddrs) { if (addr.startsWith(`${COSMOS_ATOM} `)) { const resGet = await metaspace.get({ addrs: [addr], space: localSpace }); const candidate = resGet.ibGibs?.[0] as CosmosIbGib_V1 | undefined; if (candidate?.data?.cosmosName === cosmosName || candidate?.data?.cosmosName === remoteCosmosName) { cosmos = candidate; break; } } } } catch (histErr) { if (logalot) { console.warn(`${lc} Warning extracting cosmos from saga history: ${extractErrorMsg(histErr)}`); } } } if (!cosmos) { cosmos = await getCosmosByName({ metaspace, space: localSpace, cosmosName }); } if (!cosmos && remoteCosmosName !== cosmosName) { cosmos = await getCosmosByName({ metaspace, space: localSpace, cosmosName: remoteCosmosName }); } if (!cosmos) { const all = await getAllCosmoses({ metaspace, space: localSpace }); cosmos = all.find(c => c.data?.cosmosName === cosmosName || c.data?.cosmosName === remoteCosmosName); } if (!cosmos) { throw new Error(`Failed to retrieve cloned cosmos '${cosmosName}' from localSpace after sync`); } // Ensure latest addr try { const latestAddr = await metaspace.getLatestAddr({ ibGib: cosmos, space: localSpace }); if (latestAddr && latestAddr !== getIbGibAddr({ ibGib: cosmos })) { const resLatest = await metaspace.get({ addrs: [latestAddr], space: localSpace }); if (resLatest.ibGibs?.[0]) { cosmos = resLatest.ibGibs[0] as CosmosIbGib_V1; } } } catch (latestErr) { if (logalot) { console.warn(`${lc} Warning resolving latest cosmos addr: ${extractErrorMsg(latestErr)}`); } } // Ensure physical destination directory exists for projection if (!fs.existsSync(targetPath)) { fs.mkdirSync(targetPath, { recursive: true }); } // Populate origin remote info and register with special cosmos anchor const originInfo: CosmosRemoteInfo = { remoteUrl, domainAddr: resolved.domainAddr, cosmosName, }; const resMut8 = await mut8({ src: cosmos, dataToAddOrPatch: { origin: originInfo }, dna: true, nCounter: true, }); cosmos = resMut8.newIbGib as CosmosIbGib_V1; await metaspace.persistTransformResult({ resTransform: resMut8, space: localSpace }); await metaspace.registerNewIbGib({ ibGib: cosmos, space: localSpace }); await metaspace.getSpecialIbGib({ type: COSMOS_ATOM, initialize: true, space: localSpace }); await metaspace.rel8ToSpecialIbGib({ type: COSMOS_ATOM, rel8nName: COSMOS_REL8N_NAME, ibGibsToRel8: [cosmos], space: localSpace, linked: true, }); // Register member galaxies with special galaxy anchor in localSpace const initialGalaxies = getGalaxiesFromCosmos(cosmos); for (const gEntry of initialGalaxies) { if (gEntry.galaxyAddr) { const gIbGib = await getB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyAddr: gEntry.galaxyAddr, }) || await getIbGibFromSpace({ addr: gEntry.galaxyAddr, space: localSpace }); if (gIbGib) { await metaspace.getSpecialIbGib({ type: B2TFS_GALAXY_ATOM, initialize: true, space: localSpace }); await metaspace.rel8ToSpecialIbGib({ type: B2TFS_GALAXY_ATOM, rel8nName: B2TFS_GALAXY_REL8N_NAME, ibGibsToRel8: [gIbGib], space: localSpace, linked: true, }); } } } // 5. Phase 2: Filter member galaxies based on --galaxy flag const galaxyFilter = (galaxy ?? 'root').trim(); const allGalaxies = getGalaxiesFromCosmos(cosmos); let selectedGalaxies = allGalaxies; if (galaxyFilter === 'none') { selectedGalaxies = []; } else if (galaxyFilter === 'all') { selectedGalaxies = allGalaxies; } else if (galaxyFilter === 'root') { selectedGalaxies = allGalaxies.filter(g => !g.slice?.rootPath || g.slice.rootPath === '.' || g.slice.rootPath === './'); } else { const targetNames = galaxyFilter.split(',').map(s => s.trim().toLowerCase()).filter(Boolean); const knownGalaxyNames = allGalaxies.map(g => g.galaxyName.toLowerCase()); for (const name of targetNames) { if (!knownGalaxyNames.includes(name)) { throw new Error(`Galaxy '${name}' not found in cosmos '${cosmosName}' (available: ${allGalaxies.map(g => g.galaxyName).join(', ') || '[none]'}) (E: 7c2a4e9b8f1d4365)`); } } selectedGalaxies = allGalaxies.filter(g => targetNames.includes(g.galaxyName.toLowerCase())); } const clonedGalaxies: VcsCloneResult['clonedGalaxies'] = []; // 6. Pull and materialize each selected galaxy for (const galaxyEntry of selectedGalaxies) { onProgress?.({ stage: 'syncing_galaxy', message: `Syncing galaxy '${galaxyEntry.galaxyName}'...` }); // Determine default branch and inspect branch info for spaceId let defaultBranch = B2TFS_BRANCH_DEFAULT_NAME; let targetBranchAddrs: string[] | undefined; let expectedBranchSpaceId: string | undefined; if (galaxyEntry.galaxyAddr) { const galaxyIbGib = await getB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyAddr: galaxyEntry.galaxyAddr, }) || await getIbGibFromSpace({ addr: galaxyEntry.galaxyAddr, space: localSpace }); if (galaxyIbGib?.data) { defaultBranch = (galaxyIbGib.data as any).policy?.defaultBranch ?? (galaxyIbGib.data as any).defaultBranch ?? B2TFS_BRANCH_DEFAULT_NAME; } if (galaxyIbGib) { try { const branchInfo = await getBranchInfoFromGalaxy({ galaxyIbGib: galaxyIbGib as any, branchName: defaultBranch, metaspace, }); if (branchInfo?.branchAddr) { targetBranchAddrs = [branchInfo.branchAddr]; } if (branchInfo?.branchSqAddrInfo?.spaceId) { expectedBranchSpaceId = branchInfo.branchSqAddrInfo.spaceId; } } catch { // fallback } } } // Ensure local dedicated branch space matching the branch's canonical spaceId const { space: branchSpace } = await getOrCreateBranchSpace({ metaspace, branchName: defaultBranch, galaxyName: galaxyEntry.galaxyName, cosmosName, spaceId: expectedBranchSpaceId, }); // WebSocket endpoint for this branch - queries remoteCosmosName on server const branchWsUrl = senderDomainAddr ? buildCloneWsUrl({ wsBaseUrl: resolved.wsBaseUrl, senderDomainAddr, targetDomainAddr: resolved.domainAddr, cosmosName: remoteCosmosName, galaxyName: galaxyEntry.galaxyName, branchName: defaultBranch, }) : `${resolved.wsBaseUrl}/api/sync/ws/${encodeURIComponent(resolved.domainAddr)}/${encodeURIComponent(remoteCosmosName)}/${encodeURIComponent(galaxyEntry.galaxyName)}/${encodeURIComponent(defaultBranch)}`; if (logalot) { console.log(`${lc} Phase 2 wsUrl: ${branchWsUrl} (galaxy: ${galaxyEntry.galaxyName}, branch: ${defaultBranch}, targetBranchAddrs: ${targetBranchAddrs?.join(',') ?? '[undefined]'}) (I: 21fda8119b33cfbac8dba768e3447826)`); } const branchPeer = new SyncPeerWebSocketSender_V1({ classname: 'SyncPeerWebSocketSender_V1', httpEvolveUrl: senderHttpEvolveUrl, wsUrl: branchWsUrl, destinationSpaceCoords: { cosmosName: remoteCosmosName, galaxyName: galaxyEntry.galaxyName, branchName: defaultBranch, }, }); const sagaIdPhase2 = await getUUID(); await branchPeer.initializeOpts({ localMetaspace: metaspace, controlSpace: localSpace, domainSpace: branchSpace, senderIdentity: senderIdentityInfo?.senderIdentity, fnSenderSecret, sagaId: sagaIdPhase2, targetAddrs: targetBranchAddrs, destinationSpaceCoords: { cosmosName: remoteCosmosName, galaxyName: galaxyEntry.galaxyName, branchName: defaultBranch, }, }); const branchCoordinator = new SyncSagaCoordinator(); const branchSaga = await branchCoordinator.sync({ peer: branchPeer, mode: SyncMode.pull, domainIbGibs: [], senderIdentityInfo, fnSenderSecret, controlSpace: localSpace, domainSpace: branchSpace, metaspace, targetSpaceInfo: { cosmosName: remoteCosmosName, galaxyName: galaxyEntry.galaxyName, branchName: defaultBranch, url: branchWsUrl, }, }); await branchSaga.done; if (branchCoordinator.latestSagaFrame) { const sagaHistoryPhase2 = await getFullSyncSagaHistory({ sagaIbGib: branchCoordinator.latestSagaFrame, controlSpace: localSpace }); const transferredPhase2 = getTransferredPayloadAddressesFromHistory({ sagaHistory: sagaHistoryPhase2 }); if (logalot) { console.log(`${lc} Phase 2 sync completed: transferredAddrs count = ${transferredPhase2.length}, addrs = [${transferredPhase2.join(', ')}] (I: 3a9d5e1b7c2f4860)`); } } if (branchPeer.currentSenderIdentity && senderIdentityInfo) { senderIdentityInfo.senderIdentity = branchPeer.currentSenderIdentity; } branchPeer.disconnect(); // 7. Phase 3: Project snapshot item tree onto disk const sliceRoot = galaxyEntry.slice?.rootPath && galaxyEntry.slice.rootPath !== '.' && galaxyEntry.slice.rootPath !== './' ? galaxyEntry.slice.rootPath : ''; const worktreePath = sliceRoot ? path.join(targetPath, sliceRoot) : targetPath; fs.mkdirSync(worktreePath, { recursive: true }); let projectedFilesCount = 0; if (galaxyEntry.galaxyAddr) { const galaxyIbGib = await getB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyAddr: galaxyEntry.galaxyAddr, }) || await getIbGibFromSpace({ addr: galaxyEntry.galaxyAddr, space: localSpace }); if (galaxyIbGib) { try { const branchInfo = await getBranchInfoFromGalaxy({ galaxyIbGib: galaxyIbGib as any, branchName: defaultBranch, metaspace, }); const latestBranchAddr = await metaspace.getLatestAddr({ addr: branchInfo.branchAddr, space: branchSpace }) || branchInfo.branchAddr; const branchIbGib = await getIbGibFromSpace({ addr: latestBranchAddr, space: branchSpace }); if (logalot) { console.log(`${lc} Phase 3 projecting: latestBranchAddr=${latestBranchAddr}, hasBranchIbGib=${!!branchIbGib}, snapshotAddrs=${JSON.stringify(branchIbGib?.data?.['@snapshot'] ?? [])} (I: 4f8a2c1e7b9d4350)`); } if (branchIbGib) { // Update local member galaxy to point its trunk and $@branch to the synced latestBranchAddr const branchSpaceId = getSpaceIdFromIb(branchSpace.ib); const updatedBranchSqAddr = getSpaceQualifiedIbGibAddr({ spaceId: branchSpaceId, ibGibAddr: latestBranchAddr, }); const updatedGalaxy = await updateB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyIbGib: galaxyIbGib as B2tFSGalaxyIbGib_V1, dataToUpdate: { trunkBranchSqAddr: updatedBranchSqAddr, '$@branch': [updatedBranchSqAddr], }, }).catch(err => { if (logalot) { console.warn(`${lc} Warning updating galaxy trunkBranchSqAddr: ${extractErrorMsg(err)}`); } return undefined; }); if (updatedGalaxy && cosmos?.data?.galaxies?.[galaxyEntry.galaxyName]) { const newGalaxyAddr = getIbGibAddr({ ibGib: updatedGalaxy }); const updatedCosmosGalaxies = { ...cosmos.data.galaxies, [galaxyEntry.galaxyName]: { ...cosmos.data.galaxies[galaxyEntry.galaxyName], galaxyAddr: newGalaxyAddr, }, }; const cosmosMut8 = await mut8({ src: cosmos, dataToAddOrPatch: { galaxies: updatedCosmosGalaxies, }, dna: true, nCounter: true, }); cosmos = cosmosMut8.newIbGib as CosmosIbGib_V1; await metaspace.persistTransformResult({ resTransform: cosmosMut8, space: localSpace }); await metaspace.registerNewIbGib({ ibGib: cosmos, space: localSpace }); } const snapshot = await getLatestBranchSnapshot({ branchIbGib, space: branchSpace }).catch(() => undefined); if (logalot) { console.log(`${lc} Phase 3 projecting snapshot: hasSnapshot=${!!snapshot}, itemsCount=${Object.keys(snapshot?.data?.items ?? {}).length} (I: 1e9b3d5a7c2f4861)`); } if (snapshot?.data?.items) { for (const [relPath, [itemAddr, binAddr]] of Object.entries(snapshot.data.items)) { const fullFilePath = path.join(worktreePath, relPath); if (binAddr) { // File item with binary stone fs.mkdirSync(path.dirname(fullFilePath), { recursive: true }); const binIbGib = await getIbGibFromSpace({ addr: binAddr, space: branchSpace }); if (logalot) { console.log(`${lc} Phase 3 projecting bin: relPath=${relPath}, binAddr=${binAddr}, hasBinIbGib=${!!binIbGib}, binDataType=${typeof binIbGib?.data} (I: 8a2f4c1e9b7d4352)`); } if (binIbGib?.data) { if (binIbGib.data instanceof Uint8Array || Buffer.isBuffer(binIbGib.data)) { fs.writeFileSync(fullFilePath, binIbGib.data); } else if (typeof binIbGib.data === 'string') { fs.writeFileSync(fullFilePath, binIbGib.data, 'utf8'); } } else { fs.writeFileSync(fullFilePath, '', 'utf8'); } projectedFilesCount++; } else { // Directory item fs.mkdirSync(fullFilePath, { recursive: true }); } } } } } catch (projErr) { console.warn(`${lc} Warning projecting galaxy files: ${extractErrorMsg(projErr)} (W: 3f7e1a9b5c2d4860)`); } } } clonedGalaxies.push({ galaxyName: galaxyEntry.galaxyName, branchName: defaultBranch, worktreePath, projectedFilesCount, }); } onProgress?.({ stage: 'completed', message: `Successfully cloned cosmos '${cosmosName}'.` }); return { success: true, remoteUrl, cosmosName, cosmosPath: targetPath, cosmosIbGib: cosmos, clonedGalaxies, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (senderPeerCosmos) { senderPeerCosmos.disconnect(); } } } /** * Executes VCS fork operation: * 1. Clones the remote cosmos into the local polycosmos. * 2. In-place local fork: mints a new CosmosIbGib_V1 with the local user as owner, * attaches origin info to ancestor, and registers in localSpace. * Zero duplicate file copying and zero CAS object re-downloads. */ export async function executeVcsFork(opts: VcsForkOpts): Promise { const lc = `${lcFile}[${executeVcsFork.name}]`; try { if (logalot) { console.log(`${lc} starting fork for ${opts.remoteUrl}...`); } // 1. Clone into local polycosmos (using asName if provided) const forkedCosmosName = opts.asName?.trim() || (await resolveRemoteCosmosUrl({ remoteUrl: opts.remoteUrl })).cosmosName; const cloneRes = await executeVcsClone({ ...opts, targetCosmosName: forkedCosmosName, }); const clonedCosmos = cloneRes.cosmosIbGib; // 2. Resolve owner keystone TJP for new forked cosmos const bobPrimaryTjp = opts.senderIdentityInfo?.primaryKeystone ? getIbGibAddr({ ibGib: opts.senderIdentityInfo.primaryKeystone }) : getOwnerKeystoneTjp(clonedCosmos); // 3. Mint new Genesis CosmosIbGib for the forked identity const forkedGenesis = await createCosmosIbGib({ cosmosName: forkedCosmosName, description: clonedCosmos.data?.description, ownerKeystoneTjp: bobPrimaryTjp, space: opts.localSpace, metaspace: opts.metaspace, }); // 4. Attach cloned member galaxies and set ancestor pointer const ancestorInfo: CosmosRemoteInfo = { remoteUrl: opts.remoteUrl, domainAddr: clonedCosmos.data?.origin?.domainAddr || '', cosmosName: cloneRes.cosmosName, }; const resMut8 = await mut8({ src: forkedGenesis, dataToAddOrPatch: { '@galaxy': clonedCosmos.data['@galaxy'] || [], galaxies: clonedCosmos.data.galaxies || {}, layers: clonedCosmos.data.layers || [], ancestor: ancestorInfo, origin: undefined, }, dna: true, nCounter: true, }); const finalForkedCosmos = resMut8.newIbGib as CosmosIbGib_V1; await opts.metaspace.persistTransformResult({ resTransform: resMut8, space: opts.localSpace }); await opts.metaspace.registerNewIbGib({ ibGib: finalForkedCosmos, space: opts.localSpace }); await opts.metaspace.rel8ToSpecialIbGib({ type: COSMOS_ATOM, rel8nName: COSMOS_REL8N_NAME, ibGibsToRel8: [finalForkedCosmos], space: opts.localSpace, linked: true, }); if (logalot) { console.log(`${lc} Fork complete for '${forkedCosmosName}' (addr: ${getIbGibAddr({ ibGib: finalForkedCosmos })})`); } return { ...cloneRes, cosmosName: forkedCosmosName, cosmosIbGib: finalForkedCosmos, forkedCosmosIbGib: finalForkedCosmos, ancestor: ancestorInfo, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } }