chore: add eslint/prettier gates and fix windows test failures

This commit is contained in:
wdawdwa committed 2026-08-22 15:16:47 +08:00
1 parent b366e16087
commit b47302e2ff
42 files changed
+3460 -843

No files matched your search

+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",
+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/);
});
+17 -8
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,15 +47,19 @@ 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"),
["run", "sh", "-lc", "[validation command: 18 chars]"]
@@ -68,7 +74,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 +128,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```' }]
}
]
});
+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 {
+12 -5
View File
@@ -16,11 +16,18 @@ 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 });
}
+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);
+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"
),
+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 }> = [];
+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 [];
},
+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"
}
]
};
}
+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 \|\| '' \}\}/
);
});