feat: sync ghbot-Nodeloc v1.2.0 capabilities into upstream

Merges all 33 commits from lza6/ghbot-Nodeloc (v1.0.0 through v1.2.0)
while keeping both sides' features in every conflicted file:

- EventRouter dispatch extracted from runReview.ts (7.1), with the
  runtime environment block preserved on the review-start comment
- Unified command ack messages (6.3) combined with the collapsed
  runtime environment block and bot signature on /recheck replies
- Status banner and collapsible unposted findings in review bodies (6.1)
- Centralized runtime directories behind GHBOT_RUNTIME_DIR (D-13);
  webhook knowledge cache now lives under tempRootDirectory()
- Production hardening for merge races, timeouts, webhook ops;
  atomic temp-file rename for R2 cache restores kept from upstream
- Webhook parity retained: triage events gated by WEBHOOK_TRIAGE_ENABLED,
  read-only command guidance, repository knowledge injection,
  runtime environment block on webhook chat replies
- Sanitization/secret redaction centralization, error-aware retry,
  duplicate merge prevention, in-process webhook retries, /metrics
- Infra: eslint/prettier gates with CI verify workflow, docs archives

typecheck, eslint, prettier format:check, and 164 tests all pass.
This commit is contained in:
lezi-fun committed 2026-08-24 11:47:28 +08:00
commit 9e47ab339e
180 files changed
+15130 -1209

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildChatRequesterContext,
chatReplyLanguageInstruction,
chatToolBudgetInstruction
} from "../src/chat/processor.js";
test("chinese comments produce chinese reply instructions", () => {
const instruction = chatReplyLanguageInstruction("请解释这段代码的作用");
assert.match(instruction, /Reply in Chinese/);
});
test("english comments produce english reply instructions", () => {
const instruction = chatReplyLanguageInstruction("What does this PR change?");
assert.match(instruction, /Reply in English/);
});
test("mixed comments follow the presence of han script", () => {
assert.match(chatReplyLanguageInstruction("这个 function 是干嘛的"), /Chinese/);
});
test("requester context derives actor categories deterministically", () => {
assert.deepEqual(
buildChatRequesterContext({
commenterLogin: "alice",
pullRequestAuthorLogin: "alice",
repositoryPermission: "read"
}),
{
login: "alice",
isPullRequestAuthor: true,
repositoryPermission: "read",
actorType: "repository_reader"
}
);
assert.deepEqual(
buildChatRequesterContext({
commenterLogin: "bob",
pullRequestAuthorLogin: "alice",
repositoryPermission: "none"
}),
{
login: "bob",
isPullRequestAuthor: false,
repositoryPermission: "none",
actorType: "outside_contributor"
}
);
});
test("tool budget instruction forbids asking the user to continue", () => {
const instruction = chatToolBudgetInstruction();
assert.match(instruction, /Do not ask the user whether to continue/);
});
+21
View File
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import { containsBotMention } from "../src/chat/processor.js";
test("bot mention detection accepts configured aliases", () => {
assert.equal(containsBotMention("@bot help me", "ghbot"), true);
assert.equal(containsBotMention("@ghbot please review", "ghbot"), true);
assert.equal(containsBotMention("@ghbot[bot] ping", "ghbot[bot]"), true);
});
test("partial usernames and ordinary text never trigger the bot", () => {
assert.equal(containsBotMention("email me at user@botmail.com", "ghbot"), false);
assert.equal(containsBotMention("the @botanist knows", "ghbot"), false);
assert.equal(containsBotMention("no mention here", "ghbot"), false);
assert.equal(containsBotMention("@anotherbot hi", "ghbot"), false);
});
test("mention detection is case-insensitive", () => {
assert.equal(containsBotMention("@BOT hello", "ghbot"), true);
assert.equal(containsBotMention("@GHBOT[BOT] hello", "ghbot[bot]"), true);
});
+61 -37
View File
@@ -13,42 +13,48 @@ import {
} from "../src/chat/processor.js";
test("PR chat receives host-verified requester role context", () => {
assert.deepEqual(buildChatRequesterContext({
commenterLogin: "maintainer",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "admin"
}), {
login: "maintainer",
isPullRequestAuthor: false,
repositoryPermission: "admin",
actorType: "repository_admin"
});
assert.deepEqual(
buildChatRequesterContext({
commenterLogin: "maintainer",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "admin"
}),
{
login: "maintainer",
isPullRequestAuthor: false,
repositoryPermission: "admin",
actorType: "repository_admin"
}
);
assert.deepEqual(buildChatRequesterContext({
commenterLogin: "Contributor",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "none"
}), {
login: "Contributor",
isPullRequestAuthor: true,
repositoryPermission: "none",
actorType: "outside_pull_request_author"
});
assert.deepEqual(
buildChatRequesterContext({
commenterLogin: "Contributor",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "none"
}),
{
login: "Contributor",
isPullRequestAuthor: true,
repositoryPermission: "none",
actorType: "outside_pull_request_author"
}
);
assert.equal(buildChatRequesterContext({
commenterLogin: "visitor",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "none"
}).actorType, "outside_contributor");
assert.equal(
buildChatRequesterContext({
commenterLogin: "visitor",
pullRequestAuthorLogin: "contributor",
repositoryPermission: "none"
}).actorType,
"outside_contributor"
);
});
test("PR chat replies in the language of the latest user comment", () => {
assert.match(chatReplyLanguageInstruction("@bot Introduce it"), /^Reply in English\./);
assert.match(chatReplyLanguageInstruction("@bot 请介绍一下这个 PR"), /^Reply in Chinese\./);
assert.match(
chatReplyLanguageInstruction("@bot 请 review this PR"),
/^Reply in Chinese\./
);
assert.match(chatReplyLanguageInstruction("@bot 请 review this PR"), /^Reply in Chinese\./);
});
test("PR chat must finish within its tool budget without asking to continue", () => {
@@ -58,13 +64,19 @@ test("PR chat must finish within its tool budget without asking to continue", ()
test("PR chat recognizes @bot and the configured bot login", () => {
assert.equal(containsBotMention("@bot can this merge?", "github-actions[bot]"), true);
assert.equal(containsBotMention("Could @github-actions explain this?", "github-actions[bot]"), true);
assert.equal(
containsBotMention("Could @github-actions explain this?", "github-actions[bot]"),
true
);
assert.equal(containsBotMention("Ping @github-actions[bot]", "github-actions[bot]"), true);
});
test("PR chat does not trigger on partial usernames or ordinary text", () => {
assert.equal(containsBotMention("@botany please check", "github-actions[bot]"), false);
assert.equal(containsBotMention("This mentions bot without an at sign", "github-actions[bot]"), false);
assert.equal(
containsBotMention("This mentions bot without an at sign", "github-actions[bot]"),
false
);
});
test("only collaborators with write access can invoke the full repository agent", () => {
@@ -100,16 +112,28 @@ test("PR chat snapshot excludes repository instructions, secrets, git data, and
fs.writeFile(path.join(source, "opencode.json"), "{}"),
fs.writeFile(path.join(source, ".goosehints"), "untrusted hints"),
fs.writeFile(path.join(source, "src", "index.ts"), "export const safe = true;\n"),
fs.writeFile(path.join(source, "scripts", "check.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }),
fs.writeFile(path.join(source, "scripts", "check.sh"), "#!/bin/sh\nexit 0\n", {
mode: 0o755
}),
fs.symlink(path.join(source, ".env"), path.join(source, "secret-link"))
]);
snapshot = await createRepositorySnapshot(source);
assert.equal(await fs.readFile(path.join(snapshot, "src", "index.ts"), "utf8"), "export const safe = true;\n");
assert.equal((await fs.stat(snapshot)).mode & 0o777, 0o777);
assert.equal((await fs.stat(path.join(snapshot, "src"))).mode & 0o777, 0o777);
assert.equal((await fs.stat(path.join(snapshot, "src", "index.ts"))).mode & 0o777, 0o666);
assert.equal((await fs.stat(path.join(snapshot, "scripts", "check.sh"))).mode & 0o777, 0o777);
assert.equal(
await fs.readFile(path.join(snapshot, "src", "index.ts"), "utf8"),
"export const safe = true;\n"
);
// Windows collapses chmod to read/write bits; the exact container contract
// (dirs 0o777, files 0o666/0o777) is only assertable on POSIX.
if (process.platform === "win32") {
assert.equal((await fs.stat(snapshot)).mode & 0o222, 0o222);
assert.equal((await fs.stat(path.join(snapshot, "src"))).mode & 0o222, 0o222);
} else {
assert.equal((await fs.stat(snapshot)).mode & 0o777, 0o777);
assert.equal((await fs.stat(path.join(snapshot, "src"))).mode & 0o777, 0o777);
assert.equal((await fs.stat(path.join(snapshot, "src", "index.ts"))).mode & 0o777, 0o666);
assert.equal((await fs.stat(path.join(snapshot, "scripts", "check.sh"))).mode & 0o777, 0o777);
}
for (const excluded of [
".git",
".goose",
+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatCommandAckMessage } from "../src/github/commandFeedback.js";
test("recheck ack names the requester and sets expectations", () => {
const message = formatCommandAckMessage("alice", "ghbot bot", "/recheck");
assert.match(message, /@alice/);
assert.match(message, /`\/recheck`/);
assert.match(message, /running now/);
});
test("conflict ack states the time budget and push guard", () => {
const message = formatCommandAckMessage("bob", "ghbot bot", "/conflict");
assert.match(message, /45 minutes/);
assert.match(message, /nothing is pushed unless every guard passes/);
});
+10
View File
@@ -0,0 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatPermissionDeniedMessage } from "../src/github/commandFeedback.js";
test("permission denied message names the commenter, command, and remedy", () => {
const message = formatPermissionDeniedMessage("alice", "/recheck");
assert.match(message, /@alice/);
assert.match(message, /`\/recheck`/);
assert.match(message, /write.*maintain.*admin|maintainer/i);
});
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import path from "node:path";
import test from "node:test";
function loadConfigWith(overrides: Record<string, string | undefined>) {
const env = { ...process.env };
for (const [key, value] of Object.entries(overrides)) {
if (value === undefined) {
delete env[key];
} else {
env[key] = value;
}
}
return spawnSync(process.execPath, ["--import", "tsx", "--eval", "import('./src/config.ts')"], {
cwd: path.resolve(process.cwd()),
env,
encoding: "utf8"
});
}
test("config rejects enabled webhook without a secret", () => {
const result = loadConfigWith({ WEBHOOK_ENABLED: "true", WEBHOOK_SECRET: "" });
assert.notEqual(result.status, 0);
assert.match(`${result.stdout}${result.stderr}`, /WEBHOOK_SECRET/);
});
test("config rejects partially configured R2 settings", () => {
const result = loadConfigWith({
WEBHOOK_ENABLED: "false",
R2_ENDPOINT: "https://example.r2.cloudflarestorage.com",
R2_BUCKET_NAME: "bucket",
R2_ACCESS_KEY_ID: "",
R2_SECRET_ACCESS_KEY: ""
});
assert.notEqual(result.status, 0);
assert.match(`${result.stdout}${result.stderr}`, /R2_ENDPOINT/);
});
test("config defaults the provider base URL explicitly", () => {
const result = loadConfigWith({
WEBHOOK_ENABLED: "false",
GOOSE_BASE_URL: ""
});
assert.equal(result.status, 0, result.stderr);
});
+51
View File
@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
parseFinalConfirmation,
describeConflictResolutionFailure
} from "../src/review/conflictResolver.js";
test("final confirmation parses a clean JSON body", () => {
const parsed = parseFinalConfirmation(
JSON.stringify({ safeToCommit: true, summary: "ok", concerns: [] })
);
assert.equal(parsed.safeToCommit, true);
assert.deepEqual(parsed.concerns, []);
});
test("final confirmation tolerates surrounding prose around the JSON", () => {
const parsed = parseFinalConfirmation(
`Here is my assessment:\n${JSON.stringify({
safeToCommit: false,
summary: "unsafe",
concerns: ["a", "b"]
})}\nDone.`
);
assert.equal(parsed.safeToCommit, false);
assert.deepEqual(parsed.concerns, ["a", "b"]);
});
test("final confirmation rejects structurally invalid output", () => {
assert.throws(() => parseFinalConfirmation("no json here"), /did not return the required JSON/);
assert.throws(
() => parseFinalConfirmation(JSON.stringify({ safeToCommit: "yes" })),
/did not return the required JSON/
);
});
test("failure descriptions are actionable and never expose raw command output", () => {
const timeout = describeConflictResolutionFailure(
new Error("initial goose conflict-editing pass timed out.")
);
assert.match(timeout, /No commit was pushed/);
const identity = describeConflictResolutionFailure(new Error("committer identity unknown"));
assert.match(identity, /committer identity/);
const push = describeConflictResolutionFailure(new Error("! [rejected] ... (stale info)"));
assert.match(push, /force lease rejected|Run \/conflict again/);
const generic = describeConflictResolutionFailure(new Error("something odd"));
assert.match(generic, /could not safely complete/);
const validation = describeConflictResolutionFailure(
new Error("Validation command failed after goose correction: exit 1")
);
assert.match(validation, /validation or final safety confirmation rejected/);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { acquireConflictLock } from "../src/review/conflictResolver.js";
test("conflict lock rejects overlapping runs for the same pull request", async () => {
const release = await acquireConflictLock("acme/demo#7");
await assert.rejects(() => acquireConflictLock("acme/demo#7"), /already active/);
release();
const releaseAgain = await acquireConflictLock("acme/demo#7");
releaseAgain();
});
test("conflict lock allows concurrent runs for different pull requests", async () => {
const first = await acquireConflictLock("acme/demo#8");
const second = await acquireConflictLock("acme/demo#9");
first();
second();
});
+29
View File
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
formatValidationLogOutput,
formatValidationResult
} from "../src/review/conflictResolver.js";
test("validation log output keeps the useful tail within bounds", () => {
const longOutput = "x".repeat(30_000) + "\nfinal error line";
const formatted = formatValidationLogOutput(longOutput);
assert.ok(formatted.length <= 12_100, `length ${formatted.length}`);
assert.match(formatted, /truncated \d+ leading characters/);
assert.match(formatted, /final error line/);
});
test("validation log output strips ANSI escapes and normalizes newlines", () => {
const formatted = formatValidationLogOutput("error\r\nline2");
assert.equal(formatted, "error\nline2");
});
test("validation result redacts credentials before prompt or log exposure", () => {
const formatted = formatValidationResult("npm test", {
code: 1,
stdout: "",
stderr: "fatal: https://user:ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456@github.com/x"
});
assert.equal(formatted.includes("ghp_"), false);
assert.match(formatted, /REDACTED|Exit code: 1/);
});
+115 -79
View File
@@ -32,13 +32,19 @@ const eligible = {
test("only a passing conflicted writable current head is eligible", () => {
assert.equal(canAutoResolveConflicts(eligible), true);
assert.equal(canAutoResolveConflicts({ ...eligible, reviewPassed: false }), false);
assert.equal(canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }), false);
assert.equal(
canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }),
false
);
assert.equal(canAutoResolveConflicts({ ...eligible, headRepository: "contributor/fork" }), false);
assert.equal(canAutoResolveConflicts({
...eligible,
headRepository: "contributor/fork",
maintainerCanModify: true
}), true);
assert.equal(
canAutoResolveConflicts({
...eligible,
headRepository: "contributor/fork",
maintainerCanModify: true
}),
true
);
assert.equal(canAutoResolveConflicts({ ...eligible, currentHeadSha: "new-head" }), false);
assert.equal(canAutoResolveConflicts({ ...eligible, enabled: false }), false);
});
@@ -137,26 +143,38 @@ test("validation failure logs are bounded, readable, and keep the useful tail",
});
test("validation infrastructure failures are not sent to the code-repair agent", () => {
assert.equal(isValidationInfrastructureFailure({
code: 1,
stdout: "",
stderr: "fatal: detected dubious ownership in repository at '/workspace'"
}), true);
assert.equal(isValidationInfrastructureFailure({
code: 125,
stdout: "",
stderr: "docker failed before the command started"
}), true);
assert.equal(isValidationInfrastructureFailure({
code: 1,
stdout: "",
stderr: "permission denied while trying to connect to the Docker API at unix:///docker.sock"
}), true);
assert.equal(isValidationInfrastructureFailure({
code: 1,
stdout: "AssertionError: expected 2 but received 1",
stderr: ""
}), false);
assert.equal(
isValidationInfrastructureFailure({
code: 1,
stdout: "",
stderr: "fatal: detected dubious ownership in repository at '/workspace'"
}),
true
);
assert.equal(
isValidationInfrastructureFailure({
code: 125,
stdout: "",
stderr: "docker failed before the command started"
}),
true
);
assert.equal(
isValidationInfrastructureFailure({
code: 1,
stdout: "",
stderr: "permission denied while trying to connect to the Docker API at unix:///docker.sock"
}),
true
);
assert.equal(
isValidationInfrastructureFailure({
code: 1,
stdout: "AssertionError: expected 2 but received 1",
stderr: ""
}),
false
);
});
test("initial conflict prompt leaves full validation to the isolated host pass", () => {
@@ -173,66 +191,84 @@ test("initial conflict prompt leaves full validation to the isolated host pass",
});
test("diff-check whitespace diagnostics are repaired without another agent run", () => {
const diagnostics = parseDiffCheckWhitespaceDiagnostics([
"src/app.js:2: trailing whitespace.",
"+const value = true; ",
"src/app.js:3: space before tab in indent.",
"+ \treturn value;",
"src/app.js:4: leftover conflict marker."
].join("\n"));
const diagnostics = parseDiffCheckWhitespaceDiagnostics(
[
"src/app.js:2: trailing whitespace.",
"+const value = true; ",
"src/app.js:3: space before tab in indent.",
"+ \treturn value;",
"src/app.js:4: leftover conflict marker."
].join("\n")
);
assert.deepEqual(diagnostics, [
{ file: "src/app.js", line: 2, kind: "trailing-whitespace" },
{ file: "src/app.js", line: 3, kind: "space-before-tab" }
]);
assert.equal(
repairDiffCheckContent("function check() {\nconst value = true; \n \treturn value;\n}\n", diagnostics),
repairDiffCheckContent(
"function check() {\nconst value = true; \n \treturn value;\n}\n",
diagnostics
),
"function check() {\nconst value = true;\n\treturn value;\n}\n"
);
});
test("external fork conflict pushes use a head-SHA force lease", () => {
assert.deepEqual(buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "contributor/forumlify",
headBranch: "fix/conflicts",
expectedHeadSha: "a".repeat(40)
}), [
"push",
`--force-with-lease=refs/heads/fix/conflicts:${"a".repeat(40)}`,
"https://github.com/contributor/forumlify.git",
"HEAD:refs/heads/fix/conflicts"
]);
assert.deepEqual(buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "forumlify/public",
headBranch: "fix/conflicts",
expectedHeadSha: "b".repeat(40)
}), ["push", "origin", "HEAD:refs/heads/fix/conflicts"]);
assert.throws(() => buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "contributor/forumlify",
headBranch: "bad:branch",
expectedHeadSha: "c".repeat(40)
}), /Unsafe PR head branch/);
assert.deepEqual(
buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "contributor/forumlify",
headBranch: "fix/conflicts",
expectedHeadSha: "a".repeat(40)
}),
[
"push",
`--force-with-lease=refs/heads/fix/conflicts:${"a".repeat(40)}`,
"https://github.com/contributor/forumlify.git",
"HEAD:refs/heads/fix/conflicts"
]
);
assert.deepEqual(
buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "forumlify/public",
headBranch: "fix/conflicts",
expectedHeadSha: "b".repeat(40)
}),
["push", "origin", "HEAD:refs/heads/fix/conflicts"]
);
assert.throws(
() =>
buildConflictPushArgs({
baseRepository: "forumlify/public",
headRepository: "contributor/forumlify",
headBranch: "bad:branch",
expectedHeadSha: "c".repeat(40)
}),
/Unsafe PR head branch/
);
});
test("conflict commits use the GitHub bot user id for avatar attribution", async () => {
const requestedUsernames: string[] = [];
const identity = await resolveBotCommitIdentity({
rest: {
users: {
async getByUsername({ username }: { username: string }) {
requestedUsernames.push(username);
return {
data: {
id: 316580078,
login: "forumlify[bot]"
}
};
const identity = await resolveBotCommitIdentity(
{
rest: {
users: {
async getByUsername({ username }: { username: string }) {
requestedUsernames.push(username);
return {
data: {
id: 316580078,
login: "forumlify[bot]"
}
};
}
}
}
}
} as never, "@forumlify[bot]");
} as never,
"@forumlify[bot]"
);
assert.deepEqual(requestedUsernames, ["forumlify[bot]"]);
assert.deepEqual(identity, {
@@ -252,10 +288,11 @@ test("snapshot inventory detects related file additions, changes, and deletions"
["caller.ts", { hash: "same", size: 20 }],
["compatibility.test.ts", { hash: "new", size: 40 }]
]);
assert.deepEqual(
diffSnapshotInventories(before, after),
["compatibility.test.ts", "conflicted.ts", "removed.test.ts"]
);
assert.deepEqual(diffSnapshotInventories(before, after), [
"compatibility.test.ts",
"conflicted.ts",
"removed.test.ts"
]);
});
test("validation repair prompt leaves the authoritative rerun to the isolated host", () => {
@@ -273,11 +310,10 @@ test("validation repair prompt leaves the authoritative rerun to the isolated ho
test("final confirmation parser accepts a JSON object surrounded by prose", () => {
assert.deepEqual(
parseFinalConfirmation('Result:\n{"safeToCommit":true,"summary":"validated","concerns":[]}\nDone.'),
parseFinalConfirmation(
'Result:\n{"safeToCommit":true,"summary":"validated","concerns":[]}\nDone.'
),
{ safeToCommit: true, summary: "validated", concerns: [] }
);
assert.throws(
() => parseFinalConfirmation("safe to commit"),
/required JSON object/
);
assert.throws(() => parseFinalConfirmation("safe to commit"), /required JSON object/);
});
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import test from "node:test";
import { collectValidNewLines, toDiffPosition } from "../src/github/diff.js";
function file(patch?: string) {
return { filename: "src/a.ts", patch, status: "modified", additions: 2, deletions: 1 };
}
const samplePatch = [
"@@ -1,3 +1,4 @@",
" context line",
"-removed line",
"+added line one",
"+added line two",
" more context"
].join("\n");
test("collectValidNewLines tracks added lines per file", () => {
const valid = collectValidNewLines([file(samplePatch)]);
assert.equal(valid.has("src/a.ts:2"), true);
assert.equal(valid.has("src/a.ts:3"), true);
assert.equal(valid.has("src/a.ts:1"), false);
assert.equal(valid.has("src/a.ts:4"), false);
});
test("files without patches contribute no valid lines", () => {
const valid = collectValidNewLines([file(undefined)]);
assert.equal(valid.size, 0);
});
test("toDiffPosition maps valid new lines and rejects stale ones", () => {
const valid = collectValidNewLines([file(samplePatch)]);
assert.deepEqual(toDiffPosition(file(), 2, valid), {
path: "src/a.ts",
line: 2,
side: "RIGHT"
});
assert.equal(toDiffPosition(file(), 99, valid), null);
});
test("hunk headers with ranges are parsed correctly", () => {
const valid = collectValidNewLines([file("@@ -10,5 +20,3 @@\n+first\n+second\n+third")]);
assert.equal(valid.has("src/a.ts:20"), true);
assert.equal(valid.has("src/a.ts:22"), true);
assert.equal(valid.has("src/a.ts:23"), false);
});
+79
View File
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildGooseAgentEnvironment,
extractGooseFinalText,
redactProcessArgs
} from "../src/ai/gooseCli.js";
import { config } from "../src/config.js";
const originalEffort = config.gooseThinkingEffort;
test("agent environment isolates home dirs and never carries real credentials", () => {
const env = buildGooseAgentEnvironment({ apiToken: "one-run-token", proxyPort: 45678 });
assert.equal(env.OPENAI_API_KEY, "one-run-token");
assert.equal(env.OPENAI_BASE_URL, "http://host.docker.internal:45678/v1");
assert.equal(env.HOME, "/tmp/goose-home");
assert.equal(env.GOOSE_DISABLE_KEYRING, "true");
assert.equal(env.GOOSE_TELEMETRY_ENABLED, "false");
assert.equal(env.GOOSE_MODE, "auto");
});
test("thinking effort is forwarded when configured", () => {
(config as { gooseThinkingEffort: string | undefined }).gooseThinkingEffort = "high";
const env = buildGooseAgentEnvironment({ apiToken: "t", proxyPort: 1 });
assert.equal(env.GOOSE_THINKING_EFFORT, "high");
(config as { gooseThinkingEffort: string | undefined }).gooseThinkingEffort = originalEffort;
});
test("extractGooseFinalText returns the last assistant text block", () => {
const stdout = JSON.stringify({
messages: [
{ role: "user", content: [{ type: "text", text: "hi" }] },
{ role: "assistant", content: [{ type: "text", text: "first" }] },
{ role: "assistant", content: [{ type: "text", text: "final answer" }] }
]
});
assert.equal(extractGooseFinalText(stdout), "final answer");
});
test("extractGooseFinalText strips a surrounding markdown fence", () => {
const stdout = JSON.stringify({
messages: [
{
role: "assistant",
content: [{ type: "text", text: '```json\n{"ok":true}\n```' }]
}
]
});
assert.equal(extractGooseFinalText(stdout), '{"ok":true}');
});
test("extractGooseFinalText rejects invalid or empty outputs", () => {
assert.throws(() => extractGooseFinalText("not json"), /valid JSON/);
assert.throws(
() =>
extractGooseFinalText(
JSON.stringify({ messages: [{ role: "assistant", content: [{ type: "text", text: "" }] }] })
),
/final assistant text/
);
});
test("redactProcessArgs hides the goose prompt body", () => {
const args = ["run", "--text", "secret prompt content"];
const redacted = redactProcessArgs(args, "goose process");
assert.equal(redacted[2], "[goose prompt: 21 chars]");
assert.equal(redacted[0], "run");
});
test("redactProcessArgs hides the validation command via explicit sentinel", () => {
const args = ["sh", "-lc", "bootstrap", "ghbot-validation", "npm test && cat secrets"];
const redacted = redactProcessArgs(args, "isolated repository validation", {
redactLastAsValidationCommand: true
});
assert.equal(redacted.at(-1), "[validation command: 23 chars]");
// Without the sentinel the label alone must not trigger redaction (D-09).
const untouched = redactProcessArgs(args, "isolated repository validation");
assert.equal(untouched.at(-1), "npm test && cat secrets");
});
+24 -9
View File
@@ -18,7 +18,9 @@ test("goose agent mounts the workflow binary read-only and keeps a visible insta
prompt: "introduce this pull request"
});
assert.ok(args.includes("type=bind,source=/tmp/goose/bin/goose,target=/usr/local/bin/goose,readonly"));
assert.ok(
args.includes("type=bind,source=/tmp/goose/bin/goose,target=/usr/local/bin/goose,readonly")
);
const bootstrap = args[args.indexOf("-lc") + 1];
assert.match(bootstrap!, /command -v goose/);
assert.match(bootstrap!, /cat \/tmp\/goose-install\.log >&2/);
@@ -45,17 +47,27 @@ test("isolated validation receives the repository but no model or GitHub credent
assert.match(bootstrap!, /exec sh -lc "\$1"/);
assert.equal(args.at(-2), "ghbot-validation");
assert.equal(args.at(-1), "npm ci && npm test");
assert.equal(args.some((arg) => /OPENAI|GITHUB|GHBOT_GIT_TOKEN/.test(arg)), false);
assert.equal(
args.some((arg) => /OPENAI|GITHUB|GHBOT_GIT_TOKEN/.test(arg)),
false
);
});
test("process logging redacts only prompts and trusted validation commands", () => {
assert.deepEqual(redactProcessArgs(["run", "--rm"], "workspace cleanup"), ["run", "--rm"]);
assert.deepEqual(redactProcessArgs(["run", "--text", "secret prompt"], "goose agent container"), [
"run",
"--text",
"[goose prompt: 13 chars]"
]);
assert.deepEqual(
redactProcessArgs(["run", "--text", "secret prompt"], "goose agent container"),
["run", "--text", "[goose prompt: 13 chars]"]
);
assert.deepEqual(
redactProcessArgs(["run", "sh", "-lc", "npm ci && npm test"], "isolated repository validation"),
redactProcessArgs(
["run", "sh", "-lc", "npm ci && npm test"],
"isolated repository validation",
{
redactLastAsValidationCommand: true
}
),
["run", "sh", "-lc", "[validation command: 18 chars]"]
);
});
@@ -68,7 +80,10 @@ test("goose agent can fall back to installing inside the container", () => {
prompt: "inspect this pull request"
});
assert.equal(args.some((arg) => arg.includes("target=/usr/local/bin/goose")), false);
assert.equal(
args.some((arg) => arg.includes("target=/usr/local/bin/goose")),
false
);
assert.match(args[args.indexOf("-lc") + 1]!, /GOOSE_VERSION="v1\.46\.0"/);
});
@@ -119,7 +134,7 @@ test("goose output strips a surrounding JSON markdown fence", () => {
messages: [
{
role: "assistant",
content: [{ type: "text", text: "```json\n{\"ok\":true}\n```" }]
content: [{ type: "text", text: '```json\n{"ok":true}\n```' }]
}
]
});
+14
View File
@@ -0,0 +1,14 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createEventLogger } from "../src/logger.js";
test("event logger child bindings include owner/repo/eventName", () => {
const child = createEventLogger({
eventName: "issue_comment",
owner: "acme",
repo: "demo",
pullNumber: 7
});
assert.equal(typeof child.info, "function");
assert.equal(typeof child.error, "function");
});
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
normalizeObjectPrefix,
pullRequestReviewHistoryObjectKey,
pullRequestReviewObjectKey,
repositoryKnowledgeObjectKey
} from "../src/storage/cacheStore.js";
test("object keys are scoped by repository id, pull number, and optional prefix", () => {
assert.equal(repositoryKnowledgeObjectKey("123"), "repositories/123/knowledge/repository.md");
assert.equal(pullRequestReviewObjectKey("123", 7), "repositories/123/pulls/7/latest.json");
assert.equal(
pullRequestReviewObjectKey("123", 7, "forum-1"),
"forum-1/repositories/123/pulls/7/latest.json"
);
});
test("history keys pin the reviewed head sha in lowercase hex form", () => {
const sha = "A".repeat(40).toLowerCase();
assert.equal(
pullRequestReviewHistoryObjectKey("123", 9, sha.toUpperCase()),
`repositories/123/pulls/9/reviews/${sha}.json`
);
assert.throws(() => pullRequestReviewHistoryObjectKey("123", 9, "short"), /40-64 hexadecimal/);
assert.throws(
() => pullRequestReviewHistoryObjectKey("123", -1, sha),
/Pull request number must be a positive integer/
);
});
test("normalizeObjectPrefix validates each slash-separated segment", () => {
assert.equal(normalizeObjectPrefix(undefined), "");
assert.equal(normalizeObjectPrefix(""), "");
assert.equal(normalizeObjectPrefix("/a/b/"), "a/b");
assert.throws(() => normalizeObjectPrefix("bad/../segment"), /safe slash-separated/);
assert.throws(() => normalizeObjectPrefix(".hidden"), /safe slash-separated/);
});
+22 -18
View File
@@ -51,7 +51,9 @@ test("persistent cache restores and saves validated repository and PR state", as
const objects = new Map<string, Buffer>();
const storage: PersistentObjectStore = {
download: async (key) => objects.get(key),
upload: async ({ key, body }) => { objects.set(key, Buffer.from(body)); }
upload: async ({ key, body }) => {
objects.set(key, Buffer.from(body));
}
};
try {
@@ -112,7 +114,9 @@ test("persistent cache does not overwrite newer repository knowledge when this r
]);
const storage: PersistentObjectStore = {
download: async (key) => objects.get(key),
upload: async ({ key, body }) => { objects.set(key, Buffer.from(body)); }
upload: async ({ key, body }) => {
objects.set(key, Buffer.from(body));
}
};
try {
@@ -146,12 +150,9 @@ test("persistent cache does not overwrite newer repository knowledge when this r
"# Newer knowledge\n\nKeep the Lite branch facts.\n"
);
assert.ok(objects.has(pullRequestReviewObjectKey("12345", 17, "forum-114614")));
assert.ok(objects.has(pullRequestReviewHistoryObjectKey(
"12345",
17,
"b".repeat(40),
"forum-114614"
)));
assert.ok(
objects.has(pullRequestReviewHistoryObjectKey("12345", 17, "b".repeat(40), "forum-114614"))
);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
@@ -161,16 +162,19 @@ test("persistent cache rejects a review object belonging to another repository",
const root = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-r2-invalid-"));
const key = pullRequestReviewObjectKey("12345", 17);
const storage: PersistentObjectStore = {
download: async (requestedKey) => requestedKey === key
? Buffer.from(JSON.stringify({
version: 1,
repository: "attacker/fork",
pullNumber: 17,
headSha: "b".repeat(40),
reviewedAt: new Date().toISOString(),
decision
}))
: undefined,
download: async (requestedKey) =>
requestedKey === key
? Buffer.from(
JSON.stringify({
version: 1,
repository: "attacker/fork",
pullNumber: 17,
headSha: "b".repeat(40),
reviewedAt: new Date().toISOString(),
decision
})
)
: undefined,
upload: async () => undefined
};
try {
+26
View File
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isR2Configured, normalizeEndpoint } from "../src/storage/r2.js";
test("normalizeEndpoint accepts credential-free https URLs and trims trailing slashes", () => {
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com"),
"https://account.r2.cloudflarestorage.com"
);
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com/"),
"https://account.r2.cloudflarestorage.com"
);
});
test("normalizeEndpoint rejects non-https, credentialed, or decorated URLs", () => {
assert.throws(() => normalizeEndpoint("http://insecure.example"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("https://user:pass@host"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("https://host/path?query=1"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("not a url"), /valid HTTPS URL/);
});
test("isR2Configured reflects ambient configuration without throwing", () => {
// The test environment has no R2_* env vars set; the helper must not throw.
assert.equal(typeof isR2Configured(), "boolean");
});
+15 -5
View File
@@ -16,11 +16,21 @@ test("repository knowledge round trips through the agent scratch file", async ()
try {
await writeKnowledgeScratch(root, "# Architecture\n\nUse npm test.\n");
assert.equal(await readKnowledgeScratch(root), "# Architecture\n\nUse npm test.\n");
assert.equal((await fs.stat(path.join(root, ".ghbot"))).mode & 0o777, 0o777);
assert.equal(
(await fs.stat(path.join(root, ".ghbot", "repository-knowledge.md"))).mode & 0o777,
0o666
);
// Windows maps every chmod to the read/write bits (no execute bit), so the
// container-facing 0o777/0o666 contract can only be asserted on POSIX.
if (process.platform === "win32") {
assert.equal((await fs.stat(path.join(root, ".ghbot"))).mode & 0o222, 0o222);
assert.equal(
(await fs.stat(path.join(root, ".ghbot", "repository-knowledge.md"))).mode & 0o222,
0o222
);
} else {
assert.equal((await fs.stat(path.join(root, ".ghbot"))).mode & 0o777, 0o777);
assert.equal(
(await fs.stat(path.join(root, ".ghbot", "repository-knowledge.md"))).mode & 0o777,
0o666
);
}
} finally {
await fs.rm(root, { recursive: true, force: true });
}
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import { requiredChecksAreGreen } from "../src/github/checks.js";
type CheckRun = {
name: string;
status: string;
conclusion?: string | null;
};
function octokitWith(params: {
checkRuns: CheckRun[];
combinedStatus?: { state: string; statuses: unknown[] };
}): Octokit {
return {
rest: {
checks: {
listForRef: async () => ({
data: { check_runs: params.checkRuns }
})
},
repos: {
getCombinedStatusForRef: async () => ({
data: params.combinedStatus ?? { state: "success", statuses: [] }
})
}
}
} as unknown as Octokit;
}
test("all green checks and statuses pass", async () => {
const octokit = octokitWith({
checkRuns: [
{ name: "ci", status: "completed", conclusion: "success" },
{ name: "lint", status: "completed", conclusion: "neutral" },
{ name: "docs", status: "completed", conclusion: "skipped" }
]
});
const result = await requiredChecksAreGreen(octokit, { owner: "a", repo: "b", ref: "sha" });
assert.equal(result.ok, true);
});
test("pending or failed checks block the merge", async () => {
const pending = await requiredChecksAreGreen(
octokitWith({ checkRuns: [{ name: "ci", status: "in_progress" }] }),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(pending.ok, false);
assert.match(pending.reason ?? "", /in_progress\/pending/);
const failed = await requiredChecksAreGreen(
octokitWith({
checkRuns: [{ name: "ci", status: "completed", conclusion: "failure" }]
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(failed.ok, false);
assert.match(failed.reason ?? "", /failure/);
});
test("ghbot-owned check runs are ignored", async () => {
for (const ignoredName of ["ghbot review", "bot-review", "acme/ bot-review"]) {
const result = await requiredChecksAreGreen(
octokitWith({
checkRuns: [{ name: ignoredName, status: "completed", conclusion: "action_required" }]
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(result.ok, true, `${ignoredName} should be ignored`);
}
});
test("non-success commit statuses block when present", async () => {
const result = await requiredChecksAreGreen(
octokitWith({
checkRuns: [],
combinedStatus: { state: "failure", statuses: [{ state: "failure" }] }
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(result.ok, false);
assert.match(result.reason ?? "", /Commit status is failure/);
});
+110
View File
@@ -0,0 +1,110 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRetryableError, withRetry } from "../src/retry.js";
class HttpLikeError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
test("returns immediately when the first attempt succeeds", async () => {
let attempts = 0;
const result = await withRetry(
"probe.first",
async () => {
attempts += 1;
return "ok";
},
{ baseDelayMs: 1 }
);
assert.equal(result, "ok");
assert.equal(attempts, 1);
});
test("retries transient failures and eventually succeeds", async () => {
let attempts = 0;
const result = await withRetry(
"probe.transient",
async () => {
attempts += 1;
if (attempts < 3) {
throw new HttpLikeError(502, "bad gateway");
}
return "done";
},
{ baseDelayMs: 1 }
);
assert.equal(result, "done");
assert.equal(attempts, 3);
});
test("throws the last error after exhausting attempts", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.exhausted",
async () => {
attempts += 1;
throw new HttpLikeError(503, `boom ${attempts}`);
},
{ maxAttempts: 3, baseDelayMs: 1 }
),
/boom 3$/
);
assert.equal(attempts, 3);
});
test("4xx errors are not retried by default", async () => {
let attempts = 0;
await assert.rejects(
withRetry("probe.client-error", async () => {
attempts += 1;
throw new HttpLikeError(404, "not found");
})
);
assert.equal(attempts, 1);
});
test("429 rate limits are retried by default", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.rate-limit",
async () => {
attempts += 1;
throw new HttpLikeError(429, "slow down");
},
{ maxAttempts: 2, baseDelayMs: 1 }
)
);
assert.equal(attempts, 2);
});
test("network-shaped failures are retried", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.network",
async () => {
attempts += 1;
throw Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
},
{ maxAttempts: 2, baseDelayMs: 1 }
)
);
assert.equal(attempts, 2);
});
test("isRetryableError classifies statuses and codes explicitly", () => {
assert.equal(isRetryableError(new HttpLikeError(500, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(503, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(429, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(404, "nope")), false);
assert.equal(isRetryableError(new HttpLikeError(401, "denied")), false);
assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "ETIMEDOUT" })), true);
assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "EAI_AGAIN" })), true);
assert.equal(isRetryableError(new Error("plain")), false);
});
+19 -17
View File
@@ -3,24 +3,26 @@ import test from "node:test";
import { parseReviewCacheContent } from "../src/review/cache.js";
test("review cache parser accepts the structured review result", () => {
const parsed = parseReviewCacheContent(JSON.stringify({
version: 1,
repository: "forumlify/public",
pullNumber: 17,
headSha: "a".repeat(40),
reviewedAt: "2026-08-13T00:00:00.000Z",
decision: {
review: [],
change: [],
comment: "Looks good.",
result: {
canMerge: true,
summary: "Safe to merge.",
shouldClosePullRequest: false,
closeReason: ""
const parsed = parseReviewCacheContent(
JSON.stringify({
version: 1,
repository: "forumlify/public",
pullNumber: 17,
headSha: "a".repeat(40),
reviewedAt: "2026-08-13T00:00:00.000Z",
decision: {
review: [],
change: [],
comment: "Looks good.",
result: {
canMerge: true,
summary: "Safe to merge.",
shouldClosePullRequest: false,
closeReason: ""
}
}
}
}));
})
);
assert.equal(parsed.repository, "forumlify/public");
assert.equal(parsed.pullNumber, 17);
assert.equal(parsed.decision.result.canMerge, true);
+79
View File
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatReviewBody, formatFindingReviewBody } from "../src/review/format.js";
import type { ReviewDecision, ReviewMode } from "../src/types.js";
import type { ReviewDisposition } from "../src/review/policy.js";
const mode: ReviewMode = "normal";
const passDisposition: ReviewDisposition = {
event: "APPROVE",
blocksMerge: false,
requiresAdminApproval: false,
outcome: "pass"
};
const blockDisposition: ReviewDisposition = {
event: "REQUEST_CHANGES",
blocksMerge: true,
requiresAdminApproval: false,
outcome: "block"
};
const adminDisposition: ReviewDisposition = {
event: "COMMENT",
blocksMerge: false,
requiresAdminApproval: true,
outcome: "pass"
};
function decision(overrides: Partial<ReviewDecision> = {}): ReviewDecision {
return {
review: [],
change: [],
comment: "Overall this looks fine.",
result: { canMerge: true, summary: "safe", shouldClosePullRequest: false, closeReason: "" },
...overrides
};
}
test("clean pass body shows the approve summary and merge guidance", () => {
const body = formatReviewBody(decision(), [], mode, passDisposition);
assert.match(body, /Final status: safe to merge/);
assert.match(body, /Model decision: safe to merge/);
assert.match(body, /Applied review policy/);
assert.match(body, /✅ \*\*Safe to merge\*\*/);
});
test("blocked body lists unposted findings and recheck hint", () => {
const withChange = decision({
change: [{ path: "a.ts", line: 1, title: "Fix it", body: "broken" }],
result: { ...decision().result, canMerge: false }
});
const body = formatReviewBody(
withChange,
[{ ...withChange.change[0]!, category: "change" as const }],
mode,
blockDisposition
);
assert.match(body, /Final status: changes requested/);
assert.match(body, /❌ \*\*Changes requested\*\*/);
assert.match(body, /<details>/);
assert.match(body, /could not be attached inline \(1\)/);
assert.match(body, /\/recheck/);
});
test("admin approval body states the waiting disposition", () => {
const body = formatReviewBody(decision(), [], mode, adminDisposition);
assert.match(body, /waiting for repository administrator approval/);
assert.match(body, /⏸️ \*\*Waiting for administrator approval\*\*/);
});
test("finding bodies carry the state marker and finding count", () => {
const withReview = decision({
review: [{ path: "b.ts", line: 2, title: "note", body: "nb" }]
});
const body = formatFindingReviewBody(withReview, "review", [], mode, passDisposition);
assert.match(body, /<!-- ghbot-review:v1/);
assert.match(body, /Findings: 1/);
});
+64
View File
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import test from "node:test";
import { normalizeReviewDecision } from "../src/review/normalize.js";
function finding(path: string, line: number) {
return { path, line, title: "t", body: "b" };
}
const baseResult = {
canMerge: true,
summary: "s",
shouldClosePullRequest: false,
closeReason: ""
};
test("keeps findings whose paths exist and lines are positive integers", () => {
const decision = {
review: [finding("src/a.ts", 3)],
change: [finding("src/b.ts", 1)],
comment: "c",
result: { ...baseResult }
};
const normalized = normalizeReviewDecision(decision, ["src/a.ts", "src/b.ts"]);
assert.deepEqual(normalized.decision.review, decision.review);
assert.deepEqual(normalized.decision.change, decision.change);
assert.deepEqual(normalized.warnings, []);
});
test("moves findings with unknown paths or bad lines into warnings", () => {
const decision = {
review: [finding("ghost.ts", 2), finding("src/a.ts", -1), finding("src/a.ts", 0)],
change: [],
comment: "c",
result: { ...baseResult }
};
const normalized = normalizeReviewDecision(decision, ["src/a.ts"]);
assert.equal(normalized.decision.review.length, 0);
assert.equal(normalized.warnings.length, 3);
assert.match(normalized.warnings[0] ?? "", /unknown file/);
assert.match(normalized.warnings[1] ?? "", /invalid line/);
});
test("a non-empty change list forces canMerge=false conservatively", () => {
const decision = {
review: [],
change: [finding("src/a.ts", 1)],
comment: "c",
result: { ...baseResult, canMerge: true }
};
const normalized = normalizeReviewDecision(decision, ["src/a.ts"]);
assert.equal(normalized.decision.result.canMerge, false);
});
test("shouldClosePullRequest=true forces a non-empty closeReason requirement warning-free pass", () => {
const decision = {
review: [],
change: [],
comment: "c",
result: { ...baseResult, shouldClosePullRequest: true, closeReason: "backdoor" }
};
const normalized = normalizeReviewDecision(decision, []);
assert.equal(normalized.decision.result.shouldClosePullRequest, true);
assert.equal(normalized.warnings.length, 0);
});
+45 -13
View File
@@ -94,14 +94,16 @@ test("review state markers round trip", () => {
...cleanDecision,
review: [{ path: "src/a.ts", line: 1, title: "Check", body: "Note" }]
});
assert.deepEqual(
parseReviewStateMarker(formatReviewStateMarker("strict", disposition, 1, 0)),
{ mode: "strict", outcome: "pass", requiresAdminApproval: false }
);
assert.deepEqual(
parseReviewExternalId(formatReviewExternalId("normal", disposition)),
{ mode: "normal", outcome: "pass", requiresAdminApproval: false }
);
assert.deepEqual(parseReviewStateMarker(formatReviewStateMarker("strict", disposition, 1, 0)), {
mode: "strict",
outcome: "pass",
requiresAdminApproval: false
});
assert.deepEqual(parseReviewExternalId(formatReviewExternalId("normal", disposition)), {
mode: "normal",
outcome: "pass",
requiresAdminApproval: false
});
assert.deepEqual(
parseReviewExternalId("ghbot-review:v1:mode=lenient:outcome=pass:requires-admin=false"),
{ mode: "normal", outcome: "pass", requiresAdminApproval: false }
@@ -134,11 +136,41 @@ test("only the latest decisive review per user can approve the current head", ()
assert.deepEqual(
approvedLoginsForHead(
[
{ id: 1, state: "APPROVED", commitId: "head", login: "alice", submittedAt: "2026-08-13T01:00:00Z" },
{ id: 2, state: "COMMENTED", commitId: "head", login: "alice", submittedAt: "2026-08-13T02:00:00Z" },
{ id: 3, state: "APPROVED", commitId: "old-head", login: "bob", submittedAt: "2026-08-13T03:00:00Z" },
{ id: 4, state: "APPROVED", commitId: "head", login: "carol", submittedAt: "2026-08-13T04:00:00Z" },
{ id: 5, state: "CHANGES_REQUESTED", commitId: "head", login: "carol", submittedAt: "2026-08-13T05:00:00Z" }
{
id: 1,
state: "APPROVED",
commitId: "head",
login: "alice",
submittedAt: "2026-08-13T01:00:00Z"
},
{
id: 2,
state: "COMMENTED",
commitId: "head",
login: "alice",
submittedAt: "2026-08-13T02:00:00Z"
},
{
id: 3,
state: "APPROVED",
commitId: "old-head",
login: "bob",
submittedAt: "2026-08-13T03:00:00Z"
},
{
id: 4,
state: "APPROVED",
commitId: "head",
login: "carol",
submittedAt: "2026-08-13T04:00:00Z"
},
{
id: 5,
state: "CHANGES_REQUESTED",
commitId: "head",
login: "carol",
submittedAt: "2026-08-13T05:00:00Z"
}
],
"head"
),
+66
View File
@@ -0,0 +1,66 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildReviewSubmissionPlan,
isConflictComment,
isRecheckComment,
formatSupersededReviewBody
} from "../src/review/processor.js";
import type { ReviewDecision } from "../src/types.js";
const cleanDecision: ReviewDecision = {
review: [],
change: [],
comment: "ok",
result: { canMerge: true, summary: "s", shouldClosePullRequest: false, closeReason: "" }
};
test("recheck and conflict commands match only exact bodies", () => {
assert.equal(isRecheckComment("/recheck"), true);
assert.equal(isRecheckComment(" /recheck "), true);
assert.equal(isRecheckComment("please /recheck now"), false);
assert.equal(isRecheckComment("/recheck extra"), false);
assert.equal(isConflictComment("/conflict"), true);
assert.equal(isConflictComment("/conflict?"), false);
});
test("submission plan emits change phase first, then review, then final", () => {
const decision: ReviewDecision = {
review: [{ path: "a.ts", line: 1, title: "r", body: "b" }],
change: [{ path: "b.ts", line: 2, title: "c", body: "b" }],
comment: "c",
result: { ...cleanDecision.result }
};
const approveDisposition = { event: "APPROVE" as const };
const plan = buildReviewSubmissionPlan(decision, approveDisposition);
assert.deepEqual(
plan.map((phase) => [phase.phase, phase.event]),
[
["change", "REQUEST_CHANGES"],
["review", "COMMENT"],
["final", "COMMENT"]
]
);
assert.equal(plan[0]?.findings.length, 1);
assert.equal(plan[1]?.findings.length, 1);
assert.equal(plan[2]?.findings.length, 0);
});
test("a clean decision submits a single final APPROVE review", () => {
const plan = buildReviewSubmissionPlan(cleanDecision, { event: "APPROVE" });
assert.equal(plan.length, 1);
assert.equal(plan[0]?.phase, "final");
assert.equal(plan[0]?.event, "APPROVE");
});
test("superseded review bodies keep the original state marker", () => {
const marker =
"<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=0 change=0 -->";
const body = formatSupersededReviewBody({
originalMarker: marker,
oldCommitId: "a".repeat(40),
currentCommitId: "b".repeat(40)
});
assert.ok(body.startsWith(marker));
assert.match(body, /Superseded automated review/);
});
+3 -5
View File
@@ -1,13 +1,11 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import {
beginCommitReviewProgress,
finishCommitReviewProgress
} from "../src/review/processor.js";
import { beginCommitReviewProgress, finishCommitReviewProgress } from "../src/review/processor.js";
const headSha = "1234567890abcdef1234567890abcdef12345678";
const reviewMarker = "<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=0 change=0 -->";
const reviewMarker =
"<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=0 change=0 -->";
test("new commit progress is created once and reused for the same head", async () => {
const comments: Array<{ id: number; body: string }> = [];
+39
View File
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import test from "node:test";
import { compactFilesForReview } from "../src/review/prompt.js";
function file(name: string, patch?: string) {
return { filename: name, patch, status: "modified", additions: 1, deletions: 0 };
}
test("patches within the budget pass through untouched", () => {
const files = [file("a.ts", "abc"), file("b.ts", "de")];
const result = compactFilesForReview(files, 10);
assert.deepEqual(
result.map((item) => item.patch),
["abc", "de"]
);
});
test("the last file is truncated when the budget runs out mid-list", () => {
const files = [file("a.ts", "abcdef"), file("b.ts", "ghijkl")];
const result = compactFilesForReview(files, 8);
assert.equal(result[0]?.patch, "abcdef");
assert.equal(result[1]?.patch, "gh\n[patch truncated]");
});
test("files after exhaustion lose their patch but keep metadata (D-10)", () => {
const files = [file("a.ts", "0123456789"), file("b.ts", "extra"), file("c.ts", "more")];
const result = compactFilesForReview(files, 5);
assert.equal(result[0]?.patch, "01234\n[patch truncated]");
assert.equal(result[1]?.patch, undefined);
assert.equal(result[2]?.patch, undefined);
assert.equal(result[2]?.filename, "c.ts");
});
test("empty patches are dropped (falsy) and never consume budget", () => {
const files = [file("a.ts", ""), file("b.ts", "xy")];
const result = compactFilesForReview(files, 5);
assert.equal(result[0]?.patch, undefined);
assert.equal(result[1]?.patch, "xy");
});
+85 -14
View File
@@ -8,11 +8,16 @@ import {
} from "../src/review/processor.js";
import type { ReviewDecision } from "../src/types.js";
const marker = "<!-- ghbot-review:v1 mode=normal outcome=block requires-admin=false review=1 change=1 -->";
const marker =
"<!-- ghbot-review:v1 mode=normal outcome=block requires-admin=false review=1 change=1 -->";
const decisionWithBothFindingKinds: ReviewDecision = {
review: [{ path: "src/review.ts", line: 12, title: "Clarify this branch", body: "This is non-blocking." }],
change: [{ path: "src/review.ts", line: 8, title: "Fix the null case", body: "This blocks merge." }],
review: [
{ path: "src/review.ts", line: 12, title: "Clarify this branch", body: "This is non-blocking." }
],
change: [
{ path: "src/review.ts", line: 8, title: "Fix the null case", body: "This blocks merge." }
],
comment: "The pull request needs one required fix and has one review note.",
result: {
canMerge: false,
@@ -28,7 +33,11 @@ test("review submission keeps change requests, review notes, and final comment s
});
assert.deepEqual(
phases.map(({ phase, event, findings }) => ({ phase, event, findings: findings.map((finding) => finding.category) })),
phases.map(({ phase, event, findings }) => ({
phase,
event,
findings: findings.map((finding) => finding.category)
})),
[
{ phase: "change", event: "REQUEST_CHANGES", findings: ["change"] },
{ phase: "review", event: "COMMENT", findings: ["review"] },
@@ -56,12 +65,54 @@ test("old bot reviews are cleaned only while the current review is preserved", a
const dismissedReviews: number[] = [];
const minimizedReviews: Array<{ subjectId: string; classifier: string }> = [];
const reviews = [
{ id: 10, node_id: "PRR_10", user: { type: "Bot" }, body: marker, state: "CHANGES_REQUESTED", commit_id: "a".repeat(40) },
{ id: 20, node_id: "PRR_20", user: { type: "Bot" }, body: marker, state: "APPROVED", commit_id: "b".repeat(40) },
{ id: 30, node_id: "PRR_30", user: { type: "User" }, body: marker, state: "COMMENTED", commit_id: "c".repeat(40) },
{ id: 40, node_id: "PRR_40", user: { type: "Bot" }, body: marker, state: "DISMISSED", commit_id: "d".repeat(40) },
{ id: 50, node_id: "PRR_50", user: { type: "Bot" }, body: "Unrelated automation", state: "COMMENTED", commit_id: "e".repeat(40) },
{ id: 60, node_id: "PRR_60", user: { type: "Bot" }, body: marker, state: "CHANGES_REQUESTED", commit_id: "b".repeat(40) }
{
id: 10,
node_id: "PRR_10",
user: { type: "Bot" },
body: marker,
state: "CHANGES_REQUESTED",
commit_id: "a".repeat(40)
},
{
id: 20,
node_id: "PRR_20",
user: { type: "Bot" },
body: marker,
state: "APPROVED",
commit_id: "b".repeat(40)
},
{
id: 30,
node_id: "PRR_30",
user: { type: "User" },
body: marker,
state: "COMMENTED",
commit_id: "c".repeat(40)
},
{
id: 40,
node_id: "PRR_40",
user: { type: "Bot" },
body: marker,
state: "DISMISSED",
commit_id: "d".repeat(40)
},
{
id: 50,
node_id: "PRR_50",
user: { type: "Bot" },
body: "Unrelated automation",
state: "COMMENTED",
commit_id: "e".repeat(40)
},
{
id: 60,
node_id: "PRR_60",
user: { type: "Bot" },
body: marker,
state: "CHANGES_REQUESTED",
commit_id: "b".repeat(40)
}
];
const octokit = {
paginate: async (method: unknown, params: { review_id?: number }) => {
@@ -114,7 +165,10 @@ test("old bot reviews are cleaned only while the current review is preserved", a
});
assert.deepEqual(deletedComments, [101, 102, 401, 601]);
assert.deepEqual(updatedReviews.map((item) => item.review_id), [10, 40, 60]);
assert.deepEqual(
updatedReviews.map((item) => item.review_id),
[10, 40, 60]
);
assert.match(updatedReviews[0]!.body, /bbbbbbbbbbbb/);
assert.deepEqual(dismissedReviews, [10, 60]);
assert.deepEqual(minimizedReviews, [
@@ -130,8 +184,22 @@ test("superseded inline comments are marked resolved and hidden when GitHub expo
const resolvedThreads: string[] = [];
const hiddenComments: string[] = [];
const reviews = [
{ id: 10, node_id: "PRR_10", user: { type: "Bot" }, body: marker, state: "CHANGES_REQUESTED", commit_id: "a".repeat(40) },
{ id: 20, node_id: "PRR_20", user: { type: "Bot" }, body: marker, state: "COMMENTED", commit_id: "b".repeat(40) }
{
id: 10,
node_id: "PRR_10",
user: { type: "Bot" },
body: marker,
state: "CHANGES_REQUESTED",
commit_id: "a".repeat(40)
},
{
id: 20,
node_id: "PRR_20",
user: { type: "Bot" },
body: marker,
state: "COMMENTED",
commit_id: "b".repeat(40)
}
];
const octokit = {
paginate: async (method: unknown, params: { review_id?: number }) => {
@@ -139,7 +207,10 @@ test("superseded inline comments are marked resolved and hidden when GitHub expo
return reviews;
}
if (params.review_id === 10) {
return [{ id: 101, node_id: "PRC_101" }, { id: 102, node_id: "PRC_102" }];
return [
{ id: 101, node_id: "PRC_101" },
{ id: 102, node_id: "PRC_102" }
];
}
return [];
},
+77
View File
@@ -0,0 +1,77 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import { EventRouter, type EventContext, type EventHandler } from "../src/actions/router.js";
const dummyOctokit = {} as Octokit;
test("EventRouter registers and dispatches matching events", async () => {
const router = new EventRouter();
const handledEvents: string[] = [];
const prHandler: EventHandler = {
name: "pull-request-handler",
canHandle: (eventName) => eventName === "pull_request_target",
handle: async (ctx) => {
handledEvents.push(`${ctx.eventName}:${ctx.action}`);
}
};
router.register(prHandler);
const context: EventContext = {
eventName: "pull_request_target",
action: "opened",
payload: { pull_request: { number: 1 } },
octokit: dummyOctokit
};
const result = await router.dispatch(context);
assert.equal(result.handled, true);
assert.equal(result.handlerName, "pull-request-handler");
assert.deepEqual(handledEvents, ["pull_request_target:opened"]);
});
test("EventRouter returns handled=false when no handler matches", async () => {
const router = new EventRouter();
const context: EventContext = {
eventName: "unknown_event",
payload: {},
octokit: dummyOctokit
};
const result = await router.dispatch(context);
assert.equal(result.handled, false);
assert.equal(result.handlerName, undefined);
});
test("EventRouter respects handler registration order", async () => {
const router = new EventRouter();
const order: string[] = [];
router.register({
name: "first-handler",
canHandle: (name) => name === "issue_comment",
handle: async () => {
order.push("first");
}
});
router.register({
name: "second-handler",
canHandle: (name) => name === "issue_comment",
handle: async () => {
order.push("second");
}
});
const result = await router.dispatch({
eventName: "issue_comment",
payload: {},
octokit: dummyOctokit
});
assert.equal(result.handled, true);
assert.equal(result.handlerName, "first-handler");
assert.deepEqual(order, ["first"]);
});
+15 -6
View File
@@ -17,12 +17,18 @@ test("actions mode reports trigger, runner, goose, policy, automation, cache", (
process.env.GITHUB_EVENT_NAME = "pull_request_target";
try {
const body = formatRuntimeEnvironmentDetails("actions");
assert.match(body, /- \*\*Mode:\*\* GitHub Actions \(\`pull_request_target\`\)/);
assert.match(body, /- \*\*Mode:\*\* GitHub Actions \(`pull_request_target`\)/);
assert.match(body, /- \*\*Runner:\*\* .+ · Node\.js v/);
assert.match(body, /- \*\*goose:\*\* model \`[^\`]+\` · thinking effort \`[^\`]+\`/);
assert.match(body, /- \*\*Review policy:\*\* \`(allow|require_approval|reject)\` · strictness \`(normal|strict)\`/);
assert.match(body, /- \*\*goose:\*\* model `[^`]+` · thinking effort `[^`]+`/);
assert.match(
body,
/- \*\*Review policy:\*\* `(allow|require_approval|reject)` · strictness `(normal|strict)`/
);
assert.match(body, /- \*\*Automation:\*\* auto-merge (on|off) · conflict repair (on|off)/);
assert.match(body, /- \*\*Cache:\*\* R2 (enabled|disabled) · repository knowledge (enabled|disabled)/);
assert.match(
body,
/- \*\*Cache:\*\* R2 (enabled|disabled) · repository knowledge (enabled|disabled)/
);
} finally {
if (previousEvent === undefined) {
delete process.env.GITHUB_EVENT_NAME;
@@ -39,8 +45,11 @@ test("webhook mode keeps the identical template but swaps in service facts", ()
assert.match(webhookBody, /^<details>\n<summary>⚙️ Runtime environment<\/summary>/);
assert.match(webhookBody, /- \*\*Mode:\*\* GitHub App webhook service \(read-only chat\)/);
assert.match(webhookBody, /- \*\*Host:\*\** .+Node\.js v/);
assert.match(webhookBody, /- \*\*Chat permission policy:\*\* \`(anyone|read|write)\`/);
assert.match(webhookBody, /- \*\*Tools:\*\* none · cannot edit files, run commands, or push commits/);
assert.match(webhookBody, /- \*\*Chat permission policy:\*\* `(anyone|read|write)`/);
assert.match(
webhookBody,
/- \*\*Tools:\*\* none · cannot edit files, run commands, or push commits/
);
assert.doesNotMatch(webhookBody, /GitHub Actions|Review policy|Runner:/);
const summaryOf = (body: string) => body.split("\n").slice(0, 2).join("\n");
+33
View File
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { cacheRootDirectory, runtimeDirectory, tempRootDirectory } from "../src/runtimePaths.js";
test("runtime paths default to the process working directory", () => {
delete process.env.GHBOT_RUNTIME_DIR;
assert.equal(runtimeDirectory(), process.cwd());
assert.match(tempRootDirectory(), /[\\/.]\.ghbot-tmp$/);
assert.match(cacheRootDirectory(), /[\\/.]\.ghbot-cache$/);
});
test("GHBOT_RUNTIME_DIR relocates scratch and cache roots", () => {
const root = path.join(os.tmpdir(), `ghbot-runtime-${Date.now()}`);
process.env.GHBOT_RUNTIME_DIR = root;
try {
assert.equal(runtimeDirectory(), root);
assert.equal(tempRootDirectory(), path.join(root, ".ghbot-tmp"));
assert.equal(cacheRootDirectory(), path.join(root, ".ghbot-cache"));
} finally {
delete process.env.GHBOT_RUNTIME_DIR;
}
});
test("whitespace-only GHBOT_RUNTIME_DIR falls back to cwd", () => {
process.env.GHBOT_RUNTIME_DIR = " ";
try {
assert.equal(runtimeDirectory(), process.cwd());
} finally {
delete process.env.GHBOT_RUNTIME_DIR;
}
});
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
hasProtectedSegment,
isProtectedBasename,
PROTECTED_DIRECTORIES,
PROTECTED_FILE_NAMES
} from "../src/security/sanitization.js";
import { containsSecret, redactSecrets } from "../src/security/secrets.js";
test("protected basenames cover env files, agent configs, and deploy configs", () => {
for (const name of [
".env",
".env.local",
".ENV",
"AGENTS.MD",
"opencode.json",
"wrangler.toml"
]) {
assert.equal(isProtectedBasename(name), true, `${name} should be protected`);
}
assert.equal(isProtectedBasename("environment.ts"), false);
assert.equal(isProtectedBasename("src"), false);
});
test("protected directory segments are matched case-insensitively", () => {
assert.equal(hasProtectedSegment(["src", ".Git", "config"]), true);
assert.equal(hasProtectedSegment([".claude"]), true);
assert.equal(hasProtectedSegment(["src", "lib"]), false);
assert.equal(hasProtectedSegment([""]), false);
});
test("directory and file sets are non-trivial and stable", () => {
assert.ok(PROTECTED_DIRECTORIES.has(".git"));
assert.ok(PROTECTED_FILE_NAMES.has("agents.md"));
});
test("redactSecrets masks tokens and private keys in free text", () => {
const input = [
"token=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
"key=sk-abcdefghijklmnopqrstuvwxyz012345",
"auth: Bearer abcdefghijklmnopqrstuvwxyz0123456789",
"-----BEGIN RSA PRIVATE KEY-----",
"MIIEow...",
"-----END RSA PRIVATE KEY-----"
].join("\n");
const redacted = redactSecrets(input);
assert.equal(containsSecret(redacted), false);
assert.ok(redacted.includes("[REDACTED]"));
});
test("containsSecret detects credential shapes", () => {
assert.equal(containsSecret("github_pat_ABCDEFGHIJKLMNOPQRSTUVWXYZ12"), true);
assert.equal(containsSecret("nothing to see here"), false);
});
+39 -29
View File
@@ -85,23 +85,27 @@ test("pull request evidence loads bounded recent commits and all comment kinds",
listReviews: async () => {
calls.push("reviews");
return {
data: [{
user: { login: "reviewer" },
state: "COMMENTED",
body: "Review summary",
submitted_at: "2026-08-14T00:00:00Z"
}]
data: [
{
user: { login: "reviewer" },
state: "COMMENTED",
body: "Review summary",
submitted_at: "2026-08-14T00:00:00Z"
}
]
};
},
listReviewComments: async () => {
calls.push("review-comments");
return {
data: [{
user: { login: "inline-reviewer" },
path: "src/navigation.ts",
body: "Inline compatibility concern",
created_at: "2026-08-14T00:01:00Z"
}]
data: [
{
user: { login: "inline-reviewer" },
path: "src/navigation.ts",
body: "Inline compatibility concern",
created_at: "2026-08-14T00:01:00Z"
}
]
};
}
},
@@ -109,11 +113,13 @@ test("pull request evidence loads bounded recent commits and all comment kinds",
listComments: async () => {
calls.push("comments");
return {
data: [{
user: { login: "maintainer" },
body: "Conversation context",
created_at: "2026-08-14T00:02:00Z"
}]
data: [
{
user: { login: "maintainer" },
body: "Conversation context",
created_at: "2026-08-14T00:02:00Z"
}
]
};
}
}
@@ -136,17 +142,21 @@ function evidence(number: number, commitMessage: string, commentBody: string): P
number,
commits: [{ sha: `${number}-sha`, message: commitMessage, author: "contributor" }],
comments: [{ author: "maintainer", body: commentBody, createdAt: "2026-08-14T00:00:00Z" }],
reviews: [{
author: "reviewer",
state: "COMMENTED",
body: "Review context",
submittedAt: "2026-08-14T00:00:00Z"
}],
reviewComments: [{
author: "reviewer",
path: "src/navigation.ts",
body: "Inline review context",
createdAt: "2026-08-14T00:00:00Z"
}]
reviews: [
{
author: "reviewer",
state: "COMMENTED",
body: "Review context",
submittedAt: "2026-08-14T00:00:00Z"
}
],
reviewComments: [
{
author: "reviewer",
path: "src/navigation.ts",
body: "Inline review context",
createdAt: "2026-08-14T00:00:00Z"
}
]
};
}
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { MetricsRegistry } from "../src/webhook/metrics.js";
test("counters accumulate and serialize with sorted stable output", () => {
const registry = new MetricsRegistry();
registry.inc("reviews_total", { outcome: "pass" });
registry.inc("reviews_total", { outcome: "pass" });
registry.inc("reviews_total", { outcome: "block" });
const output = registry.snapshotPrometheus();
assert.match(output, /ghbot_reviews_total\{outcome="pass"\} 2/);
assert.match(output, /ghbot_reviews_total\{outcome="block"\} 1/);
assert.match(output, /ghbot_uptime_seconds \d+/);
});
test("label values are escaped for the Prometheus text format", () => {
const registry = new MetricsRegistry();
registry.inc("events_total", { repo: 'acme "x"\n' });
const output = registry.snapshotPrometheus();
assert.ok(output.includes('ghbot_events_total{repo="acme \\"x\\"\\n"} 1'));
});
test("durations produce count, sum, and quantiles", () => {
const registry = new MetricsRegistry();
registry.observeDuration("review_duration_ms", 100);
registry.observeDuration("review_duration_ms", 300);
const output = registry.snapshotPrometheus();
assert.match(output, /ghbot_review_duration_ms_count 2/);
assert.match(output, /ghbot_review_duration_ms_sum_ms 400/);
assert.match(output, /ghbot_duration_ms\{quantile="0.5"\} \d+/);
assert.match(output, /ghbot_duration_ms\{quantile="0.95"\} \d+/);
});
test("an empty registry still emits uptime", () => {
const output = new MetricsRegistry().snapshotPrometheus();
assert.match(output, /ghbot_uptime_seconds/);
});
+66 -14
View File
@@ -36,19 +36,46 @@ test("triage events are parsed for issues and pull requests on open/edit/reopen"
number: 5
});
const pull = parseWebhookTriageEvent("pull_request", triagePayload({
action: "reopened",
pull_request: { number: 9 }
}));
const pull = parseWebhookTriageEvent(
"pull_request",
triagePayload({
action: "reopened",
pull_request: { number: 9 }
})
);
assert.equal(pull?.kind, "pull_request");
assert.equal(pull?.number, 9);
});
test("triage parsing rejects other events, pushes, PR issues, and missing installation", () => {
assert.equal(parseWebhookTriageEvent("issues", triagePayload({ action: "synchronize", issue: { number: 5 } })), null);
assert.equal(parseWebhookTriageEvent("pull_request", triagePayload({ action: "closed", pull_request: { number: 9 } })), null);
assert.equal(parseWebhookTriageEvent("issues", triagePayload({ issue: { number: 5, pull_request: { url: "x" } } })), null);
assert.equal(parseWebhookTriageEvent("issues", triagePayload({ installation: undefined, issue: { number: 5 } })), null);
assert.equal(
parseWebhookTriageEvent(
"issues",
triagePayload({ action: "synchronize", issue: { number: 5 } })
),
null
);
assert.equal(
parseWebhookTriageEvent(
"pull_request",
triagePayload({ action: "closed", pull_request: { number: 9 } })
),
null
);
assert.equal(
parseWebhookTriageEvent(
"issues",
triagePayload({ issue: { number: 5, pull_request: { url: "x" } } })
),
null
);
assert.equal(
parseWebhookTriageEvent(
"issues",
triagePayload({ installation: undefined, issue: { number: 5 } })
),
null
);
assert.equal(parseWebhookTriageEvent("issue_comment", triagePayload()), null);
});
@@ -76,8 +103,21 @@ const mention: WebhookMention = {
};
const baseContext: WebhookContext = {
repository: { fullName: "forumlify/public", description: null, defaultBranch: "main", readme: "" },
item: { number: 3, title: "t", body: "", state: "open", url: "", kind: "pull_request", author: null },
repository: {
fullName: "forumlify/public",
description: null,
defaultBranch: "main",
readme: ""
},
item: {
number: 3,
title: "t",
body: "",
state: "open",
url: "",
kind: "pull_request",
author: null
},
discussion: []
};
@@ -88,7 +128,10 @@ test("webhook chat prompt embeds host-curated knowledge when available", () => {
});
assert.match(withKnowledge, /Verified repository knowledge curated by the host process/);
assert.match(withKnowledge, /npm test\./);
assert.match(withKnowledge, /current repository evidence always takes precedence over cached knowledge/);
assert.match(
withKnowledge,
/current repository evidence always takes precedence over cached knowledge/
);
const withoutKnowledge = buildWebhookChatPrompt(mention, baseContext);
assert.doesNotMatch(withoutKnowledge, /Verified repository knowledge/);
@@ -99,15 +142,24 @@ test("uninitialized knowledge scaffold is detected and never injected", async ()
try {
const scaffold = await loadRepositoryKnowledge(runtimeDirectory);
assert.equal(isUninitializedRepositoryKnowledge(scaffold), true);
assert.equal(isUninitializedRepositoryKnowledge("# ghbot repository knowledge\n\nTests: npm test.\n"), false);
assert.equal(
isUninitializedRepositoryKnowledge("# ghbot repository knowledge\n\nTests: npm test.\n"),
false
);
} finally {
await fs.rm(runtimeDirectory, { recursive: true, force: true });
}
});
test("webhook knowledge loader degrades to undefined without R2 or repository id", async () => {
assert.equal(await loadWebhookRepositoryKnowledge({ owner: "forumlify", repo: "public" }), undefined);
assert.equal(await loadWebhookRepositoryKnowledge({ repositoryId: 7, owner: "forumlify", repo: "public" }), undefined);
assert.equal(
await loadWebhookRepositoryKnowledge({ owner: "forumlify", repo: "public" }),
undefined
);
assert.equal(
await loadWebhookRepositoryKnowledge({ repositoryId: 7, owner: "forumlify", repo: "public" }),
undefined
);
});
test("webhook chat prompt stays read-only in both variants", () => {
+71 -57
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import http from "node:http";
import type http from "node:http";
import { Readable } from "node:stream";
import test from "node:test";
import {
@@ -9,10 +9,7 @@ import {
parseWebhookMentionEvent,
webhookPermissionAllows
} from "../src/webhook/processor.js";
import {
createWebhookServer,
verifyGitHubWebhookSignature
} from "../src/webhook/server.js";
import { createWebhookServer, verifyGitHubWebhookSignature } from "../src/webhook/server.js";
const secret = "webhook-test-secret";
@@ -43,6 +40,31 @@ function signature(body: string): string {
return `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
}
type OctokitLike = Parameters<typeof getCommenterPermission>[0];
function createOctokitStub(calls: string[]): OctokitLike {
return {
rest: {
repos: {
get: async () => {
calls.push("repo");
return { data: { owner: { type: "Organization" } } };
},
getCollaboratorPermissionLevel: async () => {
calls.push("collaborator");
return { data: { permission: null } };
}
},
orgs: {
checkMembershipForUser: async () => {
calls.push("membership");
return { status: 204 };
}
}
}
} as unknown as OctokitLike;
}
class TestResponse {
statusCode = 200;
headers: Record<string, string> = {};
@@ -69,7 +91,13 @@ class TestResponse {
async function request(
server: http.Server,
options: { method?: string; path?: string; body?: string; delivery?: string; signature?: string } = {}
options: {
method?: string;
path?: string;
body?: string;
delivery?: string;
signature?: string;
} = {}
): Promise<{ status: number; body: string }> {
const body = options.body ?? JSON.stringify(issueCommentPayload());
const request = Object.assign(Readable.from([Buffer.from(body)]), {
@@ -106,35 +134,39 @@ test("Webhook event parsing only accepts supported mentions and preserves PR con
"delivery-1",
"github-actions[bot]"
);
assert.deepEqual(mention && {
eventName: mention.eventName,
installationId: mention.installationId,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
targetKind: mention.targetKind,
replyMode: mention.replyMode
}, {
eventName: "issue_comment",
installationId: 12345,
owner: "acme",
repo: "demo",
issueNumber: 7,
targetKind: "pull_request",
replyMode: "conversation"
});
assert.equal(parseWebhookMentionEvent(
"issue_comment",
issueCommentPayload("ordinary comment"),
"delivery-2",
"github-actions[bot]"
), null);
assert.equal(parseWebhookMentionEvent(
"issues",
issueCommentPayload(),
"delivery-3",
"github-actions[bot]"
), null);
assert.deepEqual(
mention && {
eventName: mention.eventName,
installationId: mention.installationId,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
targetKind: mention.targetKind,
replyMode: mention.replyMode
},
{
eventName: "issue_comment",
installationId: 12345,
owner: "acme",
repo: "demo",
issueNumber: 7,
targetKind: "pull_request",
replyMode: "conversation"
}
);
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
issueCommentPayload("ordinary comment"),
"delivery-2",
"github-actions[bot]"
),
null
);
assert.equal(
parseWebhookMentionEvent("issues", issueCommentPayload(), "delivery-3", "github-actions[bot]"),
null
);
});
test("Webhook permission policy is explicit", () => {
@@ -150,27 +182,7 @@ test("Webhook permission policy is explicit", () => {
test("organization members can use webhook chat without repository collaborator access", async () => {
const calls: string[] = [];
const octokit = {
rest: {
repos: {
get: async () => {
calls.push("repo");
return { data: { owner: { type: "Organization" } } };
},
getCollaboratorPermissionLevel: async () => {
calls.push("collaborator");
return { data: { permission: null } };
}
},
orgs: {
checkMembershipForUser: async () => {
calls.push("membership");
return { status: 204 };
}
}
}
} as any;
const octokit = createOctokitStub(calls);
const permission = await getCommenterPermission(octokit, {
eventName: "issue_comment",
action: "created",
@@ -193,7 +205,9 @@ test("organization members can use webhook chat without repository collaborator
test("Webhook server returns health, verifies signatures, queues asynchronously, and deduplicates deliveries", async () => {
const handled: string[] = [];
let resolveHandler: (() => void) | undefined;
const handlerFinished = new Promise<void>((resolve) => { resolveHandler = resolve; });
const handlerFinished = new Promise<void>((resolve) => {
resolveHandler = resolve;
});
const server = createWebhookServer({
secret,
handleDelivery: async (_eventName, _payload, deliveryId) => {
+4 -1
View File
@@ -10,5 +10,8 @@ test("pull_request_target checks out only same-repository heads without persisti
assert.match(workflow, /fetch-depth:\s*0/);
assert.doesNotMatch(workflow, /allow-unsafe-pr-checkout:\s*true/);
assert.match(workflow, /GHBOT_GOOSE_BINARY:\s*\$\{\{ runner\.temp \}\}\/goose\/bin\/goose/);
assert.match(caller, /pull_head_repository:\s*\$\{\{ github\.event\.pull_request\.head\.repo\.full_name \|\| '' \}\}/);
assert.match(
caller,
/pull_head_repository:\s*\$\{\{ github\.event\.pull_request\.head\.repo\.full_name \|\| '' \}\}/
);
});