mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-04-30 06:54:15 -07:00
refactor: rename deep-review to offload and generalize capabilities
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Universal Deep Review Checker (Local)
|
||||
*
|
||||
* Polls the remote machine for task status.
|
||||
*/
|
||||
import { spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(__dirname, '../../../..');
|
||||
|
||||
export async function runChecker(args: string[]) {
|
||||
const prNumber = args[0];
|
||||
if (!prNumber) {
|
||||
console.error('Usage: npm run review:check <PR_NUMBER>');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
|
||||
if (!fs.existsSync(settingsPath)) {
|
||||
console.error('❌ Settings not found. Run "npm run review:setup" first.');
|
||||
return 1;
|
||||
}
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
const config = settings.maintainer?.deepReview;
|
||||
if (!config) {
|
||||
console.error('❌ Deep Review configuration not found.');
|
||||
return 1;
|
||||
}
|
||||
const { remoteHost, remoteWorkDir } = config;
|
||||
|
||||
console.log(`🔍 Checking remote status for PR #${prNumber} on ${remoteHost}...`);
|
||||
|
||||
const branchView = spawnSync('gh', ['pr', 'view', prNumber, '--json', 'headRefName', '-q', '.headRefName'], { shell: true });
|
||||
const branchName = branchView.stdout.toString().trim();
|
||||
const logDir = `${remoteWorkDir}/${branchName}/.gemini/logs/review-${prNumber}`;
|
||||
|
||||
const tasks = ['build', 'ci', 'review', 'verify'];
|
||||
let allDone = true;
|
||||
|
||||
console.log('\n--- Task Status ---');
|
||||
for (const task of tasks) {
|
||||
const checkExit = spawnSync('ssh', [remoteHost, `cat ${logDir}/${task}.exit 2>/dev/null`], { shell: true });
|
||||
if (checkExit.status === 0) {
|
||||
const code = checkExit.stdout.toString().trim();
|
||||
console.log(` ${code === '0' ? '✅' : '❌'} ${task.padEnd(10)}: ${code === '0' ? 'SUCCESS' : `FAILED (exit ${code})`}`);
|
||||
} else {
|
||||
const checkRunning = spawnSync('ssh', [remoteHost, `[ -f ${logDir}/${task}.log ]`], { shell: true });
|
||||
if (checkRunning.status === 0) {
|
||||
console.log(` ⏳ ${task.padEnd(10)}: RUNNING`);
|
||||
} else {
|
||||
console.log(` 💤 ${task.padEnd(10)}: PENDING`);
|
||||
}
|
||||
allDone = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (allDone) {
|
||||
console.log('\n✨ All remote tasks complete. You can now synthesize the results.');
|
||||
} else {
|
||||
console.log('\n⏳ Some tasks are still in progress. Check again in a few minutes.');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runChecker(process.argv.slice(2)).catch(console.error);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Universal Deep Review Cleanup (Local)
|
||||
*/
|
||||
import { spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import readline from 'readline';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(__dirname, '../../../..');
|
||||
|
||||
async function confirm(question: string): Promise<boolean> {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
return new Promise((resolve) => {
|
||||
rl.question(`${question} (y/n): `, (answer) => {
|
||||
rl.close();
|
||||
resolve(answer.trim().toLowerCase() === 'y');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function runCleanup() {
|
||||
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
|
||||
if (!fs.existsSync(settingsPath)) {
|
||||
console.error('❌ Settings not found. Run "npm run review:setup" first.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
const config = settings.maintainer?.deepReview;
|
||||
|
||||
if (!config) {
|
||||
console.error('❌ Deep Review configuration not found.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { remoteHost, remoteWorkDir } = config;
|
||||
|
||||
console.log(`🧹 Starting cleanup for ${remoteHost}:${remoteWorkDir}...`);
|
||||
|
||||
// 1. Standard Cleanup
|
||||
console.log(' - Killing remote tmux sessions...');
|
||||
spawnSync('ssh', [remoteHost, 'tmux kill-server'], { shell: true });
|
||||
|
||||
console.log(' - Removing PR directories...');
|
||||
// Find all directories in the work dir that aren't .gemini and delete them
|
||||
const dirCleanup = `find ${remoteWorkDir} -mindepth 1 -maxdepth 1 -type d ! -name ".gemini" -exec rm -rf {} +`;
|
||||
spawnSync('ssh', [remoteHost, dirCleanup], { shell: true });
|
||||
|
||||
console.log('✅ Standard cleanup complete.');
|
||||
|
||||
// 2. Full Wipe Option
|
||||
const shouldWipe = await confirm('\nWould you like to COMPLETELY remove the work directory from the remote machine?');
|
||||
|
||||
if (shouldWipe) {
|
||||
console.log(`🔥 Wiping ${remoteWorkDir}...`);
|
||||
const wipeCmd = `rm -rf ${remoteWorkDir}`;
|
||||
spawnSync('ssh', [remoteHost, wipeCmd], { stdio: 'inherit', shell: true });
|
||||
console.log('✅ Remote directory wiped.');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runCleanup().catch(console.error);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Deep Review Entrypoint (Remote)
|
||||
*
|
||||
* This script is the single command executed by the remote tmux session.
|
||||
* It handles environment loading and sequence orchestration.
|
||||
*/
|
||||
import { spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const prNumber = process.argv[2];
|
||||
const branchName = process.argv[3];
|
||||
const policyPath = process.argv[4];
|
||||
const ISOLATED_CONFIG = process.env.GEMINI_CLI_HOME || path.join(process.env.HOME || '', '.gemini-deep-review');
|
||||
|
||||
async function main() {
|
||||
if (!prNumber || !branchName || !policyPath) {
|
||||
console.error('Usage: tsx entrypoint.ts <PR_NUMBER> <BRANCH_NAME> <POLICY_PATH>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const workDir = process.cwd(); // This is remoteWorkDir as set in review.ts
|
||||
const targetDir = path.join(workDir, branchName);
|
||||
|
||||
// Path to the locally installed binaries in the work directory
|
||||
const tsxBin = path.join(workDir, 'node_modules/.bin/tsx');
|
||||
const geminiBin = path.join(workDir, 'node_modules/.bin/gemini');
|
||||
|
||||
// 1. Run the Parallel Reviewer
|
||||
console.log('🚀 Launching Parallel Review Worker...');
|
||||
const workerResult = spawnSync(tsxBin, [path.join(__dirname, 'worker.ts'), prNumber, branchName, policyPath], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, GEMINI_CLI_HOME: ISOLATED_CONFIG }
|
||||
});
|
||||
|
||||
if (workerResult.status !== 0) {
|
||||
console.error('❌ Worker failed. Check the logs above.');
|
||||
}
|
||||
|
||||
// 2. Launch the Interactive Gemini Session (Local Nightly)
|
||||
console.log('\n✨ Verification complete. Joining interactive session...');
|
||||
|
||||
const geminiArgs = ['--policy', policyPath];
|
||||
geminiArgs.push('-p', `Review for PR #${prNumber} is complete. Read the logs in .gemini/logs/review-${prNumber}/ and synthesize your findings.`);
|
||||
|
||||
process.chdir(targetDir);
|
||||
spawnSync(geminiBin, geminiArgs, {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, GEMINI_CLI_HOME: ISOLATED_CONFIG }
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Universal Offload Orchestrator (Local)
|
||||
*/
|
||||
import { spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(__dirname, '../../../..');
|
||||
|
||||
const q = (str: string) => `'${str.replace(/'/g, "'\\''")}'`;
|
||||
|
||||
export async function runOrchestrator(args: string[], env: NodeJS.ProcessEnv = process.env) {
|
||||
const prNumber = args[0];
|
||||
const action = args[1] || 'review'; // Default action is review
|
||||
|
||||
if (!prNumber) {
|
||||
console.error('Usage: npm run offload <PR_NUMBER> [action]');
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Load Settings
|
||||
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
|
||||
let settings: any = {};
|
||||
if (fs.existsSync(settingsPath)) {
|
||||
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch (e) {}
|
||||
}
|
||||
|
||||
let config = settings.maintainer?.deepReview;
|
||||
if (!config) {
|
||||
console.log('⚠️ Offload configuration not found. Launching setup...');
|
||||
const setupResult = spawnSync('npm', ['run', 'offload:setup'], { stdio: 'inherit' });
|
||||
if (setupResult.status !== 0) {
|
||||
console.error('❌ Setup failed. Please run "npm run offload:setup" manually.');
|
||||
return 1;
|
||||
}
|
||||
// Reload settings after setup
|
||||
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
config = settings.maintainer.deepReview;
|
||||
}
|
||||
|
||||
const { remoteHost, remoteWorkDir, terminalType, syncAuth, geminiSetup, ghSetup } = config;
|
||||
|
||||
console.log(`🔍 Fetching metadata for PR #${prNumber}...`);
|
||||
const ghView = spawnSync('gh', ['pr', 'view', prNumber, '--json', 'headRefName', '-q', '.headRefName'], { shell: true });
|
||||
const branchName = ghView.stdout.toString().trim();
|
||||
if (!branchName) {
|
||||
console.error('❌ Failed to resolve PR branch.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const sessionName = `${prNumber}-${branchName.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
||||
|
||||
// 2. Sync Configuration Mirror (Isolated Profiles)
|
||||
const ISOLATED_GEMINI = geminiSetup === 'isolated' ? '~/.gemini-deep-review' : '~/.gemini';
|
||||
const ISOLATED_GH = ghSetup === 'isolated' ? '~/.gh-deep-review' : '~/.config/gh';
|
||||
const remotePolicyPath = `${ISOLATED_GEMINI}/policies/deep-review-policy.toml`;
|
||||
|
||||
console.log(`📡 Mirroring environment to ${remoteHost}...`);
|
||||
spawnSync('ssh', [remoteHost, `mkdir -p ${remoteWorkDir}/.gemini/skills/offload/scripts/ ${ISOLATED_GEMINI}/policies/`]);
|
||||
|
||||
// Sync the policy file specifically
|
||||
spawnSync('rsync', ['-avz', path.join(REPO_ROOT, '.gemini/skills/offload/policy.toml'), `${remoteHost}:${remotePolicyPath}`]);
|
||||
|
||||
spawnSync('rsync', ['-avz', '--delete', path.join(REPO_ROOT, '.gemini/skills/offload/scripts/'), `${remoteHost}:${remoteWorkDir}/.gemini/skills/offload/scripts/`]);
|
||||
|
||||
if (syncAuth) {
|
||||
const homeDir = env.HOME || '';
|
||||
const localGeminiDir = path.join(homeDir, '.gemini');
|
||||
const syncFiles = ['google_accounts.json', 'settings.json'];
|
||||
for (const f of syncFiles) {
|
||||
const lp = path.join(localGeminiDir, f);
|
||||
if (fs.existsSync(lp)) spawnSync('rsync', ['-avz', lp, `${remoteHost}:${ISOLATED_GEMINI}/${f}`]);
|
||||
}
|
||||
const localPolicies = path.join(localGeminiDir, 'policies/');
|
||||
if (fs.existsSync(localPolicies)) spawnSync('rsync', ['-avz', '--delete', localPolicies, `${remoteHost}:${ISOLATED_GEMINI}/policies/`]);
|
||||
const localEnv = path.join(REPO_ROOT, '.env');
|
||||
if (fs.existsSync(localEnv)) spawnSync('rsync', ['-avz', localEnv, `${remoteHost}:${remoteWorkDir}/.env`]);
|
||||
}
|
||||
|
||||
// 3. Construct Clean Command
|
||||
const envLoader = 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && \\. "$NVM_DIR/nvm.sh"';
|
||||
// Set FORCE_LOCAL_OPEN=1 to signal the worker to use OSC 1337 for links
|
||||
const remoteWorker = `export FORCE_LOCAL_OPEN=1 && export GEMINI_CLI_HOME=${ISOLATED_GEMINI} && export GH_CONFIG_DIR=${ISOLATED_GH} && ./node_modules/.bin/tsx .gemini/skills/offload/scripts/entrypoint.ts ${prNumber} ${branchName} ${remotePolicyPath} ${action}`;
|
||||
|
||||
const tmuxCmd = `cd ${remoteWorkDir} && ${envLoader} && ${remoteWorker}; exec $SHELL`;
|
||||
const sshInternal = `tmux attach-session -t ${sessionName} 2>/dev/null || tmux new-session -s ${sessionName} -n ${q(branchName)} ${q(tmuxCmd)}`;
|
||||
const sshCmd = `ssh -t ${remoteHost} ${q(sshInternal)}`;
|
||||
|
||||
// 4. Smart Context Execution
|
||||
const isWithinGemini = !!env.GEMINI_SESSION_ID || !!env.GCLI_SESSION_ID;
|
||||
const forceBackground = args.includes('--background');
|
||||
|
||||
if (isWithinGemini || forceBackground) {
|
||||
if (process.platform === 'darwin' && terminalType !== 'none' && !forceBackground) {
|
||||
// macOS: Use Window Automation
|
||||
let appleScript = `on run argv\n set theCommand to item 1 of argv\n tell application "iTerm"\n set newWindow to (create window with default profile)\n tell current session of newWindow\n write text theCommand\n end tell\n activate\n end tell\n end run`;
|
||||
if (terminalType === 'terminal') {
|
||||
appleScript = `on run argv\n set theCommand to item 1 of argv\n tell application "Terminal"\n do script theCommand\n activate\n end tell\n end run`;
|
||||
}
|
||||
|
||||
spawnSync('osascript', ['-', sshCmd], { input: appleScript });
|
||||
console.log(`✅ ${terminalType.toUpperCase()} window opened for verification.`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Cross-Platform Background Mode
|
||||
console.log(`📡 Launching remote verification in background mode...`);
|
||||
const logFile = path.join(REPO_ROOT, `.gemini/logs/offload-${prNumber}/background.log`);
|
||||
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
||||
|
||||
const backgroundCmd = `ssh ${remoteHost} ${q(tmuxCmd)} > ${q(logFile)} 2>&1 &`;
|
||||
spawnSync(backgroundCmd, { shell: true });
|
||||
|
||||
console.log(`⏳ Remote worker started in background.`);
|
||||
console.log(`📄 Tailing logs to: .gemini/logs/offload-${prNumber}/background.log`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Direct Shell Mode: Execute SSH in-place
|
||||
console.log(`🚀 Launching offload session in current terminal...`);
|
||||
const result = spawnSync(sshCmd, { stdio: 'inherit', shell: true });
|
||||
return result.status || 0;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runOrchestrator(process.argv.slice(2)).catch(console.error);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* Universal Deep Review Onboarding (Local)
|
||||
*/
|
||||
import { spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import readline from 'readline';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(__dirname, '../../../..');
|
||||
|
||||
const q = (str: string) => `'${str.replace(/'/g, "'\\''")}'`;
|
||||
|
||||
async function prompt(question: string, defaultValue: string): Promise<string> {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
return new Promise((resolve) => {
|
||||
rl.question(`${question} (default: ${defaultValue}, <Enter> to use default): `, (answer) => {
|
||||
rl.close();
|
||||
resolve(answer.trim() || defaultValue);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function confirm(question: string): Promise<boolean> {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
return new Promise((resolve) => {
|
||||
rl.question(`${question} (y/n): `, (answer) => {
|
||||
rl.close();
|
||||
resolve(answer.trim().toLowerCase() === 'y');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function runSetup(env: NodeJS.ProcessEnv = process.env) {
|
||||
console.log('\n🌟 Initializing Deep Review Skill Settings...');
|
||||
|
||||
const remoteHost = await prompt('Remote SSH Host', 'cli');
|
||||
const remoteWorkDir = await prompt('Remote Work Directory', '~/gcli/deepreview');
|
||||
|
||||
console.log(`🔍 Checking state of ${remoteHost}...`);
|
||||
|
||||
// 1. Gemini CLI Isolation Choice
|
||||
const geminiChoice = await prompt('\nGemini CLI Setup: Use [p]re-existing instance or [i]solated sandbox instance? (Isolated is recommended)', 'i');
|
||||
const geminiSetup = geminiChoice.toLowerCase() === 'p' ? 'preexisting' : 'isolated';
|
||||
|
||||
// 2. GitHub CLI Isolation Choice
|
||||
const ghChoice = await prompt('GitHub CLI Setup: Use [p]re-existing instance or [i]solated sandbox instance? (Isolated is recommended)', 'i');
|
||||
const ghSetup = ghChoice.toLowerCase() === 'p' ? 'preexisting' : 'isolated';
|
||||
|
||||
const ISOLATED_GEMINI_CONFIG = '~/.gemini-deep-review';
|
||||
const ISOLATED_GH_CONFIG = '~/.gh-deep-review';
|
||||
|
||||
console.log(`🔍 Checking state of ${remoteHost}...`);
|
||||
// Use a login shell to ensure the same PATH as the interactive user
|
||||
const ghCheck = spawnSync('ssh', [remoteHost, 'sh -lc "command -v gh"'], { stdio: 'pipe' });
|
||||
const tmuxCheck = spawnSync('ssh', [remoteHost, 'sh -lc "command -v tmux"'], { stdio: 'pipe' });
|
||||
|
||||
if (ghCheck.status !== 0 || tmuxCheck.status !== 0) {
|
||||
console.log('\n📥 System Requirements Check:');
|
||||
if (ghCheck.status !== 0) console.log(' ❌ GitHub CLI (gh) is not installed on remote.');
|
||||
if (tmuxCheck.status !== 0) console.log(' ❌ tmux is not installed on remote.');
|
||||
|
||||
const shouldProvision = await confirm('\nWould you like Gemini to automatically provision missing requirements?');
|
||||
if (shouldProvision) {
|
||||
console.log(`🚀 Attempting to provision dependencies on ${remoteHost}...`);
|
||||
const osCheck = spawnSync('ssh', [remoteHost, 'uname -s'], { stdio: 'pipe' });
|
||||
const os = osCheck.stdout.toString().trim();
|
||||
|
||||
let installCmd = '';
|
||||
if (os === 'Linux') {
|
||||
installCmd = 'sudo apt update && sudo apt install -y ' + [ghCheck.status !== 0 ? 'gh' : '', tmuxCheck.status !== 0 ? 'tmux' : ''].filter(Boolean).join(' ');
|
||||
} else if (os === 'Darwin') {
|
||||
installCmd = 'brew install ' + [ghCheck.status !== 0 ? 'gh' : '', tmuxCheck.status !== 0 ? 'tmux' : ''].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
if (installCmd) {
|
||||
spawnSync('ssh', ['-t', remoteHost, installCmd], { stdio: 'inherit' });
|
||||
}
|
||||
} else {
|
||||
console.log('⚠️ Please ensure gh and tmux are installed before running again.');
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure remote work dir and isolated config dirs exist
|
||||
spawnSync('ssh', [remoteHost, `mkdir -p ${remoteWorkDir} ${ISOLATED_GEMINI_CONFIG}/policies/ ${ISOLATED_GH_CONFIG}`], { stdio: 'pipe' });
|
||||
// Identity Synchronization Onboarding
|
||||
console.log('\n🔐 Identity & Authentication:');
|
||||
|
||||
// GH Auth Check
|
||||
const ghAuthCmd = ghSetup === 'isolated' ? `export GH_CONFIG_DIR=${ISOLATED_GH_CONFIG} && gh auth status` : 'gh auth status';
|
||||
const remoteGHAuth = spawnSync('ssh', [remoteHost, `sh -lc "${ghAuthCmd}"`], { stdio: 'pipe' });
|
||||
const isGHAuthRemote = remoteGHAuth.status === 0;
|
||||
|
||||
if (isGHAuthRemote) {
|
||||
console.log(` ✅ GitHub CLI is already authenticated on remote (${ghSetup}).`);
|
||||
} else {
|
||||
console.log(` ❌ GitHub CLI is NOT authenticated on remote (${ghSetup}).`);
|
||||
// If it's isolated but global is authenticated, offer to sync
|
||||
if (ghSetup === 'isolated') {
|
||||
const globalGHAuth = spawnSync('ssh', [remoteHost, 'sh -lc "gh auth status"'], { stdio: 'pipe' });
|
||||
if (globalGHAuth.status === 0) {
|
||||
if (await confirm(' Global GH auth found. Sync it to isolated instance?')) {
|
||||
spawnSync('ssh', [remoteHost, `cp -r ~/.config/gh/* ${ISOLATED_GH_CONFIG}/`]);
|
||||
console.log(' ✅ GH Auth synced.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isGHAuthRemote) console.log(' You may need to run "gh auth login" on the remote machine later.');
|
||||
}
|
||||
|
||||
// Gemini Auth Check
|
||||
const geminiAuthCheck = geminiSetup === 'isolated'
|
||||
? `[ -f ${ISOLATED_GEMINI_CONFIG}/google_accounts.json ]`
|
||||
: '[ -f ~/.gemini/google_accounts.json ]';
|
||||
const remoteGeminiAuth = spawnSync('ssh', [remoteHost, `sh -lc "${geminiAuthCheck}"`], { stdio: 'pipe' });
|
||||
const isGeminiAuthRemote = remoteGeminiAuth.status === 0;
|
||||
|
||||
let syncAuth = false;
|
||||
if (isGeminiAuthRemote) {
|
||||
console.log(` ✅ Gemini CLI is already authenticated on remote (${geminiSetup}).`);
|
||||
} else {
|
||||
const homeDir = env.HOME || '';
|
||||
const localAuth = path.join(homeDir, '.gemini/google_accounts.json');
|
||||
const localEnv = path.join(REPO_ROOT, '.env');
|
||||
const hasAuth = fs.existsSync(localAuth);
|
||||
const hasEnv = fs.existsSync(localEnv);
|
||||
|
||||
if (hasAuth || hasEnv) {
|
||||
console.log(` 🔍 Found local Gemini CLI credentials: ${[hasAuth ? 'Google Account' : '', hasEnv ? '.env' : ''].filter(Boolean).join(', ')}`);
|
||||
syncAuth = await confirm(' Would you like Gemini to automatically sync your local credentials to the remote workstation for seamless authentication?');
|
||||
}
|
||||
}
|
||||
|
||||
const terminalType = await prompt('\nTerminal Automation (iterm2 / terminal / none)', 'iterm2');
|
||||
|
||||
// Local Dependencies Install (Isolated)
|
||||
const envLoader = 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && \\. "$NVM_DIR/nvm.sh"';
|
||||
|
||||
console.log(`\n📦 Checking isolated dependencies in ${remoteWorkDir}...`);
|
||||
const checkCmd = `ssh ${remoteHost} ${q(`${envLoader} && [ -x ${remoteWorkDir}/node_modules/.bin/tsx ] && [ -x ${remoteWorkDir}/node_modules/.bin/gemini ]`)}`;
|
||||
const depCheck = spawnSync(checkCmd, { shell: true });
|
||||
|
||||
if (depCheck.status !== 0) {
|
||||
console.log(`📦 Installing isolated dependencies (nightly CLI & tsx) in ${remoteWorkDir}...`);
|
||||
const installCmd = `ssh ${remoteHost} ${q(`${envLoader} && mkdir -p ${remoteWorkDir} && cd ${remoteWorkDir} && [ -f package.json ] || npm init -y > /dev/null && npm install tsx @google/gemini-cli@nightly`)}`;
|
||||
spawnSync(installCmd, { stdio: 'inherit', shell: true });
|
||||
} else {
|
||||
console.log('✅ Isolated dependencies already present.');
|
||||
}
|
||||
|
||||
// Save Settings
|
||||
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
|
||||
let settings: any = {};
|
||||
if (fs.existsSync(settingsPath)) {
|
||||
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch (e) {}
|
||||
}
|
||||
settings.maintainer = settings.maintainer || {};
|
||||
settings.maintainer.deepReview = { remoteHost, remoteWorkDir, terminalType, syncAuth, geminiSetup, ghSetup };
|
||||
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
|
||||
console.log('\n✅ Onboarding complete! Settings saved to .gemini/settings.json');
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runSetup().catch(console.error);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Universal Offload Worker (Remote)
|
||||
*
|
||||
* Handles worktree provisioning and parallel task execution based on 'playbooks'.
|
||||
*/
|
||||
import { spawn, spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
const prNumber = process.argv[2];
|
||||
const branchName = process.argv[3];
|
||||
const policyPath = process.argv[4];
|
||||
const action = process.argv[5] || 'review';
|
||||
|
||||
async function main() {
|
||||
if (!prNumber || !branchName || !policyPath) {
|
||||
console.error('Usage: tsx worker.ts <PR_NUMBER> <BRANCH_NAME> <POLICY_PATH> [action]');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const workDir = process.cwd(); // This is remoteWorkDir
|
||||
const targetDir = path.join(workDir, branchName);
|
||||
|
||||
// 1. Provision PR Directory
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
console.log(`🌿 Provisioning PR #${prNumber} into ${branchName}...`);
|
||||
const cloneCmd = `git clone --filter=blob:none https://github.com/google-gemini/gemini-cli.git ${targetDir}`;
|
||||
spawnSync(cloneCmd, { stdio: 'inherit', shell: true });
|
||||
|
||||
process.chdir(targetDir);
|
||||
spawnSync('gh', ['pr', 'checkout', prNumber], { stdio: 'inherit' });
|
||||
} else {
|
||||
process.chdir(targetDir);
|
||||
}
|
||||
|
||||
const logDir = path.join(targetDir, `.gemini/logs/offload-${prNumber}`);
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
|
||||
const geminiBin = path.join(workDir, 'node_modules/.bin/gemini');
|
||||
|
||||
// 2. Define Playbooks
|
||||
let tasks: any[] = [];
|
||||
|
||||
if (action === 'review') {
|
||||
tasks = [
|
||||
{ id: 'build', name: 'Fast Build', cmd: `cd ${targetDir} && npm ci && npm run build` },
|
||||
{ id: 'ci', name: 'CI Checks', cmd: `gh pr checks ${prNumber}` },
|
||||
{ id: 'review', name: 'Gemini Analysis', cmd: `${geminiBin} --policy ${policyPath} --cwd ${targetDir} -p "/review-frontend ${prNumber}"` },
|
||||
{ id: 'verify', name: 'Behavioral Proof', cmd: `${geminiBin} --policy ${policyPath} --cwd ${targetDir} -p "Analyze the code in ${targetDir} and exercise it to prove it works."`, dep: 'build' }
|
||||
];
|
||||
} else if (action === 'fix') {
|
||||
tasks = [
|
||||
{ id: 'build', name: 'Fast Build', cmd: `cd ${targetDir} && npm ci && npm run build` },
|
||||
{ id: 'failures', name: 'Find Failures', cmd: `gh run view --log-failed` },
|
||||
{ id: 'fix', name: 'Iterative Fix', cmd: `${geminiBin} --policy ${policyPath} --cwd ${targetDir} -p "Address review comments and fix failing tests for PR ${prNumber}. Repeat until CI is green."`, dep: 'build' }
|
||||
];
|
||||
} else if (action === 'ready') {
|
||||
tasks = [
|
||||
{ id: 'clean', name: 'Clean Install', cmd: `npm run clean && npm ci` },
|
||||
{ id: 'preflight', name: 'Full Preflight', cmd: `npm run preflight`, dep: 'clean' },
|
||||
{ id: 'conflicts', name: 'Conflict Check', cmd: `git fetch origin main && git merge-base --is-ancestor origin/main HEAD || echo "CONFLICT"` }
|
||||
];
|
||||
} else if (action === 'open') {
|
||||
console.log(`🚀 Dropping into manual session for ${branchName}...`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const state: Record<string, any> = {};
|
||||
tasks.forEach(t => state[t.id] = { status: 'PENDING' });
|
||||
|
||||
return new Promise((resolve) => {
|
||||
function runTask(task: any) {
|
||||
if (task.dep && state[task.dep].status !== 'SUCCESS') {
|
||||
setTimeout(() => runTask(task), 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
state[task.id].status = 'RUNNING';
|
||||
const proc = spawn(task.cmd, { shell: true, env: { ...process.env, FORCE_COLOR: '1' } });
|
||||
const logStream = fs.createWriteStream(path.join(logDir, `${task.id}.log`));
|
||||
proc.stdout.pipe(logStream);
|
||||
proc.stderr.pipe(logStream);
|
||||
|
||||
proc.on('close', (code) => {
|
||||
const exitCode = code ?? 0;
|
||||
state[task.id].status = exitCode === 0 ? 'SUCCESS' : 'FAILED';
|
||||
fs.writeFileSync(path.join(logDir, `${task.id}.exit`), exitCode.toString());
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
function render() {
|
||||
console.clear();
|
||||
console.log(`==================================================`);
|
||||
console.log(`🚀 Offload | ${action.toUpperCase()} | PR #${prNumber}`);
|
||||
console.log(`📂 Worktree: ${targetDir}`);
|
||||
console.log(`==================================================\n`);
|
||||
|
||||
tasks.forEach(t => {
|
||||
const s = state[t.id];
|
||||
const icon = s.status === 'SUCCESS' ? '✅' : s.status === 'FAILED' ? '❌' : s.status === 'RUNNING' ? '⏳' : '💤';
|
||||
console.log(` ${icon} ${t.name.padEnd(20)}: ${s.status}`);
|
||||
});
|
||||
|
||||
const allDone = tasks.every(t => ['SUCCESS', 'FAILED'].includes(state[t.id].status));
|
||||
if (allDone) {
|
||||
console.log(`\n✨ Playbook complete. Launching interactive session...`);
|
||||
resolve(0);
|
||||
}
|
||||
}
|
||||
|
||||
tasks.filter(t => !t.dep).forEach(runTask);
|
||||
tasks.filter(t => t.dep).forEach(runTask);
|
||||
const intervalId = setInterval(render, 1500);
|
||||
|
||||
const checkAllDone = setInterval(() => {
|
||||
if (tasks.every(t => ['SUCCESS', 'FAILED'].includes(state[t.id].status))) {
|
||||
clearInterval(intervalId);
|
||||
clearInterval(checkAllDone);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
runWorker(process.argv.slice(2)).catch(console.error);
|
||||
}
|
||||
Reference in New Issue
Block a user