Integrar repositórios Git na execução de agentes e pipelines

- Módulo git-integration: clone/pull, commit/push automático, listagem de repos
- Seletor de repositório nos modais de execução (agente e pipeline)
- Seletor de branch carregado dinamicamente ao escolher repo
- Campo de diretório escondido quando repositório selecionado
- Auto-commit e push ao final da execução com mensagem descritiva
- Instrução injetada para agentes não fazerem operações git
- Rotas API: GET /repos, GET /repos/:name/branches
- Pipeline: commit automático ao final de todos os steps
This commit is contained in:
Frederico Castro
2026-02-28 04:24:47 -03:00
parent 2fae816162
commit 633b19f80d
10 changed files with 307 additions and 11 deletions

View File

@@ -0,0 +1,117 @@
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join, basename } from 'path';
const PROJECTS_DIR = '/home/projetos';
const GITEA_URL = () => process.env.GITEA_URL || 'http://gitea:3000';
const GITEA_USER = () => process.env.GITEA_USER || 'fred';
const GITEA_PASS = () => process.env.GITEA_PASS || '';
const DOMAIN = () => process.env.DOMAIN || 'nitro-cloud.duckdns.org';
function exec(cmd, cwd) {
return new Promise((resolve, reject) => {
const proc = spawn('sh', ['-c', cmd], {
cwd,
env: { ...process.env, HOME: '/tmp', GIT_TERMINAL_PROMPT: '0' },
});
let stdout = '', stderr = '';
proc.stdout.on('data', d => stdout += d);
proc.stderr.on('data', d => stderr += d);
proc.on('close', code =>
code === 0 ? resolve(stdout.trim()) : reject(new Error(stderr.trim() || `exit ${code}`))
);
});
}
function authHeader() {
return 'Basic ' + Buffer.from(`${GITEA_USER()}:${GITEA_PASS()}`).toString('base64');
}
function repoCloneUrl(repoName) {
return `${GITEA_URL().replace('://', `://${GITEA_USER()}:${GITEA_PASS()}@`)}/${GITEA_USER()}/${repoName}.git`;
}
export async function listRepos() {
const url = `${GITEA_URL()}/api/v1/user/repos?limit=50&sort=updated`;
const res = await fetch(url, { headers: { Authorization: authHeader() } });
if (!res.ok) throw new Error('Erro ao listar repositórios');
const repos = await res.json();
return repos.map(r => ({
name: r.name,
fullName: r.full_name,
description: r.description || '',
defaultBranch: r.default_branch || 'main',
updatedAt: r.updated_at,
htmlUrl: r.html_url,
cloneUrl: r.clone_url,
empty: r.empty,
}));
}
export async function listBranches(repoName) {
const url = `${GITEA_URL()}/api/v1/repos/${GITEA_USER()}/${repoName}/branches?limit=50`;
const res = await fetch(url, { headers: { Authorization: authHeader() } });
if (!res.ok) return [];
const branches = await res.json();
return branches.map(b => b.name);
}
export async function cloneOrPull(repoName, branch) {
const targetDir = join(PROJECTS_DIR, repoName);
const cloneUrl = repoCloneUrl(repoName);
if (existsSync(join(targetDir, '.git'))) {
await exec(`git remote set-url origin "${cloneUrl}"`, targetDir);
await exec('git fetch origin', targetDir);
if (branch) {
try {
await exec(`git checkout ${branch}`, targetDir);
} catch {
await exec(`git checkout -b ${branch} origin/${branch}`, targetDir);
}
await exec(`git reset --hard origin/${branch}`, targetDir);
} else {
const currentBranch = await exec('git rev-parse --abbrev-ref HEAD', targetDir);
await exec(`git reset --hard origin/${currentBranch}`, targetDir);
}
return { dir: targetDir, action: 'pull' };
}
const branchArg = branch ? `-b ${branch}` : '';
await exec(`git clone ${branchArg} "${cloneUrl}" "${targetDir}"`);
return { dir: targetDir, action: 'clone' };
}
export async function commitAndPush(repoDir, agentName, taskSummary) {
try {
const status = await exec('git status --porcelain', repoDir);
if (!status) return { changed: false };
await exec('git add -A', repoDir);
const summary = taskSummary
? taskSummary.slice(0, 100).replace(/"/g, '\\"')
: 'Alterações automáticas';
const message = `${summary}\n\nExecutado por: ${agentName}`;
await exec(
`git -c user.name="Agents Orchestrator" -c user.email="agents@${DOMAIN()}" commit -m "${message}"`,
repoDir
);
await exec('git push origin HEAD', repoDir);
const commitHash = await exec('git rev-parse --short HEAD', repoDir);
const branch = await exec('git rev-parse --abbrev-ref HEAD', repoDir);
const repoName = basename(repoDir);
const commitUrl = `https://git.${DOMAIN()}/${GITEA_USER()}/${repoName}/commit/${commitHash}`;
return { changed: true, commitHash, branch, commitUrl, filesChanged: status.split('\n').length };
} catch (err) {
return { changed: false, error: err.message };
}
}
export function getProjectDir(repoName) {
return join(PROJECTS_DIR, repoName);
}

View File

@@ -4,6 +4,7 @@ import { agentsStore, schedulesStore, executionsStore, notificationsStore, secre
import * as executor from './executor.js';
import * as scheduler from './scheduler.js';
import { generateAgentReport } from '../reports/generator.js';
import * as gitIntegration from './git-integration.js';
const DEFAULT_CONFIG = {
model: 'claude-sonnet-4-6',
@@ -180,6 +181,10 @@ export function executeTask(agentId, task, instructions, wsCallback, metadata =
effectiveInstructions += `\n\n<agentes_disponiveis>\n${agentList}\n</agentes_disponiveis>`;
}
if (metadata.repoName) {
effectiveInstructions += `\n\n<git_repository>\nVocê está trabalhando no repositório "${metadata.repoName}". NÃO faça git init, git commit, git push ou qualquer operação git. O sistema fará commit e push automaticamente ao final da execução. Foque apenas no código.\n</git_repository>`;
}
const effectiveConfig = { ...agent.config };
if (metadata.workingDirectoryOverride) {
effectiveConfig.workingDirectory = metadata.workingDirectoryOverride;
@@ -246,6 +251,23 @@ export function executeTask(agentId, task, instructions, wsCallback, metadata =
if (cb) cb({ type: 'report_generated', executionId: execId, agentId, reportFile: report.filename });
}
} catch (e) { console.error('[manager] Erro ao gerar relatório:', e.message); }
if (metadata.repoName && result.result) {
const repoDir = gitIntegration.getProjectDir(metadata.repoName);
gitIntegration.commitAndPush(repoDir, agent.agent_name, taskText.slice(0, 100))
.then(gitResult => {
if (gitResult.changed) {
console.log(`[manager] Auto-commit: ${gitResult.commitHash} em ${metadata.repoName}`);
if (cb) cb({
type: 'execution_output', executionId: execId, agentId,
data: { type: 'success', content: `Git: commit ${gitResult.commitHash} pushed para ${metadata.repoName} (${gitResult.filesChanged} arquivos) → ${gitResult.commitUrl}` },
});
} else if (gitResult.error) {
console.error(`[manager] Erro no auto-commit:`, gitResult.error);
}
})
.catch(err => console.error(`[manager] Erro no auto-commit:`, err.message));
}
if (cb) cb({ type: 'execution_complete', executionId: execId, agentId, data: result });
const isPipelineStep = !!metadata.pipelineExecutionId;

View File

@@ -1,6 +1,7 @@
import { v4 as uuidv4 } from 'uuid';
import { pipelinesStore, agentsStore, executionsStore } from '../store/db.js';
import * as executor from './executor.js';
import * as gitIntegration from './git-integration.js';
import { mem } from '../cache/index.js';
import { generatePipelineReport } from '../reports/generator.js';
@@ -293,6 +294,19 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
});
if (!pipelineState.canceled) {
if (options.repoName) {
try {
const repoDir = gitIntegration.getProjectDir(options.repoName);
const gitResult = await gitIntegration.commitAndPush(repoDir, pl.name, `Pipeline: ${pl.name}`);
if (gitResult.changed && wsCallback) {
wsCallback({
type: 'pipeline_step_output', pipelineId, stepIndex: steps.length - 1,
data: { type: 'success', content: `Git: commit ${gitResult.commitHash} pushed para ${options.repoName} (${gitResult.filesChanged} arquivos) → ${gitResult.commitUrl}` },
});
}
} catch (e) { console.error('[pipeline] Erro no auto-commit:', e.message); }
}
try {
const updated = executionsStore.getById(historyRecord.id);
if (updated) {

View File

@@ -8,6 +8,7 @@ import * as manager from '../agents/manager.js';
import { tasksStore, settingsStore, executionsStore, webhooksStore, notificationsStore, secretsStore, agentVersionsStore } from '../store/db.js';
import * as scheduler from '../agents/scheduler.js';
import * as pipeline from '../agents/pipeline.js';
import * as gitIntegration from '../agents/git-integration.js';
import { getBinPath, updateMaxConcurrent, cancelAllExecutions, getActiveExecutions } from '../agents/executor.js';
import { invalidateAgentMapCache } from '../agents/pipeline.js';
import { cached } from '../cache/index.js';
@@ -165,15 +166,24 @@ function buildContextFilesPrompt(contextFiles) {
return `\n\nArquivos de contexto anexados (leia cada um deles antes de iniciar):\n${lines.join('\n')}`;
}
router.post('/agents/:id/execute', (req, res) => {
router.post('/agents/:id/execute', async (req, res) => {
try {
const { task, instructions, contextFiles, workingDirectory } = req.body;
const { task, instructions, contextFiles, workingDirectory, repoName, repoBranch } = req.body;
if (!task) return res.status(400).json({ error: 'task é obrigatório' });
const clientId = req.headers['x-client-id'] || null;
const filesPrompt = buildContextFilesPrompt(contextFiles);
const fullTask = task + filesPrompt;
const metadata = {};
if (workingDirectory) metadata.workingDirectoryOverride = workingDirectory;
if (repoName) {
const syncResult = await gitIntegration.cloneOrPull(repoName, repoBranch || null);
metadata.workingDirectoryOverride = syncResult.dir;
metadata.repoName = repoName;
metadata.repoBranch = repoBranch || null;
} else if (workingDirectory) {
metadata.workingDirectoryOverride = workingDirectory;
}
const executionId = manager.executeTask(req.params.id, fullTask, instructions, (msg) => wsCallback(msg, clientId), metadata);
res.status(202).json({ executionId, status: 'started' });
} catch (err) {
@@ -464,11 +474,20 @@ router.delete('/pipelines/:id', (req, res) => {
router.post('/pipelines/:id/execute', async (req, res) => {
try {
const { input, workingDirectory, contextFiles } = req.body;
const { input, workingDirectory, contextFiles, repoName, repoBranch } = req.body;
if (!input) return res.status(400).json({ error: 'input é obrigatório' });
const clientId = req.headers['x-client-id'] || null;
const options = {};
if (workingDirectory) options.workingDirectory = workingDirectory;
if (repoName) {
const syncResult = await gitIntegration.cloneOrPull(repoName, repoBranch || null);
options.workingDirectory = syncResult.dir;
options.repoName = repoName;
options.repoBranch = repoBranch || null;
} else if (workingDirectory) {
options.workingDirectory = workingDirectory;
}
const filesPrompt = buildContextFilesPrompt(contextFiles);
const fullInput = input + filesPrompt;
const result = pipeline.executePipeline(req.params.id, fullInput, (msg) => wsCallback(msg, clientId), options);
@@ -1160,6 +1179,24 @@ router.delete('/files', (req, res) => {
}
});
router.get('/repos', async (req, res) => {
try {
const repos = await gitIntegration.listRepos();
res.json(repos);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/repos/:name/branches', async (req, res) => {
try {
const branches = await gitIntegration.listBranches(req.params.name);
res.json(branches);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.post('/files/publish', async (req, res) => {
const { path: projectPath } = req.body;
if (!projectPath) return res.status(400).json({ error: 'path é obrigatório' });