Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f77fecc2a0 | |||
| 071e885d63 | |||
| cac9b0e645 | |||
| 0a4fcc556a | |||
| 102417f442 | |||
| 90945a9481 | |||
| a200d07370 | |||
| af358ad671 | |||
| d44392b06d | |||
| 410aecc010 | |||
| 6bd4097992 | |||
| 2514bb1cf7 |
@@ -1,11 +1,15 @@
|
||||
# PULLFROG ACTION — DO NOT EDIT EXCEPT WHERE INDICATED
|
||||
name: Pullfrog
|
||||
run-name: ${{ inputs.name || github.workflow }}
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prompt:
|
||||
type: string
|
||||
description: Agent prompt
|
||||
name:
|
||||
type: string
|
||||
description: Run name
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -38,4 +42,4 @@ jobs:
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
|
||||
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
|
||||
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
|
||||
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
|
||||
|
||||
+3
-1
@@ -62,7 +62,9 @@ ${mcpServerSections.join("\n\n")}
|
||||
`.trim() + "\n"
|
||||
);
|
||||
|
||||
log.info(`» Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})`);
|
||||
log.info(
|
||||
`» Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})`
|
||||
);
|
||||
|
||||
return codexDir;
|
||||
}
|
||||
|
||||
+5
-8
@@ -33,14 +33,11 @@ export const agent = <const input extends AgentInput>(input: input): defineAgent
|
||||
const search = ctx.payload.search;
|
||||
const write = ctx.payload.write;
|
||||
log.info(`» running ${input.name} with effort=${ctx.payload.effort}...`);
|
||||
// build log box content: eventInstructions (if any) + user request (if any) + event data
|
||||
const logParts = [
|
||||
ctx.instructions.eventInstructions
|
||||
? `EVENT-LEVEL INSTRUCTIONS:\n${ctx.instructions.eventInstructions}`
|
||||
: null,
|
||||
ctx.instructions.user ? `USER REQUEST:\n${ctx.instructions.user}` : null,
|
||||
ctx.instructions.event,
|
||||
].filter(Boolean);
|
||||
// build log box content: user prompt first, then event data with eventInstructions as property
|
||||
const eventWithInstructions = ctx.instructions.eventInstructions
|
||||
? `additionalInstructions: ${ctx.instructions.eventInstructions}\n${ctx.instructions.event}`
|
||||
: ctx.instructions.event;
|
||||
const logParts = [ctx.instructions.user, eventWithInstructions].filter(Boolean);
|
||||
log.box(logParts.join("\n\n---\n\n"), {
|
||||
title: "Instructions",
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import * as core from "@actions/core";
|
||||
import { main } from "./main.ts";
|
||||
import { runCleanup } from "./utils/exitHandler.ts";
|
||||
|
||||
async function run(): Promise<void> {
|
||||
try {
|
||||
@@ -17,6 +18,8 @@ async function run(): Promise<void> {
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
||||
core.setFailed(`Action failed: ${errorMessage}`);
|
||||
} finally {
|
||||
await runCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25507,9 +25507,14 @@ var core3 = __toESM(require_core(), 1);
|
||||
// utils/log.ts
|
||||
var core = __toESM(require_core(), 1);
|
||||
var import_table = __toESM(require_src(), 1);
|
||||
|
||||
// utils/globals.ts
|
||||
import { existsSync } from "node:fs";
|
||||
var isCloudflareSandbox = !!process.env.CLOUDFLARE_APPLICATION_ID && !!process.env.SANDBOX_VERSION;
|
||||
var isGitHubActions = !!process.env.GITHUB_ACTIONS;
|
||||
var isInsideDocker = existsSync("/.dockerenv");
|
||||
|
||||
// utils/log.ts
|
||||
var isDebugEnabled = () => process.env.LOG_LEVEL === "debug" || process.env.ACTIONS_STEP_DEBUG === "true" || process.env.RUNNER_DEBUG === "1" || core.isDebug();
|
||||
function formatArgs(args) {
|
||||
return args.map((arg) => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* This exports the main function for programmatic usage
|
||||
*/
|
||||
|
||||
export type { Agent, AgentRunContext, AgentResult } from "./agents/shared.ts";
|
||||
export type { Agent, AgentResult, AgentRunContext } from "./agents/shared.ts";
|
||||
export {
|
||||
type Inputs as ExecutionInputs,
|
||||
type MainResult,
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
// changes to tool permissions should be reflected in wiki/granular-tools.md
|
||||
import { ensureProgressCommentUpdated } from "./mcp/comment.ts";
|
||||
import { initToolState, startMcpHttpServer } from "./mcp/server.ts";
|
||||
import { computeModes } from "./modes.ts";
|
||||
import { resolveAgent } from "./utils/agent.ts";
|
||||
import { validateApiKey } from "./utils/apiKeys.ts";
|
||||
import { validateAgentApiKey } from "./utils/apiKeys.ts";
|
||||
import { resolveBody } from "./utils/body.ts";
|
||||
import { log, writeSummary } from "./utils/cli.ts";
|
||||
import { reportErrorToComment } from "./utils/errorReport.ts";
|
||||
import { setupExitHandler } from "./utils/exitHandler.ts";
|
||||
import { createOctokit } from "./utils/github.ts";
|
||||
import { resolveInstructions } from "./utils/instructions.ts";
|
||||
import { normalizeEnv } from "./utils/normalizeEnv.ts";
|
||||
import { resolvePayload } from "./utils/payload.ts";
|
||||
import { resolveRepoData } from "./utils/repoData.ts";
|
||||
import { handleAgentResult } from "./utils/run.ts";
|
||||
import { resolveRunContextData } from "./utils/runContextData.ts";
|
||||
import { createTempDirectory, setupGit } from "./utils/setup.ts";
|
||||
import { Timer } from "./utils/timer.ts";
|
||||
import { resolveInstallationToken } from "./utils/token.ts";
|
||||
@@ -30,24 +30,25 @@ export async function main(): Promise<MainResult> {
|
||||
// normalize env var names to uppercase (handles case-insensitive workflow files)
|
||||
normalizeEnv();
|
||||
|
||||
// store original GITHUB_TOKEN
|
||||
process.env.ORIGINAL_GITHUB_TOKEN = process.env.GITHUB_TOKEN;
|
||||
|
||||
const timer = new Timer();
|
||||
|
||||
await using tokenRef = await resolveInstallationToken();
|
||||
process.env.GITHUB_TOKEN = tokenRef.token;
|
||||
|
||||
|
||||
const octokit = createOctokit(tokenRef.token);
|
||||
const runInfo = await resolveRun({ octokit });
|
||||
const toolState = initToolState({ runInfo });
|
||||
|
||||
try {
|
||||
const repo = await resolveRepoData({ octokit, token: tokenRef.token });
|
||||
timer.checkpoint("repoData");
|
||||
setupExitHandler(toolState);
|
||||
|
||||
// resolve payload after repoData so permissions can use DB settings
|
||||
try {
|
||||
const runContext = await resolveRunContextData({ octokit, token: tokenRef.token });
|
||||
timer.checkpoint("runContextData");
|
||||
|
||||
// resolve payload after runContextData so permissions can use DB settings
|
||||
// precedence: action inputs > json payload > repoSettings > fallbacks
|
||||
const payload = resolvePayload(repo.repoSettings);
|
||||
const payload = resolvePayload(runContext.repoSettings);
|
||||
if (payload.cwd && process.cwd() !== payload.cwd) {
|
||||
process.chdir(payload.cwd);
|
||||
}
|
||||
@@ -55,7 +56,11 @@ export async function main(): Promise<MainResult> {
|
||||
// resolve body - fetches body_html and converts to markdown if images present
|
||||
// this ensures agents receive markdown with working signed image URLs
|
||||
const originalBody = payload.event.body;
|
||||
const resolvedBody = await resolveBody({ event: payload.event, octokit, repo });
|
||||
const resolvedBody = await resolveBody({
|
||||
event: payload.event,
|
||||
octokit,
|
||||
repo: runContext.repo,
|
||||
});
|
||||
if (resolvedBody !== originalBody) {
|
||||
payload.event.body = resolvedBody;
|
||||
// also update prompt if original body was included there
|
||||
@@ -66,33 +71,34 @@ export async function main(): Promise<MainResult> {
|
||||
|
||||
const tmpdir = createTempDirectory();
|
||||
|
||||
const agent = resolveAgent({ payload, repoSettings: repo.repoSettings });
|
||||
const agent = resolveAgent({ payload, repoSettings: runContext.repoSettings });
|
||||
|
||||
validateApiKey({
|
||||
validateAgentApiKey({
|
||||
agent,
|
||||
owner: repo.owner,
|
||||
name: repo.name,
|
||||
owner: runContext.repo.owner,
|
||||
name: runContext.repo.name,
|
||||
});
|
||||
|
||||
await setupGit({
|
||||
token: tokenRef.token,
|
||||
originalToken: process.env.ORIGINAL_GITHUB_TOKEN,
|
||||
originalToken: tokenRef.originalToken,
|
||||
bashPermission: payload.bash,
|
||||
owner: repo.owner,
|
||||
name: repo.name,
|
||||
owner: runContext.repo.owner,
|
||||
name: runContext.repo.name,
|
||||
event: payload.event,
|
||||
octokit,
|
||||
toolState,
|
||||
});
|
||||
timer.checkpoint("git");
|
||||
|
||||
const modes = [...computeModes(), ...repo.repoSettings.modes];
|
||||
const modes = [...computeModes(), ...runContext.repoSettings.modes];
|
||||
|
||||
await using mcpHttpServer = await startMcpHttpServer({
|
||||
repo,
|
||||
repo: runContext.repo,
|
||||
payload,
|
||||
octokit,
|
||||
githubInstallationToken: tokenRef.token,
|
||||
apiToken: runContext.apiToken,
|
||||
agent,
|
||||
modes,
|
||||
toolState,
|
||||
@@ -104,7 +110,7 @@ export async function main(): Promise<MainResult> {
|
||||
|
||||
const instructions = resolveInstructions({
|
||||
payload,
|
||||
repoData: repo,
|
||||
repo: runContext.repo,
|
||||
modes,
|
||||
});
|
||||
|
||||
@@ -120,8 +126,7 @@ export async function main(): Promise<MainResult> {
|
||||
await writeSummary(toolState.lastProgressBody);
|
||||
}
|
||||
|
||||
const mainResult = await handleAgentResult(result);
|
||||
return mainResult;
|
||||
return handleAgentResult(result);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
||||
log.error(errorMessage);
|
||||
@@ -134,13 +139,5 @@ export async function main(): Promise<MainResult> {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
};
|
||||
} finally {
|
||||
// ensure progress comment is updated if it was never updated during execution
|
||||
// do this before revoking the token so we can still make API calls
|
||||
try {
|
||||
await ensureProgressCommentUpdated(toolState);
|
||||
} catch {
|
||||
// error updating comment, but don't let it mask the original error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+30
-5
@@ -7,7 +7,7 @@ this directory contains the mcp (model context protocol) server tools for intera
|
||||
### check suite tools
|
||||
|
||||
#### `get_check_suite_logs`
|
||||
get workflow run logs for a failed check suite.
|
||||
get workflow run logs for a failed check suite with intelligent log analysis.
|
||||
|
||||
**parameters:**
|
||||
- `check_suite_id` (number): the id from check_suite.id in the webhook payload
|
||||
@@ -15,16 +15,41 @@ get workflow run logs for a failed check suite.
|
||||
**replaces:** `gh run list` and `gh run view --log`
|
||||
|
||||
**returns:**
|
||||
all logs from all failed workflow runs in the check suite, including:
|
||||
- workflow run details (id, name, html_url, conclusion)
|
||||
- job details for each workflow run (id, name, status, conclusion, logs)
|
||||
structured failure information for each failed job:
|
||||
- `_instructions`: explains how to use each field
|
||||
- `failed_jobs[]`: array of failed job results, each containing:
|
||||
- `job_id`, `job_name`, `job_url`: job identification
|
||||
- `failed_steps`: which CI steps failed (e.g., "Step 6: Run tests")
|
||||
- `log_index`: array of interesting lines (errors, warnings, failures) with line numbers
|
||||
- `excerpt`: ~80 line curated window around the last error
|
||||
- `full_log_path`: path to complete log file for deeper investigation
|
||||
|
||||
**log_index types:**
|
||||
- `error`: lines matching `##[error]`, `Error:`, `ERR_`, `exit code N`
|
||||
- `warning`: lines matching `##[warning]`, `WARN`
|
||||
- `failure`: lines matching `N failed`, `FAIL`, `✕`
|
||||
- `trace`: stack trace lines (deduplicated)
|
||||
|
||||
**workflow for using results:**
|
||||
1. scan `log_index` to see where errors/warnings/failures are located in the log
|
||||
2. read `excerpt` for immediate context around the main error
|
||||
3. if excerpt doesn't show what you need, read specific line ranges from `full_log_path`
|
||||
4. check `failed_steps` and read the workflow yml to understand what command failed
|
||||
|
||||
**example:**
|
||||
```typescript
|
||||
// when handling a check_suite_completed webhook
|
||||
await mcp.call("gh_pullfrog/get_check_suite_logs", {
|
||||
const result = await mcp.call("gh_pullfrog/get_check_suite_logs", {
|
||||
check_suite_id: check_suite.id
|
||||
});
|
||||
|
||||
// result.failed_jobs[0].log_index shows:
|
||||
// [
|
||||
// { line: 181, content: "WARN Failed to create bin...", type: "warning" },
|
||||
// { line: 1079, content: "Error: expect(received).toBe(expected)", type: "error" },
|
||||
// ...
|
||||
// ]
|
||||
// use these line numbers to read specific sections from full_log_path
|
||||
```
|
||||
|
||||
### review tools
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ function spawnBash(params: SpawnParams): ChildProcess {
|
||||
// return useNamespaceIsolation
|
||||
// ? spawn("unshare", ["--pid", "--fork", "--mount-proc", "bash", "-c", params.command], spawnOpts)
|
||||
// : spawn("bash", ["-c", params.command], spawnOpts);
|
||||
return spawn("bash", ["-c", params.command], spawnOpts);
|
||||
return spawn("bash", ["-c", params.command], spawnOpts);
|
||||
}
|
||||
|
||||
/** kill process and its entire process group */
|
||||
|
||||
+203
-52
@@ -1,4 +1,7 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { type } from "arktype";
|
||||
import { log } from "../utils/log.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
@@ -6,13 +9,127 @@ export const GetCheckSuiteLogs = type({
|
||||
check_suite_id: type.number.describe("the id from check_suite.id"),
|
||||
});
|
||||
|
||||
type LogLine = {
|
||||
line: number;
|
||||
content: string;
|
||||
type: "error" | "warning" | "failure" | "trace";
|
||||
};
|
||||
|
||||
type LogAnalysis = {
|
||||
totalLines: number;
|
||||
index: LogLine[];
|
||||
excerpt: {
|
||||
content: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
};
|
||||
};
|
||||
|
||||
function analyzeLog(logs: string, excerptLines = 80): LogAnalysis {
|
||||
// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape codes use control chars
|
||||
const clean = logs.replace(/\x1b\[[0-9;]*m/g, "");
|
||||
const lines = clean.split("\n");
|
||||
const totalLines = lines.length;
|
||||
|
||||
const index: LogLine[] = [];
|
||||
|
||||
const patterns: Array<{ type: LogLine["type"]; pattern: RegExp; skip?: RegExp }> = [
|
||||
{ type: "error", pattern: /##\[error\]/i },
|
||||
{ type: "error", pattern: /\bError:/i },
|
||||
{ type: "error", pattern: /\bERR_/i },
|
||||
{ type: "error", pattern: /exit code [1-9]/i },
|
||||
{ type: "warning", pattern: /##\[warning\]/i },
|
||||
{ type: "warning", pattern: /\bWARN\b/i, skip: /apt|dpkg|Reading package/i },
|
||||
{ type: "failure", pattern: /\d+ failed/i },
|
||||
{ type: "failure", pattern: /FAIL\b/i },
|
||||
{ type: "failure", pattern: /✕|✗|×/ },
|
||||
{ type: "trace", pattern: /^\s+at\s+/i },
|
||||
];
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
for (const p of patterns) {
|
||||
if (p.pattern.test(line)) {
|
||||
if (p.skip?.test(line)) continue;
|
||||
|
||||
// dedupe consecutive traces
|
||||
if (p.type === "trace" && index.length > 0 && index[index.length - 1].type === "trace") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// truncate long lines
|
||||
const truncated = line.length > 120 ? line.slice(0, 117) + "..." : line;
|
||||
|
||||
index.push({
|
||||
line: i + 1,
|
||||
content: truncated.trim(),
|
||||
type: p.type,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// find excerpt range: focus on LAST ##[error] line
|
||||
let errorLine = -1;
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
if (/##\[error\]/i.test(lines[i])) {
|
||||
errorLine = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let start: number;
|
||||
let end: number;
|
||||
|
||||
if (errorLine === -1) {
|
||||
start = Math.max(0, totalLines - excerptLines);
|
||||
end = totalLines;
|
||||
} else {
|
||||
const contextAfter = 5;
|
||||
const contextBefore = excerptLines - contextAfter;
|
||||
start = Math.max(0, errorLine - contextBefore);
|
||||
end = Math.min(totalLines, errorLine + contextAfter);
|
||||
}
|
||||
|
||||
return {
|
||||
totalLines,
|
||||
index,
|
||||
excerpt: {
|
||||
content: lines.slice(start, end).join("\n"),
|
||||
startLine: start + 1,
|
||||
endLine: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type JobLogResult = {
|
||||
job_id: number;
|
||||
job_name: string;
|
||||
job_url: string;
|
||||
failed_steps: string[];
|
||||
log_index: LogLine[];
|
||||
excerpt: {
|
||||
start_line: number;
|
||||
end_line: number;
|
||||
total_lines: number;
|
||||
content: string;
|
||||
};
|
||||
full_log_path: string;
|
||||
};
|
||||
|
||||
export function GetCheckSuiteLogsTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "get_check_suite_logs",
|
||||
description:
|
||||
"get workflow run logs for a failed check suite. pass check_suite.id from the webhook payload.",
|
||||
"get workflow run logs for a failed check suite. returns a log_index of interesting lines, " +
|
||||
"a curated excerpt, and full_log_path for deeper investigation. " +
|
||||
"pass check_suite.id from the webhook payload.",
|
||||
parameters: GetCheckSuiteLogs,
|
||||
execute: execute(async ({ check_suite_id }) => {
|
||||
execute: execute(async (params) => {
|
||||
const check_suite_id = params.check_suite_id;
|
||||
|
||||
// get workflow runs for this specific check suite
|
||||
const workflowRuns = await ctx.octokit.paginate(
|
||||
ctx.octokit.rest.actions.listWorkflowRunsForRepo,
|
||||
@@ -30,67 +147,101 @@ export function GetCheckSuiteLogsTool(ctx: ToolContext) {
|
||||
return {
|
||||
check_suite_id,
|
||||
message: "no failed workflow runs found for this check suite",
|
||||
workflow_runs: [],
|
||||
failed_jobs: [],
|
||||
};
|
||||
}
|
||||
|
||||
// setup logs directory
|
||||
const tempDir = process.env.PULLFROG_TEMP_DIR;
|
||||
if (!tempDir) {
|
||||
throw new Error("PULLFROG_TEMP_DIR not set");
|
||||
}
|
||||
const logsDir = join(tempDir, "ci-logs");
|
||||
mkdirSync(logsDir, { recursive: true });
|
||||
|
||||
const jobResults: JobLogResult[] = [];
|
||||
|
||||
// get logs for each failed run
|
||||
const logsForRuns = await Promise.all(
|
||||
failedRuns.map(async (run) => {
|
||||
const jobs = await ctx.octokit.paginate(ctx.octokit.rest.actions.listJobsForWorkflowRun, {
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
run_id: run.id,
|
||||
});
|
||||
for (const run of failedRuns) {
|
||||
const jobs = await ctx.octokit.paginate(ctx.octokit.rest.actions.listJobsForWorkflowRun, {
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
run_id: run.id,
|
||||
});
|
||||
|
||||
const jobLogs = await Promise.all(
|
||||
jobs.map(async (job) => {
|
||||
try {
|
||||
const logsResponse = await ctx.octokit.rest.actions.downloadJobLogsForWorkflowRun({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
job_id: job.id,
|
||||
});
|
||||
// only process failed jobs
|
||||
const failedJobs = jobs.filter((job) => job.conclusion === "failure");
|
||||
|
||||
const logsUrl = logsResponse.url;
|
||||
const logsText = await fetch(logsUrl).then((r) => r.text());
|
||||
for (const job of failedJobs) {
|
||||
try {
|
||||
const logsResponse = await ctx.octokit.rest.actions.downloadJobLogsForWorkflowRun({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
job_id: job.id,
|
||||
});
|
||||
|
||||
return {
|
||||
job_id: job.id,
|
||||
job_name: job.name,
|
||||
status: job.status,
|
||||
conclusion: job.conclusion,
|
||||
started_at: job.started_at,
|
||||
completed_at: job.completed_at,
|
||||
logs: logsText,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
job_id: job.id,
|
||||
job_name: job.name,
|
||||
status: job.status,
|
||||
conclusion: job.conclusion,
|
||||
started_at: job.started_at,
|
||||
completed_at: job.completed_at,
|
||||
error: `failed to fetch logs: ${error}`,
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
const logsUrl = logsResponse.url;
|
||||
const logsText = await fetch(logsUrl).then((r) => r.text());
|
||||
|
||||
return {
|
||||
workflow_run_id: run.id,
|
||||
workflow_name: run.name,
|
||||
html_url: run.html_url,
|
||||
conclusion: run.conclusion,
|
||||
jobs: jobLogs,
|
||||
};
|
||||
})
|
||||
);
|
||||
// write full log to disk
|
||||
const logPath = join(logsDir, `job-${job.id}.log`);
|
||||
writeFileSync(logPath, logsText);
|
||||
|
||||
// analyze log
|
||||
const analysis = analyzeLog(logsText, 80);
|
||||
|
||||
// get failed steps
|
||||
const failedSteps =
|
||||
job.steps
|
||||
?.filter((s) => s.conclusion === "failure")
|
||||
.map((s) => `Step ${s.number}: ${s.name}`) ?? [];
|
||||
|
||||
jobResults.push({
|
||||
job_id: job.id,
|
||||
job_name: job.name,
|
||||
job_url: job.html_url ?? "",
|
||||
failed_steps: failedSteps,
|
||||
log_index: analysis.index,
|
||||
excerpt: {
|
||||
start_line: analysis.excerpt.startLine,
|
||||
end_line: analysis.excerpt.endLine,
|
||||
total_lines: analysis.totalLines,
|
||||
content: analysis.excerpt.content,
|
||||
},
|
||||
full_log_path: logPath,
|
||||
});
|
||||
|
||||
log.debug(`analyzed logs for job ${job.name}: ${analysis.index.length} indexed lines`);
|
||||
} catch (error) {
|
||||
log.error(`failed to fetch logs for job ${job.id}: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
_instructions: {
|
||||
overview:
|
||||
"this result contains CI failure information. use log_index to find interesting lines, then read full_log_path for details.",
|
||||
fields: {
|
||||
log_index:
|
||||
"array of interesting lines (errors, warnings, failures) with line numbers. use these to navigate the full log.",
|
||||
excerpt:
|
||||
"a curated ~80 line window around the last error. may not show all failures if they occur in different places.",
|
||||
full_log_path:
|
||||
"path to the complete log file. read specific line ranges using the line numbers from log_index.",
|
||||
failed_steps:
|
||||
"which CI steps failed. read the workflow yml to understand what commands these steps run.",
|
||||
},
|
||||
workflow: [
|
||||
"1. scan log_index to see where errors/warnings/failures are located",
|
||||
"2. read excerpt for immediate context",
|
||||
"3. if excerpt doesn't show what you need, read specific line ranges from full_log_path",
|
||||
"4. check failed_steps to understand what command failed",
|
||||
],
|
||||
},
|
||||
check_suite_id,
|
||||
workflow_runs: logsForRuns,
|
||||
repo: `${ctx.repo.owner}/${ctx.repo.name}`,
|
||||
failed_jobs: jobResults,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
+17
-93
@@ -1,9 +1,8 @@
|
||||
import { type } from "arktype";
|
||||
import type { Agent } from "../agents/index.ts";
|
||||
import { buildPullfrogFooter, stripExistingFooter } from "../utils/buildPullfrogFooter.ts";
|
||||
import { createOctokit, type OctokitWithPlugins, parseRepoContext } from "../utils/github.ts";
|
||||
import { getGitHubInstallationToken } from "../utils/token.ts";
|
||||
import type { ToolContext, ToolState } from "./server.ts";
|
||||
import { type OctokitWithPlugins, parseRepoContext } from "../utils/github.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
/**
|
||||
@@ -65,9 +64,6 @@ async function buildCommentFooter({
|
||||
return buildPullfrogFooter(footerParams);
|
||||
}
|
||||
|
||||
const SUGGESTION_FORMAT_DESCRIPTION =
|
||||
"when suggesting code changes, use GitHub's suggestion format with ```suggestion blocks to enable one-click apply (e.g., 'you could do this\\n```suggestion\\nsuggested code here\\n```'). note: suggestions only work on pull request line-level review comments, not on issue/PR-level comments.";
|
||||
|
||||
function buildImplementPlanLink(
|
||||
owner: string,
|
||||
repo: string,
|
||||
@@ -78,12 +74,12 @@ function buildImplementPlanLink(
|
||||
return `[Implement plan ➔](${apiUrl}/trigger/${owner}/${repo}/${issueNumber}?action=implement&comment_id=${commentId})`;
|
||||
}
|
||||
|
||||
interface AddFooterCtx {
|
||||
export interface AddFooterCtx {
|
||||
agent?: Agent | undefined;
|
||||
octokit?: OctokitWithPlugins | undefined;
|
||||
}
|
||||
|
||||
async function addFooter(ctx: AddFooterCtx, body: string): Promise<string> {
|
||||
export async function addFooter(ctx: AddFooterCtx, body: string): Promise<string> {
|
||||
const bodyWithoutFooter = stripExistingFooter(body);
|
||||
const footer = await buildCommentFooter({ agent: ctx.agent, octokit: ctx.octokit });
|
||||
return `${bodyWithoutFooter}${footer}`;
|
||||
@@ -91,7 +87,7 @@ async function addFooter(ctx: AddFooterCtx, body: string): Promise<string> {
|
||||
|
||||
export const Comment = type({
|
||||
issueNumber: type.number.describe("the issue number to comment on"),
|
||||
body: type.string.describe(`the comment body content. ${SUGGESTION_FORMAT_DESCRIPTION}`),
|
||||
body: type.string.describe("the comment body content"),
|
||||
});
|
||||
|
||||
export function CreateCommentTool(ctx: ToolContext) {
|
||||
@@ -122,7 +118,7 @@ export function CreateCommentTool(ctx: ToolContext) {
|
||||
|
||||
export const EditComment = type({
|
||||
commentId: type.number.describe("the ID of the comment to edit"),
|
||||
body: type.string.describe(`the new comment body content. ${SUGGESTION_FORMAT_DESCRIPTION}`),
|
||||
body: type.string.describe("the new comment body content"),
|
||||
});
|
||||
|
||||
export function EditCommentTool(ctx: ToolContext) {
|
||||
@@ -173,7 +169,7 @@ export async function reportProgress(
|
||||
// always track the body for job summary
|
||||
ctx.toolState.lastProgressBody = body;
|
||||
|
||||
const existingCommentId = ctx.toolState.progressComment.id;
|
||||
const existingCommentId = ctx.toolState.progressCommentId;
|
||||
const issueNumber =
|
||||
ctx.toolState.prNumber ?? ctx.toolState.issueNumber ?? ctx.payload.event.issue_number;
|
||||
const isPlanMode = ctx.toolState.selectedMode === "Plan";
|
||||
@@ -200,7 +196,7 @@ export async function reportProgress(
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
ctx.toolState.progressComment.wasUpdated = true;
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
return {
|
||||
commentId: result.data.id,
|
||||
@@ -229,10 +225,8 @@ export async function reportProgress(
|
||||
});
|
||||
|
||||
// store the comment ID for future updates
|
||||
ctx.toolState.progressComment = {
|
||||
id: result.data.id,
|
||||
wasUpdated: true,
|
||||
};
|
||||
ctx.toolState.progressCommentId = result.data.id;
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
// if Plan mode, update the comment to add the "Implement plan" link
|
||||
if (isPlanMode) {
|
||||
@@ -301,7 +295,7 @@ export function ReportProgressTool(ctx: ToolContext) {
|
||||
* Used after submitting a PR review since the review body contains all necessary info.
|
||||
*/
|
||||
export async function deleteProgressComment(ctx: ToolContext): Promise<boolean> {
|
||||
const existingCommentId = ctx.toolState.progressComment.id;
|
||||
const existingCommentId = ctx.toolState.progressCommentId;
|
||||
if (!existingCommentId) {
|
||||
return false;
|
||||
}
|
||||
@@ -321,88 +315,18 @@ export async function deleteProgressComment(ctx: ToolContext): Promise<boolean>
|
||||
}
|
||||
}
|
||||
|
||||
// reset state but mark as "updated" so ensureProgressCommentUpdated doesn't try to handle it
|
||||
ctx.toolState.progressComment = {
|
||||
id: null,
|
||||
wasUpdated: true,
|
||||
};
|
||||
// reset state and mark as updated so post script doesn't try to handle it
|
||||
ctx.toolState.progressCommentId = null;
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the progress comment is updated with a generic error message if it was never updated.
|
||||
* This should be called after agent execution completes to handle cases where the agent
|
||||
* exited without ever calling reportProgress.
|
||||
*
|
||||
* Works even if MCP context is not initialized (e.g., if error occurs before MCP server starts).
|
||||
* Uses comment ID from toolState (set during initToolState from initial fetch).
|
||||
*/
|
||||
export async function ensureProgressCommentUpdated(toolState: ToolState): Promise<void> {
|
||||
// skip if comment was already updated during execution
|
||||
if (toolState.progressComment.wasUpdated) {
|
||||
return;
|
||||
}
|
||||
|
||||
// skip if there's already a progress body recorded (agent called report_progress)
|
||||
if (toolState.lastProgressBody) {
|
||||
return;
|
||||
}
|
||||
|
||||
// get comment ID from toolState (already fetched during initToolState)
|
||||
const existingCommentId = toolState.progressComment.id;
|
||||
|
||||
// if still no comment ID, nothing to update
|
||||
if (!existingCommentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// check if comment still says "leaping into action" - if it's been updated with an error, don't overwrite it
|
||||
const repoContext = parseRepoContext();
|
||||
const octokit = createOctokit(getGitHubInstallationToken());
|
||||
|
||||
try {
|
||||
const existingComment = await octokit.rest.issues.getComment({
|
||||
owner: repoContext.owner,
|
||||
repo: repoContext.name,
|
||||
comment_id: existingCommentId,
|
||||
});
|
||||
|
||||
const commentBody = existingComment.data.body || "";
|
||||
// if comment doesn't start with the leaping prefix, it's already been updated with an error or progress
|
||||
if (!commentBody.startsWith(LEAPING_INTO_ACTION_PREFIX)) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// can't fetch comment, skip update
|
||||
return;
|
||||
}
|
||||
|
||||
const runId = process.env.GITHUB_RUN_ID;
|
||||
const workflowRunLink = runId
|
||||
? `[workflow run logs](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})`
|
||||
: "workflow run logs";
|
||||
|
||||
const errorMessage = `This run croaked 😵
|
||||
|
||||
The workflow encountered an error before any progress could be reported. Please check the ${workflowRunLink} for details.`;
|
||||
|
||||
// add footer without agent info (we don't have context here)
|
||||
const body = await addFooter({ octokit }, errorMessage);
|
||||
|
||||
await octokit.rest.issues.updateComment({
|
||||
owner: repoContext.owner,
|
||||
repo: repoContext.name,
|
||||
comment_id: existingCommentId,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
export const ReplyToReviewComment = type({
|
||||
pull_number: type.number.describe("the pull request number"),
|
||||
comment_id: type.number.describe("the ID of the review comment to reply to"),
|
||||
body: type.string.describe(
|
||||
`extremely brief reply (1 sentence max) explaining what was fixed, e.g. 'Fixed by renaming to X' or 'Added null check'. ${SUGGESTION_FORMAT_DESCRIPTION}`
|
||||
"extremely brief reply (1 sentence max) explaining what was fixed, e.g. 'Fixed by renaming to X' or 'Added null check'"
|
||||
),
|
||||
});
|
||||
|
||||
@@ -423,8 +347,8 @@ export function ReplyToReviewCommentTool(ctx: ToolContext) {
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
// mark progress as updated so ensureProgressCommentUpdated doesn't think the run failed
|
||||
ctx.toolState.progressComment.wasUpdated = true;
|
||||
// mark progress as updated so post script doesn't think the run failed
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { type } from "arktype";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import type { PrepResult } from "../prep/index.ts";
|
||||
import { runPrepPhase } from "../prep/index.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
// empty schema for tools with no parameters
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@ import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
export function CreateBranchTool(ctx: ToolContext) {
|
||||
const defaultBranch = ctx.repo.repo.default_branch || "main";
|
||||
const defaultBranch = ctx.repo.data.default_branch || "main";
|
||||
|
||||
const CreateBranch = type({
|
||||
branchName: type.string.describe(
|
||||
@@ -24,7 +24,7 @@ export function CreateBranchTool(ctx: ToolContext) {
|
||||
parameters: CreateBranch,
|
||||
execute: execute(async ({ branchName, baseBranch }) => {
|
||||
// baseBranch should always be defined due to default, but TypeScript needs help
|
||||
const resolvedBaseBranch = baseBranch || ctx.repo.repo.default_branch || "main";
|
||||
const resolvedBaseBranch = baseBranch || ctx.repo.data.default_branch || "main";
|
||||
|
||||
// validate branch name for secrets
|
||||
if (containsSecrets(branchName)) {
|
||||
@@ -142,7 +142,7 @@ export const PushBranch = type({
|
||||
});
|
||||
|
||||
export function PushBranchTool(ctx: ToolContext) {
|
||||
const defaultBranch = ctx.repo.repo.default_branch || "main";
|
||||
const defaultBranch = ctx.repo.data.default_branch || "main";
|
||||
|
||||
return tool({
|
||||
name: "push_branch",
|
||||
|
||||
+9
-10
@@ -8,7 +8,6 @@ import type { Mode } from "../modes.ts";
|
||||
import type { PrepResult } from "../prep/index.ts";
|
||||
import type { OctokitWithPlugins } from "../utils/github.ts";
|
||||
import type { ResolvedPayload } from "../utils/payload.ts";
|
||||
import type { RepoData } from "../utils/repoData.ts";
|
||||
|
||||
export type BackgroundProcess = {
|
||||
pid: number;
|
||||
@@ -30,11 +29,9 @@ export interface ToolState {
|
||||
promise: Promise<PrepResult[]> | undefined;
|
||||
results: PrepResult[] | undefined;
|
||||
};
|
||||
progressComment: {
|
||||
id: number | null;
|
||||
wasUpdated: boolean;
|
||||
};
|
||||
progressCommentId: number | null;
|
||||
lastProgressBody?: string;
|
||||
wasUpdated?: boolean;
|
||||
}
|
||||
|
||||
import type { ResolveRunResult } from "../utils/workflow.ts";
|
||||
@@ -46,21 +43,20 @@ interface InitToolStateParams {
|
||||
export function initToolState(ctx: InitToolStateParams): ToolState {
|
||||
const progressCommentIdStr = ctx.runInfo.workflowRunInfo.progressCommentId;
|
||||
const progressCommentId = progressCommentIdStr ? parseInt(progressCommentIdStr, 10) : null;
|
||||
const resolvedId = Number.isNaN(progressCommentId) ? null : progressCommentId;
|
||||
|
||||
return {
|
||||
progressComment: {
|
||||
id: Number.isNaN(progressCommentId) ? null : progressCommentId,
|
||||
wasUpdated: false,
|
||||
},
|
||||
progressCommentId: resolvedId,
|
||||
backgroundProcesses: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
export interface ToolContext {
|
||||
repo: RepoData;
|
||||
repo: RunContextData["repo"];
|
||||
payload: ResolvedPayload;
|
||||
octokit: OctokitWithPlugins;
|
||||
githubInstallationToken: string;
|
||||
apiToken: string;
|
||||
agent: Agent;
|
||||
modes: Mode[];
|
||||
toolState: ToolState;
|
||||
@@ -68,6 +64,7 @@ export interface ToolContext {
|
||||
jobId: string | undefined;
|
||||
}
|
||||
|
||||
import type { RunContextData } from "../utils/runContextData.ts";
|
||||
import { BashTool, KillBackgroundTool } from "./bash.ts";
|
||||
import { CheckoutPrTool } from "./checkout.ts";
|
||||
import { GetCheckSuiteLogsTool } from "./checkSuite.ts";
|
||||
@@ -94,6 +91,7 @@ import { CreatePullRequestReviewTool } from "./review.ts";
|
||||
import { GetReviewCommentsTool, ListPullRequestReviewsTool } from "./reviewComments.ts";
|
||||
import { SelectModeTool } from "./selectMode.ts";
|
||||
import { addTools } from "./shared.ts";
|
||||
import { UploadFileTool } from "./upload.ts";
|
||||
|
||||
/**
|
||||
* Find an available port starting from the given port
|
||||
@@ -180,6 +178,7 @@ export async function startMcpHttpServer(
|
||||
CreateBranchTool(ctx),
|
||||
CommitFilesTool(ctx),
|
||||
PushBranchTool(ctx),
|
||||
UploadFileTool(ctx),
|
||||
];
|
||||
|
||||
// only add BashTool when bash is "restricted"
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { type } from "arktype";
|
||||
import { fileTypeFromBuffer } from "file-type";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
const UploadFileParams = type({
|
||||
path: type.string.describe("absolute path to file to upload"),
|
||||
});
|
||||
|
||||
export function UploadFileTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "upload_file",
|
||||
description:
|
||||
"upload a file to get a permanent public URL. use for screenshots, artifacts, or any files you want to reference in PRs/comments. max 10MB, images/text/archives allowed.",
|
||||
parameters: UploadFileParams,
|
||||
execute: execute(async (params) => {
|
||||
// read file from disk eagerly on purpose to avoid its content being changed by the time it's uploaded
|
||||
const buffer = fs.readFileSync(params.path);
|
||||
const filename = path.basename(params.path);
|
||||
const contentLength = buffer.length;
|
||||
|
||||
const fileType = await fileTypeFromBuffer(buffer);
|
||||
const contentType = fileType?.mime || "application/octet-stream";
|
||||
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
|
||||
const response = await fetch(`${apiUrl}/api/upload/signed-url`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${ctx.apiToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
filename,
|
||||
contentType,
|
||||
contentLength,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(`failed to get upload URL: ${error}`);
|
||||
}
|
||||
|
||||
const { uploadUrl, publicUrl } = (await response.json()) as {
|
||||
uploadUrl: string;
|
||||
publicUrl: string;
|
||||
};
|
||||
|
||||
const uploadResponse = await fetch(uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
// should be set automatically, but given this header is signed it's better to be explicit
|
||||
"Content-Length": String(contentLength),
|
||||
},
|
||||
body: buffer,
|
||||
});
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error(`failed to upload file: ${uploadResponse.statusText}`);
|
||||
}
|
||||
|
||||
return { success: true, publicUrl, filename, contentLength, contentType };
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -19,6 +19,8 @@ const reportProgressInstruction = `Use ${ghPullfrogMcpName}/report_progress to s
|
||||
|
||||
const dependencyInstallationStep = `If this task will require running tests, builds, linters, or CLI commands that need installed packages, call \`${ghPullfrogMcpName}/start_dependency_installation\` NOW. This is non-blocking and allows dependencies to install in the background while you continue. Later, call \`${ghPullfrogMcpName}/await_dependency_installation\` before running commands that need them. Skip this step if only reading code or answering questions.`;
|
||||
|
||||
const permalinkTip = `**TIP**: To reference specific code, use GitHub permalinks: \`https://github.com/{owner}/{repo}/blob/{commit_sha}/{path}#L{start}-L{end}\`. GitHub renders these as expandable code blocks.`;
|
||||
|
||||
export function computeModes(): Mode[] {
|
||||
return [
|
||||
{
|
||||
@@ -48,7 +50,7 @@ export function computeModes(): Mode[] {
|
||||
8. ${reportProgressInstruction}
|
||||
|
||||
9. Determine whether to create a PR (if not already on a PR branch):
|
||||
- **Default behavior**: Create a PR using ${ghPullfrogMcpName}/create_pull_request with an informative title and body. If relevant, indicate which issue the PR addresses (e.g. "Fixes #123").
|
||||
- **Default behavior**: Create a PR using ${ghPullfrogMcpName}/create_pull_request with an informative title and body. If you are working in the context of an issue (check EVENT DATA for \`issue_number\` where \`is_pr\` is not true), include "Closes #<issue_number>" in the PR body to auto-close the issue when merged.
|
||||
- **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link.
|
||||
|
||||
10. Call report_progress one final time ONLY if you haven't already included all the important information (PR links, branch links, summary) in a previous report_progress call. If you already called report_progress with complete information including PR links after creating the PR, you do NOT need to call it again. Only make a final call if you need to add missing information. When making the final call, ensure it includes:
|
||||
@@ -98,36 +100,35 @@ export function computeModes(): Mode[] {
|
||||
name: "Review",
|
||||
description:
|
||||
"Review code, PRs, or implementations; provide feedback or suggestions; identify issues; or check code quality, style, and correctness",
|
||||
prompt: `Follow these steps to review the PR. Think hard. Do not nitpick.
|
||||
prompt: `Follow these steps to review the PR. Your job is to find problems—assume they exist until you've proven otherwise. Do not submit a clean review without thorough investigation.
|
||||
|
||||
1. **CHECKOUT** - Call ${ghPullfrogMcpName}/checkout_pr with the PR number. This should give you all PR metadata you need, including a \`diffPath\`: a path to a temp file containing the PR diff.
|
||||
|
||||
2. **ANALYZE** - Read the modified files to understand the changes in context.
|
||||
- **Understand the change**: What is being modified and why? What's the before/after behavior?
|
||||
- **Evaluate the approach**: Is it sound? If not, focus on approach before implementation details.
|
||||
|
||||
2. **ANALYZE**
|
||||
- Read the modified files to understand the changes in context. Make sure you understand what's being changed.
|
||||
- Is it a good idea? Think about the tradeoffs.
|
||||
- Is the approach sound? If not, focus on the approach first. Don't waste time on implementation details if the approach is wrong.
|
||||
- Can you imagine a better approach? If so, explain. Make sure it's strictly better, not just different.
|
||||
- Are there bugs, edge cases, security issues, or usability issues? Use your imagination.
|
||||
3. **INVESTIGATE** - Actively hunt for problems. Use these techniques:
|
||||
- **Trace data flow**: Use grep to follow how data moves through the system. How is state passed? Where could it get lost?
|
||||
- **Check boundaries**: What happens across process boundaries, module boundaries, async boundaries? State that exists in one context may not exist in another.
|
||||
- **Explore failure modes**: What if this throws? What if that returns null? What if the network fails? What if this runs twice?
|
||||
- **Verify assumptions**: If the code assumes X, verify X is actually true. Use grep, read related files, check documentation.
|
||||
- **Consider lifecycle**: Initialization, cleanup, error recovery. Are resources acquired before use? Released after? What happens on cancellation?
|
||||
- Do NOT stop at "this looks reasonable." Dig until you either find a problem or have concrete evidence there isn't one.
|
||||
|
||||
3. **DRAFT** - For each inline comment, find the line in the diff. Each code line shows: \`| OLD | NEW | TYPE | CODE\`. Use the NEW line number (second column). When suggesting specific code changes, use GitHub's suggestion format with \`\`\`suggestion blocks to enable one-click apply. Example:
|
||||
you could simplify this
|
||||
\`\`\`suggestion
|
||||
const result = data.map(x => x.value);
|
||||
\`\`\`
|
||||
or you could use reduce instead
|
||||
\`\`\`suggestion
|
||||
const result = data.reduce((acc, x) => [...acc, x.value], []);
|
||||
\`\`\`
|
||||
4. **DRAFT** - For each issue found, create an inline comment. Use the NEW line number from the diff (second column: \`| OLD | NEW | TYPE | CODE\`).
|
||||
|
||||
4. **FILTER COMMENTS** - Do not nitpick! Do not leave compliments that are not actionable. Do not critique the code hygiene or anything stylistic.
|
||||
5. **FILTER** - Remove noise, keep substance:
|
||||
- Remove style-only comments (formatting, naming conventions) unless they cause real confusion
|
||||
- Remove compliments that aren't actionable
|
||||
- Keep: bugs, logic errors, missing error handling, security issues, race conditions, resource leaks, incorrect assumptions
|
||||
|
||||
5. **SUBMIT** — Use ${ghPullfrogMcpName}/create_pull_request_review with:
|
||||
- \`comments\`: Array of all inline comments with file paths and line numbers
|
||||
- \`body\`: Everything else. Aim for a 1-3 sentence summary of the urgency level (e.g., "minor suggestions" vs "blocking issues") and any critical callouts (e.g., API key exposure). It can be longer if there are concerns that do not lend themselves to inline comments.
|
||||
- If you have no substantive feedback, submit an empty comments array with a brief approving body.
|
||||
- Again, do not nitpick.
|
||||
6. **SUBMIT** — Use ${ghPullfrogMcpName}/create_pull_request_review:
|
||||
- \`comments\`: Inline feedback on specific diff lines
|
||||
- \`body\`: 1-3 sentence summary with urgency level and any concerns about code outside the diff
|
||||
- If no issues found, submit with empty comments and a brief approving body
|
||||
|
||||
${permalinkTip}
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -143,7 +144,75 @@ export function computeModes(): Mode[] {
|
||||
|
||||
4. Create a structured plan with clear milestones
|
||||
|
||||
5. ${reportProgressInstruction}`,
|
||||
5. ${reportProgressInstruction}
|
||||
|
||||
${permalinkTip}`,
|
||||
},
|
||||
{
|
||||
name: "Fix",
|
||||
description:
|
||||
"Fix CI failures; debug failing tests or builds; investigate and resolve check suite failures",
|
||||
prompt: `Follow these steps to fix CI failures. THINK HARDER.
|
||||
|
||||
**CRITICAL RULE**: Only fix issues that were INTRODUCED BY THIS PR. If the CI failure is unrelated to the PR's changes, you MUST abort without committing anything and report why.
|
||||
|
||||
1. **GET FAILURE INFO** - Call ${ghPullfrogMcpName}/get_check_suite_logs with the check_suite_id from EVENT DATA. This returns:
|
||||
- \`log_index\`: array of interesting lines (errors, warnings, failures) with line numbers - scan this first
|
||||
- \`excerpt\`: curated ~80 lines around the main error - read this for immediate context
|
||||
- \`full_log_path\`: path to complete log file - read specific line ranges if needed
|
||||
- \`failed_steps\`: which CI steps failed (e.g., "Step 6: Run tests")
|
||||
|
||||
2. **CHECKOUT AND ASSESS CAUSATION** - Use ${ghPullfrogMcpName}/checkout_pr to get the PR diff. BEFORE attempting any fix, you MUST determine if this PR caused the failure:
|
||||
|
||||
**Ask yourself**: "Could the changes in this PR have caused this failure?"
|
||||
|
||||
- Read the PR diff carefully - what files were modified?
|
||||
- What is failing? (test file, module, assertion)
|
||||
- Is there a PLAUSIBLE CONNECTION between the PR changes and the failure?
|
||||
|
||||
**ABORT immediately if any of these are true:**
|
||||
- The failing test/file was NOT touched by this PR AND doesn't depend on changed code
|
||||
- The error is infrastructure-related (network timeout, runner OOM, service unavailable)
|
||||
- The error is a flaky test that passes/fails randomly
|
||||
- The error existed before this PR (pre-existing bug in main branch)
|
||||
- The error is in a dependency update not introduced by this PR
|
||||
|
||||
**When aborting**, use ${ghPullfrogMcpName}/report_progress to explain:
|
||||
"This CI failure appears unrelated to the PR's changes. [Describe the failure]. [Explain why it's not caused by the PR]. No changes made."
|
||||
|
||||
**Only proceed** if there's a clear, logical connection between the PR changes and the failure.
|
||||
|
||||
3. **UNDERSTAND HOW CI RUNS** - Read the workflow file to understand exactly what commands CI runs:
|
||||
- Look at \`.github/workflows/*.yml\` files
|
||||
- Find the job/step that failed (from \`failed_steps\`)
|
||||
- Note the EXACT command (e.g., \`pnpm -r test --filter=action\`, not just \`pnpm test\`)
|
||||
- Check for any CI-specific environment variables or setup steps
|
||||
|
||||
4. ${dependencyInstallationStep}
|
||||
|
||||
5. **REPRODUCE LOCALLY** - Run the EXACT same command that CI runs:
|
||||
- Do NOT simplify (e.g., don't run \`pnpm test\` if CI runs \`pnpm -r test --filter=action\`)
|
||||
- Check if CI uses specific flags, filters, or environment variables
|
||||
- If CI runs multiple test suites, run them all
|
||||
|
||||
6. **ANALYZE THE FAILURE** - Use the log_index and excerpt to understand:
|
||||
- What exactly failed (test name, file, assertion)
|
||||
- Are there earlier warnings that might explain the failure?
|
||||
- Is the failure flaky or deterministic?
|
||||
|
||||
7. **FIX THE ISSUE** - Make the necessary code changes. Common patterns:
|
||||
- Test assertion failures: fix the code or update the test expectation
|
||||
- Build failures: fix type errors, missing imports, syntax issues
|
||||
- Lint failures: fix code style issues
|
||||
- Timeout/flaky tests: investigate race conditions or increase timeouts
|
||||
|
||||
8. **VERIFY THE FIX** - Run the EXACT same CI command again to confirm the fix works
|
||||
|
||||
9. **COMMIT AND PUSH** - Use ${ghPullfrogMcpName}/commit_files and ${ghPullfrogMcpName}/push_branch
|
||||
|
||||
10. ${reportProgressInstruction}
|
||||
|
||||
**REMEMBER**: Your job is to fix issues THIS PR introduced, not to fix all CI failures. If in doubt about causation, abort and explain rather than making speculative changes.`,
|
||||
},
|
||||
{
|
||||
name: "Prompt",
|
||||
@@ -159,7 +228,7 @@ export function computeModes(): Mode[] {
|
||||
- Use ${ghPullfrogMcpName}/commit_files to commit your changes, then ${ghPullfrogMcpName}/push_branch to push the branch. Do NOT use git commands directly (\`git commit\`, \`git push\`, \`git checkout\`, \`git branch\`) as these will use incorrect credentials.
|
||||
- Test your changes to ensure they work correctly.
|
||||
- Determine whether to create a PR:
|
||||
- **Default behavior**: Create a PR using ${ghPullfrogMcpName}/create_pull_request with an informative title and body. If relevant, indicate which issue the PR addresses (e.g. "Fixes #123"). Include links to the issue or comment that triggered the PR in the PR body.
|
||||
- **Default behavior**: Create a PR using ${ghPullfrogMcpName}/create_pull_request with an informative title and body. If you are working in the context of an issue (check EVENT DATA for \`issue_number\` where \`is_pr\` is not true), include "Closes #<issue_number>" in the PR body to auto-close the issue when merged.
|
||||
- **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link.
|
||||
|
||||
3. ${reportProgressInstruction}
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@pullfrog/pullfrog",
|
||||
"version": "0.0.159",
|
||||
"version": "0.0.161",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"index.js",
|
||||
@@ -27,7 +27,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.11.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.2.7",
|
||||
"@ark/fs": "0.53.0",
|
||||
"@ark/util": "0.53.0",
|
||||
@@ -42,6 +41,7 @@
|
||||
"dotenv": "^17.2.3",
|
||||
"execa": "^9.6.0",
|
||||
"fastmcp": "^3.26.8",
|
||||
"file-type": "^21.3.0",
|
||||
"package-manager-detector": "^1.6.0",
|
||||
"semver": "^7.7.3",
|
||||
"table": "^6.9.0",
|
||||
|
||||
Generated
+3
-137
@@ -11,9 +11,6 @@ importers:
|
||||
'@actions/core':
|
||||
specifier: ^1.11.1
|
||||
version: 1.11.1
|
||||
'@actions/github':
|
||||
specifier: ^6.0.1
|
||||
version: 6.0.1
|
||||
'@anthropic-ai/claude-agent-sdk':
|
||||
specifier: 0.2.7
|
||||
version: 0.2.7(zod@4.3.5)
|
||||
@@ -56,6 +53,9 @@ importers:
|
||||
fastmcp:
|
||||
specifier: ^3.26.8
|
||||
version: 3.26.8(arktype@2.1.28)(hono@4.11.3)
|
||||
file-type:
|
||||
specifier: ^21.3.0
|
||||
version: 21.3.0
|
||||
package-manager-detector:
|
||||
specifier: ^1.6.0
|
||||
version: 1.6.0
|
||||
@@ -102,9 +102,6 @@ packages:
|
||||
'@actions/exec@1.1.1':
|
||||
resolution: {integrity: sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==}
|
||||
|
||||
'@actions/github@6.0.1':
|
||||
resolution: {integrity: sha512-xbZVcaqD4XnQAe35qSQqskb3SqIAfRyLBrHMd/8TuL7hJSz2QtbDwnNM8zWx4zO5l2fnGtseNE3MbEvD7BxVMw==}
|
||||
|
||||
'@actions/http-client@2.2.3':
|
||||
resolution: {integrity: sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==}
|
||||
|
||||
@@ -553,18 +550,10 @@ packages:
|
||||
'@cfworker/json-schema':
|
||||
optional: true
|
||||
|
||||
'@octokit/auth-token@4.0.0':
|
||||
resolution: {integrity: sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/auth-token@6.0.0':
|
||||
resolution: {integrity: sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==}
|
||||
engines: {node: '>= 20'}
|
||||
|
||||
'@octokit/core@5.2.2':
|
||||
resolution: {integrity: sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/core@7.0.5':
|
||||
resolution: {integrity: sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==}
|
||||
engines: {node: '>= 20'}
|
||||
@@ -573,24 +562,10 @@ packages:
|
||||
resolution: {integrity: sha512-7P1dRAZxuWAOPI7kXfio88trNi/MegQ0IJD3vfgC3b+LZo1Qe6gRJc2v0mz2USWWJOKrB2h5spXCzGbw+fAdqA==}
|
||||
engines: {node: '>= 20'}
|
||||
|
||||
'@octokit/endpoint@9.0.6':
|
||||
resolution: {integrity: sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/graphql@7.1.1':
|
||||
resolution: {integrity: sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/graphql@9.0.2':
|
||||
resolution: {integrity: sha512-iz6KzZ7u95Fzy9Nt2L8cG88lGRMr/qy1Q36ih/XVzMIlPDMYwaNLE/ENhqmIzgPrlNWiYJkwmveEetvxAgFBJw==}
|
||||
engines: {node: '>= 20'}
|
||||
|
||||
'@octokit/openapi-types@20.0.0':
|
||||
resolution: {integrity: sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==}
|
||||
|
||||
'@octokit/openapi-types@24.2.0':
|
||||
resolution: {integrity: sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==}
|
||||
|
||||
'@octokit/openapi-types@26.0.0':
|
||||
resolution: {integrity: sha512-7AtcfKtpo77j7Ts73b4OWhOZHTKo/gGY8bB3bNBQz4H+GRSWqx2yvj8TXRsbdTE0eRmYmXOEY66jM7mJ7LzfsA==}
|
||||
|
||||
@@ -603,24 +578,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@octokit/core': '>=6'
|
||||
|
||||
'@octokit/plugin-paginate-rest@9.2.2':
|
||||
resolution: {integrity: sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ==}
|
||||
engines: {node: '>= 18'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '5'
|
||||
|
||||
'@octokit/plugin-request-log@6.0.0':
|
||||
resolution: {integrity: sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==}
|
||||
engines: {node: '>= 20'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '>=6'
|
||||
|
||||
'@octokit/plugin-rest-endpoint-methods@10.4.1':
|
||||
resolution: {integrity: sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==}
|
||||
engines: {node: '>= 18'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '5'
|
||||
|
||||
'@octokit/plugin-rest-endpoint-methods@16.1.0':
|
||||
resolution: {integrity: sha512-nCsyiKoGRnhH5LkH8hJEZb9swpqOcsW+VXv1QoyUNQXJeVODG4+xM6UICEqyqe9XFr6LkL8BIiFCPev8zMDXPw==}
|
||||
engines: {node: '>= 20'}
|
||||
@@ -633,10 +596,6 @@ packages:
|
||||
peerDependencies:
|
||||
'@octokit/core': ^7.0.0
|
||||
|
||||
'@octokit/request-error@5.1.1':
|
||||
resolution: {integrity: sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/request-error@7.0.1':
|
||||
resolution: {integrity: sha512-CZpFwV4+1uBrxu7Cw8E5NCXDWFNf18MSY23TdxCBgjw1tXXHvTrZVsXlW8hgFTOLw8RQR1BBrMvYRtuyaijHMA==}
|
||||
engines: {node: '>= 20'}
|
||||
@@ -645,20 +604,10 @@ packages:
|
||||
resolution: {integrity: sha512-TXnouHIYLtgDhKo+N6mXATnDBkV05VwbR0TtMWpgTHIoQdRQfCSzmy/LGqR1AbRMbijq/EckC/E3/ZNcU92NaQ==}
|
||||
engines: {node: '>= 20'}
|
||||
|
||||
'@octokit/request@8.4.1':
|
||||
resolution: {integrity: sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/rest@22.0.0':
|
||||
resolution: {integrity: sha512-z6tmTu9BTnw51jYGulxrlernpsQYXpui1RK21vmXn8yF5bp6iX16yfTtJYGK5Mh1qDkvDOmp2n8sRMcQmR8jiA==}
|
||||
engines: {node: '>= 20'}
|
||||
|
||||
'@octokit/types@12.6.0':
|
||||
resolution: {integrity: sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==}
|
||||
|
||||
'@octokit/types@13.10.0':
|
||||
resolution: {integrity: sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==}
|
||||
|
||||
'@octokit/types@15.0.0':
|
||||
resolution: {integrity: sha512-8o6yDfmoGJUIeR9OfYU0/TUJTnMPG2r68+1yEdUeG2Fdqpj8Qetg0ziKIgcBm0RW/j29H41WP37CYCEhp6GoHQ==}
|
||||
|
||||
@@ -915,9 +864,6 @@ packages:
|
||||
resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
before-after-hook@2.2.3:
|
||||
resolution: {integrity: sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==}
|
||||
|
||||
before-after-hook@4.0.0:
|
||||
resolution: {integrity: sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==}
|
||||
|
||||
@@ -992,9 +938,6 @@ packages:
|
||||
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
|
||||
engines: {node: '>= 0.8'}
|
||||
|
||||
deprecation@2.3.1:
|
||||
resolution: {integrity: sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==}
|
||||
|
||||
dotenv@17.2.3:
|
||||
resolution: {integrity: sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -1543,9 +1486,6 @@ packages:
|
||||
resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
universal-user-agent@6.0.1:
|
||||
resolution: {integrity: sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==}
|
||||
|
||||
universal-user-agent@7.0.3:
|
||||
resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==}
|
||||
|
||||
@@ -1709,16 +1649,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@actions/io': 1.1.3
|
||||
|
||||
'@actions/github@6.0.1':
|
||||
dependencies:
|
||||
'@actions/http-client': 2.2.3
|
||||
'@octokit/core': 5.2.2
|
||||
'@octokit/plugin-paginate-rest': 9.2.2(@octokit/core@5.2.2)
|
||||
'@octokit/plugin-rest-endpoint-methods': 10.4.1(@octokit/core@5.2.2)
|
||||
'@octokit/request': 8.4.1
|
||||
'@octokit/request-error': 5.1.1
|
||||
undici: 5.29.0
|
||||
|
||||
'@actions/http-client@2.2.3':
|
||||
dependencies:
|
||||
tunnel: 0.0.6
|
||||
@@ -1998,20 +1928,8 @@ snapshots:
|
||||
- hono
|
||||
- supports-color
|
||||
|
||||
'@octokit/auth-token@4.0.0': {}
|
||||
|
||||
'@octokit/auth-token@6.0.0': {}
|
||||
|
||||
'@octokit/core@5.2.2':
|
||||
dependencies:
|
||||
'@octokit/auth-token': 4.0.0
|
||||
'@octokit/graphql': 7.1.1
|
||||
'@octokit/request': 8.4.1
|
||||
'@octokit/request-error': 5.1.1
|
||||
'@octokit/types': 13.10.0
|
||||
before-after-hook: 2.2.3
|
||||
universal-user-agent: 6.0.1
|
||||
|
||||
'@octokit/core@7.0.5':
|
||||
dependencies:
|
||||
'@octokit/auth-token': 6.0.0
|
||||
@@ -2027,27 +1945,12 @@ snapshots:
|
||||
'@octokit/types': 15.0.0
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/endpoint@9.0.6':
|
||||
dependencies:
|
||||
'@octokit/types': 13.10.0
|
||||
universal-user-agent: 6.0.1
|
||||
|
||||
'@octokit/graphql@7.1.1':
|
||||
dependencies:
|
||||
'@octokit/request': 8.4.1
|
||||
'@octokit/types': 13.10.0
|
||||
universal-user-agent: 6.0.1
|
||||
|
||||
'@octokit/graphql@9.0.2':
|
||||
dependencies:
|
||||
'@octokit/request': 10.0.5
|
||||
'@octokit/types': 15.0.0
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/openapi-types@20.0.0': {}
|
||||
|
||||
'@octokit/openapi-types@24.2.0': {}
|
||||
|
||||
'@octokit/openapi-types@26.0.0': {}
|
||||
|
||||
'@octokit/openapi-types@27.0.0': {}
|
||||
@@ -2057,20 +1960,10 @@ snapshots:
|
||||
'@octokit/core': 7.0.5
|
||||
'@octokit/types': 15.0.0
|
||||
|
||||
'@octokit/plugin-paginate-rest@9.2.2(@octokit/core@5.2.2)':
|
||||
dependencies:
|
||||
'@octokit/core': 5.2.2
|
||||
'@octokit/types': 12.6.0
|
||||
|
||||
'@octokit/plugin-request-log@6.0.0(@octokit/core@7.0.5)':
|
||||
dependencies:
|
||||
'@octokit/core': 7.0.5
|
||||
|
||||
'@octokit/plugin-rest-endpoint-methods@10.4.1(@octokit/core@5.2.2)':
|
||||
dependencies:
|
||||
'@octokit/core': 5.2.2
|
||||
'@octokit/types': 12.6.0
|
||||
|
||||
'@octokit/plugin-rest-endpoint-methods@16.1.0(@octokit/core@7.0.5)':
|
||||
dependencies:
|
||||
'@octokit/core': 7.0.5
|
||||
@@ -2082,12 +1975,6 @@ snapshots:
|
||||
'@octokit/types': 16.0.0
|
||||
bottleneck: 2.19.5
|
||||
|
||||
'@octokit/request-error@5.1.1':
|
||||
dependencies:
|
||||
'@octokit/types': 13.10.0
|
||||
deprecation: 2.3.1
|
||||
once: 1.4.0
|
||||
|
||||
'@octokit/request-error@7.0.1':
|
||||
dependencies:
|
||||
'@octokit/types': 15.0.0
|
||||
@@ -2100,13 +1987,6 @@ snapshots:
|
||||
fast-content-type-parse: 3.0.0
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/request@8.4.1':
|
||||
dependencies:
|
||||
'@octokit/endpoint': 9.0.6
|
||||
'@octokit/request-error': 5.1.1
|
||||
'@octokit/types': 13.10.0
|
||||
universal-user-agent: 6.0.1
|
||||
|
||||
'@octokit/rest@22.0.0':
|
||||
dependencies:
|
||||
'@octokit/core': 7.0.5
|
||||
@@ -2114,14 +1994,6 @@ snapshots:
|
||||
'@octokit/plugin-request-log': 6.0.0(@octokit/core@7.0.5)
|
||||
'@octokit/plugin-rest-endpoint-methods': 16.1.0(@octokit/core@7.0.5)
|
||||
|
||||
'@octokit/types@12.6.0':
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 20.0.0
|
||||
|
||||
'@octokit/types@13.10.0':
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 24.2.0
|
||||
|
||||
'@octokit/types@15.0.0':
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 26.0.0
|
||||
@@ -2326,8 +2198,6 @@ snapshots:
|
||||
|
||||
astral-regex@2.0.0: {}
|
||||
|
||||
before-after-hook@2.2.3: {}
|
||||
|
||||
before-after-hook@4.0.0: {}
|
||||
|
||||
body-parser@2.2.0:
|
||||
@@ -2399,8 +2269,6 @@ snapshots:
|
||||
|
||||
depd@2.0.0: {}
|
||||
|
||||
deprecation@2.3.1: {}
|
||||
|
||||
dotenv@17.2.3: {}
|
||||
|
||||
dunder-proto@1.0.1:
|
||||
@@ -3023,8 +2891,6 @@ snapshots:
|
||||
|
||||
unicorn-magic@0.3.0: {}
|
||||
|
||||
universal-user-agent@6.0.1: {}
|
||||
|
||||
universal-user-agent@7.0.3: {}
|
||||
|
||||
unpipe@1.0.0: {}
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type { AgentResult, ValidationCheck } from "./utils.ts";
|
||||
import { generateAgentUuids, defineFixture, getAgentOutput, runTests } from "./utils.ts";
|
||||
import { defineFixture, generateAgentUuids, getAgentOutput, runTests } from "./utils.ts";
|
||||
|
||||
/**
|
||||
* nobash test - validates agents respect bash=disabled setting.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type { AgentResult, ValidationCheck } from "./utils.ts";
|
||||
import { generateAgentUuids, defineFixture, getAgentOutput, runTests } from "./utils.ts";
|
||||
import { defineFixture, generateAgentUuids, getAgentOutput, runTests } from "./utils.ts";
|
||||
|
||||
/**
|
||||
* restricted test - validates bash=restricted environment filtering.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { config } from "dotenv";
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { type Agent, agents } from "../agents/index.ts";
|
||||
import type { AgentName } from "../external.ts";
|
||||
import { log } from "./cli.ts";
|
||||
import type { ResolvedPayload } from "./payload.ts";
|
||||
import type { RepoSettings } from "./repoSettings.ts";
|
||||
import type { RepoSettings } from "./runContext.ts";
|
||||
|
||||
/**
|
||||
* Check if an agent has API keys available (from process.env)
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ function collectApiKeys(agent: Agent): Record<string, string> {
|
||||
return apiKeys;
|
||||
}
|
||||
|
||||
export function validateApiKey(params: { agent: Agent; owner: string; name: string }): void {
|
||||
export function validateAgentApiKey(params: { agent: Agent; owner: string; name: string }): void {
|
||||
const apiKeys = collectApiKeys(params.agent);
|
||||
|
||||
if (Object.keys(apiKeys).length === 0) {
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@ import TurndownService from "turndown";
|
||||
import type { PayloadEvent } from "../external.ts";
|
||||
import { log } from "./cli.ts";
|
||||
import type { OctokitWithPlugins } from "./github.ts";
|
||||
import type { RepoData } from "./repoData.ts";
|
||||
import type { RunContextData } from "./runContextData.ts";
|
||||
|
||||
const turndown = new TurndownService();
|
||||
|
||||
@@ -14,7 +14,7 @@ function hasImages(body: string | null | undefined): boolean {
|
||||
interface ResolveBodyContext {
|
||||
event: PayloadEvent;
|
||||
octokit: OctokitWithPlugins;
|
||||
repo: RepoData;
|
||||
repo: RunContextData["repo"];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,7 +12,7 @@ interface ReportErrorParams {
|
||||
export async function reportErrorToComment(ctx: ReportErrorParams): Promise<void> {
|
||||
const formattedError = ctx.title ? `${ctx.title}\n\n${ctx.error}` : ctx.error;
|
||||
|
||||
const commentId = ctx.toolState.progressComment.id;
|
||||
const commentId = ctx.toolState.progressCommentId;
|
||||
if (!commentId) {
|
||||
return;
|
||||
}
|
||||
@@ -24,9 +24,7 @@ export async function reportErrorToComment(ctx: ReportErrorParams): Promise<void
|
||||
// build footer with workflow run link
|
||||
const footer = buildPullfrogFooter({
|
||||
triggeredBy: true,
|
||||
workflowRun: runId
|
||||
? { owner: repoContext.owner, repo: repoContext.name, runId }
|
||||
: undefined,
|
||||
workflowRun: runId ? { owner: repoContext.owner, repo: repoContext.name, runId } : undefined,
|
||||
});
|
||||
|
||||
await octokit.rest.issues.updateComment({
|
||||
@@ -36,6 +34,6 @@ export async function reportErrorToComment(ctx: ReportErrorParams): Promise<void
|
||||
body: `${formattedError}${footer}`,
|
||||
});
|
||||
|
||||
// mark as updated so ensureProgressCommentUpdated doesn't try to update again
|
||||
ctx.toolState.progressComment.wasUpdated = true;
|
||||
// mark as updated so exit handler doesn't try to update again
|
||||
ctx.toolState.wasUpdated = true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { LEAPING_INTO_ACTION_PREFIX } from "../mcp/comment.ts";
|
||||
import type { ToolState } from "../mcp/server.ts";
|
||||
import { buildPullfrogFooter } from "./buildPullfrogFooter.ts";
|
||||
import { log } from "./cli.ts";
|
||||
import { createOctokit, parseRepoContext } from "./github.ts";
|
||||
import { revokeGitHubInstallationToken } from "./token.ts";
|
||||
|
||||
let cleanupFn: ((isCancellation: boolean) => Promise<void>) | undefined;
|
||||
|
||||
export function setupExitHandler(toolState: ToolState): void {
|
||||
let hasCleanedUp = false;
|
||||
|
||||
async function cleanup(isCancellation: boolean): Promise<void> {
|
||||
if (hasCleanedUp) {
|
||||
return;
|
||||
}
|
||||
hasCleanedUp = true;
|
||||
|
||||
const token = process.env.GITHUB_TOKEN;
|
||||
const commentId = toolState.progressCommentId;
|
||||
const wasUpdated = toolState.wasUpdated === true;
|
||||
|
||||
// update progress comment if it was never updated (still shows "leaping into action")
|
||||
if (token && commentId && !wasUpdated) {
|
||||
try {
|
||||
const repoContext = parseRepoContext();
|
||||
const octokit = createOctokit(token);
|
||||
|
||||
const existingComment = await octokit.rest.issues.getComment({
|
||||
owner: repoContext.owner,
|
||||
repo: repoContext.name,
|
||||
comment_id: commentId,
|
||||
});
|
||||
|
||||
const commentBody = existingComment.data.body || "";
|
||||
|
||||
// only update if comment still shows the initial "leaping into action" message
|
||||
if (commentBody.startsWith(LEAPING_INTO_ACTION_PREFIX)) {
|
||||
const runId = process.env.GITHUB_RUN_ID;
|
||||
const workflowRunLink = runId
|
||||
? `[workflow run logs](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})`
|
||||
: "workflow run logs";
|
||||
|
||||
const errorMessage = isCancellation
|
||||
? `This run was cancelled 🛑\n\nThe workflow was cancelled before completion. Please check the ${workflowRunLink} for details.`
|
||||
: `This run croaked 😵\n\nThe workflow encountered an error before any progress could be reported. Please check the ${workflowRunLink} for details.`;
|
||||
|
||||
const footer = buildPullfrogFooter({
|
||||
triggeredBy: true,
|
||||
workflowRun: runId
|
||||
? { owner: repoContext.owner, repo: repoContext.name, runId }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
await octokit.rest.issues.updateComment({
|
||||
owner: repoContext.owner,
|
||||
repo: repoContext.name,
|
||||
comment_id: commentId,
|
||||
body: `${errorMessage}${footer}`,
|
||||
});
|
||||
|
||||
log.info("» updated progress comment with error message");
|
||||
}
|
||||
} catch {
|
||||
// ignore errors during cleanup
|
||||
}
|
||||
}
|
||||
|
||||
// revoke token
|
||||
if (token) {
|
||||
try {
|
||||
await revokeGitHubInstallationToken(token);
|
||||
log.debug("» installation token revoked");
|
||||
} catch {
|
||||
// ignore errors during cleanup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// store cleanup function for runCleanup()
|
||||
cleanupFn = cleanup;
|
||||
|
||||
// handle cancellation signals
|
||||
function handleSignal(): void {
|
||||
log.info("» workflow cancelled, cleaning up...");
|
||||
cleanup(true).finally(() => process.exit(1));
|
||||
}
|
||||
|
||||
process.on("SIGINT", handleSignal);
|
||||
process.on("SIGTERM", handleSignal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run cleanup explicitly. Called from entry.ts in finally block.
|
||||
*/
|
||||
export async function runCleanup(): Promise<void> {
|
||||
try {
|
||||
await cleanupFn?.(false);
|
||||
} catch {
|
||||
// ignore errors during cleanup
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createSign } from "node:crypto";
|
||||
import * as core from "@actions/core";
|
||||
import { throttling } from "@octokit/plugin-throttling";
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { existsSync } from "node:fs";
|
||||
|
||||
export const isCloudflareSandbox =
|
||||
!!process.env.CLOUDFLARE_APPLICATION_ID && !!process.env.SANDBOX_VERSION;
|
||||
|
||||
export const isGitHubActions = !!process.env.GITHUB_ACTIONS;
|
||||
|
||||
// detect if running inside Docker container (CI tests run in Docker with host env vars)
|
||||
export const isInsideDocker = existsSync("/.dockerenv");
|
||||
@@ -4,11 +4,11 @@ import { encode as toonEncode } from "@toon-format/toon";
|
||||
import { ghPullfrogMcpName, type PayloadEvent } from "../external.ts";
|
||||
import type { Mode } from "../modes.ts";
|
||||
import type { ResolvedPayload } from "./payload.ts";
|
||||
import type { RepoData } from "./repoData.ts";
|
||||
import type { RunContextData } from "./runContextData.ts";
|
||||
|
||||
interface InstructionsContext {
|
||||
payload: ResolvedPayload;
|
||||
repoData: RepoData;
|
||||
repo: RunContextData["repo"];
|
||||
modes: Mode[];
|
||||
}
|
||||
|
||||
@@ -33,8 +33,8 @@ function buildRuntimeContext(ctx: InstructionsContext): string {
|
||||
|
||||
const data: Record<string, unknown> = {
|
||||
...payloadRest,
|
||||
repo: `${ctx.repoData.owner}/${ctx.repoData.name}`,
|
||||
default_branch: ctx.repoData.repo.default_branch,
|
||||
repo: `${ctx.repo.owner}/${ctx.repo.name}`,
|
||||
default_branch: ctx.repo.data.default_branch,
|
||||
working_directory: process.cwd(),
|
||||
log_level: process.env.LOG_LEVEL,
|
||||
git_status: gitStatus,
|
||||
@@ -150,7 +150,7 @@ You are careful, to-the-point, and kind. You only say things you know to be true
|
||||
You do not break up sentences with hyphens. You use emdashes.
|
||||
You have a strong bias toward minimalism: no dead code, no premature abstractions, no speculative features, and no comments that merely restate what the code does.
|
||||
Your code is focused, elegant, and production-ready.
|
||||
You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so.
|
||||
You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so.
|
||||
You adapt your writing style to match existing patterns in the codebase (commit messages, PR descriptions, code comments) while never being unprofessional.
|
||||
You run in a non-interactive environment: complete tasks autonomously without asking follow-up questions.
|
||||
You are running inside a GitHub Actions ephemeral environment. All processes and resources will be cleaned up at the end of the run.
|
||||
|
||||
+1
-6
@@ -2,14 +2,9 @@
|
||||
* Logging utilities that work well in both local and GitHub Actions environments
|
||||
*/
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import * as core from "@actions/core";
|
||||
import { table } from "table";
|
||||
|
||||
const isGitHubActions = !!process.env.GITHUB_ACTIONS;
|
||||
|
||||
// detect if running inside Docker container (CI tests run in Docker with host env vars)
|
||||
const isInsideDocker = existsSync("/.dockerenv");
|
||||
import { isGitHubActions, isInsideDocker } from "./globals.ts";
|
||||
|
||||
const isDebugEnabled = () =>
|
||||
process.env.LOG_LEVEL === "debug" ||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import * as core from "@actions/core";
|
||||
import { type } from "arktype";
|
||||
import { AgentName, type AuthorPermission, Effort, type PayloadEvent } from "../external.ts";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import type { RepoSettings } from "./repoSettings.ts";
|
||||
import type { RepoSettings } from "./runContext.ts";
|
||||
import { validateCompatibility } from "./versioning.ts";
|
||||
|
||||
// tool permission enum types for inputs
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { log } from "./cli.ts";
|
||||
import { createOctokit, type OctokitWithPlugins, parseRepoContext } from "./github.ts";
|
||||
import { fetchRepoSettings, type RepoSettings } from "./repoSettings.ts";
|
||||
|
||||
export interface RepoData {
|
||||
owner: string;
|
||||
name: string;
|
||||
repo: Awaited<ReturnType<Octokit["repos"]["get"]>>["data"];
|
||||
repoSettings: RepoSettings;
|
||||
}
|
||||
|
||||
interface ResolveRepoDataParams {
|
||||
octokit: OctokitWithPlugins;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize repo data: parse context, fetch repo info and settings
|
||||
*/
|
||||
export async function resolveRepoData(params: ResolveRepoDataParams): Promise<RepoData> {
|
||||
log.info(`» running Pullfrog v${packageJson.version}...`);
|
||||
|
||||
const { owner, name } = parseRepoContext();
|
||||
|
||||
// fetch repo data and settings in parallel
|
||||
const [repoResponse, repoSettings] = await Promise.all([
|
||||
params.octokit.repos.get({ owner, repo: name }),
|
||||
fetchRepoSettings({ token: params.token, repoContext: { owner, name } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
owner,
|
||||
name,
|
||||
repo: repoResponse.data,
|
||||
repoSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// re-export for convenience
|
||||
export { createOctokit };
|
||||
@@ -18,14 +18,35 @@ export interface RepoSettings {
|
||||
bash: BashPermission;
|
||||
}
|
||||
|
||||
export interface RunContext {
|
||||
settings: RepoSettings;
|
||||
apiToken: string;
|
||||
}
|
||||
|
||||
const defaultSettings: RepoSettings = {
|
||||
defaultAgent: null,
|
||||
modes: [],
|
||||
repoInstructions: "",
|
||||
web: "enabled",
|
||||
search: "enabled",
|
||||
write: "enabled",
|
||||
bash: "restricted",
|
||||
};
|
||||
|
||||
const defaultRunContext: RunContext = {
|
||||
settings: defaultSettings,
|
||||
apiToken: "",
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch repository settings from the Pullfrog API
|
||||
* Returns defaults if repo doesn't exist or fetch fails
|
||||
* fetch run context from Pullfrog API
|
||||
* returns settings + API token for subsequent calls
|
||||
* returns defaults if fetch fails
|
||||
*/
|
||||
export async function fetchRepoSettings(params: {
|
||||
export async function fetchRunContext(params: {
|
||||
token: string;
|
||||
repoContext: RepoContext;
|
||||
}): Promise<RepoSettings> {
|
||||
}): Promise<RunContext> {
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
const timeoutMs = 30000;
|
||||
const controller = new AbortController();
|
||||
@@ -33,7 +54,7 @@ export async function fetchRepoSettings(params: {
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/settings`,
|
||||
`${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/run-context`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
@@ -47,41 +68,24 @@ export async function fetchRepoSettings(params: {
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
defaultAgent: null,
|
||||
modes: [],
|
||||
repoInstructions: "",
|
||||
web: "enabled",
|
||||
search: "enabled",
|
||||
write: "enabled",
|
||||
bash: "restricted",
|
||||
};
|
||||
return defaultRunContext;
|
||||
}
|
||||
|
||||
const settings = (await response.json()) as RepoSettings | null;
|
||||
if (settings === null) {
|
||||
return {
|
||||
defaultAgent: null,
|
||||
modes: [],
|
||||
repoInstructions: "",
|
||||
web: "enabled",
|
||||
search: "enabled",
|
||||
write: "enabled",
|
||||
bash: "restricted",
|
||||
};
|
||||
const data = (await response.json()) as {
|
||||
settings: RepoSettings | null;
|
||||
apiToken: string;
|
||||
} | null;
|
||||
|
||||
if (data === null) {
|
||||
return defaultRunContext;
|
||||
}
|
||||
|
||||
return settings;
|
||||
return {
|
||||
settings: data.settings ?? defaultSettings,
|
||||
apiToken: data.apiToken,
|
||||
};
|
||||
} catch {
|
||||
clearTimeout(timeoutId);
|
||||
return {
|
||||
defaultAgent: null,
|
||||
modes: [],
|
||||
repoInstructions: "",
|
||||
web: "enabled",
|
||||
search: "enabled",
|
||||
write: "enabled",
|
||||
bash: "restricted",
|
||||
};
|
||||
return defaultRunContext;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { log } from "./cli.ts";
|
||||
import { type OctokitWithPlugins, parseRepoContext } from "./github.ts";
|
||||
import { fetchRunContext, type RepoSettings } from "./runContext.ts";
|
||||
|
||||
export interface RunContextData {
|
||||
repo: {
|
||||
owner: string;
|
||||
name: string;
|
||||
data: Awaited<ReturnType<Octokit["repos"]["get"]>>["data"];
|
||||
};
|
||||
repoSettings: RepoSettings;
|
||||
apiToken: string;
|
||||
}
|
||||
|
||||
interface ResolveRunContextDataParams {
|
||||
octokit: OctokitWithPlugins;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* initialize run context data: parse context, fetch repo info and settings
|
||||
*/
|
||||
export async function resolveRunContextData(
|
||||
params: ResolveRunContextDataParams
|
||||
): Promise<RunContextData> {
|
||||
log.info(`» running Pullfrog v${packageJson.version}...`);
|
||||
|
||||
const repoContext = parseRepoContext();
|
||||
|
||||
const [repoResponse, runContext] = await Promise.all([
|
||||
params.octokit.repos.get({ owner: repoContext.owner, repo: repoContext.name }),
|
||||
fetchRunContext({ token: params.token, repoContext }),
|
||||
]);
|
||||
|
||||
return {
|
||||
repo: {
|
||||
owner: repoContext.owner,
|
||||
name: repoContext.name,
|
||||
data: repoResponse.data,
|
||||
},
|
||||
repoSettings: runContext.settings,
|
||||
apiToken: runContext.apiToken,
|
||||
};
|
||||
}
|
||||
+2
-4
@@ -134,10 +134,8 @@ export async function setupGit(params: SetupGitParams): Promise<void> {
|
||||
// - restricted/disabled: workflow token (limited by permissions block)
|
||||
// this protects the base repo while allowing fork PR edits via fork remote
|
||||
const originToken =
|
||||
params.bashPermission === "enabled"
|
||||
? params.token
|
||||
: (params.originalToken || params.token);
|
||||
|
||||
params.bashPermission === "enabled" ? params.token : params.originalToken || params.token;
|
||||
|
||||
// non-PR events: set up origin with token, stay on default branch
|
||||
if (params.event.is_pr !== true || !params.event.issue_number) {
|
||||
const originUrl = `https://x-access-token:${originToken}@github.com/${params.owner}/${params.name}.git`;
|
||||
|
||||
+30
-34
@@ -1,9 +1,9 @@
|
||||
import { Timer } from './timer.ts';
|
||||
import * as cli from './cli.ts';
|
||||
import * as cli from "./cli.ts";
|
||||
import { Timer } from "./timer.ts";
|
||||
|
||||
describe('Timer', () => {
|
||||
describe("Timer", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(cli.log, 'debug');
|
||||
vi.spyOn(cli.log, "debug");
|
||||
// Mock Date.now to have predictable timestamps
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
@@ -13,34 +13,32 @@ describe('Timer', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should initialize with current timestamp', () => {
|
||||
describe("constructor", () => {
|
||||
it("should initialize with current timestamp", () => {
|
||||
const mockTime = 1000000;
|
||||
vi.setSystemTime(mockTime);
|
||||
|
||||
const timer = new Timer();
|
||||
timer.checkpoint('test');
|
||||
timer.checkpoint("test");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledWith(
|
||||
expect.stringContaining('test')
|
||||
);
|
||||
expect(cli.log.debug).toHaveBeenCalledWith(expect.stringContaining("test"));
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkpoint', () => {
|
||||
it('should log duration from initial timestamp on first checkpoint', () => {
|
||||
describe("checkpoint", () => {
|
||||
it("should log duration from initial timestamp on first checkpoint", () => {
|
||||
const startTime = 1000000;
|
||||
vi.setSystemTime(startTime);
|
||||
const timer = new Timer();
|
||||
|
||||
const checkpointTime = startTime + 100;
|
||||
vi.setSystemTime(checkpointTime);
|
||||
timer.checkpoint('first');
|
||||
timer.checkpoint("first");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledWith('» first: 100ms');
|
||||
expect(cli.log.debug).toHaveBeenCalledWith("» first: 100ms");
|
||||
});
|
||||
|
||||
it('should log duration from last checkpoint on subsequent checkpoints', () => {
|
||||
it("should log duration from last checkpoint on subsequent checkpoints", () => {
|
||||
const startTime = 1000000;
|
||||
vi.setSystemTime(startTime);
|
||||
const timer = new Timer();
|
||||
@@ -48,63 +46,61 @@ describe('Timer', () => {
|
||||
// First checkpoint
|
||||
const firstCheckpointTime = startTime + 50;
|
||||
vi.setSystemTime(firstCheckpointTime);
|
||||
timer.checkpoint('first');
|
||||
timer.checkpoint("first");
|
||||
|
||||
// Second checkpoint
|
||||
const secondCheckpointTime = firstCheckpointTime + 75;
|
||||
vi.setSystemTime(secondCheckpointTime);
|
||||
timer.checkpoint('second');
|
||||
timer.checkpoint("second");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledTimes(2);
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(1, '» first: 50ms');
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(2, '» second: 75ms');
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(1, "» first: 50ms");
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(2, "» second: 75ms");
|
||||
});
|
||||
|
||||
it('should handle multiple checkpoints correctly', () => {
|
||||
it("should handle multiple checkpoints correctly", () => {
|
||||
const startTime = 1000000;
|
||||
vi.setSystemTime(startTime);
|
||||
const timer = new Timer();
|
||||
|
||||
// First checkpoint
|
||||
vi.setSystemTime(startTime + 10);
|
||||
timer.checkpoint('step1');
|
||||
timer.checkpoint("step1");
|
||||
|
||||
// Second checkpoint
|
||||
vi.setSystemTime(startTime + 25);
|
||||
timer.checkpoint('step2');
|
||||
timer.checkpoint("step2");
|
||||
|
||||
// Third checkpoint
|
||||
vi.setSystemTime(startTime + 45);
|
||||
timer.checkpoint('step3');
|
||||
timer.checkpoint("step3");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledTimes(3);
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(1, '» step1: 10ms');
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(2, '» step2: 15ms');
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(3, '» step3: 20ms');
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(1, "» step1: 10ms");
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(2, "» step2: 15ms");
|
||||
expect(cli.log.debug).toHaveBeenNthCalledWith(3, "» step3: 20ms");
|
||||
});
|
||||
|
||||
it('should handle zero duration correctly', () => {
|
||||
it("should handle zero duration correctly", () => {
|
||||
const startTime = 1000000;
|
||||
vi.setSystemTime(startTime);
|
||||
const timer = new Timer();
|
||||
|
||||
// Checkpoint immediately
|
||||
timer.checkpoint('immediate');
|
||||
timer.checkpoint("immediate");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledWith('» immediate: 0ms');
|
||||
expect(cli.log.debug).toHaveBeenCalledWith("» immediate: 0ms");
|
||||
});
|
||||
|
||||
it('should handle custom checkpoint names', () => {
|
||||
it("should handle custom checkpoint names", () => {
|
||||
const startTime = 1000000;
|
||||
vi.setSystemTime(startTime);
|
||||
const timer = new Timer();
|
||||
|
||||
vi.setSystemTime(startTime + 200);
|
||||
timer.checkpoint('Custom Checkpoint Name');
|
||||
timer.checkpoint("Custom Checkpoint Name");
|
||||
|
||||
expect(cli.log.debug).toHaveBeenCalledWith(
|
||||
'» Custom Checkpoint Name: 200ms'
|
||||
);
|
||||
expect(cli.log.debug).toHaveBeenCalledWith("» Custom Checkpoint Name: 200ms");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+29
-6
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import * as core from "@actions/core";
|
||||
import { log } from "./cli.ts";
|
||||
import { acquireNewToken } from "./github.ts";
|
||||
import { isGitHubActions } from "./globals.ts";
|
||||
|
||||
// re-export for get-installation-token action
|
||||
export { acquireNewToken as acquireInstallationToken };
|
||||
@@ -15,14 +16,36 @@ let githubInstallationToken: string | undefined;
|
||||
*/
|
||||
export async function resolveInstallationToken() {
|
||||
assert(!githubInstallationToken, "GitHub installation token is already set.");
|
||||
const acquiredToken = await acquireNewToken();
|
||||
core.setSecret(acquiredToken);
|
||||
githubInstallationToken = acquiredToken;
|
||||
const originalToken = process.env.GITHUB_TOKEN;
|
||||
if (originalToken) {
|
||||
process.env.ORIGINAL_GITHUB_TOKEN = originalToken;
|
||||
}
|
||||
const externalToken = process.env.GH_TOKEN;
|
||||
const token = externalToken || (await acquireNewToken());
|
||||
process.env.GITHUB_TOKEN = token;
|
||||
githubInstallationToken = token;
|
||||
|
||||
if (isGitHubActions) {
|
||||
// out of caution, we don't call this here outside of the GitHub Actions environment
|
||||
// given this uses `process.stdout.write(cmd.toString() + os.EOL)` under the hood,
|
||||
core.setSecret(token);
|
||||
}
|
||||
|
||||
return {
|
||||
token: acquiredToken,
|
||||
[Symbol.asyncDispose]() {
|
||||
token,
|
||||
originalToken,
|
||||
async [Symbol.asyncDispose]() {
|
||||
githubInstallationToken = undefined;
|
||||
return revokeGitHubInstallationToken(acquiredToken);
|
||||
if (originalToken) {
|
||||
process.env.GITHUB_TOKEN = originalToken;
|
||||
} else {
|
||||
delete process.env.GITHUB_TOKEN;
|
||||
}
|
||||
// GH_TOKEN isn't acquired here, so it's not revoked here either
|
||||
if (externalToken) {
|
||||
return;
|
||||
}
|
||||
return revokeGitHubInstallationToken(token);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { validateCompatibility } from './versioning.ts';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateCompatibility } from "./versioning.ts";
|
||||
|
||||
describe('validateCompatibility', () => {
|
||||
it('should throw if payload version is invalid', () => {
|
||||
expect(() => validateCompatibility('invalid', '1.0.0')).toThrow(/not a valid semantic version/);
|
||||
describe("validateCompatibility", () => {
|
||||
it("should throw if payload version is invalid", () => {
|
||||
expect(() => validateCompatibility("invalid", "1.0.0")).toThrow(/not a valid semantic version/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -17,7 +17,7 @@ describe('validateCompatibility', () => {
|
||||
["1.0.0", "1.1.0"], // action has a new feature (backward compatible)
|
||||
["1.0.1", "1.0.0"], // payload is newer (patch)
|
||||
["1.1.0", "1.0.0"], // payload is newer (feature is backward compatible)
|
||||
])('should accept compatible payload %#', (payloadVersion, actionVersion) => {
|
||||
])("should accept compatible payload %#", (payloadVersion, actionVersion) => {
|
||||
expect(() => validateCompatibility(payloadVersion, actionVersion)).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -26,7 +26,9 @@ describe('validateCompatibility', () => {
|
||||
["0.2.0", "0.1.0"], // payload had breaking changes during active development
|
||||
["2.0.0", "1.0.0"], // payload is majorly newer
|
||||
["1.0.0", "2.0.0"], // action had breaking changes
|
||||
])('should reject incompatible payload %#', (payloadVersion, actionVersion) => {
|
||||
expect(() => validateCompatibility(payloadVersion, actionVersion)).toThrow(/is incompatible with action version/);
|
||||
])("should reject incompatible payload %#", (payloadVersion, actionVersion) => {
|
||||
expect(() => validateCompatibility(payloadVersion, actionVersion)).toThrow(
|
||||
/is incompatible with action version/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+10
-8
@@ -1,4 +1,4 @@
|
||||
import semver from 'semver';
|
||||
import semver from "semver";
|
||||
|
||||
type CompatibilityPolicy =
|
||||
/**
|
||||
@@ -6,13 +6,13 @@ type CompatibilityPolicy =
|
||||
* @example Payload version 1.2.3 => ^1.2.0 range of action versions supported
|
||||
* @example Payload version 0.1.55 => ^0.1.55 range of action versions supported
|
||||
*/
|
||||
| 'same-features'
|
||||
| "same-features"
|
||||
/**
|
||||
* Loose policy: the action must have no breaking changes compared to the payload version
|
||||
* @example Payload version 1.2.3 => ^1.0.0 range of action versions supported
|
||||
* @example Payload version 0.1.55 => ^0.1.0 range of action versions supported
|
||||
*/
|
||||
| 'non-breaking';
|
||||
| "non-breaking";
|
||||
|
||||
const COMPATIBILITY_POLICY: CompatibilityPolicy = "non-breaking";
|
||||
|
||||
@@ -24,19 +24,21 @@ const COMPATIBILITY_POLICY: CompatibilityPolicy = "non-breaking";
|
||||
*/
|
||||
export function validateCompatibility(payloadVersion: string, actionVersion: string): void {
|
||||
const payloadSemVer = semver.parse(payloadVersion);
|
||||
if (!payloadSemVer) throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`);
|
||||
if (!payloadSemVer)
|
||||
throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`);
|
||||
const major = payloadSemVer.major;
|
||||
const minor = payloadSemVer.minor;
|
||||
const patch = payloadSemVer.patch;
|
||||
|
||||
const compatibilityRange = COMPATIBILITY_POLICY === 'same-features'
|
||||
? `^${major}.${minor}.${major === 0 ? patch : 0}`
|
||||
: `^${major}.${major === 0 ? minor : 0}.${major === 0 ? "x" : 0}`; // non-breaking
|
||||
const compatibilityRange =
|
||||
COMPATIBILITY_POLICY === "same-features"
|
||||
? `^${major}.${minor}.${major === 0 ? patch : 0}`
|
||||
: `^${major}.${major === 0 ? minor : 0}.${major === 0 ? "x" : 0}`; // non-breaking
|
||||
|
||||
if (!semver.satisfies(actionVersion, compatibilityRange)) {
|
||||
throw new Error(
|
||||
`Payload version ${payloadVersion} is incompatible with action version ${actionVersion}. ` +
|
||||
`Please update your workflow to use at least ${semver.minVersion(compatibilityRange)} version of the action.`
|
||||
`Please update your workflow to use at least ${semver.minVersion(compatibilityRange)} version of the action.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user