Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | /**
* Git Manager Service - Handle git operations for autonomous fixing
* Manages branches, commits, and safety features for AI-generated fixes
*/
const { exec } = require('child_process')
const { promisify } = require('util')
const path = require('path')
const chalk = require('chalk')
// const structlog = require('structlog')
const execAsync = promisify(exec)
const logger = { info: (...args) => console.log('[INFO]', ...args), error: (...args) => console.error('[ERROR]', ...args), warn: (...args) => console.warn('[WARN]', ...args), debug: (...args) => console.log('[DEBUG]', ...args) }
class GitManager {
constructor(repoPath) {
this.repoPath = path.resolve(repoPath)
this.originalBranch = null
}
/**
* Check if directory is a git repository
*/
async isGitRepo() {
try {
await this.execGit('rev-parse --git-dir')
return true
} catch (error) {
return false
}
}
/**
* Check for uncommitted changes
*/
async hasUncommittedChanges() {
try {
const { stdout } = await this.execGit('status --porcelain')
return stdout.trim().length > 0
} catch (error) {
return false
}
}
/**
* Get current branch name
*/
async getCurrentBranch() {
try {
const { stdout } = await this.execGit('rev-parse --abbrev-ref HEAD')
return stdout.trim()
} catch (error) {
throw new Error(`Failed to get current branch: ${error.message}`)
}
}
/**
* Check if branch exists
*/
async branchExists(branchName) {
try {
await this.execGit(`rev-parse --verify ${branchName}`)
return true
} catch (error) {
return false
}
}
/**
* Create new branch for fixes
*/
async createBranch(branchName) {
try {
// Store original branch
this.originalBranch = await this.getCurrentBranch()
// Create and switch to new branch
await this.execGit(`checkout -b ${branchName}`)
await logger.info('Created fixing branch', {
branch: branchName,
original_branch: this.originalBranch,
repo_path: this.repoPath
})
return branchName
} catch (error) {
throw new Error(`Failed to create branch ${branchName}: ${error.message}`)
}
}
/**
* Delete branch
*/
async deleteBranch(branchName) {
try {
// Switch to original branch first
if (this.originalBranch) {
await this.execGit(`checkout ${this.originalBranch}`)
}
// Force delete the branch
await this.execGit(`branch -D ${branchName}`)
await logger.info('Deleted branch', { branch: branchName })
} catch (error) {
throw new Error(`Failed to delete branch ${branchName}: ${error.message}`)
}
}
/**
* Commit changes with detailed message
*/
async commitChanges(message, fixes = []) {
try {
// Add all changed files
await this.execGit('add .')
// Build comprehensive commit message
const commitMessage = this.buildCommitMessage(message, fixes)
// Commit with detailed message
await this.execGit(`commit -m "${commitMessage}"`)
await logger.info('Committed autonomous fixes', {
fixes_count: fixes.length,
commit_message: message
})
return await this.getLatestCommitHash()
} catch (error) {
throw new Error(`Failed to commit changes: ${error.message}`)
}
}
/**
* Build detailed commit message for autonomous fixes
*/
buildCommitMessage(baseMessage, fixes = []) {
if (fixes.length === 0) {
return baseMessage
}
const fixSummary = fixes.reduce((acc, fix) => {
const type = fix.vulnerability_type || 'unknown'
acc[type] = (acc[type] || 0) + 1
return acc
}, {})
const summaryLines = Object.entries(fixSummary)
.map(([type, count]) => `- ${type}: ${count} fixed`)
.join('\\n')
return `${baseMessage}
Autonomous fixes applied by Vaultace AI:
${summaryLines}
Total vulnerabilities fixed: ${fixes.length}
AI Model: Claude Sonnet 4
Generated by: Vaultace CLI v1.0.0
Co-authored-by: Vaultace AI <ai@vaultace.com>`
}
/**
* Get latest commit hash
*/
async getLatestCommitHash() {
try {
const { stdout } = await this.execGit('rev-parse HEAD')
return stdout.trim()
} catch (error) {
return null
}
}
/**
* Create stash of current changes
*/
async stashChanges(stashName = 'vaultace-fixes') {
try {
await this.execGit(`stash push -m "${stashName}"`)
await logger.info('Stashed changes', { stash_name: stashName })
} catch (error) {
throw new Error(`Failed to stash changes: ${error.message}`)
}
}
/**
* Apply stashed changes
*/
async applyStash(stashName = 'vaultace-fixes') {
try {
await this.execGit('stash pop')
await logger.info('Applied stashed changes')
} catch (error) {
throw new Error(`Failed to apply stash: ${error.message}`)
}
}
/**
* Rollback to original state
*/
async rollbackToOriginal() {
try {
if (this.originalBranch) {
await this.execGit(`checkout ${this.originalBranch}`)
await logger.info('Rolled back to original branch', {
original_branch: this.originalBranch
})
}
} catch (error) {
throw new Error(`Failed to rollback: ${error.message}`)
}
}
/**
* Get diff of changes made
*/
async getDiff(fromCommit = null) {
try {
const command = fromCommit
? `diff ${fromCommit}..HEAD`
: 'diff --cached'
const { stdout } = await this.execGit(command)
return stdout
} catch (error) {
return ''
}
}
/**
* Get list of changed files
*/
async getChangedFiles() {
try {
const { stdout } = await this.execGit('diff --name-only --cached')
return stdout.trim().split('\n').filter(file => file.length > 0)
} catch (error) {
return []
}
}
/**
* Create pull request branch and prepare for PR
*/
async preparePullRequest(fixes, baseBranch = 'main') {
try {
const prTitle = `🤖 Autonomous security fixes: ${fixes.length} vulnerabilities resolved`
const prBody = this.buildPullRequestBody(fixes)
await logger.info('Pull request prepared', {
title: prTitle,
base_branch: baseBranch,
fixes_count: fixes.length
})
return {
title: prTitle,
body: prBody,
head: await this.getCurrentBranch(),
base: baseBranch
}
} catch (error) {
throw new Error(`Failed to prepare pull request: ${error.message}`)
}
}
/**
* Build pull request body with fix details
*/
buildPullRequestBody(fixes) {
const appliedFixes = fixes.filter(f => f.status === 'applied')
const failedFixes = fixes.filter(f => f.status === 'failed')
const severityBreakdown = appliedFixes.reduce((acc, fix) => {
acc[fix.severity] = (acc[fix.severity] || 0) + 1
return acc
}, {})
return `## 🤖 Autonomous Security Fixes by Vaultace AI
### Summary
This PR contains ${appliedFixes.length} autonomous security fixes generated and applied by Vaultace AI using Claude Sonnet 4.
### Vulnerabilities Fixed
${Object.entries(severityBreakdown).map(([severity, count]) =>
`- **${severity}**: ${count} vulnerabilities`
).join('\n')}
### Fixed Issues
${appliedFixes.map((fix, index) =>
`${index + 1}. **${fix.vulnerability_type}** in \`${path.basename(fix.file_path)}\`\n - ${fix.description}`
).join('\n')}
### AI Model Details
- **Model**: Claude Sonnet 4
- **Confidence Score**: ${(appliedFixes.reduce((acc, f) => acc + f.confidence, 0) / appliedFixes.length).toFixed(2)}
- **Risk Assessment**: Most fixes are low-risk automated changes
### Testing
- [x] All fixes validated by AI before application
- [x] No breaking changes introduced
- [ ] Manual testing recommended for authentication-related fixes
### Rollback Plan
If issues arise, rollback is simple:
\`\`\`bash
git revert <commit-hash>
\`\`\`
---
*Generated by Vaultace CLI v1.0.0 • [Learn more about autonomous fixing](https://docs.vaultace.com/autonomous-fixing)*`
}
/**
* Execute git command in repository directory
*/
async execGit(command) {
try {
return await execAsync(`git ${command}`, {
cwd: this.repoPath,
timeout: 30000 // 30 second timeout
})
} catch (error) {
throw new Error(`Git command failed: ${error.message}`)
}
}
}
module.exports = GitManager |