mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
397 lines
19 KiB
YAML
397 lines
19 KiB
YAML
name: triage-close-linked
|
|
|
|
# Closes what GitHub native auto-close misses on merge into the default branch:
|
|
# - additional issues in lists ("Fixes #1, #2 and #3" -> closes #2 and #3; GitHub closes #1)
|
|
# - superseded pull requests ("Supersedes #4", "Replaces #5")
|
|
#
|
|
# Runs entirely against the GitHub API with no checkout, so pull_request_target is safe.
|
|
|
|
permissions:
|
|
contents: read
|
|
|
|
on:
|
|
pull_request_target:
|
|
types: [closed]
|
|
workflow_dispatch:
|
|
inputs:
|
|
pr_number:
|
|
description: "Merged PR whose description to read"
|
|
required: true
|
|
type: string
|
|
dry_run:
|
|
description: "Log targets without closing them"
|
|
required: false
|
|
type: boolean
|
|
default: true
|
|
|
|
jobs:
|
|
close-linked:
|
|
if: >
|
|
github.repository == 'anomalyco/opencode' &&
|
|
(github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true)
|
|
runs-on: ubuntu-latest
|
|
timeout-minutes: 10
|
|
permissions:
|
|
issues: write
|
|
pull-requests: write
|
|
steps:
|
|
- name: Close linked issues and superseded PRs
|
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
|
with:
|
|
script: |
|
|
const ISSUE_KEYWORDS = new Set([
|
|
"close", "closes", "closed",
|
|
"fix", "fixes", "fixed",
|
|
"resolve", "resolves", "resolved",
|
|
]);
|
|
const PR_KEYWORDS = new Set([
|
|
"supersede", "supersedes", "superseded",
|
|
"replace", "replaces", "replaced",
|
|
]);
|
|
const KEYWORDS = new Set([...ISSUE_KEYWORDS, ...PR_KEYWORDS]);
|
|
const HEDGES = new Set([
|
|
"may", "might", "could", "would", "possibly", "probably", "potentially",
|
|
"maybe", "perhaps", "hopefully", "likely", "unlikely", "partially", "partly", "partial",
|
|
]);
|
|
const SUBORDINATORS = new Set(["if", "whether", "when", "whenever", "once", "until", "unless", "before", "after"]);
|
|
const DISQUALIFIERS = new Set([
|
|
"not", "never", "neither", "nor", "without", "cannot", "can't", "doesn't", "don't",
|
|
"won't", "didn't", "isn't", "wasn't", "hasn't", "haven't", "hadn't", "wouldn't",
|
|
"couldn't", "shouldn't", "mightn't", "mustn't",
|
|
...HEDGES,
|
|
...SUBORDINATORS,
|
|
"the", "a", "an", "of", "on", "in", "by", "from", "with", "for", "than",
|
|
]);
|
|
const BASE_FORMS = new Set(["close", "fix", "resolve", "supersede", "replace"]);
|
|
const VERB_MARKERS = new Set(["does", "do", "did", "and"]);
|
|
const DETERMINERS = new Set(["this", "that", "the", "a", "an"]);
|
|
const INTERVENING = new Set([
|
|
"also", "fully", "completely", "entirely", "actually", "really", "yet", "directly", "properly",
|
|
"have", "has", "had",
|
|
]);
|
|
const MAX_TARGETS = 10;
|
|
|
|
function stripNonProse(body) {
|
|
const lines = body.replaceAll("\r\n", "\n").split("\n");
|
|
const kept = [];
|
|
let fence = null;
|
|
let inComment = false;
|
|
let paragraph = false;
|
|
for (const line of lines) {
|
|
if (inComment) {
|
|
const end = line.indexOf("-->");
|
|
if (end === -1) { kept.push(""); continue; }
|
|
inComment = false;
|
|
kept.push(line.slice(end + 3));
|
|
continue;
|
|
}
|
|
const trimmed = line.trim();
|
|
if (fence !== null) {
|
|
if (trimmed.startsWith(fence) && [...trimmed].every(c => c === fence[0])) fence = null;
|
|
paragraph = false;
|
|
kept.push("");
|
|
continue;
|
|
}
|
|
if (trimmed === "") { paragraph = false; kept.push(""); continue; }
|
|
// Skip 4-space or tab indented code blocks outside a paragraph.
|
|
if (!paragraph && (/^ {4}/.test(line) || line.startsWith("\t"))) {
|
|
kept.push("");
|
|
continue;
|
|
}
|
|
const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed);
|
|
if (fenceMatch && (fenceMatch[1][0] === "~" || !trimmed.slice(fenceMatch[1].length).includes("`"))) {
|
|
fence = fenceMatch[1];
|
|
paragraph = false;
|
|
kept.push("");
|
|
continue;
|
|
}
|
|
if (trimmed.startsWith(">")) { paragraph = false; kept.push(""); continue; }
|
|
// Skip markdown task list items like "- [ ] Fix #99".
|
|
if (/^[-*+]\s+\[[ xX]\]/.test(trimmed)) { paragraph = false; kept.push(""); continue; }
|
|
// Strip inline code spans BEFORE HTML comments so `<!--` in backticks is not a comment.
|
|
let cleaned = line.replace(/`[^`\n]+`/g, " code ");
|
|
while (cleaned.includes("<!--")) {
|
|
const start = cleaned.indexOf("<!--");
|
|
const end = cleaned.indexOf("-->", start + 4);
|
|
if (end === -1) {
|
|
cleaned = cleaned.slice(0, start);
|
|
inComment = true;
|
|
break;
|
|
}
|
|
cleaned = cleaned.slice(0, start) + " " + cleaned.slice(end + 3);
|
|
}
|
|
paragraph = !/^#{1,6}\s/.test(trimmed);
|
|
kept.push(cleaned);
|
|
}
|
|
let text = kept.join("\n");
|
|
text = text.replace(/~~[^~\n]+~~/g, " ");
|
|
text = text.replace(/<(?:s|del|strike)\b[^>]*>[\s\S]*?<\/(?:s|del|strike)>/gi, " ");
|
|
return text;
|
|
}
|
|
|
|
function tokenize(text) {
|
|
const tokens = [];
|
|
let i = 0;
|
|
while (i < text.length) {
|
|
const c = text[i];
|
|
if (c === "\n") {
|
|
if (tokens.at(-1)?.kind === "newline") tokens[tokens.length - 1] = { kind: "break" };
|
|
else if (tokens.at(-1)?.kind !== "break") tokens.push({ kind: "newline" });
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c.trim() === "") { i++; continue; }
|
|
const urlMatch = /^https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/(?:issues|pull)\/(\d+)(?![\w])/i.exec(text.slice(i));
|
|
if (urlMatch) {
|
|
tokens.push({ kind: "ref", repository: urlMatch[1].toLowerCase(), number: Number(urlMatch[2]) });
|
|
i += urlMatch[0].length;
|
|
continue;
|
|
}
|
|
const repoRefMatch = /^([\w.-]+\/[\w.-]+)#(\d+)(?![\w'\u2019])/.exec(text.slice(i));
|
|
if (repoRefMatch) {
|
|
tokens.push({ kind: "ref", repository: repoRefMatch[1].toLowerCase(), number: Number(repoRefMatch[2]) });
|
|
i += repoRefMatch[0].length;
|
|
continue;
|
|
}
|
|
const bareRefMatch = /^#(\d+)(?![\w'\u2019])/.exec(text.slice(i));
|
|
if (bareRefMatch) {
|
|
tokens.push({ kind: "ref", repository: null, number: Number(bareRefMatch[1]) });
|
|
i += bareRefMatch[0].length;
|
|
continue;
|
|
}
|
|
const wordMatch = /^[A-Za-z][A-Za-z0-9'\u2019-]*/.exec(text.slice(i));
|
|
if (wordMatch) {
|
|
tokens.push({ kind: "word", text: wordMatch[0].toLowerCase().replaceAll("\u2019", "'") });
|
|
i += wordMatch[0].length;
|
|
continue;
|
|
}
|
|
tokens.push({ kind: "punct", text: c });
|
|
i++;
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
const isPunct = (t, s) => t?.kind === "punct" && t.text === s;
|
|
const isWord = (t, s) => t?.kind === "word" && t.text === s;
|
|
const skipEmph = (tokens, i) => { while (isPunct(tokens[i], "*") || isPunct(tokens[i], "_")) i++; return i; };
|
|
const skipEmphBack = (tokens, i) => { while (i >= 0 && (isPunct(tokens[i], "*") || isPunct(tokens[i], "_"))) i--; return i; };
|
|
const skipInterveningBack = (tokens, i) => {
|
|
for (;;) {
|
|
i = skipEmphBack(tokens, i);
|
|
if (i < 0 || tokens[i].kind !== "word" || !INTERVENING.has(tokens[i].text)) return i;
|
|
i--;
|
|
}
|
|
};
|
|
const endsWithRef = (tokens, k) => {
|
|
const p = skipEmphBack(tokens, k);
|
|
const t = tokens[p];
|
|
if (!t) return false;
|
|
if (t.kind === "ref") return true;
|
|
if (isPunct(t, ">")) return tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "<");
|
|
if (isPunct(t, ")")) {
|
|
if (tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "(")) return true;
|
|
if (isPunct(tokens[p - 2], "(") && isPunct(tokens[p - 3], "]")) return tokens[p - 4]?.kind === "ref" && isPunct(tokens[p - 5], "[");
|
|
}
|
|
return false;
|
|
};
|
|
|
|
// A continuation reference must terminate cleanly (end of text/line/clause or list separator),
|
|
// so "Fixes #12, #13 is tracked separately" does NOT close #13.
|
|
const endsCleanly = (tokens, j) => {
|
|
const next = tokens[skipEmph(tokens, j)];
|
|
if (!next || next.kind === "newline" || next.kind === "break") return true;
|
|
if (next.kind === "punct" && ".,;:)&".includes(next.text)) return true;
|
|
if (isWord(next, "and")) return true;
|
|
return false;
|
|
};
|
|
|
|
function isClosingStatement(tokens, index, keyword) {
|
|
let k = skipInterveningBack(tokens, index - 1);
|
|
// Skip parenthetical / dash / colon lead-ins from a reference ("Reverts #100 (fixes #99)", "TODO: fix #99").
|
|
if (isPunct(tokens[k], ":") && tokens[k - 1]?.kind === "word" && ["todo", "note", "fyi"].includes(tokens[k - 1].text)) return false;
|
|
if (tokens[k]?.kind === "punct" && "(—–-".includes(tokens[k].text)) {
|
|
let q = skipInterveningBack(tokens, k - 1);
|
|
while (tokens[q]?.kind === "punct" && "-—–".includes(tokens[q].text)) q = skipInterveningBack(tokens, q - 1);
|
|
if (endsWithRef(tokens, q)) return false;
|
|
}
|
|
if (endsWithRef(tokens, k)) return false;
|
|
const lineStart = tokens[k]?.kind === "newline" || tokens[k]?.kind === "break" || k < 0;
|
|
if (tokens[k]?.kind === "newline") {
|
|
const e = skipEmphBack(tokens, k - 1);
|
|
const w = skipInterveningBack(tokens, e);
|
|
if (w < e && endsWithRef(tokens, w)) return false;
|
|
k = w;
|
|
}
|
|
const before = tokens[k];
|
|
if (!before || before.kind !== "word") return true;
|
|
if (before.text === "which" || before.text === "that") {
|
|
let p = skipInterveningBack(tokens, k - 1);
|
|
while (tokens[p]?.kind === "newline" || (tokens[p]?.kind === "punct" && ",(;:-\u2013\u2014".includes(tokens[p].text))) {
|
|
p = skipInterveningBack(tokens, p - 1);
|
|
}
|
|
if (endsWithRef(tokens, p)) return false;
|
|
}
|
|
if (DISQUALIFIERS.has(before.text)) return false;
|
|
let p = skipInterveningBack(tokens, k - 1);
|
|
if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1);
|
|
if (tokens[p]?.kind === "word" && DETERMINERS.has(tokens[p].text)) {
|
|
p = skipInterveningBack(tokens, p - 1);
|
|
if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1);
|
|
}
|
|
if (isPunct(tokens[p], ",")) p = skipInterveningBack(tokens, p - 1);
|
|
if (tokens[p]?.kind === "word" && (SUBORDINATORS.has(tokens[p].text) || HEDGES.has(tokens[p].text))) return false;
|
|
if (!BASE_FORMS.has(keyword)) return true;
|
|
return lineStart ? before.text !== "to" : VERB_MARKERS.has(before.text);
|
|
}
|
|
|
|
function readRef(tokens, index) {
|
|
index = skipEmph(tokens, index);
|
|
const t = tokens[index];
|
|
if (!t) return null;
|
|
if (t.kind === "ref") return { token: t, end: index + 1 };
|
|
if (isPunct(t, "<") && tokens[index + 1]?.kind === "ref" && isPunct(tokens[index + 2], ">")) {
|
|
return { token: tokens[index + 1], end: index + 3 };
|
|
}
|
|
if (isPunct(t, "[")) {
|
|
let close = index + 1;
|
|
while (close < tokens.length && close < index + 10 && !isPunct(tokens[close], "]")) {
|
|
if (tokens[close].kind === "newline" || tokens[close].kind === "break") return null;
|
|
close++;
|
|
}
|
|
if (isPunct(tokens[close], "]") && isPunct(tokens[close + 1], "(") && isPunct(tokens[close + 3], ")")) {
|
|
if (tokens[close + 2]?.kind === "ref") return { token: tokens[close + 2], end: close + 4 };
|
|
if (close === index + 2 && tokens[index + 1]?.kind === "ref") return { token: tokens[index + 1], end: close + 4 };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function findLinkedReferences(body, repository) {
|
|
const self = repository.toLowerCase();
|
|
const tokens = tokenize(stripNonProse(body));
|
|
const found = [];
|
|
let i = 0;
|
|
while (i < tokens.length) {
|
|
const token = tokens[i];
|
|
if (token.kind !== "word" || !KEYWORDS.has(token.text) || !isClosingStatement(tokens, i, token.text)) {
|
|
i++;
|
|
continue;
|
|
}
|
|
const targetKind = PR_KEYWORDS.has(token.text) ? "pull" : "issue";
|
|
let j = i + 1;
|
|
if (isPunct(tokens[j], ":")) j++;
|
|
let ref = readRef(tokens, j);
|
|
if (!ref) { i++; continue; }
|
|
let pos = 0;
|
|
for (;;) {
|
|
// For issue keywords, GitHub natively closes pos === 0 when bare #N/URL/owner/repo#N.
|
|
// Still emit pos === 0 only for markdown-link/PR keywords, or list continuations (pos > 0),
|
|
// avoiding racing GitHub native auto-close.
|
|
const nativeClose = targetKind === "issue" && pos === 0 && tokens[skipEmph(tokens, j)]?.kind === "ref";
|
|
if (!nativeClose && (pos === 0 || endsCleanly(tokens, ref.end))) {
|
|
found.push({ repository: ref.token.repository ?? self, number: ref.token.number, keyword: token.text, targetKind });
|
|
}
|
|
j = ref.end;
|
|
pos++;
|
|
let k = skipEmph(tokens, j);
|
|
let sep = false;
|
|
if (isPunct(tokens[k], ",")) { k++; sep = true; }
|
|
if (isWord(tokens[k], "and") || isPunct(tokens[k], "&")) { k++; sep = true; }
|
|
if (!sep) break;
|
|
ref = readRef(tokens, k);
|
|
if (!ref) break;
|
|
if (!endsCleanly(tokens, ref.end)) break;
|
|
}
|
|
i = j;
|
|
}
|
|
return found;
|
|
}
|
|
|
|
const { owner, repo } = context.repo;
|
|
const repository = `${owner}/${repo}`;
|
|
const expectedRepoUrl = `https://api.github.com/repos/${repository.toLowerCase()}`;
|
|
const inputs = context.payload.inputs ?? {};
|
|
const event = context.payload.pull_request;
|
|
const prNumber = event?.number ?? Number(inputs.pr_number);
|
|
const dryRun = String(inputs.dry_run ?? "false") === "true";
|
|
|
|
if (!Number.isInteger(prNumber) || prNumber <= 0) {
|
|
core.setFailed(`Invalid pull request number: ${inputs.pr_number}`);
|
|
return;
|
|
}
|
|
|
|
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
|
|
if (!pr.merged) {
|
|
core.info(`#${prNumber}: not merged, skipping`);
|
|
return;
|
|
}
|
|
const defaultBranch = pr.base.repo.default_branch;
|
|
if (pr.base.ref !== defaultBranch) {
|
|
core.info(`#${prNumber}: merged into ${pr.base.ref}, not ${defaultBranch}, skipping`);
|
|
return;
|
|
}
|
|
|
|
const prAuthor = pr.user?.login?.toLowerCase();
|
|
const trustedAuthor = ["OWNER", "MEMBER"].includes(pr.author_association);
|
|
const body = (event ? event.body : pr.body) ?? "";
|
|
const seen = new Set();
|
|
const targets = [];
|
|
for (const ref of findLinkedReferences(body, repository)) {
|
|
if (ref.repository !== repository.toLowerCase()) continue;
|
|
if (ref.number === prNumber || seen.has(ref.number)) continue;
|
|
seen.add(ref.number);
|
|
targets.push(ref);
|
|
}
|
|
if (targets.length === 0) {
|
|
core.info(`#${prNumber}: no additional linked references to close`);
|
|
return;
|
|
}
|
|
if (targets.length > MAX_TARGETS) {
|
|
core.warning(`#${prNumber}: found ${targets.length} references (cap ${MAX_TARGETS}); refusing bulk close`);
|
|
return;
|
|
}
|
|
|
|
let failed = 0;
|
|
for (const ref of targets) {
|
|
let item;
|
|
try {
|
|
({ data: item } = await github.rest.issues.get({ owner, repo, issue_number: ref.number }));
|
|
} catch (error) {
|
|
if (error.status === 404 || error.status === 410) continue;
|
|
failed++;
|
|
core.error(`#${ref.number}: ${error.message}`);
|
|
continue;
|
|
}
|
|
if (item.repository_url && item.repository_url.toLowerCase() !== expectedRepoUrl) continue;
|
|
if (item.state !== "open") continue;
|
|
const isPull = item.pull_request !== undefined;
|
|
// Only close issues for close/fix/resolve, and only close PRs for supersede/replace.
|
|
if (ref.targetKind === "issue" && isPull) continue;
|
|
if (ref.targetKind === "pull" && !isPull) continue;
|
|
// Only allow an outside contributor PR to supersede their own PR.
|
|
if (isPull && !trustedAuthor && item.user?.login?.toLowerCase() !== prAuthor) {
|
|
core.info(`#${ref.number}: skipping supersede of another contributor PR by non-member`);
|
|
continue;
|
|
}
|
|
if (dryRun) {
|
|
core.info(`[dry-run] Would close ${isPull ? "PR" : "issue"} #${ref.number} (${ref.keyword} in #${prNumber})`);
|
|
continue;
|
|
}
|
|
try {
|
|
if (isPull) {
|
|
await github.rest.pulls.update({ owner, repo, pull_number: ref.number, state: "closed" });
|
|
} else {
|
|
await github.rest.issues.update({ owner, repo, issue_number: ref.number, state: "closed", state_reason: "completed" });
|
|
}
|
|
await github.rest.issues.createComment({
|
|
owner,
|
|
repo,
|
|
issue_number: ref.number,
|
|
body: isPull ? `Superseded by #${prNumber}.` : `Closed as completed by #${prNumber}.`,
|
|
});
|
|
} catch (error) {
|
|
failed++;
|
|
core.error(`#${ref.number}: ${error.message}`);
|
|
}
|
|
}
|
|
if (failed > 0) core.setFailed(`${failed} of ${targets.length} references could not be closed`);
|