Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ RESULTS_DIR=results
GITHUB_APP_ID=
GITHUB_INSTALLATION_ID=
GITHUB_APP_PRIVATE_KEY_PATH=
# true = refuse to start without the App (otherwise a PAT fallback posts as the token owner, with a warning)
REQUIRE_BOT_IDENTITY=
GITHUB_WEBHOOK_SECRET=
# Bearer token for /api/* (jobs, explain). Unset = API disabled (403).
ADMIN_API_TOKEN=
Expand Down
5 changes: 3 additions & 2 deletions ts/src/agents/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import type { GithubClient, PR } from "../../github/client.ts";

type Log = (msg: string, level?: string) => void;

export function buildOriginMetadata(agentName: string, model = "opencode"): string {
return `---\n🤖 **Origem Automatizada**\n- **Agente:** \`${agentName}\`\n- **Modelo:** \`${model}\`\n- **Repositório de origem:** [github-assistance](https://github.com/juninmd/github-assistance)`;
/** `model: null` omits the line (messages that no AI model produced, e.g. merge notices). */
export function buildOriginMetadata(agentName: string, model: string | null = "opencode"): string {
return `---\n🤖 **Origem Automatizada**\n- **Agente:** \`${agentName}\`\n${model ? `- **Modelo:** \`${model}\`\n` : ""}- **Repositório de origem:** [github-assistance](https://github.com/juninmd/github-assistance)`;
}
export function buildPrBody(agentName: string, title: string, opencodeOutput: string, model = "opencode"): string {
return `## 🤖 Alterações aplicadas automaticamente\n\n### O que foi feito\n${title}\n\n### Saída do opencode\n\`\`\`\n${opencodeOutput.slice(0, 1500)}\n\`\`\`\n\n### Evidências\n<!-- Anexe prints (antes/depois), saída de testes ou logs que provem a mudança. -->\n\n${buildOriginMetadata(agentName, model)}`;
Expand Down
2 changes: 1 addition & 1 deletion ts/src/agents/pr_assistant/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { GithubClient, PR } from "../../github/client.ts";
import { TelegramNotifier } from "../../notifications/telegram.ts";
import { buildOriginMetadata } from "../core/utils.ts";

const ORIGIN = buildOriginMetadata("pr_assistant");
const ORIGIN = buildOriginMetadata("pr_assistant", null);
const esc = TelegramNotifier.escapeHtml;
type Tg = Pick<TelegramNotifier, "sendMessage">;
const appendOrigin = (body: string) => `${body}\n\n${ORIGIN}`;
Expand Down
4 changes: 3 additions & 1 deletion ts/src/agents/pr_assistant/review-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ export function instructions(pr: PR): string {
"existentes; (4) conflitos: marcadores `<<<<<<<`/`>>>>>>>` esquecidos ou resolução " +
"que descartou lógica de um dos lados. Aponte apenas defeitos reais; ignore estilo.\n\n" +
"Responda com APENAS um objeto JSON, em português, sem texto fora do JSON:\n" +
'{"verdict":"APPROVE|REQUEST_CHANGES","summary":"resumo curto",' +
'{"verdict":"APPROVE|REQUEST_CHANGES","summary":"resumo curto","diagram":"mermaid opcional",' +
'"findings":[{"file":"caminho","line":0,"severity":"error|warn|nit","evidence":"linha de código copiada","issue":"...","suggestion":"código que substitui a linha (opcional)"}]}\n' +
"- `diagram` (opcional): só quando um diagrama esclarece de verdade (fluxo novo, sequência entre componentes, máquina de estados). " +
"Código mermaid puro, sem cercas, até ~15 nós, começando por flowchart, sequenceDiagram ou stateDiagram-v2; omita em mudanças triviais.\n" +
"Regras dos achados (um verificador automático confere cada um contra o código real):\n" +
"- `evidence`: copie LITERALMENTE uma linha de código do diff que prova o problema. Achado cuja " +
"evidência não existe no código é descartado; `error` sem evidência é rebaixado.\n" +
Expand Down
10 changes: 8 additions & 2 deletions ts/src/agents/pr_assistant/review-verdict.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@ const ORDER: Record<string, number> = { nit: 0, info: 0, warn: 1, warning: 1, er
export type Finding = { file: string; line: number; severity: string; issue: string; evidence?: string; suggestion?: string };
export type ReviewVerdict = {
verdict: string; summary: string; findings: Finding[]; model: string; fixed: boolean; commit: string;
harness: string; skills_used: string[]; skills_checked: boolean;
harness: string; skills_used: string[]; skills_checked: boolean; diagram?: string;
};
export const mkFinding = (o: Partial<Finding> = {}): Finding => ({ file: "", line: 0, severity: "nit", issue: "", ...o });
/** Optional mermaid source from the model: fences stripped, size-capped, dropped unless it starts with a known diagram keyword. */
export function cleanDiagram(raw: unknown): string | undefined {
const t = String(raw ?? "").replace(/^\s*```(?:mermaid)?\s*/i, "").replace(/```\s*$/, "").trim();
return t.length > 0 && t.length <= 2000 && /^(flowchart|graph|sequenceDiagram|stateDiagram|classDiagram|erDiagram)\b/.test(t) ? t : undefined;
}
export const mkVerdict = (o: Partial<ReviewVerdict> & { verdict: string; summary: string }): ReviewVerdict =>
({ findings: [], model: "", fixed: false, commit: "", harness: "", skills_used: [], skills_checked: false, ...o });

Expand Down Expand Up @@ -63,7 +68,7 @@ export function parseReview(text: string | null | undefined, model = ""): Review
if (!text) return null;
const d = extractJson(text); if (!d) return null;
const verdict = normalizeVerdict(d.verdict || d.decision); if (!verdict) return null;
return mkVerdict({ verdict, summary: String(d.summary || "").trim(), findings: parseFindings(d.findings), model });
return mkVerdict({ verdict, summary: String(d.summary || "").trim(), findings: parseFindings(d.findings), model, diagram: cleanDiagram(d.diagram) });
}

const sev = (f: Finding) => ORDER[(f.severity || "nit").toLowerCase()] ?? 0;
Expand Down Expand Up @@ -98,6 +103,7 @@ export function buildReviewComment(v: ReviewVerdict, headSha = "", fingerprint =
const summary = v.summary || (ok ? "Tudo certo por aqui." : "Encontrei pontos a corrigir.");
const footer = `<sub>🤖 Revisão automática via ${v.harness ? `\`${v.harness}\`` : "opencode"} · modelo \`${v.model || "cloud/auto"}\` · ${skillsText(v)}${headSha ? ` · SHA \`${headSha.slice(0, 8)}\`` : ""}${fingerprint ? ` · patch \`${fingerprint}\`` : ""}</sub>`;
const parts = [REVIEW_MARKER, ok ? "## ✅ Revisão aprovada! 🎉🚀" : "## ❌ Mudanças sugeridas 🛠️", `**Resumo:** ${summary}`, "### 🔎 Achados", renderFindings(v)];
if (v.diagram) parts.splice(3, 0, "### 🗺️ Diagrama", "```mermaid\n" + v.diagram + "\n```");
const fixes = renderFixes(v); if (fixes) parts.push("### 🛠️ Correções", fixes);
if (isCritical(v)) parts.push("### 🚨 Crítico", `Achados de severidade \`error\` bloqueiam o merge (draft + check \`${GATE_NAME}\`) até serem corrigidos por um novo commit.`);
parts.push(`**Veredito:** \`${v.verdict}\` · label \`${verdictLabel(v)}\``, blocks(v) ? "*Achados bloqueantes impedem o merge até serem corrigidos.*" : "*Comentário consultivo — não bloqueia o merge.*", footer, "---", buildOriginMetadata("pr_assistant", v.model || "cloud/auto"));
Expand Down
7 changes: 6 additions & 1 deletion ts/src/config/settings.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** Application settings: env/.env > config/features.toml > defaults. Bun loads .env natively. */
import { AGENT_CATALOG } from "../agents/catalog.ts";
import { applyFeaturesFile } from "./features.ts";
import { initBotAuth } from "../github/bot-auth.ts";
import { botAuthActive, initBotAuth } from "../github/bot-auth.ts";

const TRUE = new Set(["1", "true", "yes", "on"]);
const FALSE = new Set(["0", "false", "no", "off"]);
Expand Down Expand Up @@ -63,6 +63,11 @@ export async function settingsFromEnv(env: Env = process.env): Promise<Settings>
const keyPath = env.GITHUB_APP_PRIVATE_KEY_PATH ?? null;
// App identity wins over any PAT so comments/reviews never appear as the owner.
const token = (await initBotAuth(env, appId, instId, keyPath)) ?? (env.GITHUB_TOKEN || env.GH_PAT);
if (!botAuthActive()) {
// Without the App every comment, review and merge is attributed to the PAT's owner.
if (parseBool(env.REQUIRE_BOT_IDENTITY, false)) throw new Error("REQUIRE_BOT_IDENTITY is set but GITHUB_APP_ID, GITHUB_INSTALLATION_ID and GITHUB_APP_PRIVATE_KEY_PATH are not configured");
console.warn("[WARNING] GitHub App not configured: comments, reviews and merges will be posted as the PAT owner. Set GITHUB_APP_* (or REQUIRE_BOT_IDENTITY=true to fail fast).");
}
if (!token) throw new Error("GITHUB_TOKEN environment variable is required");
const enableAi = parseBool(env.ENABLE_AI, false);
const [aiProvider, aiModel] = resolveAi(env, enableAi);
Expand Down
5 changes: 5 additions & 0 deletions ts/tests/bot-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,8 @@ test("token request failure throws and never falls back to PAT", async () => {
globalThis.fetch = (async () => new Response("no", { status: 401 })) as any;
expect(initBotAuth({ GITHUB_TOKEN: "ghp_pat" }, 1, 2, key())).rejects.toThrow("installation token");
});

test("REQUIRE_BOT_IDENTITY refuses a PAT-only start", async () => {
const { settingsFromEnv } = await import("../src/config/settings.ts");
expect(settingsFromEnv({ GITHUB_TOKEN: "ghp_pat", REQUIRE_BOT_IDENTITY: "true" })).rejects.toThrow("REQUIRE_BOT_IDENTITY");
});
16 changes: 16 additions & 0 deletions ts/tests/review-diagram-origin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { expect, test } from "bun:test";
import { buildOriginMetadata } from "../src/agents/core/utils.ts";
import { buildReviewComment, cleanDiagram, mkVerdict } from "../src/agents/pr_assistant/review-verdict.ts";

test("merge notices carry no model line; AI output keeps it", () => {
expect(buildOriginMetadata("pr_assistant", null)).not.toContain("Modelo");
expect(buildOriginMetadata("pr_assistant", "x/y")).toContain("`x/y`");
});
test("review comment renders a valid mermaid block after the summary and drops invalid ones", () => {
const body = buildReviewComment(mkVerdict({ verdict: "APPROVE", summary: "ok", diagram: "flowchart TD\n A-->B" }));
expect(body.indexOf("**Resumo:**")).toBeLessThan(body.indexOf("```mermaid"));
expect(body.indexOf("```mermaid")).toBeLessThan(body.indexOf("### 🔎 Achados"));
expect(cleanDiagram("<script>x</script>")).toBeUndefined();
expect(cleanDiagram("```mermaid\nsequenceDiagram\nA->>B: hi\n```")).toStartWith("sequenceDiagram");
expect(buildReviewComment(mkVerdict({ verdict: "APPROVE", summary: "ok" }))).not.toContain("mermaid");
});
Loading