merge: bring ghbot-Nodeloc v2.0 into upstream
- Adopt nodeloc v2.0 reliability/observability work (MergeGuard, failureMessages, MetricsCollector, staleness, QueueStore, shared error helpers) and tests - Keep upstream bilingual README convention (README.md + README-zh.md); port nodeloc's first-principles intro and v2.0 module notes into both - Resolve doc conflicts in favor of upstream formatting where origin was formatting-only; drop the 计划与指南/ directory per maintainer request
This commit is contained in:
commit
77eca8a915
44 files changed
+7021
-1073
No files matched your search
@@ -0,0 +1,255 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
acquireConflictLock,
|
||||
canAutoResolveConflicts,
|
||||
describeConflictResolutionFailure
|
||||
} from "../src/review/conflictResolver.js";
|
||||
|
||||
const eligible = {
|
||||
enabled: true,
|
||||
reviewPassed: true,
|
||||
mergeable: false,
|
||||
mergeableState: "dirty",
|
||||
baseRepository: "forumlify/public",
|
||||
headRepository: "forumlify/public",
|
||||
maintainerCanModify: false,
|
||||
expectedHeadSha: "abc",
|
||||
currentHeadSha: "abc"
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// canAutoResolveConflicts — remaining condition combinations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("canAutoResolveConflicts: enabled=false returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, enabled: false }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: reviewPassed=false returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, reviewPassed: false }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: mergeable=null returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeable: null }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: mergeable=true (non-dirty) returns false", () => {
|
||||
assert.equal(
|
||||
canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: mergeableState is not 'dirty' returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "clean" }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "blocked" }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "unknown" }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "behind" }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: headRepository=null returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, headRepository: null }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: fork without maintainerCanModify returns false", () => {
|
||||
assert.equal(
|
||||
canAutoResolveConflicts({
|
||||
...eligible,
|
||||
headRepository: "contributor/forumlify",
|
||||
maintainerCanModify: false
|
||||
}),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: fork with maintainerCanModify returns true", () => {
|
||||
assert.equal(
|
||||
canAutoResolveConflicts({
|
||||
...eligible,
|
||||
headRepository: "contributor/forumlify",
|
||||
maintainerCanModify: true
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: headSha mismatch returns false", () => {
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, currentHeadSha: "different-sha" }), false);
|
||||
});
|
||||
|
||||
test("canAutoResolveConflicts: all conditions met returns true", () => {
|
||||
assert.equal(canAutoResolveConflicts(eligible), true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// acquireConflictLock — lock acquisition, duplicate rejection, release
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("acquireConflictLock: acquires a lock", async () => {
|
||||
const release = await acquireConflictLock("test/lock-single");
|
||||
assert.equal(typeof release, "function");
|
||||
release();
|
||||
});
|
||||
|
||||
test("acquireConflictLock: throws for duplicate lock", async () => {
|
||||
const release = await acquireConflictLock("test/lock-duplicate");
|
||||
await assert.rejects(
|
||||
() => acquireConflictLock("test/lock-duplicate"),
|
||||
/already active for this pull request/
|
||||
);
|
||||
release();
|
||||
});
|
||||
|
||||
test("acquireConflictLock: release function works and allows re-acquisition", async () => {
|
||||
const release = await acquireConflictLock("test/lock-reacquire");
|
||||
release();
|
||||
const releaseAgain = await acquireConflictLock("test/lock-reacquire");
|
||||
releaseAgain();
|
||||
});
|
||||
|
||||
test("acquireConflictLock: concurrent keys do not interfere", async () => {
|
||||
const releaseA = await acquireConflictLock("test/lock-concurrent-a");
|
||||
const releaseB = await acquireConflictLock("test/lock-concurrent-b");
|
||||
releaseA();
|
||||
releaseB();
|
||||
});
|
||||
|
||||
test("acquireConflictLock: double release does not throw", async () => {
|
||||
const release = await acquireConflictLock("test/lock-double-release");
|
||||
release();
|
||||
release();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// describeConflictResolutionFailure — remaining error types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("describeConflictResolutionFailure: shallow git history", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("fatal: refusing to merge unrelated histories (shallow)")
|
||||
);
|
||||
assert.match(msg, /did not contain enough Git history/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: authentication failed", () => {
|
||||
const msg = describeConflictResolutionFailure(new Error("remote: authentication failed"));
|
||||
assert.match(msg, /Allow edits from maintainers/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: write access to repository not granted", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("remote: Write access to repository not granted: contributor/forumlify")
|
||||
);
|
||||
assert.match(msg, /Allow edits from maintainers/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: permission denied", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("remote: Permission denied to fork repository")
|
||||
);
|
||||
assert.match(msg, /Allow edits from maintainers/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: status code 403", () => {
|
||||
const msg = describeConflictResolutionFailure(new Error("HTTP status code: 403 forbidden"));
|
||||
assert.match(msg, /Allow edits from maintainers/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: non-fast-forward push", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("! [rejected] HEAD -> main (non-fast-forward)")
|
||||
);
|
||||
assert.match(msg, /Run \/conflict again/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: fetch first (stale remote)", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("! [rejected] (stale info) - fetch first")
|
||||
);
|
||||
assert.match(msg, /Run \/conflict again/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: final goose confirmation did not return valid JSON", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("Final goose confirmation did not return the required JSON object.")
|
||||
);
|
||||
assert.match(msg, /invalid result/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: resolved staged diff exceeds MAX_PATCH_CHARS", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("Resolved staged diff contains 200000 characters, exceeding MAX_PATCH_CHARS=120000.")
|
||||
);
|
||||
assert.match(msg, /patch-size limit/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: conflict validation infrastructure failed", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("Conflict validation infrastructure failed: docker daemon not available")
|
||||
);
|
||||
assert.match(msg, /validation environment failed/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: isolated conflict validation timed out", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("isolated conflict validation timed out.")
|
||||
);
|
||||
assert.match(msg, /7-minute limit/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: generic error falls through to safe default", () => {
|
||||
const msg = describeConflictResolutionFailure(new Error("unexpected runtime error"));
|
||||
assert.match(msg, /could not safely complete/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: generic error with actor name", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("integration test 1 failed"),
|
||||
"custom-bot"
|
||||
);
|
||||
assert.match(msg, /^custom-bot could not safely complete/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: empty ident name", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("empty ident name (no email address) not allowed")
|
||||
);
|
||||
assert.match(msg, /no bot committer identity/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: non-Error input is handled", () => {
|
||||
const msg = describeConflictResolutionFailure("something went wrong");
|
||||
assert.match(msg, /could not safely complete/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: null input is handled", () => {
|
||||
const msg = describeConflictResolutionFailure(null);
|
||||
assert.match(msg, /could not safely complete/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
|
||||
test("describeConflictResolutionFailure: validation command failure with actor name", () => {
|
||||
const msg = describeConflictResolutionFailure(
|
||||
new Error("Validation command failed after goose correction: exit 1"),
|
||||
"test-bot"
|
||||
);
|
||||
assert.match(msg, /^test-bot produced/);
|
||||
assert.match(msg, /validation or final safety confirmation rejected/);
|
||||
assert.match(msg, /no commit was pushed/i);
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { categorizeFailure, formatFailureMessage } from "../src/ai/failureMessages.js";
|
||||
|
||||
/* ---------- categorizeFailure ---------- */
|
||||
|
||||
test("categorizeFailure: timeout by error code", () => {
|
||||
const err = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" });
|
||||
assert.equal(categorizeFailure(err), "timeout");
|
||||
});
|
||||
|
||||
test("categorizeFailure: timeout by message", () => {
|
||||
const err = new Error("the operation timed out after 30s");
|
||||
assert.equal(categorizeFailure(err), "timeout");
|
||||
});
|
||||
|
||||
test("categorizeFailure: auth by status code 401", () => {
|
||||
const err = Object.assign(new Error("unauthorized"), { status: 401 });
|
||||
assert.equal(categorizeFailure(err), "auth");
|
||||
});
|
||||
|
||||
test("categorizeFailure: auth by status code 403", () => {
|
||||
const err = Object.assign(new Error("forbidden"), { status: 403 });
|
||||
assert.equal(categorizeFailure(err), "auth");
|
||||
});
|
||||
|
||||
test("categorizeFailure: auth by message", () => {
|
||||
const err = new Error("API key is invalid");
|
||||
assert.equal(categorizeFailure(err), "auth");
|
||||
});
|
||||
|
||||
test("categorizeFailure: rate_limit by status code 429", () => {
|
||||
const err = Object.assign(new Error("too many"), { status: 429 });
|
||||
assert.equal(categorizeFailure(err), "rate_limit");
|
||||
});
|
||||
|
||||
test("categorizeFailure: rate_limit by message", () => {
|
||||
const err = new Error("rate limit exceeded, retry later");
|
||||
assert.equal(categorizeFailure(err), "rate_limit");
|
||||
});
|
||||
|
||||
test("categorizeFailure: network by error code ECONNRESET", () => {
|
||||
const err = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
|
||||
assert.equal(categorizeFailure(err), "network");
|
||||
});
|
||||
|
||||
test("categorizeFailure: network by error code ECONNREFUSED", () => {
|
||||
const err = Object.assign(new Error("refused"), { code: "ECONNREFUSED" });
|
||||
assert.equal(categorizeFailure(err), "network");
|
||||
});
|
||||
|
||||
test("categorizeFailure: network by error code EAI_AGAIN", () => {
|
||||
const err = Object.assign(new Error("again"), { code: "EAI_AGAIN" });
|
||||
assert.equal(categorizeFailure(err), "network");
|
||||
});
|
||||
|
||||
test("categorizeFailure: network by message", () => {
|
||||
const err = new Error("network error: unable to reach host");
|
||||
assert.equal(categorizeFailure(err), "network");
|
||||
});
|
||||
|
||||
test("categorizeFailure: model by status 502", () => {
|
||||
const err = Object.assign(new Error("upstream error"), { status: 502 });
|
||||
assert.equal(categorizeFailure(err), "model");
|
||||
});
|
||||
|
||||
test("categorizeFailure: model by message", () => {
|
||||
const err = new Error("model completion failed: context length exceeded");
|
||||
assert.equal(categorizeFailure(err), "model");
|
||||
});
|
||||
|
||||
test("categorizeFailure: validation by status 422", () => {
|
||||
const err = Object.assign(new Error("invalid"), { status: 422 });
|
||||
assert.equal(categorizeFailure(err), "validation");
|
||||
});
|
||||
|
||||
test("categorizeFailure: validation by message", () => {
|
||||
const err = new Error("validation error: invalid schema");
|
||||
assert.equal(categorizeFailure(err), "validation");
|
||||
});
|
||||
|
||||
test("categorizeFailure: null input returns unknown", () => {
|
||||
assert.equal(categorizeFailure(null), "unknown");
|
||||
});
|
||||
|
||||
test("categorizeFailure: string input returns unknown", () => {
|
||||
assert.equal(categorizeFailure("some error"), "unknown");
|
||||
});
|
||||
|
||||
test("categorizeFailure: plain error with no recognizable pattern returns unknown", () => {
|
||||
const err = new Error("something unexpected happened");
|
||||
assert.equal(categorizeFailure(err), "unknown");
|
||||
});
|
||||
|
||||
/* ---------- formatFailureMessage ---------- */
|
||||
|
||||
test("formatFailureMessage: timeout includes action and attempts", () => {
|
||||
const msg = formatFailureMessage("timeout", { action: "runReview", attempts: 3 });
|
||||
assert.ok(msg.includes("runReview"));
|
||||
assert.ok(msg.includes("3"));
|
||||
assert.ok(msg.includes("timed out"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: auth includes action and attempts", () => {
|
||||
const msg = formatFailureMessage("auth", { action: "createComment", attempts: 2 });
|
||||
assert.ok(msg.includes("createComment"));
|
||||
assert.ok(msg.includes("2"));
|
||||
assert.ok(msg.includes("authentication error"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: rate_limit mentions backing off", () => {
|
||||
const msg = formatFailureMessage("rate_limit", { action: "listReviews", attempts: 5 });
|
||||
assert.ok(msg.includes("rate-limited"));
|
||||
assert.ok(msg.includes("backing off"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: network mentions service unreachable", () => {
|
||||
const msg = formatFailureMessage("network", { action: "fetchData", attempts: 1 });
|
||||
assert.ok(msg.includes("network error"));
|
||||
assert.ok(msg.includes("unreachable"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: model mentions model error", () => {
|
||||
const msg = formatFailureMessage("model", { action: "runReview", attempts: 3 });
|
||||
assert.ok(msg.includes("model error"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: validation mentions validation check", () => {
|
||||
const msg = formatFailureMessage("validation", { action: "parseResponse", attempts: 2 });
|
||||
assert.ok(msg.includes("validation check"));
|
||||
});
|
||||
|
||||
test("formatFailureMessage: unknown mentions unknown error", () => {
|
||||
const msg = formatFailureMessage("unknown", { action: "someAction", attempts: 4 });
|
||||
assert.ok(msg.includes("unknown error"));
|
||||
assert.ok(msg.includes("Check the logs") || msg.includes("check the logs"));
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { GooseReviewer } from "../src/review/gooseReviewer.js";
|
||||
import type { PullRequestFile, ReviewMode } from "../src/types.js";
|
||||
import type { PreviousReview } from "../src/review/cache.js";
|
||||
|
||||
const validReviewDecision = {
|
||||
review: [],
|
||||
change: [],
|
||||
comment: "Looks good.",
|
||||
result: {
|
||||
canMerge: true,
|
||||
summary: "Safe to merge.",
|
||||
shouldClosePullRequest: false,
|
||||
closeReason: ""
|
||||
}
|
||||
};
|
||||
|
||||
const mockFiles: PullRequestFile[] = [
|
||||
{
|
||||
filename: "src/index.ts",
|
||||
patch: "+export const foo = 1;",
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 0
|
||||
}
|
||||
];
|
||||
|
||||
const baseInput = {
|
||||
title: "Add foo constant",
|
||||
body: "Adds a simple constant.",
|
||||
files: mockFiles,
|
||||
mode: "normal" as ReviewMode
|
||||
};
|
||||
|
||||
// Helper: create a GooseReviewer that records the prompt and returns a controlled value
|
||||
function createReviewer(
|
||||
response: unknown = validReviewDecision,
|
||||
onPrompt?: (prompt: string) => void
|
||||
): GooseReviewer {
|
||||
const promptRunner = async (prompt: string) => {
|
||||
onPrompt?.(prompt);
|
||||
const value = response;
|
||||
if (value instanceof Error) {
|
||||
throw value;
|
||||
}
|
||||
return typeof value === "function" ? value(prompt) : JSON.stringify(value);
|
||||
};
|
||||
return new GooseReviewer(promptRunner);
|
||||
}
|
||||
|
||||
// 1. review() with valid input returns ReviewDecision
|
||||
test("review() with valid input returns ReviewDecision", async () => {
|
||||
const reviewer = createReviewer();
|
||||
const decision = await reviewer.review(baseInput);
|
||||
|
||||
assert.equal(decision.result.canMerge, true);
|
||||
assert.equal(decision.comment, "Looks good.");
|
||||
assert.deepEqual(decision.review, []);
|
||||
assert.deepEqual(decision.change, []);
|
||||
assert.equal(decision.result.summary, "Safe to merge.");
|
||||
assert.equal(decision.result.shouldClosePullRequest, false);
|
||||
assert.equal(decision.result.closeReason, "");
|
||||
});
|
||||
|
||||
// 2. review() with previousReview context includes it in the prompt
|
||||
test("review() with previousReview context includes it in the prompt", async () => {
|
||||
let capturedPrompt = "";
|
||||
const previousReview: PreviousReview = {
|
||||
headSha: "a".repeat(40),
|
||||
reviewedAt: "2026-08-13T00:00:00.000Z",
|
||||
decision: validReviewDecision
|
||||
};
|
||||
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review({ ...baseInput, previousReview });
|
||||
|
||||
assert.ok(capturedPrompt.includes("Previous review context"));
|
||||
assert.ok(capturedPrompt.includes(previousReview.headSha));
|
||||
assert.ok(capturedPrompt.includes("Re-evaluate every previous finding"));
|
||||
});
|
||||
|
||||
// 3. review() with repositoryKnowledge includes it in the prompt
|
||||
test("review() with repositoryKnowledge includes it in the prompt", async () => {
|
||||
let capturedPrompt = "";
|
||||
const knowledge = "This repository uses React 18 and follows atomic design principles.";
|
||||
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review({ ...baseInput, repositoryKnowledge: knowledge });
|
||||
|
||||
assert.ok(capturedPrompt.includes("repository-scoped private object storage"));
|
||||
assert.ok(capturedPrompt.includes(knowledge));
|
||||
assert.ok(capturedPrompt.includes("Trusted repository knowledge"));
|
||||
});
|
||||
|
||||
// 4. review() with strict mode uses strict prompt
|
||||
test("review() with strict mode captures the strict review instructions", async () => {
|
||||
let capturedPrompt = "";
|
||||
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review({ ...baseInput, mode: "strict" });
|
||||
|
||||
assert.ok(capturedPrompt.includes("strict review explicitly requested"));
|
||||
assert.ok(capturedPrompt.includes("This is a strict review"));
|
||||
});
|
||||
|
||||
// 5. buildPrompt() output contains PR title and files
|
||||
test("review() prompt contains PR title and file metadata", async () => {
|
||||
let capturedPrompt = "";
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review(baseInput);
|
||||
|
||||
assert.ok(capturedPrompt.includes("Add foo constant"));
|
||||
assert.ok(capturedPrompt.includes("src/index.ts"));
|
||||
assert.ok(capturedPrompt.includes("+export const foo = 1;"));
|
||||
assert.ok(capturedPrompt.includes("modified"));
|
||||
assert.ok(capturedPrompt.includes("Pull request payload"));
|
||||
});
|
||||
|
||||
// 6. buildPrompt() contains output contract instructions
|
||||
test("review() prompt contains output contract instructions", async () => {
|
||||
let capturedPrompt = "";
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review(baseInput);
|
||||
|
||||
assert.ok(capturedPrompt.includes("four top-level keys"));
|
||||
assert.ok(capturedPrompt.includes("review, change, comment, result"));
|
||||
assert.ok(capturedPrompt.includes("path, line, title, body"));
|
||||
assert.ok(capturedPrompt.includes("canMerge, summary, shouldClosePullRequest, closeReason"));
|
||||
assert.ok(capturedPrompt.includes("only one valid JSON object"));
|
||||
});
|
||||
|
||||
// 7. buildPrompt() with previousReview contains previous review JSON
|
||||
test("review() prompt with previousReview contains serialized previous review", async () => {
|
||||
let capturedPrompt = "";
|
||||
const previousReview: PreviousReview = {
|
||||
headSha: "abc123def456".repeat(4),
|
||||
reviewedAt: "2026-08-13T00:00:00.000Z",
|
||||
decision: validReviewDecision
|
||||
};
|
||||
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review({ ...baseInput, previousReview });
|
||||
|
||||
assert.ok(capturedPrompt.includes(previousReview.headSha));
|
||||
assert.ok(capturedPrompt.includes(previousReview.reviewedAt));
|
||||
assert.ok(capturedPrompt.includes("Previous review context"));
|
||||
});
|
||||
|
||||
// 8. System prompt for normal mode is not strict
|
||||
test("normal mode prompt does not contain strict review text", async () => {
|
||||
let capturedPrompt = "";
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review(baseInput);
|
||||
|
||||
assert.ok(capturedPrompt.includes("normal review"));
|
||||
assert.ok(capturedPrompt.includes("Do not nitpick or pursue minor details"));
|
||||
assert.ok(!capturedPrompt.includes("strict review"));
|
||||
});
|
||||
|
||||
// 9. System prompt for strict mode includes "strict review"
|
||||
test("strict mode prompt includes strict review admonition", async () => {
|
||||
let capturedPrompt = "";
|
||||
const reviewer = createReviewer(validReviewDecision, (p) => {
|
||||
capturedPrompt = p;
|
||||
});
|
||||
await reviewer.review({ ...baseInput, mode: "strict" });
|
||||
|
||||
assert.ok(
|
||||
capturedPrompt.includes("strict review explicitly requested by the repository administrators")
|
||||
);
|
||||
assert.ok(!capturedPrompt.includes("Do not nitpick or pursue minor details"));
|
||||
});
|
||||
|
||||
// 10. Schema validation: invalid JSON from goose throws
|
||||
test("invalid JSON from goose throws a non-retryable error", async () => {
|
||||
const reviewer = createReviewer(() => "not valid json {{{");
|
||||
await assert.rejects(
|
||||
() => reviewer.review(baseInput),
|
||||
/Unexpected token|not valid JSON|JSON\.parse|SyntaxError/
|
||||
);
|
||||
});
|
||||
|
||||
// 11. Schema validation: missing required fields throws
|
||||
test("missing required fields in goose output throws a Zod validation error", async () => {
|
||||
const reviewer = createReviewer({ incomplete: true });
|
||||
await assert.rejects(() => reviewer.review(baseInput), /review|Required|change|comment|result/);
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { MergeGuard } from "../src/review/merge-guard.js";
|
||||
|
||||
test("markAttempt followed by isAlreadyAttempted returns true", () => {
|
||||
const guard = new MergeGuard();
|
||||
guard.markAttempt("owner1", "repo1", 42);
|
||||
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 42), true);
|
||||
});
|
||||
|
||||
test("isAlreadyAttempted returns false for a never-attempted PR", () => {
|
||||
const guard = new MergeGuard();
|
||||
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 99), false);
|
||||
});
|
||||
|
||||
test("getRecentAttempts returns list of attempted PR keys", () => {
|
||||
const guard = new MergeGuard();
|
||||
guard.markAttempt("a", "repo-a", 1);
|
||||
guard.markAttempt("b", "repo-b", 2);
|
||||
const attempts = guard.getRecentAttempts();
|
||||
assert.equal(attempts.length, 2);
|
||||
assert.ok(attempts.includes("a/repo-a#1"));
|
||||
assert.ok(attempts.includes("b/repo-b#2"));
|
||||
});
|
||||
|
||||
test("multiple attempts on the same PR increment count", () => {
|
||||
const guard = new MergeGuard();
|
||||
guard.markAttempt("same", "pr", 1);
|
||||
guard.markAttempt("same", "pr", 1);
|
||||
guard.markAttempt("same", "pr", 1);
|
||||
assert.equal(guard.getAttemptedCount(), 3);
|
||||
assert.equal(guard.isAlreadyAttempted("same", "pr", 1), true);
|
||||
});
|
||||
|
||||
test("different PRs are tracked independently", () => {
|
||||
const guard = new MergeGuard();
|
||||
guard.markAttempt("owner1", "repo1", 10);
|
||||
guard.markAttempt("owner2", "repo2", 20);
|
||||
|
||||
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 10), true);
|
||||
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 11), false);
|
||||
assert.equal(guard.isAlreadyAttempted("owner2", "repo2", 20), true);
|
||||
assert.equal(guard.isAlreadyAttempted("owner2", "repo2", 21), false);
|
||||
|
||||
assert.equal(guard.getAttemptedCount(), 2);
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { MetricsCollector, metrics } from "../src/metrics/collector.js";
|
||||
|
||||
test("recordReviewDuration increments count", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordReviewDuration(150);
|
||||
mc.recordReviewDuration(250);
|
||||
const s = mc.snapshot();
|
||||
assert.equal(s.reviewCount, 2);
|
||||
assert.equal(s.reviewDurationTotalMs, 400);
|
||||
assert.equal(s.reviewDurationAvgMs, 200);
|
||||
});
|
||||
|
||||
test("recordReviewResult tracks outcome counts", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordReviewResult("block");
|
||||
mc.recordReviewResult("malicious");
|
||||
const s = mc.snapshot();
|
||||
const outcomes = s.reviewOutcomes as Record<string, number>;
|
||||
assert.equal(outcomes.pass, 2);
|
||||
assert.equal(outcomes.block, 1);
|
||||
assert.equal(outcomes.malicious, 1);
|
||||
});
|
||||
|
||||
test("recordGooseCall tracks success/failure counts", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordGooseCall(100, true);
|
||||
mc.recordGooseCall(200, true);
|
||||
mc.recordGooseCall(300, false);
|
||||
const s = mc.snapshot();
|
||||
assert.equal(s.gooseCallCount, 3);
|
||||
assert.equal(s.gooseCallDurationTotalMs, 600);
|
||||
assert.equal(s.gooseCallAvgMs, 200);
|
||||
assert.equal(s.gooseSuccessCount, 2);
|
||||
assert.equal(s.gooseFailureCount, 1);
|
||||
});
|
||||
|
||||
test("recordConflictResolution tracks status counts", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordConflictResolution("resolved");
|
||||
mc.recordConflictResolution("resolved");
|
||||
mc.recordConflictResolution("failed");
|
||||
mc.recordConflictResolution("skipped");
|
||||
const s = mc.snapshot();
|
||||
const conflicts = s.conflictStatuses as Record<string, number>;
|
||||
assert.equal(conflicts.resolved, 2);
|
||||
assert.equal(conflicts.failed, 1);
|
||||
assert.equal(conflicts.skipped, 1);
|
||||
});
|
||||
|
||||
test("recordMergeAttempt tracks merge counts", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordMergeAttempt("merged");
|
||||
mc.recordMergeAttempt("already_merged");
|
||||
mc.recordMergeAttempt("failed");
|
||||
const s = mc.snapshot();
|
||||
const merges = s.mergeStatuses as Record<string, number>;
|
||||
assert.equal(merges.merged, 1);
|
||||
assert.equal(merges.already_merged, 1);
|
||||
assert.equal(merges.failed, 1);
|
||||
});
|
||||
|
||||
test("recordCacheHit tracks cache hits", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordCacheHit("review");
|
||||
mc.recordCacheHit("review");
|
||||
mc.recordCacheHit("knowledge");
|
||||
const s = mc.snapshot();
|
||||
const cache = s.cacheHits as Record<string, number>;
|
||||
assert.equal(cache.review, 2);
|
||||
assert.equal(cache.knowledge, 1);
|
||||
});
|
||||
|
||||
test("snapshot returns all metrics", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordReviewDuration(500);
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordGooseCall(1000, true);
|
||||
mc.recordConflictResolution("resolved");
|
||||
mc.recordMergeAttempt("merged");
|
||||
mc.recordCacheHit("review");
|
||||
|
||||
const s = mc.snapshot();
|
||||
assert.ok(typeof s.uptimeSeconds === "number");
|
||||
assert.equal(s.reviewCount, 1);
|
||||
assert.equal(s.reviewDurationTotalMs, 500);
|
||||
assert.equal(s.reviewDurationAvgMs, 500);
|
||||
assert.deepEqual(s.reviewOutcomes, { pass: 1 });
|
||||
assert.equal(s.gooseCallCount, 1);
|
||||
assert.equal(s.gooseCallDurationTotalMs, 1000);
|
||||
assert.equal(s.gooseCallAvgMs, 1000);
|
||||
assert.equal(s.gooseSuccessCount, 1);
|
||||
assert.equal(s.gooseFailureCount, 0);
|
||||
assert.deepEqual(s.conflictStatuses, { resolved: 1 });
|
||||
assert.deepEqual(s.mergeStatuses, { merged: 1 });
|
||||
assert.deepEqual(s.cacheHits, { review: 1 });
|
||||
});
|
||||
|
||||
test("formatMarkdown generates table with headers", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordReviewDuration(300);
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordGooseCall(500, true);
|
||||
mc.recordConflictResolution("resolved");
|
||||
mc.recordMergeAttempt("merged");
|
||||
mc.recordCacheHit("review");
|
||||
|
||||
const md = mc.formatMarkdown();
|
||||
assert.match(md, /## Metrics Summary/);
|
||||
assert.match(md, /\| Metric \| Value \|/);
|
||||
assert.match(md, /\| Reviews \| 1 \|/);
|
||||
assert.match(md, /\| Review Outcome: pass \| 1 \|/);
|
||||
assert.match(md, /\| Goose Calls \| 1 \|/);
|
||||
assert.match(md, /\| Goose Success \| 1 \|/);
|
||||
assert.match(md, /\| Conflict: resolved \| 1 \|/);
|
||||
assert.match(md, /\| Merge: merged \| 1 \|/);
|
||||
assert.match(md, /\| Cache Hit: review \| 1 \|/);
|
||||
});
|
||||
|
||||
test("reset clears all metrics", () => {
|
||||
const mc = new MetricsCollector();
|
||||
mc.recordReviewDuration(100);
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordGooseCall(200, false);
|
||||
mc.recordConflictResolution("failed");
|
||||
mc.recordMergeAttempt("failed");
|
||||
mc.recordCacheHit("knowledge");
|
||||
mc.reset();
|
||||
|
||||
const s = mc.snapshot();
|
||||
assert.equal(s.reviewCount, 0);
|
||||
assert.equal(s.reviewDurationTotalMs, 0);
|
||||
assert.equal(s.reviewDurationAvgMs, 0);
|
||||
assert.deepEqual(s.reviewOutcomes, {});
|
||||
assert.equal(s.gooseCallCount, 0);
|
||||
assert.equal(s.gooseCallDurationTotalMs, 0);
|
||||
assert.equal(s.gooseCallAvgMs, 0);
|
||||
assert.equal(s.gooseSuccessCount, 0);
|
||||
assert.equal(s.gooseFailureCount, 0);
|
||||
assert.deepEqual(s.conflictStatuses, {});
|
||||
assert.deepEqual(s.mergeStatuses, {});
|
||||
assert.deepEqual(s.cacheHits, {});
|
||||
});
|
||||
|
||||
test("Multiple calls accumulate correctly", () => {
|
||||
const mc = new MetricsCollector();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
mc.recordReviewDuration(100);
|
||||
mc.recordReviewResult("pass");
|
||||
mc.recordGooseCall(200, i % 3 !== 0);
|
||||
mc.recordConflictResolution(i < 5 ? "resolved" : "failed");
|
||||
mc.recordMergeAttempt(i < 7 ? "merged" : "failed");
|
||||
mc.recordCacheHit(i < 6 ? "review" : "knowledge");
|
||||
}
|
||||
|
||||
const s = mc.snapshot();
|
||||
assert.equal(s.reviewCount, 10);
|
||||
assert.equal(s.reviewDurationTotalMs, 1000);
|
||||
assert.equal(s.reviewDurationAvgMs, 100);
|
||||
assert.equal(s.gooseCallCount, 10);
|
||||
assert.equal(s.gooseCallDurationTotalMs, 2000);
|
||||
assert.equal(s.gooseCallAvgMs, 200);
|
||||
// 10 calls; i%3===0 fails (indices 0,3,6,9 = 4), rest succeed (indices 1,2,4,5,7,8 = 6)
|
||||
assert.equal(s.gooseSuccessCount, 6);
|
||||
assert.equal(s.gooseFailureCount, 4);
|
||||
// i < 5 resolved, rest failed
|
||||
const conflicts = s.conflictStatuses as Record<string, number>;
|
||||
assert.equal(conflicts.resolved, 5);
|
||||
assert.equal(conflicts.failed, 5);
|
||||
// i < 7 merged, rest failed
|
||||
const merges = s.mergeStatuses as Record<string, number>;
|
||||
assert.equal(merges.merged, 7);
|
||||
assert.equal(merges.failed, 3);
|
||||
// i < 6 review, rest knowledge
|
||||
const cache = s.cacheHits as Record<string, number>;
|
||||
assert.equal(cache.review, 6);
|
||||
assert.equal(cache.knowledge, 4);
|
||||
});
|
||||
|
||||
test("singleton is exported", () => {
|
||||
assert.ok(metrics instanceof MetricsCollector);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { QueueStore } from "../src/webhook/queueStore.js";
|
||||
|
||||
test("QueueStore writes and restores tasks", async () => {
|
||||
const base = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-queue-test-"));
|
||||
try {
|
||||
const store = new QueueStore(base);
|
||||
const task = {
|
||||
deliveryId: "abc123",
|
||||
eventName: "issue_comment",
|
||||
payload: { action: "created" },
|
||||
enqueuedAt: Date.now()
|
||||
};
|
||||
await store.write(task);
|
||||
assert.equal(await store.exists("abc123"), true);
|
||||
const restored = await store.restore();
|
||||
assert.equal(restored.length, 1);
|
||||
assert.equal(restored[0]!.deliveryId, "abc123");
|
||||
assert.equal(restored[0]!.eventName, "issue_comment");
|
||||
assert.deepEqual(restored[0]!.payload, { action: "created" });
|
||||
} finally {
|
||||
await fs.rm(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("QueueStore removes tasks by delivery id", async () => {
|
||||
const base = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-queue-rm-"));
|
||||
try {
|
||||
const store = new QueueStore(base);
|
||||
await store.write({
|
||||
deliveryId: "x1",
|
||||
eventName: "pull_request",
|
||||
payload: { action: "opened" },
|
||||
enqueuedAt: Date.now()
|
||||
});
|
||||
await store.remove("x1");
|
||||
assert.equal(await store.exists("x1"), false);
|
||||
assert.equal((await store.restore()).length, 0);
|
||||
} finally {
|
||||
await fs.rm(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("QueueStore restore handles missing directory and corrupted files", async () => {
|
||||
const base = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-queue-empty-"));
|
||||
try {
|
||||
const store = new QueueStore(base);
|
||||
// No directory yet
|
||||
assert.deepEqual(await store.restore(), []);
|
||||
// Write a valid task + a corrupted file
|
||||
await store.write({
|
||||
deliveryId: "ok1",
|
||||
eventName: "schedule",
|
||||
payload: {},
|
||||
enqueuedAt: Date.now()
|
||||
});
|
||||
await fs.writeFile(path.join(base, ".ghbot-webhook-queue", "corrupt.json"), "not-json", "utf8");
|
||||
const restored = await store.restore();
|
||||
assert.equal(restored.length, 1);
|
||||
assert.equal(restored[0]!.deliveryId, "ok1");
|
||||
} finally {
|
||||
await fs.rm(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,380 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test, mock } from "node:test";
|
||||
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
import { config } from "../src/config.js";
|
||||
import {
|
||||
normalizeEndpoint,
|
||||
isR2Configured,
|
||||
downloadR2Object,
|
||||
uploadR2Object
|
||||
} from "../src/storage/r2.js";
|
||||
|
||||
// ── Mock S3Client.prototype.send ──────────────────────────────────────────
|
||||
const mockSend = mock.fn<(...args: unknown[]) => Promise<unknown>>();
|
||||
mock.method(S3Client.prototype, "send", mockSend);
|
||||
|
||||
let _lastGetObjectInput: Record<string, unknown> | undefined;
|
||||
let _lastPutObjectInput: Record<string, unknown> | undefined;
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
function setR2Config(
|
||||
opts: {
|
||||
endpoint?: string;
|
||||
bucketName?: string;
|
||||
accessKeyId?: string;
|
||||
secretAccessKey?: string;
|
||||
} = {}
|
||||
): void {
|
||||
config.r2Endpoint = opts.endpoint;
|
||||
config.r2BucketName = opts.bucketName;
|
||||
config.r2AccessKeyId = opts.accessKeyId;
|
||||
config.r2SecretAccessKey = opts.secretAccessKey;
|
||||
}
|
||||
|
||||
function clearR2Config(): void {
|
||||
setR2Config();
|
||||
}
|
||||
|
||||
/** Reset the S3 send mock and attach a default handler that captures commands. */
|
||||
function resetSendMock(handler?: (command: unknown) => Promise<unknown>): void {
|
||||
mockSend.mock.resetCalls();
|
||||
_lastGetObjectInput = undefined;
|
||||
_lastPutObjectInput = undefined;
|
||||
|
||||
mockSend.mock.mockImplementation(
|
||||
handler ??
|
||||
(async (command: unknown) => {
|
||||
if (command instanceof GetObjectCommand) {
|
||||
_lastGetObjectInput = command.input;
|
||||
return { Body: undefined };
|
||||
}
|
||||
if (command instanceof PutObjectCommand) {
|
||||
_lastPutObjectInput = command.input;
|
||||
return {};
|
||||
}
|
||||
return {};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// normalizeEndpoint
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("normalizeEndpoint with valid HTTPS URL returns normalized", () => {
|
||||
assert.equal(
|
||||
normalizeEndpoint("https://account.r2.cloudflarestorage.com"),
|
||||
"https://account.r2.cloudflarestorage.com"
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint removes trailing slash", () => {
|
||||
assert.equal(
|
||||
normalizeEndpoint("https://account.r2.cloudflarestorage.com/"),
|
||||
"https://account.r2.cloudflarestorage.com"
|
||||
);
|
||||
assert.equal(
|
||||
normalizeEndpoint("https://account.r2.cloudflarestorage.com/my-prefix/"),
|
||||
"https://account.r2.cloudflarestorage.com/my-prefix"
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint with invalid URL throws", () => {
|
||||
assert.throws(() => normalizeEndpoint("not a url"), /valid HTTPS URL/);
|
||||
assert.throws(() => normalizeEndpoint(""), /valid HTTPS URL/);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint with userinfo in URL throws", () => {
|
||||
assert.throws(() => normalizeEndpoint("https://user:pass@host.com"), /credential-free HTTPS/);
|
||||
assert.throws(() => normalizeEndpoint("https://user@host.com"), /credential-free HTTPS/);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint with non-HTTPS protocol throws", () => {
|
||||
assert.throws(() => normalizeEndpoint("http://r2.example.com"), /credential-free HTTPS/);
|
||||
assert.throws(() => normalizeEndpoint("ftp://r2.example.com"), /credential-free HTTPS/);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint with query string throws", () => {
|
||||
assert.throws(() => normalizeEndpoint("https://r2.example.com?foo=bar"), /credential-free HTTPS/);
|
||||
});
|
||||
|
||||
test("normalizeEndpoint with hash fragment throws", () => {
|
||||
assert.throws(() => normalizeEndpoint("https://r2.example.com#section"), /credential-free HTTPS/);
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// isR2Configured
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("isR2Configured returns false when no config values set", () => {
|
||||
clearR2Config();
|
||||
assert.equal(isR2Configured(), false);
|
||||
});
|
||||
|
||||
test("isR2Configured throws when config is partial", () => {
|
||||
clearR2Config();
|
||||
config.r2Endpoint = "https://example.r2.cloudflarestorage.com";
|
||||
|
||||
assert.throws(() => isR2Configured(), /R2 cache configuration is incomplete/);
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// downloadR2Object
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("downloadR2Object returns Buffer for valid response", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async (command: unknown) => {
|
||||
if (command instanceof GetObjectCommand) {
|
||||
_lastGetObjectInput = command.input;
|
||||
return {
|
||||
Body: {
|
||||
transformToByteArray: async () => new Uint8Array([104, 101, 108, 108, 111])
|
||||
}
|
||||
};
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
const result = await downloadR2Object("some/key.json");
|
||||
assert.ok(result !== undefined, "expected a Buffer, got undefined");
|
||||
assert.ok(Buffer.isBuffer(result));
|
||||
assert.equal(result.toString(), "hello");
|
||||
assert.equal(mockSend.mock.calls.length, 1);
|
||||
});
|
||||
|
||||
test("downloadR2Object returns empty Buffer when Body is absent", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async (command: unknown) => {
|
||||
if (command instanceof GetObjectCommand) {
|
||||
_lastGetObjectInput = command.input;
|
||||
return { Body: undefined };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
const result = await downloadR2Object("some/key.json");
|
||||
assert.ok(result !== undefined, "expected a Buffer, got undefined");
|
||||
assert.ok(Buffer.isBuffer(result));
|
||||
assert.equal(result.byteLength, 0);
|
||||
assert.equal(mockSend.mock.calls.length, 1);
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// uploadR2Object
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("uploadR2Object calls PutObjectCommand with correct params", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock();
|
||||
|
||||
await uploadR2Object({
|
||||
key: "test/object.json",
|
||||
body: JSON.stringify({ foo: "bar" }),
|
||||
contentType: "application/json"
|
||||
});
|
||||
|
||||
assert.equal(mockSend.mock.calls.length, 1);
|
||||
assert.ok(_lastPutObjectInput, "PutObjectCommand was not instantiated");
|
||||
assert.equal(_lastPutObjectInput!.Bucket, "my-bucket");
|
||||
assert.equal(_lastPutObjectInput!.Key, "test/object.json");
|
||||
assert.equal(_lastPutObjectInput!.ContentType, "application/json");
|
||||
assert.equal(_lastPutObjectInput!.CacheControl, "no-store");
|
||||
assert.deepEqual(_lastPutObjectInput!.Metadata, { "ghbot-format": "v1" });
|
||||
assert.equal(_lastPutObjectInput!.Body, JSON.stringify({ foo: "bar" }));
|
||||
});
|
||||
|
||||
test("uploadR2Object with Uint8Array body", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock();
|
||||
|
||||
const binaryBody = new Uint8Array([1, 2, 3]);
|
||||
await uploadR2Object({
|
||||
key: "binary/data.bin",
|
||||
body: binaryBody,
|
||||
contentType: "application/octet-stream"
|
||||
});
|
||||
|
||||
assert.equal(mockSend.mock.calls.length, 1);
|
||||
assert.ok(_lastPutObjectInput, "PutObjectCommand was not instantiated");
|
||||
assert.equal(_lastPutObjectInput!.Body, binaryBody);
|
||||
assert.equal(_lastPutObjectInput!.ContentType, "application/octet-stream");
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// validateBucketName (tested through isR2Configured)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("validateBucketName with valid name passes", () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-valid-bucket-123",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
assert.doesNotThrow(() => isR2Configured());
|
||||
});
|
||||
|
||||
test("validateBucketName with invalid name throws", () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "UPPERCASE_BUCKET",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
assert.throws(() => isR2Configured(), /R2_BUCKET_NAME must be a valid S3-compatible bucket name/);
|
||||
});
|
||||
|
||||
test("validateBucketName with name starting with dash throws", () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "-invalid-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
assert.throws(() => isR2Configured(), /R2_BUCKET_NAME must be a valid S3-compatible bucket name/);
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// isMissingObject (tested through downloadR2Object)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("isMissingObject with NoSuchKey returns undefined", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
const err = new Error("NoSuchKey") as Error & { name: string };
|
||||
err.name = "NoSuchKey";
|
||||
throw err;
|
||||
});
|
||||
|
||||
const result = await downloadR2Object("missing-key.json");
|
||||
assert.equal(result, undefined);
|
||||
});
|
||||
|
||||
test("isMissingObject with 404 status returns undefined", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
const err = new Error("NotFound") as Error & {
|
||||
name: string;
|
||||
$metadata?: { httpStatusCode: number };
|
||||
};
|
||||
err.name = "NotFound";
|
||||
err.$metadata = { httpStatusCode: 404 };
|
||||
throw err;
|
||||
});
|
||||
|
||||
const result = await downloadR2Object("missing-key.json");
|
||||
assert.equal(result, undefined);
|
||||
});
|
||||
|
||||
test("isMissingObject with other errors rethrows", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
throw new Error("Network failure");
|
||||
});
|
||||
|
||||
await assert.rejects(() => downloadR2Object("some-key.json"), /Network failure/);
|
||||
});
|
||||
|
||||
test("isMissingObject with non-object error rethrows", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
throw new Error("string error");
|
||||
});
|
||||
|
||||
await assert.rejects(() => downloadR2Object("some-key.json"), /string error/);
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Extra edge cases
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
test("downloadR2Object with 403 error rethrows", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
const err = new Error("Forbidden") as Error & {
|
||||
name: string;
|
||||
$metadata?: { httpStatusCode: number };
|
||||
};
|
||||
err.name = "Forbidden";
|
||||
err.$metadata = { httpStatusCode: 403 };
|
||||
throw err;
|
||||
});
|
||||
|
||||
await assert.rejects(() => downloadR2Object("forbidden-key.json"), /Forbidden/);
|
||||
});
|
||||
|
||||
test("downloadR2Object with AccessDenied error rethrows", async () => {
|
||||
setR2Config({
|
||||
endpoint: "https://example.r2.cloudflarestorage.com",
|
||||
bucketName: "my-bucket",
|
||||
accessKeyId: "akid",
|
||||
secretAccessKey: "sak"
|
||||
});
|
||||
|
||||
resetSendMock(async () => {
|
||||
const err = new Error("AccessDenied") as Error & { name: string };
|
||||
err.name = "AccessDenied";
|
||||
throw err;
|
||||
});
|
||||
|
||||
await assert.rejects(() => downloadR2Object("restricted-key.json"), /AccessDenied/);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import path from "node:path";
|
||||
import test from "node:test";
|
||||
import {
|
||||
loadRepositoryKnowledge,
|
||||
normalizeKnowledge,
|
||||
readKnowledgeScratch,
|
||||
saveRepositoryKnowledgeCache,
|
||||
validateRepositoryKnowledge,
|
||||
@@ -61,6 +62,13 @@ test("loading an empty repository knowledge cache initializes the persisted file
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizeKnowledge normalizes CRLF and CR line endings to LF", () => {
|
||||
assert.equal(normalizeKnowledge("# A\r\n\r\nB\r\n"), "# A\n\nB\n");
|
||||
assert.equal(normalizeKnowledge("# A\rB\r"), "# A\nB\n");
|
||||
assert.equal(normalizeKnowledge("x\n".repeat(100)), `${"x\n".repeat(100)}`);
|
||||
assert.equal(normalizeKnowledge("# A\n\nB\n"), "# A\n\nB\n");
|
||||
});
|
||||
|
||||
test("repository knowledge rejects credentials and oversized content", () => {
|
||||
assert.throws(
|
||||
() => validateRepositoryKnowledge("-----BEGIN PRIVATE KEY-----\nsecret"),
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { withRetry } from "../src/retry.js";
|
||||
|
||||
class HttpLikeError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
test("custom retryable predicate treats specific errors as retryable", async () => {
|
||||
let attempts = 0;
|
||||
const result = await withRetry(
|
||||
"custom-retryable",
|
||||
async () => {
|
||||
attempts += 1;
|
||||
if (attempts < 3) {
|
||||
throw new HttpLikeError(403, "forbidden but transient per our rule");
|
||||
}
|
||||
return "done";
|
||||
},
|
||||
{
|
||||
baseDelayMs: 1,
|
||||
retryable: (error) => {
|
||||
if (typeof error === "object" && error !== null && "status" in error) {
|
||||
const e = error as { status: number };
|
||||
return e.status === 403;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
assert.equal(result, "done");
|
||||
assert.equal(attempts, 3);
|
||||
});
|
||||
|
||||
test("custom retryable predicate prevents retry when it returns false", async () => {
|
||||
let attempts = 0;
|
||||
await assert.rejects(
|
||||
withRetry(
|
||||
"custom-non-retryable",
|
||||
async () => {
|
||||
attempts += 1;
|
||||
throw new HttpLikeError(500, "always fatal per our rule");
|
||||
},
|
||||
{
|
||||
baseDelayMs: 1,
|
||||
retryable: () => false
|
||||
}
|
||||
),
|
||||
/always fatal/
|
||||
);
|
||||
assert.equal(attempts, 1);
|
||||
});
|
||||
|
||||
test("default behavior unchanged when no custom retryable provided", async () => {
|
||||
let attempts = 0;
|
||||
const result = await withRetry(
|
||||
"default-behavior",
|
||||
async () => {
|
||||
attempts += 1;
|
||||
if (attempts < 3) {
|
||||
throw new HttpLikeError(502, "bad gateway");
|
||||
}
|
||||
return "ok";
|
||||
},
|
||||
{ baseDelayMs: 1 }
|
||||
);
|
||||
assert.equal(result, "ok");
|
||||
assert.equal(attempts, 3);
|
||||
});
|
||||
|
||||
test("default behavior still rejects non-retryable errors", async () => {
|
||||
let attempts = 0;
|
||||
await assert.rejects(
|
||||
withRetry("default-non-retryable", async () => {
|
||||
attempts += 1;
|
||||
throw new HttpLikeError(404, "not found");
|
||||
})
|
||||
);
|
||||
assert.equal(attempts, 1);
|
||||
});
|
||||
|
||||
test("maxTotalTimeoutMs stops retries when elapsed time exceeds limit", async () => {
|
||||
const startTime = Date.now();
|
||||
let attempts = 0;
|
||||
await assert.rejects(
|
||||
withRetry(
|
||||
"timeout-limit",
|
||||
async () => {
|
||||
attempts += 1;
|
||||
// Simulate a brief operation that takes some time
|
||||
throw new HttpLikeError(502, "timeout test");
|
||||
},
|
||||
{ maxAttempts: 5, baseDelayMs: 100, maxTotalTimeoutMs: 50 }
|
||||
)
|
||||
);
|
||||
const elapsed = Date.now() - startTime;
|
||||
assert.ok(attempts > 0, "at least one attempt was made");
|
||||
assert.ok(attempts < 5, "should not reach max attempts due to total timeout");
|
||||
assert.ok(elapsed < 500, "should complete within reasonable time given the short timeout");
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildReviewSubmissionPlan,
|
||||
formatSupersededReviewBody,
|
||||
isConflictComment,
|
||||
isRecheckComment,
|
||||
shortSha,
|
||||
shouldFallbackToCommentReview
|
||||
} from "../src/review/processor.js";
|
||||
import type { ReviewDecision } from "../src/types.js";
|
||||
|
||||
type DispositionEvent = "APPROVE" | "COMMENT" | "REQUEST_CHANGES";
|
||||
|
||||
const cleanDecision: ReviewDecision = {
|
||||
review: [],
|
||||
change: [],
|
||||
comment: "looks fine",
|
||||
result: { canMerge: true, summary: "approved", shouldClosePullRequest: false, closeReason: "" }
|
||||
};
|
||||
|
||||
function finding(path: string, line: number, title: string, body: string) {
|
||||
return { path, line, title, body };
|
||||
}
|
||||
|
||||
test("buildReviewSubmissionPlan emits REQUEST_CHANGES first when change findings exist", () => {
|
||||
const decision: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")]
|
||||
};
|
||||
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
|
||||
|
||||
assert.equal(plan[0]?.phase, "change");
|
||||
assert.equal(plan[0]?.event, "REQUEST_CHANGES");
|
||||
assert.equal(plan[0]?.findings.length, 1);
|
||||
assert.equal(plan[0]?.findings[0]?.category, "change");
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan emits a COMMENT phase for review findings", () => {
|
||||
const decision: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
|
||||
|
||||
assert.equal(plan[0]?.phase, "review");
|
||||
assert.equal(plan[0]?.event, "COMMENT");
|
||||
assert.equal(plan[0]?.findings.length, 1);
|
||||
assert.equal(plan[0]?.findings[0]?.category, "review");
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan orders change before review when both exist", () => {
|
||||
const decision: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")],
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
|
||||
|
||||
assert.deepEqual(
|
||||
plan.map((phase) => phase.phase),
|
||||
["change", "review", "final"]
|
||||
);
|
||||
assert.deepEqual(
|
||||
plan.map((phase) => phase.event),
|
||||
["REQUEST_CHANGES", "COMMENT", "COMMENT"]
|
||||
);
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan emits final APPROVE when there are no findings", () => {
|
||||
const plan = buildReviewSubmissionPlan(cleanDecision, { event: "APPROVE" });
|
||||
|
||||
assert.equal(plan.length, 1);
|
||||
assert.equal(plan[0]?.phase, "final");
|
||||
assert.equal(plan[0]?.event, "APPROVE");
|
||||
assert.deepEqual(plan[0]?.findings, []);
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan always ends with a final phase", () => {
|
||||
const withChangeOnly: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")]
|
||||
};
|
||||
const withReviewOnly: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
const both: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")],
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
|
||||
for (const [label, decision, event] of [
|
||||
["clean", cleanDecision, "APPROVE" as DispositionEvent],
|
||||
["change only", withChangeOnly, "REQUEST_CHANGES" as DispositionEvent],
|
||||
["review only", withReviewOnly, "COMMENT" as DispositionEvent],
|
||||
["both", both, "REQUEST_CHANGES" as DispositionEvent]
|
||||
]) {
|
||||
const plan = buildReviewSubmissionPlan(decision, { event });
|
||||
const last = plan.at(-1);
|
||||
assert.equal(last?.phase, "final", `${label}: last phase must be final`);
|
||||
assert.deepEqual(last?.findings ?? [], [], `${label}: final phase carries no findings`);
|
||||
}
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan forces final event to COMMENT when change findings exist", () => {
|
||||
const withChangeOnly: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")]
|
||||
};
|
||||
const withChangeThenReview: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
change: [finding("a.ts", 1, "change it", "blocking")],
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
|
||||
const changePlan = buildReviewSubmissionPlan(withChangeOnly, { event: "REQUEST_CHANGES" });
|
||||
assert.equal(changePlan.at(-1)?.event, "COMMENT");
|
||||
|
||||
const bothPlan = buildReviewSubmissionPlan(withChangeThenReview, { event: "REQUEST_CHANGES" });
|
||||
assert.equal(bothPlan.at(-1)?.event, "COMMENT");
|
||||
});
|
||||
|
||||
test("buildReviewSubmissionPlan leaves final event to the disposition when no change findings exist", () => {
|
||||
const withReviewOnly: ReviewDecision = {
|
||||
...cleanDecision,
|
||||
review: [finding("b.ts", 2, "note", "non-blocking")]
|
||||
};
|
||||
|
||||
const plan = buildReviewSubmissionPlan(withReviewOnly, { event: "APPROVE" });
|
||||
assert.equal(plan.at(-1)?.event, "APPROVE");
|
||||
});
|
||||
|
||||
test("shouldFallbackToCommentReview returns false for non-APPROVE events", () => {
|
||||
const error = {
|
||||
status: 422,
|
||||
message: "GitHub Actions is not permitted to approve pull requests."
|
||||
};
|
||||
assert.equal(shouldFallbackToCommentReview(error, "COMMENT"), false);
|
||||
assert.equal(shouldFallbackToCommentReview(error, "REQUEST_CHANGES"), false);
|
||||
});
|
||||
|
||||
test("shouldFallbackToCommentReview returns false for non-422 errors", () => {
|
||||
const error = {
|
||||
status: 403,
|
||||
message: "GitHub Actions is not permitted to approve pull requests."
|
||||
};
|
||||
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), false);
|
||||
});
|
||||
|
||||
test("shouldFallbackToCommentReview returns true for 422 with GitHub Actions not permitted", () => {
|
||||
const error = {
|
||||
status: 422,
|
||||
message: "GitHub Actions is not permitted to approve pull requests."
|
||||
};
|
||||
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), true);
|
||||
});
|
||||
|
||||
test("shouldFallbackToCommentReview returns false for 422 with unrelated message", () => {
|
||||
const error = { status: 422, message: "Validation error: body is too long." };
|
||||
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), false);
|
||||
});
|
||||
|
||||
test("shouldFallbackToCommentReview returns false for non-object errors", () => {
|
||||
assert.equal(shouldFallbackToCommentReview("string error", "APPROVE"), false);
|
||||
assert.equal(shouldFallbackToCommentReview(null, "APPROVE"), false);
|
||||
assert.equal(shouldFallbackToCommentReview(undefined, "APPROVE"), false);
|
||||
});
|
||||
|
||||
test("shortSha returns first 12 characters", () => {
|
||||
const sha = "abcdef0123456789abcdef0123456789abcdef01";
|
||||
assert.equal(shortSha(sha), "abcdef012345");
|
||||
assert.equal(shortSha(sha).length, 12);
|
||||
});
|
||||
|
||||
test("isRecheckComment matches the exact command", () => {
|
||||
assert.equal(isRecheckComment("/recheck"), true);
|
||||
});
|
||||
|
||||
test("isRecheckComment matches with surrounding whitespace", () => {
|
||||
assert.equal(isRecheckComment(" /recheck "), true);
|
||||
assert.equal(isRecheckComment("\t/recheck\n"), true);
|
||||
});
|
||||
|
||||
test("isRecheckComment rejects different text", () => {
|
||||
assert.equal(isRecheckComment("please recheck"), false);
|
||||
assert.equal(isRecheckComment("/refresh"), false);
|
||||
assert.equal(isRecheckComment(""), false);
|
||||
});
|
||||
|
||||
test("isConflictComment matches the exact command", () => {
|
||||
assert.equal(isConflictComment("/conflict"), true);
|
||||
});
|
||||
|
||||
test("isConflictComment matches with surrounding whitespace", () => {
|
||||
assert.equal(isConflictComment(" /conflict "), true);
|
||||
assert.equal(isConflictComment("\t/conflict\n"), true);
|
||||
});
|
||||
|
||||
test("isConflictComment rejects different text", () => {
|
||||
assert.equal(isConflictComment("resolve conflict"), false);
|
||||
assert.equal(isConflictComment("/conflicts"), false);
|
||||
assert.equal(isConflictComment(""), false);
|
||||
});
|
||||
|
||||
test("formatSupersededReviewBody keeps the original state marker", () => {
|
||||
const originalMarker =
|
||||
"<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=1 change=0 -->";
|
||||
const body = formatSupersededReviewBody({
|
||||
originalMarker,
|
||||
oldCommitId: "a".repeat(40),
|
||||
currentCommitId: "b".repeat(40)
|
||||
});
|
||||
|
||||
assert.ok(body.startsWith(originalMarker), "body must start with the original marker line");
|
||||
});
|
||||
|
||||
test("formatSupersededReviewBody includes old and new commit SHAs (short form)", () => {
|
||||
const oldCommitId = "a".repeat(40);
|
||||
const currentCommitId = "b".repeat(40);
|
||||
const body = formatSupersededReviewBody({
|
||||
originalMarker: "<!-- ghbot-review:v1 superseded=true -->",
|
||||
oldCommitId,
|
||||
currentCommitId
|
||||
});
|
||||
|
||||
assert.ok(body.includes(oldCommitId.slice(0, 12)), "body must mention the old short SHA");
|
||||
assert.ok(body.includes(currentCommitId.slice(0, 12)), "body must mention the new short SHA");
|
||||
assert.equal(body.includes(oldCommitId), false, "full old SHA should not be used");
|
||||
assert.equal(body.includes(currentCommitId), false, "full current SHA should not be used");
|
||||
});
|
||||
|
||||
test("formatSupersededReviewBody marks the review as Superseded", () => {
|
||||
const body = formatSupersededReviewBody({
|
||||
originalMarker: "<!-- ghbot-review:v1 superseded=true -->",
|
||||
oldCommitId: "a".repeat(40),
|
||||
currentCommitId: "b".repeat(40)
|
||||
});
|
||||
|
||||
assert.match(body, /## Superseded automated review/);
|
||||
assert.match(body, /Superseded automated review/);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { evaluateReviewStaleness } from "../src/review/staleness.js";
|
||||
import type { PullRequestFile } from "../src/types.js";
|
||||
|
||||
const SHA_A = "a".repeat(40);
|
||||
const SHA_B = "b".repeat(40);
|
||||
|
||||
function file(filename: string, patch: string): PullRequestFile {
|
||||
return { filename, patch, status: "modified", additions: 0, deletions: 0 };
|
||||
}
|
||||
|
||||
test("returns unchanged when heads match", () => {
|
||||
const result = evaluateReviewStaleness({
|
||||
beforeFiles: [file("a.ts", "+1")],
|
||||
afterFiles: [file("a.ts", "+1")],
|
||||
oldHeadSha: SHA_A,
|
||||
newHeadSha: SHA_A,
|
||||
maxPatchChars: 1000
|
||||
});
|
||||
assert.deepEqual(result, { action: "unchanged" });
|
||||
});
|
||||
|
||||
test("returns discard when an existing file's patch changed", () => {
|
||||
const result = evaluateReviewStaleness({
|
||||
beforeFiles: [file("a.ts", "+1")],
|
||||
afterFiles: [file("a.ts", "+changed")],
|
||||
oldHeadSha: SHA_A,
|
||||
newHeadSha: SHA_B,
|
||||
maxPatchChars: 1000
|
||||
});
|
||||
assert.deepEqual(result, { action: "discard" });
|
||||
});
|
||||
|
||||
test("returns discard when delta exceeds half the max patch", () => {
|
||||
const big = "+".repeat(600);
|
||||
const result = evaluateReviewStaleness({
|
||||
beforeFiles: [file("a.ts", "+1")],
|
||||
afterFiles: [file("a.ts", "+1"), file("big.ts", big)],
|
||||
oldHeadSha: SHA_A,
|
||||
newHeadSha: SHA_B,
|
||||
maxPatchChars: 1000
|
||||
});
|
||||
assert.deepEqual(result, { action: "discard" });
|
||||
});
|
||||
|
||||
test("returns append when only small additive files were added", () => {
|
||||
const result = evaluateReviewStaleness({
|
||||
beforeFiles: [file("a.ts", "+1")],
|
||||
afterFiles: [file("a.ts", "+1"), file("b.ts", "+2")],
|
||||
oldHeadSha: SHA_A,
|
||||
newHeadSha: SHA_B,
|
||||
maxPatchChars: 1000
|
||||
});
|
||||
assert.equal(result.action, "append");
|
||||
if (result.action === "append") {
|
||||
assert.ok(result.additionalPrompt.includes("b.ts"));
|
||||
assert.ok(result.additionalPrompt.includes("+2"));
|
||||
assert.ok(!result.additionalPrompt.includes("a.ts"));
|
||||
}
|
||||
});
|
||||
|
||||
test("returns discard when added files have no patch content", () => {
|
||||
const result = evaluateReviewStaleness({
|
||||
beforeFiles: [file("a.ts", "+1")],
|
||||
afterFiles: [file("a.ts", "+1"), file("empty.ts", "")],
|
||||
oldHeadSha: SHA_A,
|
||||
newHeadSha: SHA_B,
|
||||
maxPatchChars: 1000
|
||||
});
|
||||
assert.deepEqual(result, { action: "discard" });
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import { config } from "../src/config.js";
|
||||
import {
|
||||
buildPullRequestCoarsePrompt,
|
||||
buildPullRequestDuplicatePrompt,
|
||||
buildTriagePrompt,
|
||||
labelName,
|
||||
processIssueTriage,
|
||||
processPullRequestTriage,
|
||||
type PullRequestEvidence
|
||||
} from "../src/triage/processor.js";
|
||||
|
||||
const originalTriageEnabled = config.triageEnabled;
|
||||
|
||||
test.afterEach(() => {
|
||||
config.triageEnabled = originalTriageEnabled;
|
||||
});
|
||||
|
||||
function issueTarget(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
number: 7,
|
||||
title: "Broken login button",
|
||||
body: "Clicking login does nothing.",
|
||||
htmlUrl: "https://github.com/acme/app/issues/7",
|
||||
existingLabels: [],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
function candidate(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
number: 9,
|
||||
title: "Login button styling",
|
||||
body: "Adjusts the login button.",
|
||||
state: "open",
|
||||
htmlUrl: "https://github.com/acme/app/issues/9",
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
function emptyEvidence(number: number): PullRequestEvidence {
|
||||
return {
|
||||
number,
|
||||
commits: [],
|
||||
comments: [],
|
||||
reviews: [],
|
||||
reviewComments: []
|
||||
};
|
||||
}
|
||||
|
||||
test("buildPullRequestCoarsePrompt embeds the target, labels, and duplicate candidates", () => {
|
||||
const prompt = buildPullRequestCoarsePrompt(issueTarget(), [candidate()]);
|
||||
|
||||
assert.match(prompt, /"title": "Broken login button"/);
|
||||
assert.match(prompt, /must contain at least one value and may only use:/);
|
||||
assert.match(prompt, /"bug"/);
|
||||
assert.match(prompt, /"number": 9/);
|
||||
assert.match(prompt, /"number": 7/);
|
||||
});
|
||||
|
||||
test("buildPullRequestDuplicatePrompt embeds target evidence and candidate evidence", () => {
|
||||
const targetEvidence = emptyEvidence(7);
|
||||
const candidateEvidence = [emptyEvidence(9)];
|
||||
const prompt = buildPullRequestDuplicatePrompt({
|
||||
target: issueTarget(),
|
||||
targetEvidence,
|
||||
candidates: [candidate()],
|
||||
candidateEvidence
|
||||
});
|
||||
|
||||
assert.match(prompt, /"number": 7/);
|
||||
assert.match(prompt, /"number": 9/);
|
||||
assert.match(prompt, /Target pull request and detailed evidence:/);
|
||||
assert.match(prompt, /"evidence": \{/);
|
||||
assert.match(prompt, /"commits": \[\]/);
|
||||
assert.match(prompt, /"comments": \[\]/);
|
||||
assert.match(prompt, /"reviews": \[\]/);
|
||||
assert.match(prompt, /"reviewComments": \[\]/);
|
||||
});
|
||||
|
||||
test("buildTriagePrompt advertises issue triage for an issue target", () => {
|
||||
const prompt = buildTriagePrompt("issue", issueTarget(), [candidate()]);
|
||||
assert.match(prompt, /triaging a GitHub issue/);
|
||||
assert.doesNotMatch(prompt, /pull request/);
|
||||
assert.match(prompt, /"body": "Clicking login does nothing\."/);
|
||||
});
|
||||
|
||||
test("buildTriagePrompt advertises pull request triage for a pull request target", () => {
|
||||
const prompt = buildTriagePrompt("pull_request", issueTarget(), [candidate()]);
|
||||
assert.match(prompt, /triaging a GitHub pull request/);
|
||||
});
|
||||
|
||||
test("buildTriagePrompt includes labels, target, and candidates", () => {
|
||||
const prompt = buildTriagePrompt("issue", issueTarget(), [candidate({ number: 9 })]);
|
||||
assert.match(prompt, /"bug"/);
|
||||
assert.match(prompt, /"title": "Broken login button"/);
|
||||
assert.match(prompt, /"title": "Login button styling"/);
|
||||
});
|
||||
|
||||
test("labelName handles a plain string label", () => {
|
||||
assert.equal(labelName("bug"), "bug");
|
||||
});
|
||||
|
||||
test("labelName extracts the name from an object label", () => {
|
||||
assert.equal(labelName({ name: "documentation", node_id: "MDU6TGFiZWwx" }), "documentation");
|
||||
});
|
||||
|
||||
test("labelName returns an empty string for an object label without a name", () => {
|
||||
assert.equal(labelName({ id: 123 }), "");
|
||||
});
|
||||
|
||||
test("labelName returns an empty string for an empty-name object label", () => {
|
||||
assert.equal(labelName({ name: "" }), "");
|
||||
});
|
||||
|
||||
test("processIssueTriage returns immediately when triage is disabled", async () => {
|
||||
config.triageEnabled = false;
|
||||
|
||||
await assert.doesNotReject(
|
||||
processIssueTriage({} as Octokit, { owner: "acme", repo: "app", issueNumber: 7 })
|
||||
);
|
||||
});
|
||||
|
||||
test("processPullRequestTriage returns immediately when triage is disabled", async () => {
|
||||
config.triageEnabled = false;
|
||||
|
||||
await assert.doesNotReject(
|
||||
processPullRequestTriage({} as Octokit, {
|
||||
owner: "acme",
|
||||
repo: "app",
|
||||
pullNumber: 9
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,821 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { parseWebhookMentionEvent, webhookPermissionAllows } from "../src/webhook/processor.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// parseWebhookMentionEvent
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("parseWebhookMentionEvent for issue_comment with missing fields returns null", () => {
|
||||
// Missing issue number
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { title: "test" },
|
||||
comment: { id: 88, body: "@bot hello", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-1",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing comment id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7, pull_request: { url: "" } },
|
||||
comment: { body: "@bot hello", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-2",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing comment body
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-3",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing repository owner
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { name: "demo" },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot hello", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-4",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review_comment with valid data", () => {
|
||||
const mention = parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot please review this comment",
|
||||
user: { login: "alice", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-review-comment",
|
||||
"bot"
|
||||
);
|
||||
|
||||
assert.ok(mention);
|
||||
assert.equal(mention.eventName, "pull_request_review_comment");
|
||||
assert.equal(mention.installationId, 12345);
|
||||
assert.equal(mention.owner, "acme");
|
||||
assert.equal(mention.repo, "demo");
|
||||
assert.equal(mention.issueNumber, 7);
|
||||
assert.equal(mention.targetKind, "pull_request");
|
||||
assert.equal(mention.sourceCommentId, 88);
|
||||
assert.equal(mention.commentBody, "@bot please review this comment");
|
||||
assert.equal(mention.commenterLogin, "alice");
|
||||
assert.equal(mention.commenterType, "User");
|
||||
assert.equal(mention.replyMode, "review_comment");
|
||||
assert.equal(mention.action, "created");
|
||||
assert.equal(mention.deliveryId, "delivery-review-comment");
|
||||
assert.equal(mention.repositoryId, 99);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review submitted action", () => {
|
||||
const mention = parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: {
|
||||
id: 88,
|
||||
body: "@bot thanks for the review",
|
||||
user: { login: "bob", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-review-submitted",
|
||||
"bot"
|
||||
);
|
||||
|
||||
assert.ok(mention);
|
||||
assert.equal(mention.eventName, "pull_request_review");
|
||||
assert.equal(mention.installationId, 12345);
|
||||
assert.equal(mention.owner, "acme");
|
||||
assert.equal(mention.repo, "demo");
|
||||
assert.equal(mention.issueNumber, 7);
|
||||
assert.equal(mention.targetKind, "pull_request");
|
||||
assert.equal(mention.sourceCommentId, 88);
|
||||
assert.equal(mention.commentBody, "@bot thanks for the review");
|
||||
assert.equal(mention.commenterLogin, "bob");
|
||||
assert.equal(mention.commenterType, "User");
|
||||
assert.equal(mention.replyMode, "conversation");
|
||||
assert.equal(mention.action, "submitted");
|
||||
assert.equal(mention.deliveryId, "delivery-review-submitted");
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for non-submitted pull_request_review returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "dismissed",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-dismissed",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "edited",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-edited",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent with non-created/edited action returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "deleted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-deleted",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// "edited" should still work for issue_comment
|
||||
assert.ok(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "edited",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7, pull_request: { url: "" } },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-edited-ok",
|
||||
"bot"
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent with bot sender returns null", () => {
|
||||
// Bot type sender
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "some-app", type: "Bot" }
|
||||
}
|
||||
},
|
||||
"delivery-bot-type",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Login matching botName (case-insensitive)
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "BOT", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-bot-login",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Login matching botName with [bot] suffix
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "github-actions[bot]", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-bot-suffix",
|
||||
"github-actions[bot]"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent with empty payload or deliveryId returns null", () => {
|
||||
assert.equal(parseWebhookMentionEvent("issue_comment", null, "delivery-1", "bot"), null);
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent("issue_comment", "not-an-object", "delivery-2", "bot"),
|
||||
null
|
||||
);
|
||||
assert.equal(parseWebhookMentionEvent("issue_comment", { action: "created" }, "", "bot"), null);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review with missing review fields returns null", () => {
|
||||
// Missing review id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: { body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-missing-review-id",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing review body
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: { id: 88, user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-missing-review-body",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing pull_request number
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: {},
|
||||
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-missing-pr-number",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review_comment with missing fields returns null", () => {
|
||||
// Missing pull_request number
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: {},
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-pr-comment-missing-pr",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing comment id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
comment: { body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-pr-comment-missing-id",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Missing comment body
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
comment: { id: 88, user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-pr-comment-missing-body",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review_comment non-created/edited action returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "deleted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-pr-comment-deleted",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review_comment without bot mention returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "ordinary comment without mention",
|
||||
user: { login: "alice", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-pr-comment-no-mention",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review submitted without bot mention returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: {
|
||||
id: 88,
|
||||
body: "ordinary review without mention",
|
||||
user: { login: "alice", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-review-no-mention",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for pull_request_review with bot reviewer returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"pull_request_review",
|
||||
{
|
||||
action: "submitted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
pull_request: { number: 7 },
|
||||
review: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "some-app", type: "Bot" }
|
||||
}
|
||||
},
|
||||
"delivery-review-bot-reviewer",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("parseWebhookMentionEvent for issue_comment with null/undefined installation returns null", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-no-installation",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// webhookPermissionAllows
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("webhookPermissionAllows with anyone policy always returns true", () => {
|
||||
assert.equal(webhookPermissionAllows(null, "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows(undefined, "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows("none", "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows("read", "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows("write", "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows("admin", "anyone"), true);
|
||||
assert.equal(webhookPermissionAllows("", "anyone"), true);
|
||||
});
|
||||
|
||||
test("webhookPermissionAllows with read policy requires read+ permissions", () => {
|
||||
// Allowed
|
||||
assert.equal(webhookPermissionAllows("organization", "read"), true);
|
||||
assert.equal(webhookPermissionAllows("read", "read"), true);
|
||||
assert.equal(webhookPermissionAllows("triage", "read"), true);
|
||||
assert.equal(webhookPermissionAllows("write", "read"), true);
|
||||
assert.equal(webhookPermissionAllows("maintain", "read"), true);
|
||||
assert.equal(webhookPermissionAllows("admin", "read"), true);
|
||||
|
||||
// Denied
|
||||
assert.equal(webhookPermissionAllows(null, "read"), false);
|
||||
assert.equal(webhookPermissionAllows(undefined, "read"), false);
|
||||
});
|
||||
|
||||
test("webhookPermissionAllows with write policy requires write+ permissions", () => {
|
||||
// Allowed
|
||||
assert.equal(webhookPermissionAllows("write", "write"), true);
|
||||
assert.equal(webhookPermissionAllows("maintain", "write"), true);
|
||||
assert.equal(webhookPermissionAllows("admin", "write"), true);
|
||||
|
||||
// Denied
|
||||
assert.equal(webhookPermissionAllows(null, "write"), false);
|
||||
assert.equal(webhookPermissionAllows(undefined, "write"), false);
|
||||
assert.equal(webhookPermissionAllows("organization", "write"), false);
|
||||
assert.equal(webhookPermissionAllows("read", "write"), false);
|
||||
assert.equal(webhookPermissionAllows("triage", "write"), false);
|
||||
});
|
||||
|
||||
test("webhookPermissionAllows with null permission returns false for read/write", () => {
|
||||
assert.equal(webhookPermissionAllows(null, "read"), false);
|
||||
assert.equal(webhookPermissionAllows(undefined, "read"), false);
|
||||
assert.equal(webhookPermissionAllows(null, "write"), false);
|
||||
assert.equal(webhookPermissionAllows(undefined, "write"), false);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isCreatedOrEdited (tested indirectly through parseWebhookMentionEvent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("isCreatedOrEdited returns true for created and edited (indirect)", () => {
|
||||
// "created" action accepted for issue_comment
|
||||
assert.ok(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7, pull_request: { url: "" } },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-created",
|
||||
"bot"
|
||||
)
|
||||
);
|
||||
|
||||
// "edited" action accepted for issue_comment
|
||||
assert.ok(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "edited",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7, pull_request: { url: "" } },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-edited",
|
||||
"bot"
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test("isCreatedOrEdited returns false for deleted (indirect)", () => {
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "deleted",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-deleted",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isBotSender (tested indirectly through parseWebhookMentionEvent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("isBotSender checks type === Bot and login case-insensitive match (indirect)", () => {
|
||||
// Bot type
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "some-app", type: "Bot" }
|
||||
}
|
||||
},
|
||||
"delivery-bot-type",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Case-insensitive login match with botName
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "Bot", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-bot-login-ci",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Non-bot, non-matching login is allowed
|
||||
assert.ok(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7, pull_request: { url: "" } },
|
||||
comment: {
|
||||
id: 88,
|
||||
body: "@bot test",
|
||||
user: { login: "alice", type: "User" }
|
||||
}
|
||||
},
|
||||
"delivery-human-user",
|
||||
"bot"
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isRecord (tested indirectly through parseWebhookMentionEvent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("isRecord returns false for non-objects (indirect)", () => {
|
||||
// Non-object payload
|
||||
assert.equal(parseWebhookMentionEvent("issue_comment", "string", "delivery-1", "bot"), null);
|
||||
|
||||
// Null payload
|
||||
assert.equal(parseWebhookMentionEvent("issue_comment", null, "delivery-2", "bot"), null);
|
||||
|
||||
// Number payload
|
||||
assert.equal(parseWebhookMentionEvent("issue_comment", 42, "delivery-3", "bot"), null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// asString (tested indirectly through parseWebhookMentionEvent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("asString returns undefined for non-strings (indirect)", () => {
|
||||
// Non-string comment body (number)
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: 123, user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-non-string-body",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Non-string owner login (array)
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: ["acme"] } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-non-string-owner",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// asPositiveInteger (tested indirectly through parseWebhookMentionEvent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("asPositiveInteger validates positive safe integers (indirect)", () => {
|
||||
// Zero installation id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 0 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-zero-installation",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Negative installation id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: -1 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-negative-installation",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Non-integer installation id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 1.5 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-float-installation",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
|
||||
// Non-number installation id
|
||||
assert.equal(
|
||||
parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: "12345" },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-string-installation",
|
||||
"bot"
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue with null targetKind (issue without pull_request marker)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("parseWebhookMentionEvent for issue_comment on an issue (not PR)", () => {
|
||||
const mention = parseWebhookMentionEvent(
|
||||
"issue_comment",
|
||||
{
|
||||
action: "created",
|
||||
installation: { id: 12345 },
|
||||
repository: { id: 99, name: "demo", owner: { login: "acme" } },
|
||||
issue: { number: 7 },
|
||||
comment: { id: 88, body: "@bot question about issue", user: { login: "alice", type: "User" } }
|
||||
},
|
||||
"delivery-issue-only",
|
||||
"bot"
|
||||
);
|
||||
|
||||
assert.ok(mention);
|
||||
assert.equal(mention.targetKind, "issue");
|
||||
assert.equal(mention.issueNumber, 7);
|
||||
assert.equal(mention.replyMode, "conversation");
|
||||
});
|
||||
Reference in new issue
Block a user