const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); /** * TITAN VAULT v8.0 - GITHUB AUTO-SYNC * Uses Environment Variables for stateless authentication. */ const VAULT_DIR = path.join(__dirname, '../../vault_archive'); exports.uploadToVault = async (filePath, fileName) => { try { console.log(`Vault: Preparing to archive ${fileName}...`); // 1. Ensure Vault Directory Exists if (!fs.existsSync(VAULT_DIR)) fs.mkdirSync(VAULT_DIR, { recursive: true }); // 2. Move file to Vault const targetPath = path.join(VAULT_DIR, fileName); fs.copyFileSync(filePath, targetPath); // 3. Construct Secure Remote URL (Using Env Vars) // This prevents the need for manual login on Render const username = process.env.GITHUB_USERNAME || 'zhaliejx'; const token = process.env.GITHUB_TOKEN; const repo = 'Codex-'; // Your repository name if (!token) { throw new Error("GITHUB_TOKEN is missing from Environment Variables."); } const remoteUrl = `https://${username}:${token}@github.com/${username}/${repo}.git`; // 4. Execute Git Sync Sequence try { const rootDir = path.join(__dirname, '../../'); // Define identity flags to prevent "unable to auto-detect email" errors const gitIdent = `-c user.name="Codex AI" -c user.email="ai@codex.bot"`; // Add, Commit, Push execSync(`git add vault_archive/"${fileName}"`, { cwd: rootDir }); execSync(`git ${gitIdent} commit -m "Vault: Archived ${fileName} [Auto-Sync]"`, { cwd: rootDir }); console.log("Vault: Pushing to remote..."); if (process.env.SPACE_ID) { console.log("Vault: [HF_SPACE_DETECTED] Skipping remote push to prevent restart loop."); } else { execSync(`git push "${remoteUrl}" main`, { cwd: rootDir }); } console.log(`Vault: Sync Complete -> ${process.env.SPACE_ID ? 'Local Archive Only' : 'GitHub'}`); } catch (gitErr) { console.error('Vault: Git Command Failed:', gitErr.message); // We don't throw here to avoid crashing the chat, but we log the error return { success: true, link: "Local_Only_Git_Error" }; } return { success: true, link: `https://github.com/${username}/${repo}/blob/main/vault_archive/${fileName}` }; } catch (err) { console.error('Vault_System_Failure:', err.message); return { success: false, error: err.message }; } };