Spaces:
Sleeping
Sleeping
File size: 10,306 Bytes
ccb6b75 | 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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | import logger from '../utils/logger.js';
import { sample, shuffle } from 'lodash-es';
class SDLCManager {
constructor(githubService, aiProvider, codeGenerator, schedule) {
this.github = githubService;
this.ai = aiProvider;
this.codeGen = codeGenerator;
this.schedule = schedule;
this.state = {
currentPhase: 'idle',
activeIssues: [],
activeBranches: [],
activePRs: [],
sessionCommits: 0,
};
}
async runCycle() {
if (!this.schedule.isWorkHours()) {
logger.info('Outside work hours, skipping cycle');
return;
}
const energy = this.schedule.getEnergyLevel();
logger.info(`Starting SDLC cycle (energy: ${(energy * 100).toFixed(0)}%)`);
await this._syncState();
const action = this._decideNextAction();
logger.info(`Decided action: ${action.type}`);
try {
switch (action.type) {
case 'create_issue':
await this._createIssue();
break;
case 'work_on_issue':
await this._workOnIssue(action.issue);
break;
case 'review_pr':
await this._reviewPR(action.pr);
break;
case 'merge_pr':
await this._mergePR(action.pr);
break;
case 'fix_review_comment':
await this._fixReviewComment(action.pr);
break;
case 'close_issue':
await this._closeIssue(action.issue);
break;
default:
logger.info('No actionable task, waiting');
}
} catch (error) {
logger.error(`SDLC cycle error: ${error.message}`);
}
this.state.sessionCommits++;
}
async _syncState() {
const [issues, prs] = await Promise.all([
this.github.listIssues('open'),
this.github.listPullRequests('open'),
]);
this.state.activeIssues = issues;
this.state.activePRs = prs;
logger.debug(`Synced state: ${issues.length} open issues, ${prs.length} open PRs`);
}
_decideNextAction() {
const { activeIssues, activePRs, sessionCommits } = this.state;
const maxCommits = this.schedule.config?.activity?.maxCommitsPerSession || 8;
if (sessionCommits >= maxCommits) {
return { type: 'idle', reason: 'max commits reached' };
}
const openPRs = activePRs.filter(pr => pr.state === 'open');
if (openPRs.length > 0 && Math.random() < 0.3) {
const pr = sample(openPRs);
if (Math.random() < 0.4) {
return { type: 'review_pr', pr };
}
if (Math.random() < 0.3) {
return { type: 'merge_pr', pr };
}
if (Math.random() < 0.2) {
return { type: 'fix_review_comment', pr };
}
}
const workableIssues = activeIssues.filter(
issue => !issue.labels?.some(l => l.name === 'in-progress')
);
if (workableIssues.length > 0 && Math.random() < 0.6) {
return { type: 'work_on_issue', issue: sample(workableIssues) };
}
if (Math.random() < 0.5) {
return { type: 'create_issue' };
}
const closableIssues = activeIssues.filter(
issue => issue.labels?.some(l => l.name === 'done' || l.name === 'resolved')
);
if (closableIssues.length > 0) {
return { type: 'close_issue', issue: sample(closableIssues) };
}
return { type: 'create_issue' };
}
async _createIssue() {
logger.info('Creating new issue');
const projectContext = await this._getProjectContext();
const title = await this.ai.generateIssueTitle(projectContext);
const body = await this.ai.generateIssueBody(title, projectContext);
const labels = this._generateIssueLabels(title);
const issue = await this.github.createIssue(title, body, labels);
this.state.activeIssues.push(issue);
logger.info(`Created issue #${issue.number}: ${title}`);
}
async _workOnIssue(issue) {
logger.info(`Working on issue #${issue.number}: ${issue.title}`);
await this.github.addLabels(issue.number, ['in-progress']);
const branchName = this._generateBranchName(issue.title);
try {
await this.github.createBranch(branchName);
} catch (error) {
logger.warn(`Branch ${branchName} exists, using it`);
}
this.state.activeBranches.push(branchName);
const structure = this.codeGen.generateProjectStructure();
const numFiles = Math.min(
structure.files.length,
(this.schedule.config?.activity?.maxFilesPerCommit || 3)
);
const filesToCreate = shuffle(structure.files).slice(0, numFiles);
for (const file of filesToCreate) {
await this._createFileInBranch(file, branchName, issue);
}
const prTitle = this._generatePRTitle(issue.title, structure.name);
const prBody = await this.ai.generatePRDescription(
branchName,
`Implemented ${structure.name} functionality for issue #${issue.number}`
);
const pr = await this.github.createPullRequest(prTitle, prBody, branchName);
this.state.activePRs.push(pr);
await this.github.addLabels(issue.number, ['done']);
logger.info(`Created PR #${pr.number} for issue #${issue.number}`);
}
async _createFileInBranch(file, branchName, issue) {
const content = this.codeGen.generateFileContent(file.type, {
issue: issue.title,
project: await this._getProjectContext(),
});
const commitMessage = this.codeGen.generateCommitMessageForFile(file.path, file.type);
await this.github.createOrUpdateFile(
file.path,
content,
commitMessage,
branchName
);
logger.info(`Created ${file.path} on ${branchName}`);
}
async _reviewPR(pr) {
logger.info(`Reviewing PR #${pr.number}: ${pr.title}`);
const files = await this.github.getPullRequestFiles(pr.number);
if (files.length === 0) {
return;
}
const fileToReview = sample(files);
try {
const content = await this._getFileContent(fileToReview);
const comment = await this.ai.generateReviewComment(
content || 'Code review pending',
fileToReview.filename
);
const reviewType = this._decideReviewType();
if (reviewType === 'comment') {
await this.github.addPullRequestComment(pr.number, comment);
} else {
await this.github.addPullRequestReview(
pr.number,
reviewType,
comment,
pr.head?.sha
);
}
logger.info(`Added ${reviewType} review to PR #${pr.number}`);
} catch (error) {
logger.error(`Review error: ${error.message}`);
}
}
async _mergePR(pr) {
logger.info(`Merging PR #${pr.number}`);
try {
await this.github.mergePullRequest(pr.number);
if (pr.head?.ref) {
await this.github.deleteBranch(pr.head.ref);
}
this.state.activePRs = this.state.activePRs.filter(p => p.number !== pr.number);
} catch (error) {
logger.error(`Merge error: ${error.message}`);
}
}
async _fixReviewComment(pr) {
logger.info(`Fixing review comments on PR #${pr.number}`);
const files = await this.github.getPullRequestFiles(pr.number);
if (files.length === 0) return;
const file = sample(files);
const content = this.codeGen.generateFileContent(file.type || 'utility', {
fix: true,
original: file.filename,
});
await this.github.createOrUpdateFile(
file.filename || file.path,
content,
'fix: address review comments',
pr.head?.ref || 'main'
);
await this.github.addPullRequestComment(
pr.number,
"Thanks for the review! I've addressed the feedback in this commit."
);
}
async _closeIssue(issue) {
logger.info(`Closing issue #${issue.number}`);
await this.github.closeIssue(issue.number);
this.state.activeIssues = this.state.activeIssues.filter(i => i.number !== issue.number);
}
_generateBranchName(issueTitle) {
const sanitized = issueTitle
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.slice(0, 50);
const prefix = this._getBranchPrefix(issueTitle);
return `${prefix}/${sanitized}`;
}
_getBranchPrefix(title) {
const lower = title.toLowerCase();
if (lower.includes('add') || lower.includes('implement') || lower.includes('new')) return 'feat';
if (lower.includes('fix') || lower.includes('bug') || lower.includes('error')) return 'fix';
if (lower.includes('refactor') || lower.includes('clean') || lower.includes('improve')) return 'refactor';
if (lower.includes('test') || lower.includes('coverage')) return 'test';
if (lower.includes('doc') || lower.includes('readme')) return 'docs';
return 'chore';
}
_generatePRTitle(issueTitle, featureName) {
const prefix = this._getBranchPrefix(issueTitle);
return `${prefix}: ${issueTitle.charAt(0).toLowerCase() + issueTitle.slice(1)}`;
}
_generateIssueLabels(title) {
const labels = [];
const lower = title.toLowerCase();
if (lower.includes('add') || lower.includes('implement') || lower.includes('new')) {
labels.push('enhancement');
}
if (lower.includes('fix') || lower.includes('bug') || lower.includes('error')) {
labels.push('bug');
}
if (lower.includes('performance') || lower.includes('optimize')) {
labels.push('performance');
}
if (lower.includes('security') || lower.includes('auth')) {
labels.push('security');
}
if (labels.length === 0) {
labels.push(sample(['enhancement', 'maintenance', 'task']));
}
return labels;
}
_decideReviewType() {
const rand = Math.random();
if (rand < 0.6) return 'comment';
if (rand < 0.85) return 'approve';
return 'request_changes';
}
async _getProjectContext() {
try {
const commits = await this.github.getCommitHistory('main', 5);
return `Recent activity: ${commits.length} commits. Project uses JavaScript/Node.js.`;
} catch {
return 'JavaScript/Node.js project';
}
}
async _getFileContent(file) {
try {
const content = await this.github.getRepositoryContent(file.filename || file.path);
if (content?.content) {
return Buffer.from(content.content, 'base64').toString();
}
} catch {
return null;
}
return null;
}
}
export default SDLCManager;
|