Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | 1x 1x 185x 185x 185x 185x 7x 7x 178x 1x 207x 207x 24x 23x 1x 1x 1x 1x 1x 1x 24x 27x 1x 1x 23x 26x 26x 23x 23x 23x 47x 47x 48x 47x 1x 48x 47x 47x 47x 16x 16x 16x 44x 16x 47x 47x 47x 47x | /**
* Workflow Base
*
* Shared infrastructure for PR and schedule workflows.
*/
import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, relative } from 'node:path';
import { randomUUID } from 'node:crypto';
import type { Octokit } from '@octokit/rest';
import { execFileNonInteractive } from '../../utils/exec.js';
import { isRepoRelativePath, normalizePath } from '../../utils/path.js';
import type { EventContext, SkillReport } from '../../types/index.js';
import { countSeverity } from '../../triggers/matcher.js';
import type { TriggerResult } from '../triggers/executor.js';
import type { ActionInputs } from '../inputs.js';
/**
* Sentinel error thrown by setFailed() so the top-level catch handler
* can distinguish expected failures from unexpected crashes.
*/
export class ActionFailedError extends Error {
constructor(message: string) {
super(message);
this.name = 'ActionFailedError';
}
}
// -----------------------------------------------------------------------------
// GitHub Actions Helpers
// -----------------------------------------------------------------------------
/**
* Set a GitHub Actions output variable.
*/
export function setOutput(name: string, value: string | number): void {
const outputFile = process.env['GITHUB_OUTPUT'];
Eif (outputFile) {
const stringValue = String(value);
// Use heredoc format with random delimiter for multiline values
// Random delimiter prevents injection if value contains the delimiter
if (stringValue.includes('\n')) {
const delimiter = `ghadelim_${randomUUID()}`;
appendFileSync(outputFile, `${name}<<${delimiter}\n${stringValue}\n${delimiter}\n`);
} else {
appendFileSync(outputFile, `${name}=${stringValue}\n`);
}
}
}
/**
* Fail the GitHub Action with an error message.
* Throws ActionFailedError so spans end cleanly before the process exits.
*/
export function setFailed(message: string): never {
throw new ActionFailedError(message);
}
/** Validate Claude runtime auth before invoking the Claude Code SDK. */
export function ensureClaudeAuth(inputs: ActionInputs): void {
if (inputs.anthropicApiKey || inputs.oauthToken) {
return;
}
setFailed(
'Authentication not found. Provide an API key via anthropic-api-key input, ' +
'WARDEN_ANTHROPIC_API_KEY env var, or OAuth token via CLAUDE_CODE_OAUTH_TOKEN env var.'
);
}
/**
* Start a collapsible log group.
*/
export function logGroup(name: string): void {
console.log(`::group::${name}`);
}
/**
* End a collapsible log group.
*/
export function logGroupEnd(): void {
console.log('::endgroup::');
}
// -----------------------------------------------------------------------------
// Claude Code CLI
// -----------------------------------------------------------------------------
/**
* Test whether a path is an executable file.
*/
function isExecutable(path: string): boolean {
try {
execFileNonInteractive('test', ['-x', path]);
return true;
} catch {
return false;
}
}
/**
* Find the Claude Code CLI executable path.
* Required in CI environments where the SDK can't auto-detect the CLI location.
*/
export async function findClaudeCodeExecutable(): Promise<string> {
// Check environment variable first (set by action.yml)
const envPath = process.env['CLAUDE_CODE_PATH'];
if (envPath && isExecutable(envPath)) {
return envPath;
}
// Standard install location from claude.ai/install.sh
const homeLocalBin = `${process.env['HOME']}/.local/bin/claude`;
if (isExecutable(homeLocalBin)) {
return homeLocalBin;
}
// Try which command
try {
const path = execFileNonInteractive('which', ['claude']);
if (path) return path;
} catch {
// which command failed
}
// Other common installation paths as fallback
const commonPaths = ['/usr/local/bin/claude', '/usr/bin/claude'];
for (const p of commonPaths) {
if (isExecutable(p)) return p;
}
setFailed(
'Claude Code CLI not found. Ensure Claude Code is installed via https://claude.ai/install.sh'
);
}
// -----------------------------------------------------------------------------
// Trigger Error Handling
// -----------------------------------------------------------------------------
/**
* Log trigger error summary and fail if all triggers failed.
*/
export function handleTriggerErrors(triggerErrors: string[], totalTriggers: number): void {
if (triggerErrors.length === 0) {
return;
}
logGroup('Trigger Errors Summary');
for (const err of triggerErrors) {
console.error(` - ${err}`);
}
logGroupEnd();
// Fail if ALL triggers failed (no successful analysis was performed)
Eif (triggerErrors.length === totalTriggers && totalTriggers > 0) {
setFailed(`All ${totalTriggers} trigger(s) failed: ${triggerErrors.join('; ')}`);
}
}
/**
* Collect error messages from trigger results.
*/
export function collectTriggerErrors(results: TriggerResult[]): string[] {
return results
.filter((r) => r.error)
.map((r) => {
const errorMessage = r.error instanceof Error ? r.error.message : String(r.error);
return `${r.triggerName}: ${errorMessage}`;
});
}
// -----------------------------------------------------------------------------
// Output Aggregation
// -----------------------------------------------------------------------------
export interface WorkflowOutputs {
findingsCount: number;
highCount: number;
summary: string;
}
/**
* Compute workflow outputs from reports.
*/
export function computeWorkflowOutputs(reports: SkillReport[]): WorkflowOutputs {
return {
findingsCount: reports.reduce((sum, r) => sum + r.findings.length, 0),
highCount: countSeverity(reports, 'high'),
summary: reports.map((r) => r.summary).join('\n'),
};
}
/**
* Set workflow output variables.
*/
export function setWorkflowOutputs(outputs: WorkflowOutputs): void {
setOutput('findings-count', outputs.findingsCount);
setOutput('high-count', outputs.highCount);
setOutput('summary', outputs.summary);
}
// -----------------------------------------------------------------------------
// GitHub API Helpers
// -----------------------------------------------------------------------------
/**
* Get the authenticated bot's login name.
*
* Tries three strategies in order:
* 1. GraphQL `viewer` query (works for both installation tokens and PATs)
* 2. `octokit.apps.getAuthenticated()` → `${slug}[bot]` (GitHub App JWT fallback)
* 3. `octokit.users.getAuthenticated()` (PAT fallback)
*/
export async function getAuthenticatedBotLogin(octokit: Octokit): Promise<string | null> {
// Strategy 1: GraphQL viewer (works for installation tokens and PATs)
try {
const result: { viewer: { login: string } } = await octokit.graphql('query { viewer { login } }');
if (result.viewer?.login) {
return result.viewer.login;
}
} catch {
// GraphQL may not be available or may fail for certain token types
}
// Strategy 2: GitHub App JWT endpoint
try {
const { data: app } = await octokit.apps.getAuthenticated();
if (app?.slug) {
return `${app.slug}[bot]`;
}
} catch {
// Not a GitHub App token
}
// Strategy 3: PAT user endpoint
try {
const { data: user } = await octokit.users.getAuthenticated();
return user.login;
} catch {
// Token doesn't have user scope
}
return null;
}
/**
* Get the default branch for a repository from the GitHub API.
*/
export async function getDefaultBranchFromAPI(
octokit: Octokit,
owner: string,
repo: string
): Promise<string> {
const { data } = await octokit.repos.get({ owner, repo });
return data.default_branch;
}
// -----------------------------------------------------------------------------
// Findings Output File
// -----------------------------------------------------------------------------
function getFindingsOutputValue(filePath: string, repoPath: string): string {
const relativePath = normalizePath(relative(repoPath, filePath));
return isRepoRelativePath(relativePath) ? relativePath : filePath;
}
/**
* Get the path for the findings output file.
*
* Uses the GitHub Actions workspace when available so action consumers can pass
* the output to upload actions that expect repo-relative paths. Falls back to
* RUNNER_TEMP for local callers and tests.
*/
export function getFindingsOutputPath(repoPath?: string): string {
if (repoPath && process.env['GITHUB_WORKSPACE']) {
return join(repoPath, 'warden-findings.json');
}
const tmpDir = process.env['RUNNER_TEMP'] ?? tmpdir();
return join(tmpDir, 'warden-findings.json');
}
/**
* Write structured findings data to a JSON file for external export (GCS, S3, etc.).
*
* Sets `findings-file` to a repo-relative path when possible so downstream
* steps can reference the path without tripping ignore processors on absolute
* runner temp paths.
*/
export function writeFindingsOutput(
reports: SkillReport[],
context: EventContext
): string {
const filePath = getFindingsOutputPath(context.repoPath);
const allFindings = reports.flatMap((r) => r.findings);
const output = {
version: '1',
timestamp: new Date().toISOString(),
repository: {
owner: context.repository.owner,
name: context.repository.name,
fullName: context.repository.fullName,
},
event: context.eventType,
...(context.pullRequest && {
pullRequest: {
number: context.pullRequest.number,
author: context.pullRequest.author,
title: context.pullRequest.title,
baseBranch: context.pullRequest.baseBranch,
headBranch: context.pullRequest.headBranch,
headSha: context.pullRequest.headSha,
},
}),
runId: process.env['GITHUB_RUN_ID'] ?? '',
summary: {
totalFindings: allFindings.length,
findingsBySeverity: {
high: allFindings.filter((f) => f.severity === 'high').length,
medium: allFindings.filter((f) => f.severity === 'medium').length,
low: allFindings.filter((f) => f.severity === 'low').length,
},
totalSkills: reports.length,
},
skills: reports.map((r) => ({
name: r.skill,
summary: r.summary,
model: r.model,
durationMs: r.durationMs,
usage: r.usage,
findings: r.findings.map((f) => ({
id: f.id,
severity: f.severity,
confidence: f.confidence,
title: f.title,
description: f.description,
location: f.location,
additionalLocations: f.additionalLocations,
suggestedFix: f.suggestedFix,
})),
})),
};
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, JSON.stringify(output, null, 2));
setOutput('findings-file', getFindingsOutputValue(filePath, context.repoPath));
return filePath;
}
|