/** * @module pr-helpers * * Helper functions for Pull Request lifecycle, cryptographic Sync Delegate Keystone * verification, admission policy gating, and AOT target index synchronization. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { ROOT } from '@ibgib/ts-gib/dist/V1/constants.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 { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs'; import { putInSpace } from '../../witness/space/space-helper.mjs'; import { getIbGibFromSpace, getTjpAddr } from '../../common/other/ibgib-helper.mjs'; import { MetaspaceService } from '../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs'; import { KeystoneIbGib_V1 } from '../../keystone/keystone-types.mjs'; import { KEYSTONE_ROLE_SYNC_DELEGATE, KEYSTONE_ROLE_AUTHOR_DELEGATE } from '../../keystone/delegate/delegate-constants.mjs'; import { KEYSTONE_VERB_SIGN, KEYSTONE_VERB_SYNC, KEYSTONE_VERB_AUTHOR } from '../../keystone/keystone-constants.mjs'; import { KeystoneService_V1 } from '../../keystone/keystone-service-v1.mjs'; import { CosmosIbGib_V1 } from '../cosmos/cosmos-types.mjs'; import { isAuthorizedToPost } from '../cosmos/cosmos-helpers.mjs'; import { B2tFSBranchIbGib_V1 } from '../branching/branch/branch-types.mjs'; import { B2tFSGalaxyIbGib_V1 } from '../branching/b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { commitChangesToGalaxyBranch, getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib, getFileContent, getFileItemFromPath, } from '../branching/item/item-helpers.mjs'; import { deserializeTargetsIndex, extractTargetUrlsFromMarkdown, serializeTargetsIndex, updateTargetsIndexData, } from '../metatext/metatext-helpers.mjs'; import { TARGETS_INDEX_FILE_PATH } from '../metatext/metatext-constants.mjs'; import { TargetsIndexData } from '../metatext/metatext-types.mjs'; import { PULL_REQUEST_ATOM, PR_REL8N_NAME, LEGACY_PR_REL8N_NAME, PR_STATUS_AUTO_MERGED, PR_STATUS_MERGED, PR_STATUS_PENDING, PR_STATUS_REJECTED, } from './pr-constants.mjs'; import { ApprovePullRequestOpts, IngestionGateResult, IngestPullRequestCommitOpts, PullRequestData_V1, PullRequestIb_V1, PullRequestIbGib_V1, PullRequestRel8ns_V1, PullRequestSubmission, RejectPullRequestOpts, ValidateSyncDelegateKeystoneParams, ValidateSyncDelegateKeystoneResult, } from './pr-types.mjs'; const lcFile = `[pr-helpers]`; const logalot = GLOBAL_LOG_A_LOT; /** * Constructs an ib string for a PullRequestIbGib. * Format: `pull-request ` */ export function getPullRequestIb({ targetCosmosName, targetGalaxyName, targetBranchName, }: { targetCosmosName: string; targetGalaxyName: string; targetBranchName: string; }): string { return `${PULL_REQUEST_ATOM} ${targetCosmosName} ${targetGalaxyName} ${targetBranchName}`; } /** * Parses a pull-request ib string into its constituent cosmos, galaxy, and branch names. */ export function parsePullRequestIb({ ib }: { ib: string }): PullRequestIb_V1 { const parts = (ib || '').split(' '); if (parts.length < 4 || parts[0] !== PULL_REQUEST_ATOM) { throw new Error(`Invalid pull request ib: "${ib}". Expected "${PULL_REQUEST_ATOM} ". (E: 7a8b9c0d1e2f34567890abcdef123456)`); } return { atom: PULL_REQUEST_ATOM, targetCosmosName: parts[1], targetGalaxyName: parts[2], targetBranchName: parts[3], }; } /** * Type guard for PullRequestIbGib_V1. */ export function isPullRequest(x: any): x is PullRequestIbGib_V1 { if (!x?.ib || !x.data) { return false; } const parts = x.ib.split(' '); return parts[0] === PULL_REQUEST_ATOM && typeof x.data.targetCosmosName === 'string'; } /** * Creates a new Genesis PullRequestIbGib representing a candidate PR or staged submission. */ export async function createPullRequestIbGib({ submission, status = PR_STATUS_PENDING, rejectionReason, mergedCommitAddr, reviewerKeystoneTjp, space, metaspace, }: { submission: PullRequestSubmission; status?: typeof PR_STATUS_PENDING | typeof PR_STATUS_AUTO_MERGED | typeof PR_STATUS_MERGED | typeof PR_STATUS_REJECTED; rejectionReason?: string; mergedCommitAddr?: string; reviewerKeystoneTjp?: string; space: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const lc = `${lcFile}[${createPullRequestIbGib.name}]`; try { const uuid = await getUUID(); const ib = getPullRequestIb({ targetCosmosName: submission.targetCosmosName, targetGalaxyName: submission.targetGalaxyName, targetBranchName: submission.targetBranchName, }); const data: PullRequestData_V1 = { targetCosmosName: submission.targetCosmosName, targetGalaxyName: submission.targetGalaxyName, targetBranchName: submission.targetBranchName, candidateCommitAddr: submission.candidateCommitAddr, summary: submission.summary, authorPrimaryTjpAddr: submission.authorPrimaryTjpAddr, authorHandle: submission.authorHandle, status, createdAt: new Date().toISOString(), ...(reviewerKeystoneTjp ? { reviewerKeystoneTjp, reviewedAt: new Date().toISOString() } : {}), ...(rejectionReason ? { rejectionReason } : {}), ...(mergedCommitAddr ? { mergedCommitAddr } : {}), ...(submission.candidateChanges ? { changes: submission.candidateChanges } : {}), uuid, classname: 'PullRequestIbGib_V1', }; const delegateTjp = submission.evolvedSyncDelegateKeystone ? getTjpAddr({ ibGib: submission.evolvedSyncDelegateKeystone }) : undefined; const rel8ns: PullRequestRel8ns_V1 = { ...(submission.authorPrimaryTjpAddr?.includes('^') ? { author_keystone: [submission.authorPrimaryTjpAddr] } : {}), ...(delegateTjp?.includes('^') ? { delegate_keystone: [delegateTjp] } : {}), ...(submission.candidateCommitAddr?.includes('^') ? { candidate_commit: [submission.candidateCommitAddr] } : {}), }; const resGen = await Factory_V1.firstGen({ parentIbGib: ROOT, ib, data, ...(Object.keys(rel8ns).length > 0 ? { rel8ns } : {}), dna: true, tjp: { timestamp: true }, }); const pullRequestIbGib = resGen.newIbGib as PullRequestIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform: resGen, space }); await metaspace.registerNewIbGib({ ibGib: pullRequestIbGib, space }); } else { await putInSpace({ ibGib: pullRequestIbGib, space }); } if (logalot) { console.log(`${lc} Created PullRequestIbGib: ${pullRequestIbGib.ib} (addr: ${getIbGibAddr({ ibGib: pullRequestIbGib })})`); } return pullRequestIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 8b9c0d1e2f3a4567890abcdef1234567)`); throw error; } } /** * Links a pull request stone to a CosmosIbGib under the `@pull_request` soft link in data. */ export async function linkPullRequestToCosmos({ cosmosIbGib, pullRequestIbGib, space, metaspace, }: { cosmosIbGib: CosmosIbGib_V1; pullRequestIbGib: PullRequestIbGib_V1; space: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const lc = `${lcFile}[${linkPullRequestToCosmos.name}]`; try { const prAddr = getIbGibAddr({ ibGib: pullRequestIbGib }); const existingPrs = cosmosIbGib.data?.['@pull_request'] || cosmosIbGib.rel8ns?.[LEGACY_PR_REL8N_NAME] || []; if (existingPrs.includes(prAddr)) { return cosmosIbGib; } const resTransform = await mut8({ src: cosmosIbGib, dataToAddOrPatch: { '@pull_request': [...existingPrs, prAddr], }, dna: true, nCounter: true, }); const updatedCosmos = resTransform.newIbGib as CosmosIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform, space }); await metaspace.registerNewIbGib({ ibGib: updatedCosmos, space }); } else { await putInSpace({ ibGib: updatedCosmos, space }); } return updatedCosmos; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Retrieves all staged/pending pull requests linked to a CosmosIbGib. */ export async function getStagedPullRequests({ cosmosIbGib, space, metaspace, }: { cosmosIbGib: CosmosIbGib_V1; space: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const prAddrs = cosmosIbGib.data?.['@pull_request'] || cosmosIbGib.rel8ns?.[LEGACY_PR_REL8N_NAME] || []; const prs: PullRequestIbGib_V1[] = []; for (const prAddr of prAddrs) { const latestAddr = metaspace ? (await metaspace.getLatestAddr({ addr: prAddr, space })) || prAddr : prAddr; const prIbGib = await getIbGibFromSpace({ addr: latestAddr, space }); if (prIbGib && isPullRequest(prIbGib)) { prs.push(prIbGib); } } return prs; } /** * Cryptographically validates an evolved Sync Delegate Keystone: * 1. Validates intrinsic hash integrity of the keystone stone. * 2. Verifies proof and claim: claim verb must be 'sync' or 'sign'. * 3. Enforces cryptographic target binding (claim.target matches expected candidate target address, if specified). * 4. Verifies delegate lineage and permissions under author's primary keystone identity. * 5. Enforces server lock-step invariant and keystone evolution transition (n -> n+1). * 6. Burns frame against replay attacks by persisting frame n+1 in server space. */ export async function validateSyncDelegateKeystone( params: ValidateSyncDelegateKeystoneParams ): Promise { const lc = `${lcFile}[${validateSyncDelegateKeystone.name}]`; try { const { evolvedSyncDelegateKeystone, authorPrimaryTjpAddr, expectedTargetAddr, allowedVerbs, metaspace, space, } = params; if (!evolvedSyncDelegateKeystone) { return { isValid: false, statusCode: 400, error: 'evolvedSyncDelegateKeystone is required' }; } if (!authorPrimaryTjpAddr) { return { isValid: false, statusCode: 400, error: 'authorPrimaryTjpAddr is required' }; } // 1. Intrinsic hash validation const intrinsicErrors = await validateIbGibIntrinsically({ ibGib: evolvedSyncDelegateKeystone }); if (intrinsicErrors && intrinsicErrors.length > 0) { return { isValid: false, statusCode: 422, error: `Keystone intrinsic validation failed: ${intrinsicErrors.join(', ')}`, }; } // 2. Proofs & Claim Verb Verification const proofs = evolvedSyncDelegateKeystone.data?.proofs ?? []; if (proofs.length === 0) { return { isValid: false, statusCode: 422, error: 'No proofs found in evolved keystone' }; } const claim = proofs[0].claim; if (!claim) { return { isValid: false, statusCode: 422, error: 'proof.claim is missing' }; } const validVerbs = allowedVerbs ?? [KEYSTONE_VERB_SYNC, 'sync', KEYSTONE_VERB_AUTHOR, 'author', KEYSTONE_VERB_SIGN, 'sign']; const isVerbAuthorized = claim.verb ? validVerbs.includes(claim.verb) : false; if (!isVerbAuthorized) { return { isValid: false, statusCode: 422, error: `Claim verb must be one of [${validVerbs.join(', ')}], got '${claim.verb}'`, }; } // Optional target binding check if (expectedTargetAddr && claim.target && claim.target !== expectedTargetAddr) { return { isValid: false, statusCode: 422, error: `Claim target '${claim.target}' does not match expected target '${expectedTargetAddr}'`, }; } // 3. Delegate Lineage & Status Verification const delegateTjpAddr = getTjpAddr({ ibGib: evolvedSyncDelegateKeystone }); if (!delegateTjpAddr) { return { isValid: false, statusCode: 400, error: 'Incoming delegate keystone missing TJP address' }; } const keystoneService = new KeystoneService_V1(); const delegateStatus = await keystoneService.getDelegateStatus({ parentTjpAddr: authorPrimaryTjpAddr, delegateTjpAddr, metaspace, space, }); if (!delegateStatus.registered || !delegateStatus.delegateInfo) { return { isValid: false, statusCode: 403, error: `Delegate ${delegateTjpAddr} is not registered under author identity ${authorPrimaryTjpAddr} or is expired`, }; } const delegateAllowedVerbs = delegateStatus.delegateInfo.allowedVerbs ?? []; const isAuthorized = (delegateStatus.delegateInfo as any).role === KEYSTONE_ROLE_SYNC_DELEGATE || (delegateStatus.delegateInfo as any).role === 'sync-delegate' || (delegateStatus.delegateInfo as any).role === KEYSTONE_ROLE_AUTHOR_DELEGATE || (delegateStatus.delegateInfo as any).role === 'author-delegate' || delegateAllowedVerbs.includes('sync') || delegateAllowedVerbs.includes(KEYSTONE_VERB_SYNC) || delegateAllowedVerbs.includes('author') || delegateAllowedVerbs.includes(KEYSTONE_VERB_AUTHOR) || delegateAllowedVerbs.includes('sign') || delegateAllowedVerbs.includes(KEYSTONE_VERB_SIGN) || delegateAllowedVerbs.length === 0; if (!isAuthorized) { return { isValid: false, statusCode: 403, error: `Delegate ${delegateTjpAddr} is not authorized for sync/author/sign actions`, }; } // 4. Server Lock-Step Requirement: Retrieve delegate tip in space let prevDelegateTip: KeystoneIbGib_V1 | undefined; try { prevDelegateTip = await keystoneService.getLatestKeystone({ addr: delegateTjpAddr, metaspace, space }); } catch (err) { return { isValid: false, statusCode: 422, error: `Previous delegate tip for ${delegateTjpAddr} not found in space: ${extractErrorMsg(err)}`, }; } if (!prevDelegateTip) { return { isValid: false, statusCode: 422, error: `Previous delegate tip for ${delegateTjpAddr} does not exist in space.`, }; } // 5. Keystone Transition Validation (Replay Defense: n -> n+1) const transitionErrors = await keystoneService.validate({ currentIbGib: evolvedSyncDelegateKeystone, prevIbGib: prevDelegateTip, }); if (transitionErrors && transitionErrors.length > 0) { return { isValid: false, statusCode: 422, error: `Keystone transition validation failed: ${transitionErrors.join(', ')}`, }; } // 6. Persist & Register New Delegate Tip (Burns frame against replay) await metaspace.put({ ibGibs: [evolvedSyncDelegateKeystone], space }); await metaspace.registerNewIbGib({ ibGib: evolvedSyncDelegateKeystone, space }); let parentKeystone: KeystoneIbGib_V1 | undefined; try { parentKeystone = await keystoneService.getLatestKeystone({ addr: authorPrimaryTjpAddr, metaspace, space }); } catch { // Optional root parent lookup } return { isValid: true, statusCode: 200, parentKeystone, delegateTjpAddr, }; } catch (error) { const emsg = `${lc} Unexpected auth error: ${extractErrorMsg(error)}`; console.error(emsg); return { isValid: false, statusCode: 500, error: emsg }; } } /** * Primary Ingestion Gate: * Ingests a candidate commit or pull request submission into a Cosmos/Galaxy branch. * * 1. Cryptographically validates evolvedSyncDelegateKeystone (intrinsic hash, claim verb, * n -> n+1 transition, frame burning). * 2. Evaluates admission policy via `isAuthorizedToPost` on target Cosmos. * 3. Handles: * - Rejection (returns status: 'rejected') * - Moderation (stages in PR queue, returns status: 'staged-pr') * - Public-open / Authorized Auto-Merge (commits files, updates Metatext AOT targets index, * returns status: 'auto-merged'). */ export async function ingestPullRequestCommit( opts: IngestPullRequestCommitOpts ): Promise { const lc = `${lcFile}[${ingestPullRequestCommit.name}]`; try { const { cosmosIbGib, submission, galaxyIbGib, branchSpace, space, metaspace, localSpace, skipKeystoneVerification = false, autoMergeMetatext = true, } = opts; // 1. Cryptographic Authentication if (!skipKeystoneVerification) { const delegateToValidate = submission.evolvedAuthorDelegateKeystone || submission.evolvedSyncDelegateKeystone; if (!delegateToValidate) { return { isAuthorized: false, status: 'rejected', reason: 'Delegate Keystone signature (author or sync) is required for pull request submission.', }; } const authRes = await validateSyncDelegateKeystone({ evolvedSyncDelegateKeystone: delegateToValidate, authorPrimaryTjpAddr: submission.authorPrimaryTjpAddr, expectedTargetAddr: submission.candidateCommitAddr, metaspace, space, }); if (!authRes.isValid) { return { isAuthorized: false, status: 'rejected', reason: authRes.error || 'Cryptographic validation failed', }; } } // 2. Admission Policy Evaluation const authCheck = isAuthorizedToPost({ cosmosIbGib, galaxyName: submission.targetGalaxyName, branchName: submission.targetBranchName, candidateKeystoneTjp: submission.authorPrimaryTjpAddr, }); // Case A: Outright Rejection (e.g. not on allowlist or admin-only) if (!authCheck.isAuthorized && !authCheck.requiresModeration) { return { isAuthorized: false, status: 'rejected', reason: authCheck.reason || 'Unauthorized to contribute to this cosmos/galaxy', }; } // Case B: Moderation Required if (authCheck.requiresModeration) { const pullRequestIbGib = await createPullRequestIbGib({ submission, status: PR_STATUS_PENDING, space, metaspace, }); const updatedCosmos = await linkPullRequestToCosmos({ cosmosIbGib, pullRequestIbGib, space, metaspace, }); return { isAuthorized: false, status: 'staged-pr', reason: authCheck.reason || 'Submission requires maintainer review / moderation.', pullRequest: pullRequestIbGib, pullRequestAddr: getIbGibAddr({ ibGib: pullRequestIbGib }), updatedCosmos, }; } // Case C: Authorized for Auto-Merge if (autoMergeMetatext && branchSpace && submission.candidateChanges && submission.candidateChanges.length > 0) { // Resolve branch stone and root item let targetBranchIbGib: B2tFSBranchIbGib_V1 | undefined; let targetRootFolder: any; if (galaxyIbGib) { const info = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName: submission.targetBranchName, metaspace, }); targetBranchIbGib = info.branchIbGib; targetRootFolder = info.rootItemIbGib_latest; } if (!targetBranchIbGib) { throw new Error(`Target branch [${submission.targetBranchName}] could not be resolved from galaxy.`); } // 1. Commit candidate changes to branch let commitRes = await commitChangesToGalaxyBranch({ metaspace, branchSpace, branchIbGib: targetBranchIbGib, rootFolderItem: targetRootFolder, changes: submission.candidateChanges, message: submission.summary, author: submission.authorHandle || submission.authorPrimaryTjpAddr, galaxyIbGib, localSpace: localSpace || space, }); // 2. Metatext Galaxy AOT Targets Index Synchronization const isMetatext = submission.targetGalaxyName.toLowerCase().includes('metatext') || submission.targetGalaxyName.toLowerCase().includes('notes') || (galaxyIbGib?.data as any)?.discriminator === 'metatext'; let targetsIndex: TargetsIndexData | undefined; if (isMetatext) { targetsIndex = { targets: {} }; const existingIndexItem = await getFileItemFromPath({ branchSpace, rootItem: commitRes.evolvedRootFolder, filePath: TARGETS_INDEX_FILE_PATH, }); if (existingIndexItem) { const rawJson = await getFileContent({ branchSpace, fileItem: existingIndexItem }); if (rawJson) { try { targetsIndex = deserializeTargetsIndex(rawJson); } catch { targetsIndex = { targets: {} }; } } } let hasTargetsToRecord = false; for (const change of submission.candidateChanges) { if (change.path.endsWith('.md') && change.content) { const parsedUrls = extractTargetUrlsFromMarkdown(change.content); if (parsedUrls.length > 0) { targetsIndex = updateTargetsIndexData({ currentIndex: targetsIndex, targetUrls: parsedUrls, commentFilePath: change.path, author: submission.authorHandle || submission.authorPrimaryTjpAddr, authorKeystoneTjp: submission.authorPrimaryTjpAddr, timestamp: new Date().toISOString(), }); hasTargetsToRecord = true; } } } if (hasTargetsToRecord) { const serialized = serializeTargetsIndex(targetsIndex); const indexCommitRes = await commitChangesToGalaxyBranch({ metaspace, branchSpace, branchIbGib: commitRes.evolvedBranch, rootFolderItem: commitRes.evolvedRootFolder, changes: [{ path: TARGETS_INDEX_FILE_PATH, content: serialized, status: existingIndexItem ? 'modified' : 'untracked', }], message: `Update ${TARGETS_INDEX_FILE_PATH} AOT index`, author: submission.authorHandle || submission.authorPrimaryTjpAddr, galaxyIbGib: commitRes.updatedGalaxy, localSpace: localSpace || space, }); commitRes = { ...indexCommitRes, committedCount: commitRes.committedCount + 1, }; } } // 3. Create pull request stone recording auto-merge const pullRequestIbGib = await createPullRequestIbGib({ submission, status: PR_STATUS_AUTO_MERGED, mergedCommitAddr: commitRes.newTipAddr, space, metaspace, }); const updatedCosmos = await linkPullRequestToCosmos({ cosmosIbGib, pullRequestIbGib, space, metaspace, }); return { isAuthorized: true, status: 'auto-merged', mergedCommitAddr: commitRes.newTipAddr, updatedBranch: commitRes.evolvedBranch, updatedGalaxy: commitRes.updatedGalaxy, updatedTargetsIndex: targetsIndex, pullRequest: pullRequestIbGib, pullRequestAddr: getIbGibAddr({ ibGib: pullRequestIbGib }), updatedCosmos, }; } // If no direct changes to auto-merge or headless submission const pullRequestIbGib = await createPullRequestIbGib({ submission, status: PR_STATUS_PENDING, space, metaspace, }); const updatedCosmos = await linkPullRequestToCosmos({ cosmosIbGib, pullRequestIbGib, space, metaspace, }); return { isAuthorized: true, status: 'staged-pr', pullRequest: pullRequestIbGib, pullRequestAddr: getIbGibAddr({ ibGib: pullRequestIbGib }), updatedCosmos, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 9c0d1e2f3a4b567890abcdef12345678)`); throw error; } } /** * Approves a staged Pull Request, committing its candidate changes into the target branch * and synchronizing AOT target indices if in a Metatext galaxy. */ export async function approvePullRequest( opts: ApprovePullRequestOpts ): Promise { const lc = `${lcFile}[${approvePullRequest.name}]`; try { const { cosmosIbGib, pullRequestIbGib, reviewerKeystoneTjp, galaxyIbGib, branchSpace, metaspace, localSpace, } = opts; // 1. Check reviewer authorization const authCheck = isAuthorizedToPost({ cosmosIbGib, galaxyName: pullRequestIbGib.data.targetGalaxyName, branchName: pullRequestIbGib.data.targetBranchName, candidateKeystoneTjp: reviewerKeystoneTjp, }); if (!authCheck.isAuthorized) { throw new Error(`Reviewer ${reviewerKeystoneTjp} is not authorized to approve pull requests on this cosmos.`); } if (pullRequestIbGib.data.status === PR_STATUS_MERGED || pullRequestIbGib.data.status === PR_STATUS_AUTO_MERGED) { throw new Error(`Pull request ${pullRequestIbGib.ib} is already merged.`); } const changes = pullRequestIbGib.data.changes || []; if (changes.length === 0) { throw new Error(`Pull request has no candidate changes to merge.`); } // 2. Resolve target branch and root item const { branchIbGib, rootItemIbGib_latest } = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName: pullRequestIbGib.data.targetBranchName, metaspace, }); // 3. Commit changes to branch let commitRes = await commitChangesToGalaxyBranch({ metaspace, branchSpace, branchIbGib, rootFolderItem: rootItemIbGib_latest, changes, message: pullRequestIbGib.data.summary, author: pullRequestIbGib.data.authorHandle || pullRequestIbGib.data.authorPrimaryTjpAddr, galaxyIbGib, localSpace: localSpace || branchSpace, }); // 4. Update Metatext AOT targets index if applicable const isMetatext = pullRequestIbGib.data.targetGalaxyName.toLowerCase().includes('metatext') || pullRequestIbGib.data.targetGalaxyName.toLowerCase().includes('notes'); let targetsIndex: TargetsIndexData | undefined; if (isMetatext) { targetsIndex = { targets: {} }; const existingIndexItem = await getFileItemFromPath({ branchSpace, rootItem: commitRes.evolvedRootFolder, filePath: TARGETS_INDEX_FILE_PATH, }); if (existingIndexItem) { const rawJson = await getFileContent({ branchSpace, fileItem: existingIndexItem }); if (rawJson) { try { targetsIndex = deserializeTargetsIndex(rawJson); } catch { targetsIndex = { targets: {} }; } } } let hasTargets = false; for (const change of changes) { if (change.path.endsWith('.md') && change.content) { const parsedUrls = extractTargetUrlsFromMarkdown(change.content); if (parsedUrls.length > 0) { targetsIndex = updateTargetsIndexData({ currentIndex: targetsIndex, targetUrls: parsedUrls, commentFilePath: change.path, author: pullRequestIbGib.data.authorHandle || pullRequestIbGib.data.authorPrimaryTjpAddr, authorKeystoneTjp: pullRequestIbGib.data.authorPrimaryTjpAddr, timestamp: new Date().toISOString(), }); hasTargets = true; } } } if (hasTargets) { const serialized = serializeTargetsIndex(targetsIndex); commitRes = await commitChangesToGalaxyBranch({ metaspace, branchSpace, branchIbGib: commitRes.evolvedBranch, rootFolderItem: commitRes.evolvedRootFolder, changes: [{ path: TARGETS_INDEX_FILE_PATH, content: serialized, status: existingIndexItem ? 'modified' : 'untracked', }], message: `Update ${TARGETS_INDEX_FILE_PATH} AOT index`, author: reviewerKeystoneTjp, galaxyIbGib: commitRes.updatedGalaxy, localSpace: localSpace || branchSpace, }); } } // 5. Evolve pull request stone to status 'merged' const resMut8 = await mut8({ src: pullRequestIbGib, dataToAddOrPatch: { status: PR_STATUS_MERGED, reviewedAt: new Date().toISOString(), reviewerKeystoneTjp, mergedCommitAddr: commitRes.newTipAddr, }, dna: true, nCounter: true, }); const evolvedPr = resMut8.newIbGib as PullRequestIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform: resMut8, space: branchSpace }); await metaspace.registerNewIbGib({ ibGib: evolvedPr, space: branchSpace }); } else { await putInSpace({ ibGib: evolvedPr, space: branchSpace }); } return { isAuthorized: true, status: 'auto-merged', mergedCommitAddr: commitRes.newTipAddr, updatedBranch: commitRes.evolvedBranch, updatedGalaxy: commitRes.updatedGalaxy, updatedTargetsIndex: targetsIndex, pullRequest: evolvedPr, pullRequestAddr: getIbGibAddr({ ibGib: evolvedPr }), }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Rejects a staged Pull Request with a reason. */ export async function rejectPullRequest( opts: RejectPullRequestOpts ): Promise { const lc = `${lcFile}[${rejectPullRequest.name}]`; try { const { pullRequestIbGib, reviewerKeystoneTjp, reason, space, metaspace } = opts; const resMut8 = await mut8({ src: pullRequestIbGib, dataToAddOrPatch: { status: PR_STATUS_REJECTED, reviewedAt: new Date().toISOString(), reviewerKeystoneTjp, rejectionReason: reason, }, dna: true, nCounter: true, }); const evolvedPr = resMut8.newIbGib as PullRequestIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform: resMut8, space }); await metaspace.registerNewIbGib({ ibGib: evolvedPr, space }); } else { await putInSpace({ ibGib: evolvedPr, space }); } return evolvedPr; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } }