/** * @module item-helper * * B2tFS Item Helper functions: graph diff generation, filesystem projection materialization, * and two-pass transform application. */ import { extractErrorMsg, getUUID, hash } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs'; import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs'; import { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { TransformResult, IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { getIbGibFromSpace, getIbGibsFromSpace, getTjpAddr, isIbGib, getSpaceQualifiedIbGibAddr } from '../../../common/other/ibgib-helper.mjs'; import { persistTransformResult, putInSpace } from '../../../witness/space/space-helper.mjs'; import { reifyDependencyGraph } from '../../../common/other/graph-helper.mjs'; import { BinIbGib_V1 } from '../../../common/bin/bin-types.mjs'; import { createBinIbGib } from '../../../common/bin/bin-helpers.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { B2TFS_ITEM_ATOM, getB2tFSItemIb } from './item-atom-helpers.mjs'; import { B2tFSItemIbGib_V1, B2tFSItemData_V1, B2tFSItemRel8ns_V1, B2TFS_CHILD_ITEM_REL8N_NAME, BINARY_REL8N_NAME, B2tFSItemDiffInfo, BranchAndRootItemInfosAndIbGibsAndSpace, } from './item-types.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { B2tFSGalaxyIbGib_V1 } from '../b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { updateB2tFSGalaxyIbGib } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { getBranchInfoFromGalaxy, evolveB2tFSBranchIbGib } from '../branch/branch-helpers.mjs'; import { CommentIbGib_V1 } from '../../../common/comment/comment-types.mjs'; import { createCommentIbGib } from '../../../common/comment/comment-helper.mjs'; const logalot = GLOBAL_LOG_A_LOT; const lcFile = `[item-helpers]`; export function isB2tFSItemIbGib(x: any): x is B2tFSItemIbGib_V1 { if (!x) { return false; } if (!isIbGib(x)) { return false; } return x.ib.startsWith(B2TFS_ITEM_ATOM) || x.data?.classname === 'B2tFSItemIbGib_V1'; } export interface CreateB2tFSItemIbGibOpts { fsType: 'file' | 'folder'; name: string; data?: Partial; rel8ns?: Partial; } export interface EvolveB2tFSItemIbGibOpts { existingItem: B2tFSItemIbGib_V1; dataToUpdate?: Partial; rel8nsToUpdate?: Partial; rel8nsToRemove?: Partial; } /** * Creates a brand-new B2tFSItemIbGib_V1 node using Factory_V1.firstGen with TJP, DNA, and nCounter. * Used ONLY for brand-new files or folders. */ export async function createB2tFSItemIbGib({ fsType, name, data, rel8ns, }: CreateB2tFSItemIbGibOpts): Promise> { const lc = `${lcFile}[${createB2tFSItemIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 9f7d189b5bbb4ad5a819c568ce0d7826)`); } if (!fsType || !name) { throw new Error(`fsType and name are required (E: 488874f761040744a89ef772af873826)`); } const nameHash = data?.nameHash || (await hash({ s: name })); const uuid = data?.uuid || (await getUUID()); const diffTransactionId = data?.diffTransactionId || (await getUUID()); let fileNameSansExt: string | undefined; let fileExt: string | undefined; if (fsType === 'file') { const lastDot = name.lastIndexOf('.'); if (lastDot > 0) { fileNameSansExt = name.slice(0, lastDot); fileExt = name.slice(lastDot + 1); } else { fileNameSansExt = name; fileExt = ''; } } const itemData: B2tFSItemData_V1 = { name, nameHash, fsType, diffTransactionId, uuid, classname: 'B2tFSItemIbGib_V1', ...(fsType === 'file' ? { fileNameSansExt, fileExt } : {}), ...data, }; const ib = getB2tFSItemIb(fsType, name, nameHash); const res = await Factory_V1.firstGen({ parentIbGib: Factory_V1.primitive({ ib: B2TFS_ITEM_ATOM }), ib, data: itemData, rel8ns: rel8ns as any, tjp: { timestamp: true, uuid: true }, dna: true, nCounter: true, }); if (logalot) { console.log(`${lc} Created new B2tFSItemIbGib: ${res.newIbGib.ib}^${res.newIbGib.gib} (I: aaf52cddf678c29a25875843cf2fd826)`); } return res; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: edcfc8414233fa9b6658558808c6a826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 4927283a2dd82bc9abc4af0be0f2b826)`); } } } /** * Evolves an existing B2tFSItemIbGib_V1 node using mut8 (for data/hash updates) * and rel8 (for binary/child link updates) with DNA, nCounter, and timeline tracking. * Populates rel8ns.past and rel8ns.ancestor, preserving the item's TJP to generate * composite two-part timeline gib addresses (^). */ export async function evolveB2tFSItemIbGib({ existingItem, dataToUpdate, rel8nsToUpdate, rel8nsToRemove, }: EvolveB2tFSItemIbGibOpts): Promise> { const lc = `${lcFile}[${evolveB2tFSItemIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: d35e11bfe428b5dfe1dfb7b74602c826)`); } if (!existingItem || !existingItem.ib || !existingItem.gib) { throw new Error(`existingItem with valid ib and gib is required (E: 258048f80f954dc9786434c8dc0e8b26)`); } let currentItem: B2tFSItemIbGib_V1 = existingItem; const dnas: IbGib_V1[] = []; const intermediateIbGibs: IbGib_V1[] = []; // Ensure rel8ns.ancestor is populated if missing if (!currentItem.rel8ns?.ancestor || currentItem.rel8ns.ancestor.length === 0) { currentItem = { ...currentItem, rel8ns: { ...(currentItem.rel8ns || {}), ancestor: [`${B2TFS_ITEM_ATOM}^gib`], }, }; } const hasDataChanges = dataToUpdate && Object.keys(dataToUpdate).length > 0; const hasRel8nsChanges = (rel8nsToUpdate && Object.keys(rel8nsToUpdate).length > 0) || (rel8nsToRemove && Object.keys(rel8nsToRemove).length > 0); // If neither data nor rel8ns explicitly specified, update diffTransactionId to evolve timeline const patchData: Partial = { ...(dataToUpdate || {}), diffTransactionId: dataToUpdate?.diffTransactionId || (await getUUID()), }; // Pass 1: mut8 for data/hash updates const resMut8 = await mut8({ src: currentItem, dataToAddOrPatch: patchData, dna: true, nCounter: patchData.n ? false : true, // if we manually set data.n, turn nCounter off }); currentItem = resMut8.newIbGib as B2tFSItemIbGib_V1; if (resMut8.dnas) { dnas.push(...resMut8.dnas); } // Pass 2: rel8 for binary/child link updates if rel8ns specified if (hasRel8nsChanges) { intermediateIbGibs.push(currentItem); const resRel8 = await rel8({ src: currentItem, rel8nsToAddByAddr: rel8nsToUpdate as any, rel8nsToRemoveByAddr: rel8nsToRemove as any, // B2tFS file items represent point-in-time filesystem entries pointing to a single content stone. // We designate BINARY_REL8N_NAME as a linked relation so rel8 automatically preserves only the latest // binary stone address ([bin.at(-1)]) instead of accumulating all historical versions on the item stone. // Historical versions remain preserved along the item's timeline via rel8ns.past. linkedRel8ns: [BINARY_REL8N_NAME], dna: true, nCounter: true, }); currentItem = resRel8.newIbGib as B2tFSItemIbGib_V1; if (resRel8.dnas) { dnas.push(...resRel8.dnas); } } // Verify rel8ns.ancestor exists on evolved item if (!currentItem.rel8ns?.ancestor || currentItem.rel8ns.ancestor.length === 0) { currentItem.rel8ns = { ...(currentItem.rel8ns || {}), ancestor: [`${B2TFS_ITEM_ATOM}^gib`], }; } if (logalot) { console.log(`${lc} Evolved B2tFSItemIbGib: ${currentItem.ib}^${currentItem.gib} (I: 5a5d21af206847cde30c2728bfdb3226)`); } return { newIbGib: currentItem, intermediateIbGibs: intermediateIbGibs.length > 0 ? intermediateIbGibs : undefined, dnas: dnas.length > 0 ? dnas : undefined, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 25eae258d173872aa8cc83dc2b7e6926)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: fe33389c0ed1777ce89d3428a7419826)`); } } } /** * Projects a B2tFS item graph back onto the workspace using a WorkspaceProjectionSpace. */ export async function writeB2tFSItemToWorkspace({ item, workspaceSpace, }: { item: B2tFSItemIbGib_V1; workspaceSpace: IbGibSpaceAny; }): Promise { const lc = `${lcFile}[${writeB2tFSItemToWorkspace.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 21fba83a3c88709276c9625b5ad80b26)`); } if (!item || !item.data) { throw new Error(`Invalid B2tFS item provided (E: 32a09c81b29e4d5867198204b12541a5)`); } await putInSpace({ space: workspaceSpace, ibGib: item, }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: b444478ae603d05b5df93ecdedebd826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 397c884b1e77625c21c634cf2c787926)`); } } } /** * Projects a B2tFS item graph onto a workspace projection space. * Retained with backward-compatible signature for existing calls. */ export async function writeB2tFSItemToFS({ item, workspaceSpace, space, }: { item: B2tFSItemIbGib_V1; workspaceSpace?: IbGibSpaceAny; destPath?: string; space?: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const targetSpace = workspaceSpace || space; if (!targetSpace) { throw new Error(`workspaceSpace or space required for writeB2tFSItemToFS (E: 086978143d36022108c686681ce37826)`); } await writeB2tFSItemToWorkspace({ item, workspaceSpace: targetSpace, }); } /** * Executes two-pass application of diff transform results: * 1. Persists all child and parent transform results to space. * 2. Registers new IbGib pointers with metaspace to advance timeline tips. */ export async function applyB2tFSItemDiff({ diff, space, metaspace, }: { diff: B2tFSItemDiffInfo; space: IbGibSpaceAny; metaspace: MetaspaceService; }): Promise { const lc = `${lcFile}[${applyB2tFSItemDiff.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: f9110875f76830803873b2c8a96f5826)`); } if (diff.childDiffs && diff.childDiffs.length > 0) { for (const childDiff of diff.childDiffs) { await applyB2tFSItemDiff({ diff: childDiff, space, metaspace }); } } const results = diff.transformResults || []; for (const tr of results) { await persistTransformResult({ resTransform: tr, space }); } for (const tr of results) { if (tr.newIbGib) { await metaspace.registerNewIbGib({ ibGib: tr.newIbGib }); } } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: f37c92fc6f71f2557534a1f882122826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 1fd63c9da70c7e5e18de21982d8ba826)`); } } } // #region reifyB2tFSHierarchy export interface ReifyB2tFSHierarchyOpts { /** Root B2tFS item (folder or file). Either rootItem or rootItemAddr required. */ rootItem?: B2tFSItemIbGib_V1; /** Address of root B2tFS item. Either rootItem or rootItemAddr required. */ rootItemAddr?: IbGibAddr; /** Space containing the branch items and updated timeline tips. */ space: IbGibSpaceAny; /** Metaspace service instance for lookups and registrations. */ metaspace: MetaspaceService; } export interface ReifyB2tFSHierarchyResult { /** The reified root B2tFS item (evolved if any descendants changed, or unchanged if no descendants changed). */ reifiedRootItem: B2tFSItemIbGib_V1; /** True if one or more folder/file nodes in the hierarchy evolved to new tips. */ hasChanges: boolean; /** Map of old address -> new address for every node that evolved in this reification run. */ reifiedAddrsMap: { [oldAddr: string]: string }; /** All newly evolved and persisted intermediate/root folder items created during reification. */ evolvedItems: B2tFSItemIbGib_V1[]; } /** * Reifies a B2tFS filesystem item hierarchy (folders and files) bottom-up. * * Traverses `b2tfs_child` relationship edges. If any child timeline advanced * in `space` (e.g. during a 3-way merge or parallel commit), the parent folders * are evolved in-place using `rel8` with the updated child tip addresses. */ export async function reifyB2tFSHierarchy({ rootItem, rootItemAddr, space, metaspace, }: ReifyB2tFSHierarchyOpts): Promise { const lc = `${lcFile}[${reifyB2tFSHierarchy.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 428138d15828380a13dfff9a51944826)`); } const res = await reifyDependencyGraph({ ibGib: rootItem, ibGibAddr: rootItemAddr, onlyRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space, metaspace, }); return { reifiedRootItem: res.reifiedIbGib as B2tFSItemIbGib_V1, hasChanges: res.hasChanges, reifiedAddrsMap: res.reifiedAddrsMap, evolvedItems: res.evolvedIbGibs as B2tFSItemIbGib_V1[], }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: f4ef9c7357e883019c09e84887ad3826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 071471754e888273f8abcfe85d478826)`); } } } // #endregion reifyB2tFSHierarchy /** * gets the root item addr for the branch ({@link B2tFSBranchRel8ns_V1.b2tfs_item}). * * if {@link addrOnly}, gets the ibGib as well from {@link branchSpace} */ export async function getRootItemFromBranchIbGib({ branchIbGib, addrOnly, branchSpace, }: { /** * branch ibgib whose root item we are getting. */ branchIbGib: B2tFSBranchIbGib_V1, /** * if true, only will get the root item's addr from {@link branchIbGib}, * else will get the full {@link B2tFSItemIbGib_V1} ibgib. */ addrOnly: boolean, /** * if {@link addrOnly} is false, this is required and used for getting the * full {@link B2tFSItemIbGib_V1} ibgib. */ branchSpace?: IbGibSpaceAny, }): Promise<{ rootItemAddr: IbGibAddr, rootItemIbGib?: B2tFSItemIbGib_V1 }> { const lc = `[${getRootItemFromBranchIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 92cc9882ded8da7128efcbd8b37ec826)`); } if (!branchIbGib.rel8ns) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns falsy? (E: 433b027e958503e648a0858807b85826)`); } if (!branchIbGib.rel8ns.b2tfs_item) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? (E: c5989d7fa2f836e6781a929d76958726)`); } if (branchIbGib.rel8ns.b2tfs_item.length === 0) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? (E: 2c634c54ec485ed638eb12083ea93826)`); } const rootItemAddr = branchIbGib.rel8ns.b2tfs_item.at(-1)!; let rootItemIbGib: B2tFSItemIbGib_V1 | undefined = undefined; if (!addrOnly) { if (!branchSpace) { throw new Error(`branchSpace required when addrOnly is false. (E: 51fa687228a82f3638517c7e4b249826)`); } rootItemIbGib = await getIbGibFromSpace({ addr: rootItemAddr, space: branchSpace, }); } return { rootItemAddr, rootItemIbGib }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Goes from a galaxy ibgib all the way down to the latest root item ibgib. * * ## notes * * I usually don't do these long methods like this, but there are just so many * places where we want to get all of these things and we want to get the * latest, and this just DRYs up the code. * * @returns The Works: branch stuff, root stuff, ibgibs, and the branch space * @see {@link BranchAndRootItemInfosAndIbGibsAndSpace} */ export async function getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName, metaspace, }: { galaxyIbGib: B2tFSGalaxyIbGib_V1, branchName: string, metaspace: MetaspaceService, }): Promise { const lc = `[${getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: acae374202688beed805e578fec3ea26)`); } const branchInfo = await getBranchInfoFromGalaxy({ galaxyIbGib, branchName, metaspace, }); const galaxyName = galaxyIbGib.data?.galaxyName || galaxyIbGib.data?.name; const branchSpace = await metaspace.getLocalUserSpace({ localSpaceId: branchInfo.branchSqAddrInfo.spaceId, lock: false, galaxyName, branchName, } as any); if (!branchSpace) { throw new Error(`branchSpace not found from branchSqAddr: ${branchInfo.branchSqAddr} (E: 62dd9fb2a5b8cea6734a6038c8c6fb26)`); } const { branchAddr } = branchInfo; const branchAddr_latest = await metaspace.getLatestAddr({ addr: branchAddr, space: branchSpace }) || branchAddr; const branchIbGib = await getIbGibFromSpace({ addr: branchAddr_latest, space: branchSpace, }); if (!branchIbGib) { throw new Error(`(UNEXPECTED) branchAddr (${branchAddr_latest}) not found in branchSpace (${branchSpace.ib})? (E: 8f9a48a0d5a88c99468b121edbc51826)`); } const { rootItemAddr, rootItemIbGib } = await getRootItemFromBranchIbGib({ branchIbGib, branchSpace, addrOnly: false, }); if (!rootItemIbGib) { throw new Error(`(UNEXPECTED) rootItemIbGib falsy? (E: 883d18f3c978a919a8f298b9d6971826)`); } const rootItemAddr_latest = await metaspace.getLatestAddr({ addr: rootItemAddr, space: branchSpace }) || rootItemAddr; let rootItemIbGib_latest: B2tFSItemIbGib_V1 | undefined = rootItemIbGib; if (rootItemAddr_latest !== rootItemAddr) { rootItemIbGib_latest = await getIbGibFromSpace({ addr: rootItemAddr_latest, space: branchSpace, }); if (!rootItemIbGib_latest) { throw new Error(`(UNEXPECTED) rootItemIbGib_latest falsy? We just got rootItemAddr_latest (${rootItemAddr_latest}) from branchSpace (${branchSpace.ib}), so we should have been able to get the corresponding ibgib. (E: 86bd690fb143f0a1e80209387ff7c426)`); } } return { branchIbGib, branchInfo, branchSpace, rootItemAddr, rootItemAddr_latest, rootItemIbGib, rootItemIbGib_latest, } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Creates a virtual/non-CAS B2tFS item IbGib whose content is inlined directly * in `virtualFileContents`. * * Used primarily for scaffolding workspace artifacts (such as companion markdown * notes `.ib..md` or template files) that need to be projected onto * a workspace without creating or linking underlying CAS BinIbGibs. */ export async function createVirtualItemIbGib({ name, content, }: { /** * File path or file name relative to the workspace projection target (e.g. `src/.ib.auth.ts.md`). */ name: string; /** * Direct string contents to be written to the workspace file. */ content: string; }): Promise { const res = await createB2tFSItemIbGib({ fsType: 'file', name, data: { isVirtual: true, virtualFileContents: content, }, }); return res.newIbGib as B2tFSItemIbGib_V1; } /** * Retrieves the text content of a B2tFS file item by inspecting its binary stone or virtual payload. */ export async function getFileContent({ branchSpace, fileItem, }: { branchSpace: IbGibSpaceAny; fileItem: B2tFSItemIbGib_V1; }): Promise { const lc = `${lcFile}[${getFileContent.name}]`; try { if (fileItem.data?.isVirtual && fileItem.data?.virtualFileContents !== undefined) { return fileItem.data.virtualFileContents; } const binAddrs = fileItem.rel8ns?.[BINARY_REL8N_NAME] || []; const binAddr = binAddrs.at(-1); if (binAddr) { const binIbGib = await getIbGibFromSpace({ addr: binAddr, space: branchSpace }); if (binIbGib?.data) { if (binIbGib.data instanceof Uint8Array) { return new TextDecoder().decode(binIbGib.data); } else if (typeof binIbGib.data === 'string') { return binIbGib.data; } else if ((binIbGib.data as any)?.type === 'Buffer' && Array.isArray((binIbGib.data as any)?.data)) { return new TextDecoder().decode(new Uint8Array((binIbGib.data as any).data)); } } } return ''; } catch (err) { console.error(`${lc} Failed to get file content: ${extractErrorMsg(err)}`); return ''; } } /** * Recursively resolves a file or folder item by relative path (e.g. 'welcome.ts' or 'src/index.ts'). */ export async function getFileItemFromPath({ branchSpace, rootItem, filePath, }: { branchSpace: IbGibSpaceAny; rootItem: B2tFSItemIbGib_V1; filePath: string; }): Promise { const lc = `${lcFile}[${getFileItemFromPath.name}]`; try { const parts = filePath.split('/').filter(Boolean); if (parts.length === 0) { return rootItem; } // If rootItem is already a file (e.g. in a single-file branch), check if it matches the target file if (rootItem?.data?.fsType === 'file') { const targetFileName = parts[parts.length - 1]; if (rootItem.data?.name === targetFileName || rootItem.data?.name === filePath) { return rootItem; } return undefined; } let currentFolder: B2tFSItemIbGib_V1 = rootItem; for (let i = 0; i < parts.length; i++) { const partName = parts[i]; const childAddrs = currentFolder.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; let foundChild: B2tFSItemIbGib_V1 | undefined; for (const childAddr of childAddrs) { const childItem = await getIbGibFromSpace({ addr: childAddr, space: branchSpace }); if (childItem?.data?.name === partName) { foundChild = childItem; break; } } if (!foundChild) { return undefined; } if (i === parts.length - 1) { return foundChild; } else { currentFolder = foundChild; } } return undefined; } catch (err) { console.error(`${lc} Failed to resolve file item from path [${filePath}]: ${extractErrorMsg(err)}`); return undefined; } } /** * Lists all direct children of a folder item from the branch space using batch get. */ export async function getFolderChildren({ branchSpace, folderItem, }: { branchSpace: IbGibSpaceAny; folderItem: B2tFSItemIbGib_V1; }): Promise { const lc = `${lcFile}[${getFolderChildren.name}]`; try { const childAddrs = folderItem.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length === 0) { return []; } const children = await getIbGibsFromSpace({ addrs: childAddrs, space: branchSpace, }); const validChildren = children || []; // Defensive deduplication: if multiple children share the same name, keep the latest const byName = new Map(); for (const child of validChildren) { if (child?.data?.name) { byName.set(child.data.name, child); } } return Array.from(byName.values()); } catch (err) { console.error(`${lc} Failed to get folder children: ${extractErrorMsg(err)}`); return []; } } export interface CreateFileInGalaxyBranchOpts { metaspace: MetaspaceService; branchSpace: IbGibSpaceAny; branchIbGib: B2tFSBranchIbGib_V1; parentFolderItem: B2tFSItemIbGib_V1; fileName: string; content: string; } export interface CreateFileInGalaxyBranchResult { fileItem: B2tFSItemIbGib_V1; evolvedFolder: B2tFSItemIbGib_V1; evolvedBranch: B2tFSBranchIbGib_V1; } /** * Creates a file in a B2tFS branch space, attaches it to the parent folder, * and evolves the branch pointer (a real commit). */ export async function createFileInGalaxyBranch({ metaspace, branchSpace, branchIbGib, parentFolderItem, fileName, content, }: CreateFileInGalaxyBranchOpts): Promise { const lc = `${lcFile}[${createFileInGalaxyBranch.name}]`; try { if (logalot) { console.log(`${lc} Creating and committing file [${fileName}] in branch [${branchIbGib.data.name}]...`); } // 0. Ensure item does not already exist in parent folder const existingChildren = await getFolderChildren({ branchSpace, folderItem: parentFolderItem }); if (existingChildren.some(c => c.data?.name === fileName)) { throw new Error(`Item with name [${fileName}] already exists in this folder.`); } // 1. Create binary stone for content const { binAddr, binHash } = await createBinIbGib({ data: content, space: branchSpace, metaspace, }); // 2. Create B2tFS file item const fileRes = await createB2tFSItemIbGib({ fsType: 'file', name: fileName, data: { fileHash: binHash, isVirtual: false, }, rel8ns: { [BINARY_REL8N_NAME]: [binAddr], }, }); const fileItem = fileRes.newIbGib as B2tFSItemIbGib_V1; await persistTransformResult({ resTransform: fileRes, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: fileItem, space: branchSpace }); const fileAddr = getIbGibAddr({ ibGib: fileItem }); // 3. Evolve parent folder to include the new file item in b2tfs_child const resRel8 = await rel8({ src: parentFolderItem, rel8nsToAddByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [fileAddr], }, dna: true, nCounter: true, }); const evolvedFolder = resRel8.newIbGib as B2tFSItemIbGib_V1; await persistTransformResult({ resTransform: resRel8, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedFolder, space: branchSpace }); // 4. Evolve branch pointer to point to the new root snapshot const evolvedBranch = await evolveB2tFSBranchIbGib({ existingBranch: branchIbGib, rootItem: evolvedFolder, space: branchSpace, metaspace, }); if (logalot) { console.log(`${lc} Successfully created file [${fileName}] (${fileAddr}) and evolved branch to tip: ${evolvedBranch.ib}^${evolvedBranch.gib}`); } return { fileItem, evolvedFolder, evolvedBranch, }; } catch (err) { console.error(`${lc} Failed to create file in galaxy branch: ${extractErrorMsg(err)}`); throw err; } } export interface ChangedFileInfo { path: string; status: 'untracked' | 'modified' | 'deleted'; content?: string; } export interface CommitChangesToGalaxyBranchOpts { metaspace: MetaspaceService; branchSpace: IbGibSpaceAny; branchIbGib: B2tFSBranchIbGib_V1; rootFolderItem: B2tFSItemIbGib_V1; changes: ChangedFileInfo[]; message: string; author?: string; galaxyIbGib?: B2tFSGalaxyIbGib_V1; localSpace?: IbGibSpaceAny; } export interface CommitChangesToGalaxyBranchResult { evolvedBranch: B2tFSBranchIbGib_V1; evolvedRootFolder: B2tFSItemIbGib_V1; newTipAddr: string; committedCount: number; updatedGalaxy?: B2tFSGalaxyIbGib_V1; commitCommentAddr?: string; commitCommentIbGib?: CommentIbGib_V1; } /** * Commits a batch of working tree changes (new, modified, and deleted files) * directly to a B2tFS branch space, evolving intermediate/root folder items, * and evolving the branch pointer to advance the Merkle timeline. */ export async function commitChangesToGalaxyBranch({ metaspace, branchSpace, branchIbGib, rootFolderItem, changes, message, author = 'You', galaxyIbGib, localSpace, }: CommitChangesToGalaxyBranchOpts): Promise { const lc = `${lcFile}[${commitChangesToGalaxyBranch.name}]`; try { if (logalot) { console.log(`${lc} Committing ${changes.length} change(s) to branch [${branchIbGib.data.name}] with message: "${message}"...`); } if (changes.length === 0) { throw new Error(`No changes provided to commit.`); } let currentRoot = rootFolderItem; for (const change of changes) { const segments = change.path.split('/').filter(Boolean); const fileName = segments.pop() || change.path; const dirSegments = segments; const content = change.content ?? ''; // 1. Build or traverse folder chain from currentRoot const folderChain: B2tFSItemIbGib_V1[] = [currentRoot]; let currFolder = currentRoot; for (const dirName of dirSegments) { const existingChildren = await getFolderChildren({ branchSpace, folderItem: currFolder }); let childFolder = existingChildren.find(c => c.data?.fsType === 'folder' && c.data?.name === dirName); if (!childFolder) { const folderRes = await createB2tFSItemIbGib({ fsType: 'folder', name: dirName, }); childFolder = folderRes.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: folderRes, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: childFolder, space: branchSpace }); } folderChain.push(childFolder); currFolder = childFolder; } const targetFolder = folderChain[folderChain.length - 1]; let evolvedTargetFolder: B2tFSItemIbGib_V1 | undefined; if (change.status === 'untracked') { // 1. Create binary stone const { binAddr, binHash } = await createBinIbGib({ data: content, space: branchSpace, metaspace, }); // 2. Create B2tFS file item const fileRes = await createB2tFSItemIbGib({ fsType: 'file', name: fileName, data: { fileHash: binHash, isVirtual: false, }, rel8ns: { [BINARY_REL8N_NAME]: [binAddr], }, }); const fileItem = fileRes.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: fileRes, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: fileItem, space: branchSpace }); const fileAddr = getIbGibAddr({ ibGib: fileItem }); // Check if an item with this path already exists in targetFolder const existingChildren = await getFolderChildren({ branchSpace, folderItem: targetFolder }); const existingFile = existingChildren.find(c => c.data?.fsType === 'file' && c.data?.name === fileName); const oldFileAddr = existingFile ? getIbGibAddr({ ibGib: existingFile }) : undefined; // 3. Attach to target folder const resRel8 = await rel8({ src: targetFolder, rel8nsToAddByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [fileAddr], }, ...(oldFileAddr ? { rel8nsToRemoveByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [oldFileAddr], }, } : {}), dna: true, nCounter: true, }); evolvedTargetFolder = resRel8.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: resRel8, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedTargetFolder, space: branchSpace }); } else if (change.status === 'modified') { const existingChildren = await getFolderChildren({ branchSpace, folderItem: targetFolder }); const existingFile = existingChildren.find(c => c.data?.fsType === 'file' && c.data?.name === fileName); if (!existingFile) { throw new Error(`Cannot modify file [${change.path}]: file item not found in branch.`); } const oldFileAddr = getIbGibAddr({ ibGib: existingFile }); // Create new binary stone const { binAddr, binHash } = await createBinIbGib({ data: content, space: branchSpace, metaspace, }); // Evolve file item const evolveRes = await evolveB2tFSItemIbGib({ existingItem: existingFile, dataToUpdate: { fileHash: binHash, }, rel8nsToUpdate: { [BINARY_REL8N_NAME]: [binAddr], }, }); const evolvedFile = evolveRes.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: evolveRes, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedFile, space: branchSpace }); const newFileAddr = getIbGibAddr({ ibGib: evolvedFile }); // Replace old address with new address in target folder const resRel8 = await rel8({ src: targetFolder, rel8nsToAddByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [newFileAddr], }, rel8nsToRemoveByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [oldFileAddr], }, dna: true, nCounter: true, }); evolvedTargetFolder = resRel8.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: resRel8, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedTargetFolder, space: branchSpace }); } else if (change.status === 'deleted') { const existingChildren = await getFolderChildren({ branchSpace, folderItem: targetFolder }); const existingFile = existingChildren.find(c => c.data?.fsType === 'file' && c.data?.name === fileName); if (existingFile) { const oldFileAddr = getIbGibAddr({ ibGib: existingFile }); const resRel8 = await rel8({ src: targetFolder, rel8nsToRemoveByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [oldFileAddr], }, dna: true, nCounter: true, }); evolvedTargetFolder = resRel8.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: resRel8, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedTargetFolder, space: branchSpace }); } } // Bubble up through folderChain to currentRoot if (evolvedTargetFolder) { let currentEvolvedChild = evolvedTargetFolder; for (let i = folderChain.length - 2; i >= 0; i--) { const parentFolder = folderChain[i]; const oldChildFolder = folderChain[i + 1]; const oldChildAddr = getIbGibAddr({ ibGib: oldChildFolder }); const newChildAddr = getIbGibAddr({ ibGib: currentEvolvedChild }); const resRel8Parent = await rel8({ src: parentFolder, rel8nsToAddByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [newChildAddr], }, rel8nsToRemoveByAddr: { [B2TFS_CHILD_ITEM_REL8N_NAME]: [oldChildAddr], }, dna: true, nCounter: true, }); currentEvolvedChild = resRel8Parent.newIbGib as B2tFSItemIbGib_V1; await metaspace.persistTransformResult({ resTransform: resRel8Parent, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: currentEvolvedChild, space: branchSpace }); } currentRoot = currentEvolvedChild; } } // 3.5 Create commit comment stone if message provided let commitCommentAddr: string | undefined; let commitCommentIbGib: CommentIbGib_V1 | undefined; if (message && message.trim().length > 0) { const commentRes = await createCommentIbGib({ text: message.trim(), saveInSpace: true, space: branchSpace, }); commitCommentIbGib = commentRes.newIbGib as CommentIbGib_V1; commitCommentAddr = getIbGibAddr({ ibGib: commitCommentIbGib }); await metaspace.registerNewIbGib({ ibGib: commitCommentIbGib, space: branchSpace }); } // 4. Evolve branch pointer to point to the newly reified root snapshot const evolvedBranch = await evolveB2tFSBranchIbGib({ existingBranch: branchIbGib, rootItem: currentRoot, space: branchSpace, metaspace, commentAddr: commitCommentAddr, }); const newTipAddr = getIbGibAddr({ ibGib: evolvedBranch }); // 5. Update galaxy trunk pointer in localSpace if galaxyIbGib and localSpace are provided and branch is trunk let updatedGalaxy: B2tFSGalaxyIbGib_V1 | undefined = galaxyIbGib; if (galaxyIbGib && localSpace) { const trunkBranchName = (galaxyIbGib.data?.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME).toLowerCase(); const committedBranchName = (branchIbGib.data?.name || '').toLowerCase(); if (committedBranchName === trunkBranchName) { const branchSpaceId = getSpaceIdFromIb(branchSpace.ib); const newBranchSqAddr = getSpaceQualifiedIbGibAddr({ spaceId: branchSpaceId, ibGibAddr: newTipAddr, }); updatedGalaxy = await updateB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyIbGib, dataToUpdate: { trunkBranchSqAddr: newBranchSqAddr, '$@branch': [newBranchSqAddr], }, }); } } if (logalot) { console.log(`${lc} Successfully committed ${changes.length} change(s) to branch [${branchIbGib.data.name}]. New tip: ${newTipAddr}`); } return { evolvedBranch, evolvedRootFolder: currentRoot, newTipAddr, committedCount: changes.length, updatedGalaxy, commitCommentAddr, commitCommentIbGib, }; } catch (err) { console.error(`${lc} Failed to commit changes to galaxy branch: ${extractErrorMsg(err)}`); throw err; } } /** * Resolves the concrete filesystem or virtual substrate filename for an item. * For Package items, this returns the concrete versioned package filename (e.g. 'core-gib-0.1.96.tgz'). * For standard items, this returns the item's raw name (e.g. 'index.mts'). */ export function getProjectedItemFilename(item: B2tFSItemIbGib_V1): string { return item.data?.packageInfo?.filename || item.data?.name || ''; }