Merge upstream/main with Gitea support preserved
- design_task → research_task (breaking change) - QA role → Tester role (renamed) - Auto-merge for approved PRs - Enhanced workspace scaffolding - Preserved Gitea provider support (github|gitlab|gitea) - Preserved business hours scheduling (stashed)
This commit is contained in:
@@ -6,8 +6,11 @@ import {
|
||||
type Issue,
|
||||
type StateLabel,
|
||||
type IssueComment,
|
||||
type PrStatus,
|
||||
PrState,
|
||||
} from "./provider.js";
|
||||
import { runCommand } from "../run-command.js";
|
||||
import { withResilience } from "./resilience.js";
|
||||
import {
|
||||
DEFAULT_WORKFLOW,
|
||||
getStateLabels,
|
||||
@@ -41,8 +44,38 @@ export class GitHubProvider implements IssueProvider {
|
||||
}
|
||||
|
||||
private async gh(args: string[]): Promise<string> {
|
||||
const result = await runCommand(["gh", ...args], { timeoutMs: 30_000, cwd: this.repoPath });
|
||||
return result.stdout.trim();
|
||||
return withResilience(async () => {
|
||||
const result = await runCommand(["gh", ...args], { timeoutMs: 30_000, cwd: this.repoPath });
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find PRs associated with an issue.
|
||||
* Primary: match by head branch pattern (fix/123-, feature/123-, etc.)
|
||||
* Fallback: word-boundary match on #123 in title/body.
|
||||
*/
|
||||
private async findPrsForIssue<T extends { title: string; body: string; headRefName?: string }>(
|
||||
issueId: number,
|
||||
state: "open" | "merged" | "all",
|
||||
fields: string,
|
||||
): Promise<T[]> {
|
||||
try {
|
||||
const args = ["pr", "list", "--json", fields, "--limit", "50"];
|
||||
if (state !== "all") args.push("--state", state);
|
||||
const raw = await this.gh(args);
|
||||
if (!raw) return [];
|
||||
const prs = JSON.parse(raw) as T[];
|
||||
const branchPat = new RegExp(`^(?:fix|feature|chore|bugfix|hotfix)/${issueId}-`);
|
||||
const titlePat = new RegExp(`\\b#${issueId}\\b`);
|
||||
|
||||
// Primary: match by branch name
|
||||
const byBranch = prs.filter((pr) => pr.headRefName && branchPat.test(pr.headRefName));
|
||||
if (byBranch.length > 0) return byBranch;
|
||||
|
||||
// Fallback: word-boundary match in title/body
|
||||
return prs.filter((pr) => titlePat.test(pr.title) || titlePat.test(pr.body ?? ""));
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
async ensureLabel(name: string, color: string): Promise<void> {
|
||||
@@ -97,6 +130,17 @@ export class GitHubProvider implements IssueProvider {
|
||||
await this.gh(args);
|
||||
}
|
||||
|
||||
async addLabel(issueId: number, label: string): Promise<void> {
|
||||
await this.gh(["issue", "edit", String(issueId), "--add-label", label]);
|
||||
}
|
||||
|
||||
async removeLabels(issueId: number, labels: string[]): Promise<void> {
|
||||
if (labels.length === 0) return;
|
||||
const args = ["issue", "edit", String(issueId)];
|
||||
for (const l of labels) args.push("--remove-label", l);
|
||||
await this.gh(args);
|
||||
}
|
||||
|
||||
async closeIssue(issueId: number): Promise<void> { await this.gh(["issue", "close", String(issueId)]); }
|
||||
async reopenIssue(issueId: number): Promise<void> { await this.gh(["issue", "reopen", String(issueId)]); }
|
||||
|
||||
@@ -108,20 +152,47 @@ export class GitHubProvider implements IssueProvider {
|
||||
}
|
||||
|
||||
async hasMergedMR(issueId: number): Promise<boolean> {
|
||||
try {
|
||||
const raw = await this.gh(["pr", "list", "--state", "merged", "--json", "title,body"]);
|
||||
const prs = JSON.parse(raw) as Array<{ title: string; body: string }>;
|
||||
const pat = `#${issueId}`;
|
||||
return prs.some((pr) => pr.title.includes(pat) || (pr.body ?? "").includes(pat));
|
||||
} catch { return false; }
|
||||
const prs = await this.findPrsForIssue(issueId, "merged", "title,body,headRefName");
|
||||
return prs.length > 0;
|
||||
}
|
||||
|
||||
async getMergedMRUrl(issueId: number): Promise<string | null> {
|
||||
type MergedPr = { title: string; body: string; headRefName: string; url: string; mergedAt: string };
|
||||
const prs = await this.findPrsForIssue<MergedPr>(issueId, "merged", "title,body,headRefName,url,mergedAt");
|
||||
if (prs.length === 0) return null;
|
||||
prs.sort((a, b) => new Date(b.mergedAt).getTime() - new Date(a.mergedAt).getTime());
|
||||
return prs[0].url;
|
||||
}
|
||||
|
||||
async getPrStatus(issueId: number): Promise<PrStatus> {
|
||||
// Check open PRs first
|
||||
type OpenPr = { title: string; body: string; headRefName: string; url: string; reviewDecision: string };
|
||||
const open = await this.findPrsForIssue<OpenPr>(issueId, "open", "title,body,headRefName,url,reviewDecision");
|
||||
if (open.length > 0) {
|
||||
const pr = open[0];
|
||||
const state = pr.reviewDecision === "APPROVED" ? PrState.APPROVED : PrState.OPEN;
|
||||
return { state, url: pr.url };
|
||||
}
|
||||
// Check merged PRs
|
||||
type MergedPr = { title: string; body: string; headRefName: string; url: string };
|
||||
const merged = await this.findPrsForIssue<MergedPr>(issueId, "merged", "title,body,headRefName,url");
|
||||
if (merged.length > 0) return { state: PrState.MERGED, url: merged[0].url };
|
||||
return { state: PrState.CLOSED, url: null };
|
||||
}
|
||||
|
||||
async mergePr(issueId: number): Promise<void> {
|
||||
type OpenPr = { title: string; body: string; headRefName: string; url: string };
|
||||
const prs = await this.findPrsForIssue<OpenPr>(issueId, "open", "title,body,headRefName,url");
|
||||
if (prs.length === 0) throw new Error(`No open PR found for issue #${issueId}`);
|
||||
await this.gh(["pr", "merge", prs[0].url, "--merge"]);
|
||||
}
|
||||
|
||||
async getPrDiff(issueId: number): Promise<string | null> {
|
||||
type OpenPr = { title: string; body: string; headRefName: string; number: number };
|
||||
const prs = await this.findPrsForIssue<OpenPr>(issueId, "open", "title,body,headRefName,number");
|
||||
if (prs.length === 0) return null;
|
||||
try {
|
||||
const raw = await this.gh(["pr", "list", "--state", "merged", "--json", "number,title,body,url,mergedAt", "--limit", "20"]);
|
||||
const prs = JSON.parse(raw) as Array<{ number: number; title: string; body: string; url: string; mergedAt: string }>;
|
||||
const pat = `#${issueId}`;
|
||||
return prs.find((pr) => pr.title.includes(pat) || (pr.body ?? "").includes(pat))?.url ?? null;
|
||||
return await this.gh(["pr", "diff", String(prs[0].number)]);
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
type Issue,
|
||||
type StateLabel,
|
||||
type IssueComment,
|
||||
type PrStatus,
|
||||
PrState,
|
||||
} from "./provider.js";
|
||||
import { runCommand } from "../run-command.js";
|
||||
import { withResilience } from "./resilience.js";
|
||||
import {
|
||||
DEFAULT_WORKFLOW,
|
||||
getStateLabels,
|
||||
@@ -15,6 +18,16 @@ import {
|
||||
type WorkflowConfig,
|
||||
} from "../workflow.js";
|
||||
|
||||
type GitLabMR = {
|
||||
iid: number;
|
||||
title: string;
|
||||
description: string;
|
||||
web_url: string;
|
||||
state: string;
|
||||
merged_at: string | null;
|
||||
approved_by?: Array<unknown>;
|
||||
};
|
||||
|
||||
export class GitLabProvider implements IssueProvider {
|
||||
private repoPath: string;
|
||||
private workflow: WorkflowConfig;
|
||||
@@ -25,8 +38,19 @@ export class GitLabProvider implements IssueProvider {
|
||||
}
|
||||
|
||||
private async glab(args: string[]): Promise<string> {
|
||||
const result = await runCommand(["glab", ...args], { timeoutMs: 30_000, cwd: this.repoPath });
|
||||
return result.stdout.trim();
|
||||
return withResilience(async () => {
|
||||
const result = await runCommand(["glab", ...args], { timeoutMs: 30_000, cwd: this.repoPath });
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/** Get MRs linked to an issue via GitLab's native related_merge_requests API. */
|
||||
private async getRelatedMRs(issueId: number): Promise<GitLabMR[]> {
|
||||
try {
|
||||
const raw = await this.glab(["api", `projects/:id/issues/${issueId}/related_merge_requests`, "--paginate"]);
|
||||
if (!raw) return [];
|
||||
return JSON.parse(raw) as GitLabMR[];
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
async ensureLabel(name: string, color: string): Promise<void> {
|
||||
@@ -91,6 +115,17 @@ export class GitLabProvider implements IssueProvider {
|
||||
await this.glab(args);
|
||||
}
|
||||
|
||||
async addLabel(issueId: number, label: string): Promise<void> {
|
||||
await this.glab(["issue", "update", String(issueId), "--label", label]);
|
||||
}
|
||||
|
||||
async removeLabels(issueId: number, labels: string[]): Promise<void> {
|
||||
if (labels.length === 0) return;
|
||||
const args = ["issue", "update", String(issueId)];
|
||||
for (const l of labels) args.push("--unlabel", l);
|
||||
await this.glab(args);
|
||||
}
|
||||
|
||||
async closeIssue(issueId: number): Promise<void> { await this.glab(["issue", "close", String(issueId)]); }
|
||||
async reopenIssue(issueId: number): Promise<void> { await this.glab(["issue", "reopen", String(issueId)]); }
|
||||
|
||||
@@ -102,23 +137,55 @@ export class GitLabProvider implements IssueProvider {
|
||||
}
|
||||
|
||||
async hasMergedMR(issueId: number): Promise<boolean> {
|
||||
try {
|
||||
const raw = await this.glab(["mr", "list", "--output", "json", "--state", "merged"]);
|
||||
const mrs = JSON.parse(raw) as Array<{ title: string; description: string }>;
|
||||
const pat = `#${issueId}`;
|
||||
return mrs.some((mr) => mr.title.includes(pat) || (mr.description ?? "").includes(pat));
|
||||
} catch { return false; }
|
||||
const mrs = await this.getRelatedMRs(issueId);
|
||||
return mrs.some((mr) => mr.state === "merged");
|
||||
}
|
||||
|
||||
async getMergedMRUrl(issueId: number): Promise<string | null> {
|
||||
const mrs = await this.getRelatedMRs(issueId);
|
||||
const merged = mrs
|
||||
.filter((mr) => mr.state === "merged" && mr.merged_at)
|
||||
.sort((a, b) => new Date(b.merged_at!).getTime() - new Date(a.merged_at!).getTime());
|
||||
return merged[0]?.web_url ?? null;
|
||||
}
|
||||
|
||||
async getPrStatus(issueId: number): Promise<PrStatus> {
|
||||
const mrs = await this.getRelatedMRs(issueId);
|
||||
// Check open MRs first
|
||||
const open = mrs.find((mr) => mr.state === "opened");
|
||||
if (open) {
|
||||
// related_merge_requests doesn't populate approved_by — use dedicated approvals endpoint
|
||||
const approved = await this.isMrApproved(open.iid);
|
||||
return { state: approved ? PrState.APPROVED : PrState.OPEN, url: open.web_url };
|
||||
}
|
||||
// Check merged MRs
|
||||
const merged = mrs.find((mr) => mr.state === "merged");
|
||||
if (merged) return { state: PrState.MERGED, url: merged.web_url };
|
||||
return { state: PrState.CLOSED, url: null };
|
||||
}
|
||||
|
||||
/** Check if an MR is approved via the dedicated approvals endpoint. */
|
||||
private async isMrApproved(mrIid: number): Promise<boolean> {
|
||||
try {
|
||||
const raw = await this.glab(["mr", "list", "--output", "json", "--state", "merged"]);
|
||||
const mrs = JSON.parse(raw) as Array<{ iid: number; title: string; description: string; web_url: string; merged_at: string }>;
|
||||
const pat = `#${issueId}`;
|
||||
const mr = mrs
|
||||
.filter((mr) => mr.title.includes(pat) || (mr.description ?? "").includes(pat))
|
||||
.sort((a, b) => new Date(b.merged_at).getTime() - new Date(a.merged_at).getTime())[0];
|
||||
return mr?.web_url ?? null;
|
||||
const raw = await this.glab(["api", `projects/:id/merge_requests/${mrIid}/approvals`]);
|
||||
const data = JSON.parse(raw) as { approved?: boolean; approvals_left?: number };
|
||||
return data.approved === true || (data.approvals_left ?? 1) === 0;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
async mergePr(issueId: number): Promise<void> {
|
||||
const mrs = await this.getRelatedMRs(issueId);
|
||||
const open = mrs.find((mr) => mr.state === "opened");
|
||||
if (!open) throw new Error(`No open MR found for issue #${issueId}`);
|
||||
await this.glab(["mr", "merge", String(open.iid)]);
|
||||
}
|
||||
|
||||
async getPrDiff(issueId: number): Promise<string | null> {
|
||||
const mrs = await this.getRelatedMRs(issueId);
|
||||
const open = mrs.find((mr) => mr.state === "opened");
|
||||
if (!open) return null;
|
||||
try {
|
||||
return await this.glab(["mr", "diff", String(open.iid)]);
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
|
||||
@@ -2,34 +2,13 @@
|
||||
* IssueProvider — Abstract interface for issue tracker operations.
|
||||
*
|
||||
* Implementations: GitHub (gh CLI), GitLab (glab CLI).
|
||||
*
|
||||
* Note: STATE_LABELS and LABEL_COLORS are kept for backward compatibility
|
||||
* but new code should use the workflow config via lib/workflow.ts.
|
||||
*/
|
||||
import { DEFAULT_WORKFLOW, getStateLabels, getLabelColors } from "../workflow.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// State labels — derived from default workflow for backward compatibility
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @deprecated Use workflow.getStateLabels() instead.
|
||||
* Kept for backward compatibility with existing code.
|
||||
*/
|
||||
export const STATE_LABELS = getStateLabels(DEFAULT_WORKFLOW) as readonly string[];
|
||||
|
||||
/**
|
||||
* StateLabel type — union of all valid state labels.
|
||||
* This remains a string type for flexibility with custom workflows.
|
||||
* StateLabel type — string for flexibility with custom workflows.
|
||||
*/
|
||||
export type StateLabel = string;
|
||||
|
||||
/**
|
||||
* @deprecated Use workflow.getLabelColors() instead.
|
||||
* Kept for backward compatibility with existing code.
|
||||
*/
|
||||
export const LABEL_COLORS: Record<string, string> = getLabelColors(DEFAULT_WORKFLOW);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue types
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -49,6 +28,20 @@ export type IssueComment = {
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
/** Built-in PR states. */
|
||||
export const PrState = {
|
||||
OPEN: "open",
|
||||
APPROVED: "approved",
|
||||
MERGED: "merged",
|
||||
CLOSED: "closed",
|
||||
} as const;
|
||||
export type PrState = (typeof PrState)[keyof typeof PrState];
|
||||
|
||||
export type PrStatus = {
|
||||
state: PrState;
|
||||
url: string | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider interface
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -61,15 +54,17 @@ export interface IssueProvider {
|
||||
getIssue(issueId: number): Promise<Issue>;
|
||||
listComments(issueId: number): Promise<IssueComment[]>;
|
||||
transitionLabel(issueId: number, from: StateLabel, to: StateLabel): Promise<void>;
|
||||
addLabel(issueId: number, label: string): Promise<void>;
|
||||
removeLabels(issueId: number, labels: string[]): Promise<void>;
|
||||
closeIssue(issueId: number): Promise<void>;
|
||||
reopenIssue(issueId: number): Promise<void>;
|
||||
hasStateLabel(issue: Issue, expected: StateLabel): boolean;
|
||||
getCurrentStateLabel(issue: Issue): StateLabel | null;
|
||||
hasMergedMR(issueId: number): Promise<boolean>;
|
||||
getMergedMRUrl(issueId: number): Promise<string | null>;
|
||||
getPrStatus(issueId: number): Promise<PrStatus>;
|
||||
mergePr(issueId: number): Promise<void>;
|
||||
getPrDiff(issueId: number): Promise<string | null>;
|
||||
addComment(issueId: number, body: string): Promise<void>;
|
||||
healthCheck(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** @deprecated Use IssueProvider */
|
||||
export type TaskManager = IssueProvider;
|
||||
|
||||
49
lib/providers/resilience.ts
Normal file
49
lib/providers/resilience.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* providers/resilience.ts — Retry and circuit breaker policies for provider calls.
|
||||
*
|
||||
* Uses cockatiel for lightweight resilience without heavyweight orchestration.
|
||||
* Applied to GitHub/GitLab CLI calls that can fail due to network, rate limits, or timeouts.
|
||||
*/
|
||||
import {
|
||||
ExponentialBackoff,
|
||||
retry,
|
||||
circuitBreaker,
|
||||
ConsecutiveBreaker,
|
||||
handleAll,
|
||||
wrap,
|
||||
type IPolicy,
|
||||
} from "cockatiel";
|
||||
|
||||
/**
|
||||
* Default retry policy: 3 attempts with exponential backoff.
|
||||
* Handles all errors (network, timeout, CLI failure).
|
||||
*/
|
||||
const retryPolicy = retry(handleAll, {
|
||||
maxAttempts: 3,
|
||||
backoff: new ExponentialBackoff({
|
||||
initialDelay: 500,
|
||||
maxDelay: 5_000,
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Circuit breaker: opens after 5 consecutive failures, half-opens after 30s.
|
||||
* Prevents hammering a provider that's down.
|
||||
*/
|
||||
const breakerPolicy = circuitBreaker(handleAll, {
|
||||
halfOpenAfter: 30_000,
|
||||
breaker: new ConsecutiveBreaker(5),
|
||||
});
|
||||
|
||||
/**
|
||||
* Combined policy: circuit breaker wrapping retry.
|
||||
* If circuit is open, calls fail fast without retrying.
|
||||
*/
|
||||
export const providerPolicy: IPolicy = wrap(breakerPolicy, retryPolicy);
|
||||
|
||||
/**
|
||||
* Execute a provider call with retry + circuit breaker.
|
||||
*/
|
||||
export function withResilience<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return providerPolicy.execute(() => fn());
|
||||
}
|
||||
Reference in New Issue
Block a user