«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
217 lines
11 KiB
TypeScript
217 lines
11 KiB
TypeScript
import { m } from "@peppa/shared/i18n";
|
||
import { isProjectPaused, actorColumns } from "@peppa/core";
|
||
// Gitea → Peppa (PEP-46): issues become stories, comments and "changes requested" reviews in
|
||
// a story's PR go to its agent, a PR merged by hand in Gitea closes the story; a finished
|
||
// story closes its issue. CI results are handled in ci-feedback.ts (PEP-57).
|
||
//
|
||
// Gitea 1.22 names review events and PR comments alike (`pull_request_comment`), so the kind
|
||
// of event is taken from the payload shape, not from the header.
|
||
import { answerQuestion, createTask, giteaForBot, listSessions, taskForCheck, type GiteaClient, type Project, type TaskRef } from "@peppa/core";
|
||
import { events, projectMembers, questions, tasks, users, type Db } from "@peppa/db";
|
||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||
import { and, eq, gt, isNull, sql } from "drizzle-orm";
|
||
import { sendToSession } from "./sessions.ts";
|
||
import { moveTask } from "./flow.ts";
|
||
import { syncWorkspace } from "./workspace-sync.ts";
|
||
|
||
type Payload = Record<string, unknown>;
|
||
interface GUser {
|
||
login?: string;
|
||
username?: string;
|
||
}
|
||
interface GIssue {
|
||
number: number;
|
||
title?: string;
|
||
body?: string;
|
||
html_url?: string;
|
||
user?: GUser;
|
||
pull_request?: unknown;
|
||
}
|
||
interface GPull {
|
||
number: number;
|
||
merged?: boolean;
|
||
html_url?: string;
|
||
head?: { ref?: string };
|
||
}
|
||
|
||
export type GiteaEventKind = "issue" | "issue_comment" | "pr_comment" | "review" | "pull_request" | "other";
|
||
|
||
/** What a webhook is about, from the payload shape (Gitea 1.22 reuses event names). */
|
||
export function giteaEventKind(p: Payload): GiteaEventKind {
|
||
if (p.comment && p.issue) return (p.issue as GIssue).pull_request || p.is_pull ? "pr_comment" : "issue_comment";
|
||
if (p.review && p.pull_request) return "review";
|
||
if (p.pull_request && p.action) return "pull_request";
|
||
if (p.issue && p.action) return "issue";
|
||
return "other";
|
||
}
|
||
|
||
const loginOf = (u: GUser | undefined) => (u?.login ?? u?.username ?? "").trim();
|
||
const isBot = (login: string) => login.toLowerCase() === loadEnv().GITEA_BOT_LOGIN.toLowerCase();
|
||
const webUrl = () => loadEnv().PEPPA_WEB_URL.replace(/\/$/, "");
|
||
|
||
/** True when the Gitea login is a Peppa user (Gitea account) who owns or shares the project. */
|
||
export async function giteaLoginHasAccess(db: Db, project: Project, login: string): Promise<boolean> {
|
||
if (!login) return false;
|
||
const [u] = await db
|
||
.select({ id: users.id, disabledAt: users.disabledAt })
|
||
.from(users)
|
||
.where(and(sql`lower(${users.login}) = ${login.toLowerCase()}`, gt(users.giteaId, 0)));
|
||
if (!u || u.disabledAt) return false;
|
||
if (project.ownerId === u.id) return true;
|
||
const [m] = await db
|
||
.select({ id: projectMembers.userId })
|
||
.from(projectMembers)
|
||
.where(and(eq(projectMembers.projectId, project.id), eq(projectMembers.userId, u.id)));
|
||
return !!m;
|
||
}
|
||
|
||
async function logProjectEvent(db: Db, project: Project, type: string, payload: Record<string, unknown>, taskId?: number) {
|
||
await db.insert(events).values({ projectId: project.id, taskId, type, payload, ...actorColumns() });
|
||
}
|
||
|
||
export interface IssueImport {
|
||
key: string;
|
||
created: boolean;
|
||
}
|
||
|
||
/** Story for an issue (idempotent by issue number); peppa-bot links back from the issue. */
|
||
export async function importIssue(db: Db, project: Project, issue: GIssue, gitea?: GiteaClient): Promise<IssueImport> {
|
||
const [have] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, issue.number)));
|
||
if (have) return { key: formatTaskKey(project.key, have.number), created: false };
|
||
const title = (issue.title ?? "").trim().slice(0, 200) || `Issue #${issue.number}`;
|
||
const body = (issue.body ?? "").trim();
|
||
const link = issue.html_url ?? `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${project.giteaOwner}/${project.giteaRepo}/issues/${issue.number}`;
|
||
const ref = await createTask(db, { projectId: project.id, title, description: `${body ? `${body}\n\n` : ""}Issue Gitea: ${link}` });
|
||
await db.update(tasks).set({ giteaIssue: issue.number }).where(eq(tasks.id, ref.task.id));
|
||
await logProjectEvent(db, project, "issue_imported", { issue: issue.number, author: loginOf(issue.user) }, ref.task.id);
|
||
try {
|
||
await (gitea ?? giteaForBot()).commentIssue(project.giteaOwner, project.giteaRepo, issue.number, `Стори ${ref.key} в FORGE: ${webUrl()}/t/${ref.key}`);
|
||
} catch {}
|
||
return { key: ref.key, created: true };
|
||
}
|
||
|
||
/** One-time import of the repo's open issues (the PM asked: no author check). */
|
||
export async function importIssues(db: Db, project: Project, gitea: GiteaClient = giteaForBot()): Promise<IssueImport[]> {
|
||
const out: IssueImport[] = [];
|
||
for (const i of await gitea.listOpenIssues(project.giteaOwner, project.giteaRepo)) out.push(await importIssue(db, project, i, gitea));
|
||
return out;
|
||
}
|
||
|
||
/** A finished story closes its issue with a comment (best effort). */
|
||
export async function closeLinkedIssue(ref: TaskRef, gitea?: GiteaClient): Promise<boolean> {
|
||
if (!ref.task.giteaIssue) return false;
|
||
try {
|
||
const c = gitea ?? giteaForBot();
|
||
await c.commentIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue, `✅ Стори ${ref.key} готова${ref.task.prUrl ? `: ${ref.task.prUrl}` : ""}.`);
|
||
await c.closeIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
const ACTIVE = ["proposing", "in_progress", "review", "blocked"];
|
||
|
||
/** Text from a human in Gitea → the story's agent: live runner, else a new one (story back in work). */
|
||
async function toAgent(db: Db, ref: TaskRef, text: string, restart: boolean): Promise<"agent" | "restarted" | "none"> {
|
||
// PEP-174: on pause the comment stays in Gitea; no agent is started.
|
||
if (await isProjectPaused(db, ref.project.id)) return "none";
|
||
const [s] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||
if (s) {
|
||
try {
|
||
await sendToSession(db, s.id, text);
|
||
if (ref.task.status === "review") await moveTask(db, ref, "in_progress");
|
||
return "agent";
|
||
} catch {}
|
||
}
|
||
if (!restart) return "none";
|
||
await moveTask(db, ref, "in_progress", { prompt: text });
|
||
return "restarted";
|
||
}
|
||
|
||
async function taskByIssue(db: Db, project: Project, n: number): Promise<TaskRef | null> {
|
||
const [t] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, n)));
|
||
return t ? { project, task: t, key: formatTaskKey(project.key, t.number) } : null;
|
||
}
|
||
|
||
export interface GiteaEventOutcome {
|
||
kind: GiteaEventKind;
|
||
task?: string | null;
|
||
action: string;
|
||
}
|
||
|
||
/** Dispatches a Gitea webhook (other than CI reports) for a project. */
|
||
export async function handleGiteaEvent(db: Db, project: Project, payload: Payload, gitea?: GiteaClient): Promise<GiteaEventOutcome> {
|
||
const kind = giteaEventKind(payload);
|
||
const sender = loginOf(payload.sender as GUser);
|
||
const action = String(payload.action ?? "");
|
||
|
||
if (kind === "issue") {
|
||
const issue = payload.issue as GIssue;
|
||
if (action !== "opened" && action !== "reopened") return { kind, action: "none" };
|
||
const author = loginOf(issue.user) || sender;
|
||
if (isBot(author)) return { kind, action: "none" };
|
||
if (!(await giteaLoginHasAccess(db, project, author))) return { kind, action: "no_access" };
|
||
const r = await importIssue(db, project, issue, gitea);
|
||
return { kind, task: r.key, action: r.created ? "imported" : "exists" };
|
||
}
|
||
|
||
if (kind === "pull_request") {
|
||
const pull = payload.pull_request as GPull;
|
||
if (action !== "closed" || !pull.merged) return { kind, action: "none" };
|
||
const ref = await taskForCheck(db, project, pull.head?.ref, pull.number ?? (payload.number as number));
|
||
if (!ref || ref.task.status === "done") return { kind, task: ref?.key ?? null, action: "none" };
|
||
// Merged by hand in Gitea (Peppa's own merges move the story to done right after).
|
||
await closeMergedStory(db, ref, pull.number ?? (payload.number as number), sender, gitea);
|
||
return { kind, task: ref.key, action: "done" };
|
||
}
|
||
|
||
if (kind === "pr_comment" || kind === "review" || kind === "issue_comment") {
|
||
if (!sender || isBot(sender)) return { kind, action: "none" };
|
||
let ref: TaskRef | null;
|
||
let text: string;
|
||
if (kind === "review") {
|
||
const pull = payload.pull_request as GPull;
|
||
const review = payload.review as { type?: string; content?: string };
|
||
const type = `${review.type ?? ""} ${action}`.toLowerCase();
|
||
if (type.includes("approved")) return { kind, action: "none" };
|
||
const content = (review.content ?? "").trim();
|
||
if (!content) return { kind, action: "none" };
|
||
ref = await taskForCheck(db, project, pull.head?.ref, pull.number);
|
||
const verdict = type.includes("rejected") ? "просит изменений" : "оставил ревью";
|
||
text = `💬 ${sender} ${verdict} в PR #${pull.number}${pull.html_url ? ` (${pull.html_url}/files)` : ""}:\n\n${content}\n\nРазбери замечания (комментарии к строкам — в PR), исправь и запушь в ту же ветку.`;
|
||
} else {
|
||
if (action && action !== "created") return { kind, action: "none" };
|
||
const issue = payload.issue as GIssue;
|
||
const comment = payload.comment as { body?: string; html_url?: string };
|
||
const body = (comment.body ?? "").trim();
|
||
if (!body) return { kind, action: "none" };
|
||
ref = kind === "pr_comment" ? await taskForCheck(db, project, null, issue.number) : await taskByIssue(db, project, issue.number);
|
||
text =
|
||
kind === "pr_comment"
|
||
? `💬 ${sender} в PR #${issue.number}${comment.html_url ? ` (${comment.html_url})` : ""}:\n\n${body}\n\nЭто замечание к стори: исправь и запушь в ту же ветку (или ответь, почему не нужно).`
|
||
: `💬 ${sender} в issue #${issue.number}:\n\n${body}`;
|
||
}
|
||
if (!ref || !ACTIVE.includes(ref.task.status)) return { kind, task: ref?.key ?? null, action: "none" };
|
||
if (!(await giteaLoginHasAccess(db, project, sender))) return { kind, task: ref.key, action: "no_access" };
|
||
const out = await toAgent(db, ref, text, kind !== "issue_comment");
|
||
await logProjectEvent(db, project, "gitea_comment", { from: sender, kind, delivered: out }, ref.task.id);
|
||
return { kind, task: ref.key, action: out };
|
||
}
|
||
return { kind, action: "none" };
|
||
}
|
||
|
||
/**
|
||
* The story's result is merged in Gitea: its «готово» messages are answered, the story is done
|
||
* (its issue closed), the working copy synced. The merge webhook calls it, and the stuck-story
|
||
* healing (PEP-209) when the webhook was lost.
|
||
*/
|
||
export async function closeMergedStory(db: Db, ref: TaskRef, pr: number | null, sender: string | null | undefined, gitea?: GiteaClient): Promise<void> {
|
||
for (const q of await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt), eq(questions.kind, "attention")))) {
|
||
await answerQuestion(db, q.id, sender ? m("✅ Изменения приняты в код проекта ({sender})", { sender }) : m("✅ Изменения приняты в код проекта"), "system").catch(() => {});
|
||
}
|
||
await moveTask(db, ref, "done", {}, gitea); // also closes the story's issue
|
||
await syncWorkspace(db, ref).catch(() => {});
|
||
await logProjectEvent(db, ref.project, "pr_merged_in_gitea", { pr, by: sender ?? null }, ref.task.id);
|
||
}
|