release-cherry-pick 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +186 -2
- package/package.json +64 -4
- package/src/cli/index.js +13 -0
- package/src/config/ai-providers.js +285 -0
- package/src/config/defaults.js +45 -0
- package/src/config/loader.js +127 -0
- package/src/config/setup.js +463 -0
- package/src/config/validator.js +80 -0
- package/src/doc/agents-generator.js +83 -0
- package/src/doc/rpd-generator.js +87 -0
- package/src/git/branch-parser.js +88 -0
- package/src/git/branch-selector.js +97 -0
- package/src/git/cherry-pick.js +216 -0
- package/src/git/git-auth.js +41 -0
- package/src/git/release-branch.js +106 -0
- package/src/git/release-status.js +121 -0
- package/src/git/remote-url.js +34 -0
- package/src/git/repo-state.js +153 -0
- package/src/gitlab/ai-description.js +157 -0
- package/src/gitlab/client.js +324 -0
- package/src/gitlab/mr-creator.js +55 -0
- package/src/gitlab/reviewer-selector.js +52 -0
- package/src/index.js +58 -0
- package/src/report/summary.js +91 -0
- package/src/utils/errors.js +47 -0
- package/src/utils/logger.js +36 -0
- package/src/utils/prompts.js +59 -0
- package/src/utils/secrets.js +24 -0
- package/src/workflow/release.js +464 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const simpleGit = require('simple-git');
|
|
4
|
+
const logger = require('../utils/logger');
|
|
5
|
+
const { GitError } = require('../utils/errors');
|
|
6
|
+
|
|
7
|
+
const git = simpleGit();
|
|
8
|
+
|
|
9
|
+
function buildReleaseBranchName(sourceBranch, branchPrefix = {}) {
|
|
10
|
+
let name = sourceBranch;
|
|
11
|
+
for (const prefix of Object.values(branchPrefix)) {
|
|
12
|
+
if (prefix && prefix !== branchPrefix.release && name.startsWith(prefix)) {
|
|
13
|
+
name = name.slice(prefix.length);
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return `${branchPrefix.release || 'release/'}${name}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function createReleaseBranch(sourceBranch, stagingBranch = 'staging', branchPrefix = {}) {
|
|
21
|
+
const releaseBranchName = buildReleaseBranchName(sourceBranch, branchPrefix);
|
|
22
|
+
|
|
23
|
+
logger.info(`Creating release branch: ${releaseBranchName}`);
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
// Fetch latest changes
|
|
27
|
+
await git.fetch();
|
|
28
|
+
|
|
29
|
+
// Check if release branch already exists (exact name match: a substring check would make
|
|
30
|
+
// e.g. release/PB-12 look taken just because release/PB-123 exists)
|
|
31
|
+
const remoteBranches = await git.branch(['-r']);
|
|
32
|
+
const existsOnOrigin = remoteBranches.all.includes(`origin/${releaseBranchName}`);
|
|
33
|
+
|
|
34
|
+
if (existsOnOrigin) {
|
|
35
|
+
// Deleting/overwriting a remote branch here would be a destructive action on shared
|
|
36
|
+
// state (it may already have commits or an open MR) — never do it automatically, even
|
|
37
|
+
// behind a confirmation prompt. Report it and let the user resolve it manually.
|
|
38
|
+
logger.error(`Release branch ${releaseBranchName} already exists on origin. Resolve this manually (delete it, or pick a different branch) and re-run.`);
|
|
39
|
+
return {
|
|
40
|
+
success: false,
|
|
41
|
+
branch: releaseBranchName,
|
|
42
|
+
reason: `Release branch ${releaseBranchName} already exists on origin — needs manual decision by the user`
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A local-only leftover (e.g. from an earlier run, possibly with manual work on it) is not
|
|
47
|
+
// deleted automatically either — same reasoning, and it's the user's work to decide about.
|
|
48
|
+
const localBranches = await git.branchLocal();
|
|
49
|
+
if (localBranches.all.includes(releaseBranchName)) {
|
|
50
|
+
logger.error(`Release branch ${releaseBranchName} already exists locally. If it's not needed, delete it with \`git branch -D ${releaseBranchName}\` and re-run.`);
|
|
51
|
+
return {
|
|
52
|
+
success: false,
|
|
53
|
+
branch: releaseBranchName,
|
|
54
|
+
reason: `Release branch ${releaseBranchName} already exists locally — delete it (\`git branch -D ${releaseBranchName}\`) if it's not needed and re-run`
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Checkout staging and create release branch
|
|
59
|
+
await git.checkout(stagingBranch);
|
|
60
|
+
await git.pull('origin', stagingBranch);
|
|
61
|
+
await git.checkoutLocalBranch(releaseBranchName);
|
|
62
|
+
|
|
63
|
+
logger.success(`Release branch ${releaseBranchName} created from ${stagingBranch}`);
|
|
64
|
+
|
|
65
|
+
return { success: true, created: true, branch: releaseBranchName };
|
|
66
|
+
} catch (error) {
|
|
67
|
+
throw new GitError(`Failed to create release branch: ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function checkoutBranch(branchName) {
|
|
72
|
+
try {
|
|
73
|
+
await git.checkout(branchName);
|
|
74
|
+
logger.info(`Checked out branch: ${branchName}`);
|
|
75
|
+
return true;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw new GitError(`Failed to checkout branch: ${error.message}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function getLatestCommitHash(branchName) {
|
|
82
|
+
try {
|
|
83
|
+
const result = await git.log([branchName, '-1']);
|
|
84
|
+
return result.latest.hash;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw new GitError(`Failed to get commit hash: ${error.message}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function pushBranch(branchName) {
|
|
91
|
+
try {
|
|
92
|
+
await git.push(['-u', 'origin', branchName]);
|
|
93
|
+
logger.success(`Pushed ${branchName} to origin`);
|
|
94
|
+
return true;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new GitError(`Failed to push branch ${branchName}: ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = {
|
|
101
|
+
buildReleaseBranchName,
|
|
102
|
+
createReleaseBranch,
|
|
103
|
+
checkoutBranch,
|
|
104
|
+
getLatestCommitHash,
|
|
105
|
+
pushBranch
|
|
106
|
+
};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const logger = require('../utils/logger');
|
|
4
|
+
|
|
5
|
+
class ReleaseStatus {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.results = [];
|
|
8
|
+
// Warnings recorded while a task is processed, attached to its result when it's marked
|
|
9
|
+
this.pendingNotes = new Map();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// e.g. commits that mention the task ID without following the "[TASK-ID] ..." convention
|
|
13
|
+
addNote(taskId, note) {
|
|
14
|
+
if (!this.pendingNotes.has(taskId)) {
|
|
15
|
+
this.pendingNotes.set(taskId, []);
|
|
16
|
+
}
|
|
17
|
+
this.pendingNotes.get(taskId).push(note);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
addResult(taskId, branch, status, details = {}) {
|
|
21
|
+
this.results.push({
|
|
22
|
+
taskId,
|
|
23
|
+
branch,
|
|
24
|
+
status, // 'PROCEDE' | 'NO PROCEDE' | 'CONFLICT' | 'SKIPPED'
|
|
25
|
+
mrLink: details.mrLink || null,
|
|
26
|
+
conflicts: details.conflicts || [],
|
|
27
|
+
reason: details.reason || null,
|
|
28
|
+
notes: this.pendingNotes.get(taskId) || [],
|
|
29
|
+
timestamp: new Date().toISOString()
|
|
30
|
+
});
|
|
31
|
+
this.pendingNotes.delete(taskId);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
markProcede(taskId, branch, mrLink = null) {
|
|
35
|
+
this.addResult(taskId, branch, 'PROCEDE', { mrLink });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// reasons: why the branch couldn't be processed (e.g. release branch already exists, git error)
|
|
39
|
+
markNoProcede(taskId, branch, reasons = []) {
|
|
40
|
+
this.addResult(taskId, branch, 'NO PROCEDE', { reason: reasons.join('; ') || null });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
markConflict(taskId, branch, conflicts = []) {
|
|
44
|
+
this.addResult(taskId, branch, 'CONFLICT', { conflicts });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
markSkipped(taskId, branch, reason = null) {
|
|
48
|
+
this.addResult(taskId, branch, 'SKIPPED', { reason });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
getResults() {
|
|
52
|
+
return this.results;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
getProcedeCount() {
|
|
56
|
+
return this.results.filter(r => r.status === 'PROCEDE').length;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
getNoProcedeCount() {
|
|
60
|
+
return this.results.filter(r => r.status === 'NO PROCEDE').length;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
getConflictCount() {
|
|
64
|
+
return this.results.filter(r => r.status === 'CONFLICT').length;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
getSkippedCount() {
|
|
68
|
+
return this.results.filter(r => r.status === 'SKIPPED').length;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Release branches actually left behind by this run: only PROCEDE ones were pushed and kept —
|
|
72
|
+
// CONFLICT/SKIPPED/NO PROCEDE branches are either never created or deleted again as empty
|
|
73
|
+
// (see restoreStartingPoint in git/repo-state.js).
|
|
74
|
+
getCreatedBranches() {
|
|
75
|
+
return this.results.filter(r => r.status === 'PROCEDE').map(r => r.branch);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
getSummary() {
|
|
79
|
+
return {
|
|
80
|
+
total: this.results.length,
|
|
81
|
+
procede: this.getProcedeCount(),
|
|
82
|
+
noProcede: this.getNoProcedeCount(),
|
|
83
|
+
conflict: this.getConflictCount(),
|
|
84
|
+
skipped: this.getSkippedCount(),
|
|
85
|
+
results: this.results
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
displaySummary() {
|
|
90
|
+
logger.header('Release Summary');
|
|
91
|
+
|
|
92
|
+
console.log('\nResults:');
|
|
93
|
+
console.log('─'.repeat(80));
|
|
94
|
+
|
|
95
|
+
for (const result of this.results) {
|
|
96
|
+
const icon = result.status === 'PROCEDE' ? '✓' : (result.status === 'CONFLICT' ? '⚠' : (result.status === 'SKIPPED' ? '·' : '✖'));
|
|
97
|
+
console.log(`${icon} [${result.taskId}] ${result.branch} — ${result.status}`);
|
|
98
|
+
|
|
99
|
+
if (result.mrLink) {
|
|
100
|
+
console.log(` MR: ${result.mrLink}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (result.status === 'CONFLICT') {
|
|
104
|
+
console.log(` Needs manual resolution. Conflicting files: ${result.conflicts.join(', ')}`);
|
|
105
|
+
} else if (result.status === 'SKIPPED') {
|
|
106
|
+
console.log(` ${result.reason || 'Nothing to release — no action needed.'}`);
|
|
107
|
+
} else if (result.status === 'NO PROCEDE' && result.reason) {
|
|
108
|
+
console.log(` Reason: ${result.reason}`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const note of result.notes) {
|
|
112
|
+
console.log(` ⚠ ${note}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
console.log('─'.repeat(80));
|
|
117
|
+
console.log(`\nTotal: ${this.results.length} | PROCEDE: ${this.getProcedeCount()} | NO PROCEDE: ${this.getNoProcedeCount()} | CONFLICT: ${this.getConflictCount()} | SKIPPED: ${this.getSkippedCount()}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = ReleaseStatus;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Parses a git remote URL into { host, protocol, projectPath }. Handles SCP-like SSH remotes
|
|
4
|
+
// (git@host:group/proj.git) and scheme URLs (https://[user@]host[:port]/group/proj.git,
|
|
5
|
+
// ssh://git@host:2222/group/proj.git). Only http(s) keeps the port in `host`: an SSH port isn't
|
|
6
|
+
// where the web API lives. Returns null if the URL can't be parsed.
|
|
7
|
+
function parseRemoteUrl(url) {
|
|
8
|
+
const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(url);
|
|
9
|
+
if (!hasScheme) {
|
|
10
|
+
// SCP-like syntax: "[user@]host:path" (checking for a scheme first matters: "https://..."
|
|
11
|
+
// contains ":" too, which used to be misread as SCP syntax)
|
|
12
|
+
const scp = url.match(/^(?:[^@/]+@)?([^:/]+):(.+)$/);
|
|
13
|
+
return scp ? { host: scp[1], protocol: 'https', projectPath: normalizeProjectPath(scp[2]) } : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
const parsed = new URL(url);
|
|
18
|
+
const isHttp = /^https?:$/.test(parsed.protocol);
|
|
19
|
+
return {
|
|
20
|
+
host: isHttp ? parsed.host : parsed.hostname,
|
|
21
|
+
// Web/API protocol: an http:// remote means GitLab is served over plain http
|
|
22
|
+
protocol: isHttp ? parsed.protocol.slice(0, -1) : 'https',
|
|
23
|
+
projectPath: normalizeProjectPath(parsed.pathname)
|
|
24
|
+
};
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function normalizeProjectPath(projectPath) {
|
|
31
|
+
return decodeURIComponent(projectPath).replace(/^\/+/, '').replace(/\/+$/, '').replace(/\.git$/, '');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = { parseRemoteUrl };
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const simpleGit = require('simple-git');
|
|
6
|
+
const logger = require('../utils/logger');
|
|
7
|
+
const { GitError } = require('../utils/errors');
|
|
8
|
+
|
|
9
|
+
const git = simpleGit();
|
|
10
|
+
|
|
11
|
+
// Checks for .git/CHERRY_PICK_HEAD directly: `git rev-parse -q --verify CHERRY_PICK_HEAD` fails
|
|
12
|
+
// silently (no stderr), and simple-git only rejects when stderr has content, so it can't be used.
|
|
13
|
+
async function isCherryPickInProgress() {
|
|
14
|
+
try {
|
|
15
|
+
const gitPath = (await git.raw(['rev-parse', '--git-path', 'CHERRY_PICK_HEAD'])).trim();
|
|
16
|
+
return fs.existsSync(path.resolve(process.cwd(), gitPath));
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Preflight before the release touches any branch: refuses to start with uncommitted changes to
|
|
23
|
+
// tracked files (checking out staging would fail or carry them onto a release branch) or with a
|
|
24
|
+
// cherry-pick in progress. Untracked files are fine.
|
|
25
|
+
// Returns where HEAD is now (branch name, or commit hash if detached) so it can be restored later.
|
|
26
|
+
async function captureStartingPoint() {
|
|
27
|
+
let status;
|
|
28
|
+
try {
|
|
29
|
+
status = await git.status();
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new GitError(`Not a usable git repository here: ${error.message}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (await isCherryPickInProgress()) {
|
|
35
|
+
throw new GitError('A cherry-pick is in progress in this repository. Finish it (`git cherry-pick --continue`) or abort it (`git cherry-pick --abort`), then re-run.');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const changed = status.files.filter(file => file.index !== '?' && file.working_dir !== '?');
|
|
39
|
+
if (changed.length > 0) {
|
|
40
|
+
const list = changed.slice(0, 10).map(file => ` - ${file.path}`).join('\n');
|
|
41
|
+
const more = changed.length > 10 ? `\n ...and ${changed.length - 10} more` : '';
|
|
42
|
+
throw new GitError(`You have uncommitted changes. Commit or stash them before running a release:\n${list}${more}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (status.detached) {
|
|
46
|
+
const hash = (await git.revparse(['HEAD'])).trim();
|
|
47
|
+
return { ref: hash, label: `detached HEAD at ${hash.slice(0, 8)}` };
|
|
48
|
+
}
|
|
49
|
+
return { ref: status.current, label: status.current };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Puts the repo back where the release started and deletes the empty release branches this run
|
|
53
|
+
// created (conflicts, skipped and failed tasks). Never throws: each step only warns on failure, so
|
|
54
|
+
// it's safe to call from a finally block after an error.
|
|
55
|
+
async function restoreStartingPoint(startingPoint, branchesToDelete = []) {
|
|
56
|
+
if (await isCherryPickInProgress()) {
|
|
57
|
+
try {
|
|
58
|
+
await git.raw(['cherry-pick', '--abort']);
|
|
59
|
+
logger.warn('Aborted a cherry-pick left in progress');
|
|
60
|
+
} catch (error) {
|
|
61
|
+
logger.warn(`Could not abort the cherry-pick in progress: ${error.message}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let restored = false;
|
|
66
|
+
try {
|
|
67
|
+
await git.checkout(startingPoint.ref);
|
|
68
|
+
restored = true;
|
|
69
|
+
logger.info(`Returned to ${startingPoint.label}`);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
logger.warn(`Could not return to ${startingPoint.label}: ${error.message}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
for (const branch of branchesToDelete) {
|
|
75
|
+
if (!restored) {
|
|
76
|
+
logger.warn(`Kept empty local release branch ${branch} (could not leave it safely)`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
await git.raw(['branch', '-D', branch]);
|
|
81
|
+
logger.info(`Deleted empty local release branch ${branch}`);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
logger.warn(`Could not delete local release branch ${branch}: ${error.message}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// How long to wait after Ctrl+C for `work` to reach a checkpoint before cleaning up anyway. Needed
|
|
89
|
+
// when it's blocked on an Inquirer prompt: Inquirer closes the prompt and re-sends SIGINT, but the
|
|
90
|
+
// prompt's promise never settles, so `work` never gets to its checkpoint.
|
|
91
|
+
const INTERRUPT_GRACE_MS = 2000;
|
|
92
|
+
|
|
93
|
+
// Runs `work(signal)` so that Ctrl+C still restores the repository. The first Ctrl+C sets
|
|
94
|
+
// `signal.interrupted` — `work` must check it between steps and stop — then, once `work` has
|
|
95
|
+
// stopped (or after the grace period), runs `cleanup` and exits with code 130. A second Ctrl+C
|
|
96
|
+
// exits right away. Without interruption, `cleanup` runs once when `work` finishes or throws.
|
|
97
|
+
async function runInterruptible(work, cleanup) {
|
|
98
|
+
const signal = { interrupted: false };
|
|
99
|
+
let cleanupPromise = null;
|
|
100
|
+
const cleanupOnce = () => {
|
|
101
|
+
cleanupPromise = cleanupPromise || Promise.resolve().then(cleanup);
|
|
102
|
+
return cleanupPromise;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
let markWorkStopped;
|
|
106
|
+
const workStopped = new Promise(resolve => { markWorkStopped = resolve; });
|
|
107
|
+
|
|
108
|
+
const onSigint = () => {
|
|
109
|
+
if (signal.interrupted) {
|
|
110
|
+
logger.error('Forced exit — the repository may need manual cleanup (check `git status`)');
|
|
111
|
+
process.exit(130);
|
|
112
|
+
}
|
|
113
|
+
signal.interrupted = true;
|
|
114
|
+
logger.warn('Interrupted — restoring the repository before exiting (press Ctrl+C again to force quit)...');
|
|
115
|
+
const grace = new Promise(resolve => setTimeout(resolve, INTERRUPT_GRACE_MS));
|
|
116
|
+
Promise.race([workStopped, grace])
|
|
117
|
+
.then(cleanupOnce)
|
|
118
|
+
.finally(() => process.exit(130));
|
|
119
|
+
};
|
|
120
|
+
process.on('SIGINT', onSigint);
|
|
121
|
+
|
|
122
|
+
// On Ctrl+C during a prompt, Inquirer closes it and re-sends the signal with
|
|
123
|
+
// process.kill(process.pid, 'SIGINT'). On Windows, process.kill terminates the process
|
|
124
|
+
// unconditionally (no handlers run), so while `work` runs, turn that self-sent SIGINT into a
|
|
125
|
+
// regular SIGINT event instead.
|
|
126
|
+
const realKill = process.kill;
|
|
127
|
+
process.kill = function (pid, sig) {
|
|
128
|
+
if (pid === process.pid && sig === 'SIGINT') {
|
|
129
|
+
process.emit('SIGINT', 'SIGINT');
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
return realKill.apply(process, arguments);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
try {
|
|
136
|
+
return await work(signal);
|
|
137
|
+
} finally {
|
|
138
|
+
markWorkStopped();
|
|
139
|
+
await cleanupOnce();
|
|
140
|
+
if (signal.interrupted) {
|
|
141
|
+
// Don't return to the caller (it would go on to the summary prompts); the handler exits
|
|
142
|
+
process.exit(130);
|
|
143
|
+
}
|
|
144
|
+
process.kill = realKill;
|
|
145
|
+
process.removeListener('SIGINT', onSigint);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
module.exports = {
|
|
150
|
+
captureStartingPoint,
|
|
151
|
+
restoreStartingPoint,
|
|
152
|
+
runInterruptible
|
|
153
|
+
};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const Anthropic = require('@anthropic-ai/sdk');
|
|
4
|
+
const logger = require('../utils/logger');
|
|
5
|
+
const {
|
|
6
|
+
DEFAULT_PROVIDER,
|
|
7
|
+
loadProviderCatalog,
|
|
8
|
+
resolveApiKey,
|
|
9
|
+
resolveBaseURL
|
|
10
|
+
} = require('../config/ai-providers');
|
|
11
|
+
|
|
12
|
+
function buildPrompt(taskId, description, commitLines) {
|
|
13
|
+
return `Estás generando el título y la descripción de un merge request de GitLab para un cherry-pick de release.
|
|
14
|
+
ID de tarea: ${taskId}
|
|
15
|
+
Descripción de la tarea: ${description}
|
|
16
|
+
Commits incluidos:
|
|
17
|
+
${commitLines}
|
|
18
|
+
|
|
19
|
+
Escribe todo el contenido en español, sin importar en qué idioma esté la descripción de la tarea o los mensajes de los commits:
|
|
20
|
+
1. Un título de MR conciso, en español, máx. ~72 caracteres, que empiece con "[${taskId}] " seguido de un resumen breve.
|
|
21
|
+
2. Una descripción de MR clara en Markdown, en español, que resuma el cambio y haga referencia a ${taskId}.
|
|
22
|
+
|
|
23
|
+
Devuelve SOLO JSON, sin fences de markdown, exactamente así: {"title": "...", "description": "..."}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function generateWithAnthropic({ apiKey, model, prompt, baseURL }) {
|
|
27
|
+
const client = new Anthropic({ apiKey, baseURL: baseURL || undefined });
|
|
28
|
+
const response = await client.messages.create({
|
|
29
|
+
model,
|
|
30
|
+
max_tokens: 4096,
|
|
31
|
+
messages: [{ role: 'user', content: prompt }]
|
|
32
|
+
});
|
|
33
|
+
const textBlock = response.content.find((b) => b.type === 'text');
|
|
34
|
+
if (!textBlock) {
|
|
35
|
+
throw new Error('Anthropic response contained no text block');
|
|
36
|
+
}
|
|
37
|
+
return textBlock.text.trim();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function generateWithGoogle({ apiKey, model, prompt }) {
|
|
41
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
|
|
42
|
+
const response = await globalThis.fetch(url, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: { 'Content-Type': 'application/json' },
|
|
45
|
+
body: JSON.stringify({
|
|
46
|
+
contents: [{ role: 'user', parts: [{ text: prompt }] }],
|
|
47
|
+
generationConfig: { maxOutputTokens: 4096 }
|
|
48
|
+
})
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
const errorBody = await response.text();
|
|
53
|
+
throw new Error(`Google API error ${response.status}: ${errorBody}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const data = await response.json();
|
|
57
|
+
const parts = data.candidates && data.candidates[0] && data.candidates[0].content
|
|
58
|
+
? data.candidates[0].content.parts || []
|
|
59
|
+
: [];
|
|
60
|
+
const text = parts.map((part) => part.text || '').join('').trim();
|
|
61
|
+
if (!text) {
|
|
62
|
+
throw new Error('Google response contained no content');
|
|
63
|
+
}
|
|
64
|
+
return text;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function generateWithOpenAICompatible({ apiKey, model, prompt, baseURL }) {
|
|
68
|
+
if (!baseURL) {
|
|
69
|
+
throw new Error('No API base URL configured for this provider');
|
|
70
|
+
}
|
|
71
|
+
const url = `${String(baseURL).replace(/\/+$/, '')}/chat/completions`;
|
|
72
|
+
const response = await globalThis.fetch(url, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: {
|
|
75
|
+
'Content-Type': 'application/json',
|
|
76
|
+
Authorization: `Bearer ${apiKey}`
|
|
77
|
+
},
|
|
78
|
+
body: JSON.stringify({
|
|
79
|
+
model,
|
|
80
|
+
// Generous budget: some models (e.g. reasoning/"thinking" variants) spend part of
|
|
81
|
+
// max_tokens on hidden reasoning before writing the visible answer, and a small budget can
|
|
82
|
+
// leave `content` empty with finish_reason "length" even though the request "succeeded".
|
|
83
|
+
max_tokens: 4096,
|
|
84
|
+
messages: [{ role: 'user', content: prompt }]
|
|
85
|
+
})
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (!response.ok) {
|
|
89
|
+
const errorBody = await response.text();
|
|
90
|
+
throw new Error(`Provider API error ${response.status}: ${errorBody}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const data = await response.json();
|
|
94
|
+
const choice = data.choices && data.choices[0];
|
|
95
|
+
const content = choice && choice.message ? choice.message.content : null;
|
|
96
|
+
if (!content) {
|
|
97
|
+
// Surface finish_reason (e.g. "length", "content_filter") so a future failure is diagnosable
|
|
98
|
+
// instead of a bare "no content" — this is what happens if max_tokens runs out before the
|
|
99
|
+
// model writes visible output, or if the provider filtered the response.
|
|
100
|
+
const finishReason = choice ? choice.finish_reason : undefined;
|
|
101
|
+
const hint = finishReason ? ` (finish_reason: ${finishReason})` : ` — raw response: ${JSON.stringify(data).slice(0, 300)}`;
|
|
102
|
+
throw new Error(`Provider response contained no content${hint}`);
|
|
103
|
+
}
|
|
104
|
+
return content.trim();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function generateMRTitleAndDescription(config, taskId, description, commits = []) {
|
|
108
|
+
if (!config.ai || !config.ai.enabled) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const providerId = String(config.ai.provider || DEFAULT_PROVIDER).toLowerCase();
|
|
113
|
+
|
|
114
|
+
const catalog = await loadProviderCatalog().catch(() => ({}));
|
|
115
|
+
const providerEntry = catalog[providerId];
|
|
116
|
+
|
|
117
|
+
const apiKey = resolveApiKey(config, providerId, providerEntry);
|
|
118
|
+
if (!apiKey) {
|
|
119
|
+
const envHint = providerEntry ? ` or its env var` : '';
|
|
120
|
+
logger.warn(`AI enabled but no API key for ${providerId} (config.ai.apiKey${envHint}); using template MR content`);
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const baseURL = resolveBaseURL(providerId, providerEntry, config);
|
|
125
|
+
const model = config.ai.model;
|
|
126
|
+
if (!model) {
|
|
127
|
+
logger.warn('AI enabled but no model saved in configuration; using template MR content');
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const commitLines = commits.map((c) => `- ${c.hash}: ${c.message}`).join('\n') || '(no commit messages available)';
|
|
132
|
+
const prompt = buildPrompt(taskId, description, commitLines);
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
let rawText;
|
|
136
|
+
if (providerId === 'anthropic' || (baseURL && baseURL.includes('api.anthropic.com'))) {
|
|
137
|
+
rawText = await generateWithAnthropic({ apiKey, model, prompt, baseURL });
|
|
138
|
+
} else if (providerId === 'google') {
|
|
139
|
+
rawText = await generateWithGoogle({ apiKey, model, prompt });
|
|
140
|
+
} else {
|
|
141
|
+
rawText = await generateWithOpenAICompatible({ apiKey, model, prompt, baseURL });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const cleaned = rawText.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
|
|
145
|
+
const parsed = JSON.parse(cleaned);
|
|
146
|
+
if (!parsed.title || !parsed.description) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { title: parsed.title, description: parsed.description };
|
|
151
|
+
} catch (error) {
|
|
152
|
+
logger.warn(`AI MR content generation failed, falling back to template: ${error.message}`);
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { generateMRTitleAndDescription };
|