/** * @module add-cmd * * Isomorphic execution engine for `vcs add `. * Stages files into candidate B2tFSItemIbGib_V1 and BinIbGib_V1 nodes * and updates in-band B2tFSGalaxyIbGib_V1. */ import { extractErrorMsg, hash } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { joinPaths } from '@ibgib/helper-gib/dist/helpers/path-helper.mjs'; import { getGib } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs'; import { getIbGibAddr, getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs'; import { TransformResult } from '@ibgib/ts-gib/dist/types.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { BinIbGib_V1 } from '../../../common/bin/bin-types.mjs'; import { putInSpace, persistTransformResult } from '../../../witness/space/space-helper.mjs'; import { CMD_MODIFIER_WORKSPACE_SCAN } from '../../../witness/space/workspace-projection-space/workspace-projection-space-constants.mjs'; import { WorkspaceScanResultData } from '../../../witness/space/workspace-projection-space/workspace-projection-space-types.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../item/item-types.mjs'; import { createB2tFSItemIbGib, evolveB2tFSItemIbGib, getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib, getProjectedItemFilename, } from '../item/item-helpers.mjs'; import { globToRegExp } from '../filter/glob-helpers.mjs'; import { updateB2tFSGalaxyIbGib, normalizeRepoRelPath, } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { B2tFSStagedItemRecord } from '../b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { VcsAddOpts, VcsAddResult } from './command-types.mjs'; import { getIbGibFromSpace } from '../../../common/other/ibgib-helper.mjs'; import { resolveContextualBranchName } from '../branch/branch-helpers.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { getLatestBranchSnapshot } from '../snapshot/snapshot-helpers.mjs'; import { isPackageGalaxyIbGib, stagePackageReleaseItem } from '../../package-galaxy/package-timeline-helpers.mjs'; import { tryResolvePackageVersion, comparePackageVersions } from '../../package-galaxy/version-parser/version-parser-resolver.mjs'; import { PackageVersionInfo } from '../../package-galaxy/version-parser/version-parser-types.mjs'; const lcFile = `[add-cmd]`; const logalot = GLOBAL_LOG_A_LOT; export async function executeVcsAdd({ metaspace, localSpace, branchName: explicitBranchName, activeBranchSpace: givenActiveBranchSpace, branchSpace: givenBranchSpace, workspaceSpace, galaxyIbGib, paths = [], all = false, b2tfsGalaxyRoot, targetDir = b2tfsGalaxyRoot, vcsFolderName = '.vcsgib', }: VcsAddOpts): Promise { const lc = `${lcFile}[${executeVcsAdd.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: d6173882c2b3e92748569c165050a826)`); } // 1. Scan workspace space let physicalFilesMap = new Map(); const scanRes = await workspaceSpace.witness({ data: { cmd: 'get', cmdModifiers: [CMD_MODIFIER_WORKSPACE_SCAN], }, }); const scanData = (scanRes?.data as any)?.scanResult as WorkspaceScanResultData; if (scanData?.files) { physicalFilesMap = scanData.files; } if (!b2tfsGalaxyRoot) { throw new Error(`b2tfsGalaxyRoot required for executeVcsAdd (E: e934e81561a84f3c9217646a78248826)`); } // 2. Walk active branch graph items to find committed files in snapshot const activeBranchName = explicitBranchName || resolveContextualBranchName({ targetDir: targetDir || b2tfsGalaxyRoot, b2tfsGalaxyRoot, galaxyIbGib, }); const { branchIbGib, branchSpace: resolvedBranchSpace, rootItemIbGib_latest: rootItem, } = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName: activeBranchName, metaspace, }); const activeBranchSpace = givenBranchSpace || givenActiveBranchSpace || resolvedBranchSpace; if (!activeBranchSpace) { throw new Error(`(UNEXPECTED) branchSpace falsy for branch "${activeBranchName}" (E: 4f11c1546e8280a36c9c213b853e8bc3)`); } const committedBranchItemsMap = new Map(); const currentRootItemAddr = rootItem ? getIbGibAddr({ ibGib: rootItem }) : undefined; if (branchIbGib && activeBranchSpace) { const snapshot = await getLatestBranchSnapshot({ branchIbGib, space: activeBranchSpace, }).catch(() => undefined); const snapshotRootAddr = snapshot?.data?.items?.['']?.[0]; const isSnapshotFresh = !currentRootItemAddr || snapshotRootAddr === currentRootItemAddr; if (isSnapshotFresh && snapshot?.data?.items) { for (const [relPath, [itemAddr, binAddr]] of Object.entries(snapshot.data.items)) { if (!relPath || relPath === '' || relPath === '.') { continue; } if (binAddr) { const { ib } = getIbAndGib({ ibGibAddr: binAddr }); const fileHash = ib.startsWith('bin ') ? ib.slice(4) : undefined; committedBranchItemsMap.set(relPath, { relPath, fileHash, fsType: 'file', itemAddr, }); } else { const item = await getIbGibFromSpace({ addr: itemAddr, space: activeBranchSpace, }).catch(() => undefined); const fsType = item?.data?.fsType ?? 'folder'; committedBranchItemsMap.set(relPath, { relPath, fileHash: item?.data?.fileHash, fsType, item, itemAddr, }); } } } } if (committedBranchItemsMap.size === 0 && rootItem) { await addCmd_walkBranchGraph({ item: rootItem, space: activeBranchSpace, metaspace, currentRelPath: '', outMap: committedBranchItemsMap, }); } // 3. Determine candidate relative file paths to stage const targetRelPaths: string[] = []; const activeWorktreeDir = activeBranchName === B2TFS_BRANCH_DEFAULT_NAME ? b2tfsGalaxyRoot : `${b2tfsGalaxyRoot}/b/${activeBranchName}`; const isDotOrEmpty = (x?: string) => !x || x === '.' || x === './' || x === '.\\'; if (all || paths.length === 0 || (paths.length === 1 && isDotOrEmpty(paths[0]))) { // Stage all existing physical files for (const [relPath, info] of physicalFilesMap.entries()) { if (!info.isDirectory) { targetRelPaths.push(relPath); } } // Stage all deleted files that were committed in branch for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath)) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } } } else { for (const p of paths) { const normalized = normalizeRepoRelPath(p, targetDir, activeWorktreeDir); if (!normalized) { // Stage all existing physical files for (const [relPath, info] of physicalFilesMap.entries()) { if (!info.isDirectory && !targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath)) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } } continue; } if (normalized.includes('*') || normalized.includes('?')) { const rx = globToRegExp(normalized); let matchedCount = 0; for (const [relPath, info] of physicalFilesMap.entries()) { if (!info.isDirectory) { const pathBasename = relPath.split('/').pop() || relPath; if (rx.test(relPath) || rx.test(pathBasename)) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } matchedCount++; } } } for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath)) { const pathBasename = relPath.split('/').pop() || relPath; if (rx.test(relPath) || rx.test(pathBasename)) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } matchedCount++; } } } if (matchedCount === 0) { throw new Error(`No files matched glob pattern: ${p} (E: b4f9586075918649820246a804c8be26)`); } } else { const exactMatch = physicalFilesMap.get(normalized); const committedMatch = committedBranchItemsMap.get(normalized); if (exactMatch) { if (exactMatch.isDirectory) { for (const [relPath, info] of physicalFilesMap.entries()) { if (!info.isDirectory && (relPath === normalized || relPath.startsWith(normalized + '/'))) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } } // Also include any committed files under this folder that were deleted on disk for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath) && (relPath === normalized || relPath.startsWith(normalized + '/'))) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } } } else { if (!targetRelPaths.includes(normalized)) { targetRelPaths.push(normalized); } } } else if (committedMatch) { // Path was deleted from physical disk, but exists in committed branch if (committedMatch.fsType === 'folder') { for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath) && (relPath === normalized || relPath.startsWith(normalized + '/'))) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } } } } else { if (!targetRelPaths.includes(normalized)) { targetRelPaths.push(normalized); } } } else { // Check if directory prefix in physical files OR committed files let dirMatchCount = 0; for (const [relPath, info] of physicalFilesMap.entries()) { if (!info.isDirectory && relPath.startsWith(normalized + '/')) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } dirMatchCount++; } } for (const [relPath, info] of committedBranchItemsMap.entries()) { if (info.fsType === 'file' && !physicalFilesMap.has(relPath) && relPath.startsWith(normalized + '/')) { if (!targetRelPaths.includes(relPath)) { targetRelPaths.push(relPath); } dirMatchCount++; } } if (dirMatchCount === 0) { throw new Error(`Path does not exist: ${p} (E: 10c11d12e13f14a15b16c17d18e19f20)`); } } } } } const stagedItemAddrs: string[] = [...(galaxyIbGib.data?.staged_item || [])]; const stagedPathsMap: { [relPath: string]: B2tFSStagedItemRecord } = { ...(galaxyIbGib.data?.stagedPaths || {}) }; const newlyStagedPaths: string[] = []; const isPkgGalaxy = isPackageGalaxyIbGib(galaxyIbGib); const handledByPackageTimeline = new Set(); if (isPkgGalaxy) { // Map existing committed package items by (dirPrefix + packageName) -> { relPath, info } const committedPkgMap = new Map(); for (const [cRelPath, cInfo] of committedBranchItemsMap.entries()) { if (cInfo.fsType !== 'file') { continue; } const slashIdx = cRelPath.lastIndexOf('/'); const dirPrefix = slashIdx >= 0 ? cRelPath.slice(0, slashIdx + 1) : ''; const cFileName = slashIdx >= 0 ? cRelPath.slice(slashIdx + 1) : cRelPath; const parsed = tryResolvePackageVersion({ filename: cFileName }); if (parsed) { const pkgKey = `${dirPrefix}${parsed.packageName}`; const existing = committedPkgMap.get(pkgKey); if (!existing) { committedPkgMap.set(pkgKey, { relPath: cRelPath, info: cInfo }); } else { const prevFileName = existing.relPath.split('/').pop() || existing.relPath; const prevParsed = tryResolvePackageVersion({ filename: prevFileName }); if (prevParsed && comparePackageVersions(prevParsed.version, parsed.version) < 0) { committedPkgMap.set(pkgKey, { relPath: cRelPath, info: cInfo }); } } } } // Group physical candidate files that match a versioned package convention by (dirPrefix + packageName) const candidateGroups = new Map>(); for (const relPath of targetRelPaths) { const physInfo = physicalFilesMap.get(relPath); if (!physInfo || physInfo.isDirectory) { continue; } const slashIdx = relPath.lastIndexOf('/'); const dirPrefix = slashIdx >= 0 ? relPath.slice(0, slashIdx + 1) : ''; const fileName = slashIdx >= 0 ? relPath.slice(slashIdx + 1) : relPath; const parsed = tryResolvePackageVersion({ filename: fileName }); if (parsed) { const pkgKey = `${dirPrefix}${parsed.packageName}`; const list = candidateGroups.get(pkgKey) || []; list.push({ relPath, fileName, parsed }); candidateGroups.set(pkgKey, list); handledByPackageTimeline.add(relPath); } } for (const [pkgKey, candidates] of candidateGroups.entries()) { candidates.sort((a, b) => comparePackageVersions(a.parsed.version, b.parsed.version)); const committedPkg = committedPkgMap.get(pkgKey); // If a newer version is replacing an older committed filename, suppress raw deletion staging of the old filename if (committedPkg) { handledByPackageTimeline.add(committedPkg.relPath); } let currentExistingItem: B2tFSItemIbGib_V1 | undefined = committedPkg?.info.item; if (!currentExistingItem && committedPkg?.info.itemAddr) { currentExistingItem = await getIbGibFromSpace({ addr: committedPkg.info.itemAddr, space: activeBranchSpace, }); } // Also check if an item for this package was already staged in a prior `vcs add` before commit if (!currentExistingItem) { const slashIdx = pkgKey.lastIndexOf('/'); const dirPrefix = slashIdx >= 0 ? pkgKey.slice(0, slashIdx + 1) : ''; const pkgNameOnly = slashIdx >= 0 ? pkgKey.slice(slashIdx + 1) : pkgKey; for (const [stPath, stRec] of Object.entries(stagedPathsMap)) { if (stRec.isDeleted || !stRec.itemAddr) { continue; } const stSlash = stPath.lastIndexOf('/'); const stDir = stSlash >= 0 ? stPath.slice(0, stSlash + 1) : ''; const stFile = stSlash >= 0 ? stPath.slice(stSlash + 1) : stPath; const stParsed = tryResolvePackageVersion({ filename: stFile }); if (stDir === dirPrefix && stParsed?.packageName === pkgNameOnly) { currentExistingItem = await getIbGibFromSpace({ addr: stRec.itemAddr, space: activeBranchSpace, }); if (stPath !== candidates[candidates.length - 1].relPath) { delete stagedPathsMap[stPath]; } break; } } } let lastIngestRes: Awaited> | undefined; let anyChanged = false; for (const cand of candidates) { const fileGetRes = await workspaceSpace.witness({ data: { cmd: 'get', ibGibAddrs: [cand.relPath], }, }); const binIbGib = fileGetRes?.ibGibs?.find((x: any) => !(!x)) as BinIbGib_V1 | undefined; if (!binIbGib || !binIbGib.data) { throw new Error(`Failed to load file data for '${cand.relPath}' from workspace space (E: 8a67b120f2694b6ca5610ec1f2e34567)`); } const binData = binIbGib.data instanceof Uint8Array ? binIbGib.data : new Uint8Array(binIbGib.data as any); const ingestRes = await stagePackageReleaseItem({ space: activeBranchSpace, metaspace, fileBytes: binData, filename: cand.fileName, existingItem: currentExistingItem, }); currentExistingItem = ingestRes.item; lastIngestRes = ingestRes; if (ingestRes.action !== 'unchanged') { anyChanged = true; } } const winningCandidate = candidates[candidates.length - 1]; if (lastIngestRes && (anyChanged || (committedPkg && committedPkg.relPath !== winningCandidate.relPath))) { if (!stagedItemAddrs.includes(lastIngestRes.itemAddr)) { stagedItemAddrs.push(lastIngestRes.itemAddr); } stagedPathsMap[winningCandidate.relPath] = { itemAddr: lastIngestRes.itemAddr, binAddr: lastIngestRes.binAddr, fileHash: lastIngestRes.fileHash, fsType: 'file', stagedAt: new Date().toISOString(), }; newlyStagedPaths.push(winningCandidate.relPath); // Mark any superseded committed filename as deleted so the tree & disk only keep the latest version if (committedPkg && committedPkg.relPath !== winningCandidate.relPath) { stagedPathsMap[committedPkg.relPath] = { previousItemAddr: committedPkg.info.itemAddr, fsType: 'file', stagedAt: new Date().toISOString(), isDeleted: true, }; } // Mark any intermediate physical version files in the same batch as deleted so commit unlinks them from disk for (let i = 0; i < candidates.length - 1; i++) { const olderCand = candidates[i]; if (olderCand.relPath !== winningCandidate.relPath) { stagedPathsMap[olderCand.relPath] = { fsType: 'file', stagedAt: new Date().toISOString(), isDeleted: true, }; } } } } } for (const relPath of targetRelPaths) { if (handledByPackageTimeline.has(relPath)) { continue; } const physInfo = physicalFilesMap.get(relPath); const committedItem = committedBranchItemsMap.get(relPath); // Handle staged deletion if (!physInfo && committedItem) { const prevAddr = committedItem.item ? getIbGibAddr({ ibGib: committedItem.item }) : undefined; stagedPathsMap[relPath] = { previousItemAddr: prevAddr, fsType: committedItem.fsType, stagedAt: new Date().toISOString(), isDeleted: true, }; newlyStagedPaths.push(relPath); continue; } let fileHash = physInfo?.fileHash; let binData: Uint8Array | undefined; // Fetch binary data from workspace space const fileGetRes = await workspaceSpace.witness({ data: { cmd: 'get', ibGibAddrs: [relPath], }, }); const binIbGib = fileGetRes?.ibGibs?.find(x => !(!x)) as BinIbGib_V1 | undefined; if (!binIbGib || !binIbGib.data) { throw new Error(`Failed to load file data for '${relPath}' from workspace space (E: 8a67b120f2694b6ca5610ec1f2e34567)`); } binData = binIbGib.data instanceof Uint8Array ? binIbGib.data : new Uint8Array(binIbGib.data as any); if (!fileHash) { const hashBuf = await crypto.subtle.digest('SHA-256', binData.buffer as ArrayBuffer); fileHash = Array.from(new Uint8Array(hashBuf)).map(b => b.toString(16).padStart(2, '0')).join(''); } // Skip staging if candidate file matches active branch committed snapshot if (committedItem && committedItem.fileHash && committedItem.fileHash === fileHash) { continue; } // 1. Create/put BinIbGib_V1 in activeSpace const binIb = `bin ${fileHash}`; const binGib = await getGib({ ibGib: { ib: binIb, data: binData as any } }); const binNode: BinIbGib_V1 = { ib: binIb, gib: binGib, data: binData as any, }; const binAddr = getIbGibAddr({ ibGib: binNode }); await putInSpace({ ibGib: binNode, space: activeBranchSpace }); await metaspace.registerNewIbGib({ ibGib: binNode, space: activeBranchSpace }); // 2. Create or Evolve B2tFSItemIbGib_V1 candidate graph node const fileName = relPath.split('/').pop() || relPath; const nameHash = await hash({ s: fileName }); let itemRes: TransformResult; if (committedItem && !committedItem.item && committedItem.itemAddr) { committedItem.item = await getIbGibFromSpace({ addr: committedItem.itemAddr, space: activeBranchSpace, }); } if (committedItem && committedItem.item) { itemRes = await evolveB2tFSItemIbGib({ existingItem: committedItem.item, dataToUpdate: { fileHash, }, rel8nsToUpdate: { bin: [binAddr], }, }); } else { itemRes = await createB2tFSItemIbGib({ fsType: 'file', name: fileName, data: { nameHash, fileHash, fileEncoding: 'utf8', }, rel8ns: { bin: [binAddr], }, }); } const itemIbGib = itemRes.newIbGib as B2tFSItemIbGib_V1; const itemAddr = getIbGibAddr({ ibGib: itemIbGib }); await persistTransformResult({ resTransform: itemRes, space: activeBranchSpace }); await metaspace.registerNewIbGib({ ibGib: itemIbGib, space: activeBranchSpace }); if (!stagedItemAddrs.includes(itemAddr)) { stagedItemAddrs.push(itemAddr); } stagedPathsMap[relPath] = { itemAddr, binAddr, fileHash, fsType: 'file', stagedAt: new Date().toISOString(), }; newlyStagedPaths.push(relPath); } // 3. Update B2tFSGalaxyIbGib_V1 in localSpace if (!localSpace) { throw new Error(`localSpace is required to update repository galaxy (E: 99ea3cac6d28432c4fa9dbf84e680826)`); } const updatedGalaxy = await updateB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyIbGib, dataToUpdate: { stagedPaths: stagedPathsMap, staged_item: stagedItemAddrs, }, }); return { stagedPaths: newlyStagedPaths, stagedCount: newlyStagedPaths.length, updatedGalaxy, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 82708be03354a87ad499f6536eb55a26)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: f5cfeba2cbe8e5a76e617348895bd326)`); } } } async function addCmd_walkBranchGraph({ item, space, metaspace, currentRelPath, outMap, }: { item: B2tFSItemIbGib_V1; space: any; metaspace?: any; currentRelPath: string; outMap: Map; }): Promise { if (!item || !item.data) { return; } const { fsType, fileHash } = item.data; if (currentRelPath) { outMap.set(currentRelPath, { relPath: currentRelPath, fileHash, fsType, item }); } if (fsType === 'folder') { const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; for (const childAddr of childAddrs) { const childItem = await getIbGibFromSpace({ addr: childAddr, space, metaspace, }); if (childItem && childItem.data) { const childName = getProjectedItemFilename(childItem) || childItem.data.name; const childRelPath = currentRelPath ? joinPaths(currentRelPath, childName) : childName; await addCmd_walkBranchGraph({ item: childItem, space, metaspace, currentRelPath: childRelPath, outMap, }); } else { console.warn(`${lcFile}[${addCmd_walkBranchGraph.name}] child item '${childAddr}' could not be loaded from space during add branch graph walk (W: 4f7c19a024ef11eebe560242ac120002)`); } } } }