From 8edec3e39e59ce412cde45a6dbf1b6c74ad2b7ce Mon Sep 17 00:00:00 2001
From: pelikhan <4175913+pelikhan@users.noreply.github.com>
Date: Mon, 23 Nov 2026 17:46:12 +0000
Subject: [PATCH 1/4] Route simple skip-if queries through GraphQL/REST to
reduce search API pressure
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
---
.changeset/skip-if-query-api-routing.md | 5 +
actions/setup/js/check_skip_if_helpers.cjs | 11 +-
actions/setup/js/skip_if_query.cjs | 379 ++++++++++++++++++++
actions/setup/js/skip_if_query.test.cjs | 153 ++++++++
docs/src/content/docs/reference/triggers.md | 2 +
5 files changed, 543 insertions(+), 7 deletions(-)
create mode 100644 .changeset/skip-if-query-api-routing.md
create mode 100644 actions/setup/js/skip_if_query.cjs
create mode 100644 actions/setup/js/skip_if_query.test.cjs
diff --git a/.changeset/skip-if-query-api-routing.md b/.changeset/skip-if-query-api-routing.md
new file mode 100644
index 00000000000..0de0835aa29
--- /dev/null
+++ b/.changeset/skip-if-query-api-routing.md
@@ -0,0 +1,5 @@
+---
+"gh-aw": patch
+---
+
+Evaluate simple `skip-if-match`/`skip-if-no-match` queries through GraphQL or REST list endpoints instead of the rate-limited search API, choosing the backend from current rate-limit pressure and falling back to search for queries that need it.
diff --git a/actions/setup/js/check_skip_if_helpers.cjs b/actions/setup/js/check_skip_if_helpers.cjs
index 19d8e4f9a12..9375e9ad255 100644
--- a/actions/setup/js/check_skip_if_helpers.cjs
+++ b/actions/setup/js/check_skip_if_helpers.cjs
@@ -4,6 +4,7 @@
const { getErrorMessage } = require("./error_helpers.cjs");
const { ERR_API, ERR_CONFIG } = require("./error_codes.cjs");
const { writeDenialSummary } = require("./pre_activation_summary.cjs");
+const { countSearchMatches } = require("./skip_if_query.cjs");
/**
* Builds the GitHub search query, optionally scoping it to the current repository.
@@ -74,14 +75,10 @@ async function runSkipQueryGate(options) {
const searchQuery = buildSearchQuery(skipQuery, skipScope);
try {
- const {
- data: { total_count: totalCount },
- } = await github.rest.search.issuesAndPullRequests({
- q: searchQuery,
- per_page: 1,
- });
+ const { totalCount, exact, backend } = await countSearchMatches(searchQuery, threshold);
- core.info(`Search found ${totalCount} matching items`);
+ core.info(`Evaluated query via ${backend} API`);
+ core.info(`Search found ${exact ? "" : "at least "}${totalCount} matching items`);
if (shouldSkip(totalCount, threshold)) {
core.warning(warningMessage(totalCount, threshold));
diff --git a/actions/setup/js/skip_if_query.cjs b/actions/setup/js/skip_if_query.cjs
new file mode 100644
index 00000000000..8257c8c3536
--- /dev/null
+++ b/actions/setup/js/skip_if_query.cjs
@@ -0,0 +1,379 @@
+// @ts-check
+///
+
+/**
+ * Mini GitHub issue/PR search query parser and count evaluator for skip-if gates.
+ *
+ * The search API has a much lower rate limit (30 req/min) than REST (core) or
+ * GraphQL. Simple queries (repo-scoped issue/PR listing with state, label,
+ * author, assignee, or mention filters) are evaluated through GraphQL or REST
+ * instead. Anything the parser cannot translate exactly falls back to search.
+ */
+
+const { getErrorMessage } = require("./error_helpers.cjs");
+
+/** @typedef {"graphql" | "rest" | "search"} QueryBackend */
+
+/**
+ * @typedef {Object} ParsedQuery
+ * @property {"issue" | "pr" | null} type
+ * @property {"open" | "closed" | "merged" | null} state
+ * @property {string[]} labels - Labels combined with AND semantics
+ * @property {{ owner: string, repo: string } | null} repo
+ * @property {string | null} author
+ * @property {string | null} assignee
+ * @property {string | null} mentions
+ */
+
+/**
+ * @typedef {{ ok: true, query: ParsedQuery } | { ok: false, reason: string }} ParseResult
+ */
+
+/**
+ * @typedef {Object} CountResult
+ * @property {number} totalCount - Number of matches (a lower bound when `exact` is false)
+ * @property {boolean} exact - Whether totalCount is the full match count
+ * @property {QueryBackend} backend
+ */
+
+/** Preferred backend order when there is no rate-limit pressure. */
+/** @type {QueryBackend[]} */
+const BACKEND_PREFERENCE = ["graphql", "rest", "search"];
+
+/** Rate-limit resource consumed by each backend. */
+const BACKEND_RESOURCE = { graphql: "graphql", rest: "core", search: "search" };
+
+/** A backend is under pressure when less than this fraction of its quota remains. */
+const LOW_QUOTA_FRACTION = 0.1;
+
+/** Maximum REST pages fetched while counting before deferring to another backend. */
+const REST_MAX_PAGES = 5;
+const REST_PAGE_SIZE = 100;
+
+const LOGIN_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
+const REPO_PATTERN = /^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/;
+
+/**
+ * Splits a search query into whitespace-separated tokens, keeping quoted
+ * segments intact. Returns null when quotes are unbalanced.
+ * @param {string} query
+ * @returns {string[] | null}
+ */
+function tokenizeSearchQuery(query) {
+ /** @type {string[]} */
+ const tokens = [];
+ let current = "";
+ let inQuotes = false;
+ for (const ch of query) {
+ if (ch === '"') {
+ inQuotes = !inQuotes;
+ current += ch;
+ } else if (!inQuotes && /\s/.test(ch)) {
+ if (current) tokens.push(current);
+ current = "";
+ } else {
+ current += ch;
+ }
+ }
+ if (inQuotes) return null;
+ if (current) tokens.push(current);
+ return tokens;
+}
+
+/**
+ * @param {string} value
+ * @returns {string}
+ */
+function unquote(value) {
+ return value.length >= 2 && value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
+}
+
+/**
+ * Parses a GitHub issue/PR search query into a structured filter when every
+ * qualifier can be evaluated without the search API.
+ * @param {string} query
+ * @returns {ParseResult}
+ */
+function parseSearchQuery(query) {
+ const tokens = tokenizeSearchQuery(query);
+ if (!tokens) return { ok: false, reason: "unbalanced quotes" };
+ if (tokens.length === 0) return { ok: false, reason: "empty query" };
+
+ /** @type {ParsedQuery} */
+ const parsed = { type: null, state: null, labels: [], repo: null, author: null, assignee: null, mentions: null };
+
+ /**
+ * @param {"type" | "state"} field
+ * @param {any} value
+ * @returns {string | null} conflict reason
+ */
+ const setOnce = (field, value) => {
+ if (parsed[field] !== null && parsed[field] !== value) return `conflicting ${field} qualifiers`;
+ parsed[field] = value;
+ return null;
+ };
+
+ for (const token of tokens) {
+ if (token.startsWith("-")) return { ok: false, reason: `negated qualifier "${token}"` };
+ const colon = token.indexOf(":");
+ if (colon <= 0) return { ok: false, reason: `free-text term "${token}"` };
+
+ const key = token.slice(0, colon).toLowerCase();
+ const rawValue = unquote(token.slice(colon + 1));
+ const value = rawValue.toLowerCase();
+ if (!rawValue) return { ok: false, reason: `empty qualifier "${token}"` };
+
+ /** @type {string | null} */
+ let conflict = null;
+ switch (key) {
+ case "is":
+ if (value === "issue" || value === "pr" || value === "pull-request") conflict = setOnce("type", value === "issue" ? "issue" : "pr");
+ else if (value === "open" || value === "closed") conflict = setOnce("state", value);
+ else if (value === "merged") conflict = setOnce("state", "merged") || setOnce("type", "pr");
+ else return { ok: false, reason: `unsupported qualifier "${token}"` };
+ break;
+ case "type":
+ if (value === "issue" || value === "pr" || value === "pull-request") conflict = setOnce("type", value === "issue" ? "issue" : "pr");
+ else return { ok: false, reason: `unsupported qualifier "${token}"` };
+ break;
+ case "state":
+ if (value === "open" || value === "closed") conflict = setOnce("state", value);
+ else return { ok: false, reason: `unsupported qualifier "${token}"` };
+ break;
+ case "label":
+ // Comma-separated labels use OR semantics in search; REST label filters are AND-only.
+ if (rawValue.includes(",")) return { ok: false, reason: `OR label list "${token}"` };
+ if (!parsed.labels.includes(rawValue)) parsed.labels.push(rawValue);
+ break;
+ case "repo": {
+ const match = REPO_PATTERN.exec(rawValue);
+ if (!match) return { ok: false, reason: `unsupported repository "${rawValue}"` };
+ const repo = { owner: match[1], repo: match[2] };
+ // Multiple repo: qualifiers use OR semantics.
+ if (parsed.repo && (parsed.repo.owner.toLowerCase() !== repo.owner.toLowerCase() || parsed.repo.repo.toLowerCase() !== repo.repo.toLowerCase())) {
+ return { ok: false, reason: "multiple repo qualifiers" };
+ }
+ parsed.repo = repo;
+ break;
+ }
+ case "author":
+ case "assignee":
+ case "mentions": {
+ if (!LOGIN_PATTERN.test(rawValue)) return { ok: false, reason: `unsupported ${key} "${rawValue}"` };
+ if (parsed[key] !== null && parsed[key]?.toLowerCase() !== value) return { ok: false, reason: `multiple ${key} qualifiers` };
+ parsed[key] = rawValue;
+ break;
+ }
+ case "sort":
+ // Sorting does not affect the match count.
+ break;
+ default:
+ return { ok: false, reason: `unsupported qualifier "${token}"` };
+ }
+ if (conflict) return { ok: false, reason: conflict };
+ }
+
+ if (parsed.type === "issue" && parsed.state === "merged") return { ok: false, reason: "is:merged applies only to pull requests" };
+ if (!parsed.repo) return { ok: false, reason: "query is not scoped to a single repository" };
+
+ return { ok: true, query: parsed };
+}
+
+/**
+ * Returns the backends able to evaluate the parsed query exactly, in preference order.
+ * @param {ParseResult} parseResult
+ * @returns {QueryBackend[]}
+ */
+function getCapableBackends(parseResult) {
+ if (!parseResult.ok) return ["search"];
+ const q = parseResult.query;
+ /** @type {QueryBackend[]} */
+ const backends = [];
+ // GraphQL label filters use OR semantics, so only a single label is exact.
+ // Pull request connections cannot filter by author/assignee/mentions.
+ const hasUserFilters = Boolean(q.author || q.assignee || q.mentions);
+ if (q.labels.length <= 1 && (q.type === "issue" || !hasUserFilters)) backends.push("graphql");
+ backends.push("rest", "search");
+ return backends;
+}
+
+/**
+ * Fetches current rate-limit resources. Returns null when unavailable.
+ * The rate_limit endpoint does not count against any quota.
+ * @returns {Promise | null>}
+ */
+async function fetchRateLimitResources() {
+ try {
+ const { data } = await github.rest.rateLimit.get();
+ return /** @type {any} */ data?.resources ?? null;
+ } catch (error) {
+ core.info(`Rate limit lookup failed: ${getErrorMessage(error)}`);
+ return null;
+ }
+}
+
+/**
+ * Orders capable backends by preference, demoting backends under rate-limit pressure.
+ * @param {QueryBackend[]} capable
+ * @param {Record | null} resources
+ * @returns {QueryBackend[]}
+ */
+function orderBackendsByPressure(capable, resources) {
+ const ordered = BACKEND_PREFERENCE.filter(b => capable.includes(b));
+ if (!resources) return ordered;
+
+ /** @param {QueryBackend} backend */
+ const headroom = backend => {
+ const resource = resources[BACKEND_RESOURCE[backend]];
+ if (!resource || !(resource.limit > 0)) return 1;
+ return resource.remaining / resource.limit;
+ };
+ /** @param {QueryBackend} backend */
+ const remaining = backend => resources[BACKEND_RESOURCE[backend]]?.remaining ?? Infinity;
+
+ const healthy = ordered.filter(b => remaining(b) > 0 && headroom(b) >= LOW_QUOTA_FRACTION);
+ const pressured = ordered.filter(b => !healthy.includes(b)).sort((a, b) => headroom(b) - headroom(a));
+ return [...healthy, ...pressured];
+}
+
+/**
+ * @param {ParsedQuery} q
+ * @returns {Promise}
+ */
+async function countWithGraphQL(q) {
+ if (!q.repo) throw new Error("query is not scoped to a repository");
+ const { owner, repo } = q.repo;
+ const labels = q.labels.length ? q.labels : null;
+ const includeIssues = q.type !== "pr";
+ const includePRs = q.type !== "issue";
+
+ const issueStates = q.state === "open" ? ["OPEN"] : q.state === "closed" ? ["CLOSED"] : null;
+ const prStates = q.state === "open" ? ["OPEN"] : q.state === "closed" ? ["CLOSED", "MERGED"] : q.state === "merged" ? ["MERGED"] : null;
+ // Omit unset filters: an explicit `assignee: null` means "unassigned" in GraphQL.
+ /** @type {Record} */
+ const filterBy = {};
+ if (q.assignee) filterBy.assignee = q.assignee;
+ if (q.author) filterBy.createdBy = q.author;
+ if (q.mentions) filterBy.mentioned = q.mentions;
+
+ // GraphQL rejects declared-but-unused variables, so declare only what each field uses.
+ const declarations = ["$owner: String!", "$repo: String!", "$labels: [String!]"];
+ /** @type {Record} */
+ const variables = { owner, repo, labels };
+ const fields = [];
+ if (includeIssues) {
+ declarations.push("$issueStates: [IssueState!]", "$filterBy: IssueFilters");
+ Object.assign(variables, { issueStates, filterBy });
+ fields.push("issues(states: $issueStates, labels: $labels, filterBy: $filterBy) { totalCount }");
+ }
+ if (includePRs) {
+ declarations.push("$prStates: [PullRequestState!]");
+ variables.prStates = prStates;
+ fields.push("pullRequests(states: $prStates, labels: $labels) { totalCount }");
+ }
+
+ const query = `query(${declarations.join(", ")}) { repository(owner: $owner, name: $repo) { ${fields.join(" ")} } }`;
+ /** @type {any} */
+ const result = await github.graphql(query, variables);
+ if (!result?.repository) throw new Error(`Repository ${owner}/${repo} not found`);
+ const totalCount = (result.repository.issues?.totalCount ?? 0) + (result.repository.pullRequests?.totalCount ?? 0);
+ return { totalCount, exact: true, backend: "graphql" };
+}
+
+/**
+ * Counts matches through REST list endpoints, stopping once the threshold is reached.
+ * @param {ParsedQuery} q
+ * @param {number} threshold
+ * @returns {Promise}
+ */
+async function countWithRest(q, threshold) {
+ if (!q.repo) throw new Error("query is not scoped to a repository");
+ const { owner, repo } = q.repo;
+ /** @type {"open" | "closed" | "all"} */
+ const apiState = q.state === "merged" ? "closed" : (q.state ?? "all");
+ const usePulls = q.type === "pr" && q.labels.length === 0 && !q.author && !q.assignee && !q.mentions;
+ const needsClientFilter = q.type !== null || q.state === "merged";
+ const perPage = needsClientFilter ? REST_PAGE_SIZE : Math.min(REST_PAGE_SIZE, threshold);
+
+ /** @param {any} item */
+ const matches = item => {
+ const isPR = usePulls || Boolean(item.pull_request);
+ if (q.type === "issue" && isPR) return false;
+ if (q.type === "pr" && !isPR) return false;
+ if (q.state === "merged") return Boolean(usePulls ? item.merged_at : item.pull_request?.merged_at);
+ return true;
+ };
+
+ let count = 0;
+ for (let page = 1; page <= REST_MAX_PAGES; page++) {
+ /** @type {any[]} */
+ let items;
+ if (usePulls) {
+ ({ data: items } = await github.rest.pulls.list({ owner, repo, state: apiState, per_page: perPage, page }));
+ } else {
+ /** @type {any} */
+ const params = { owner, repo, state: apiState, per_page: perPage, page };
+ if (q.labels.length) params.labels = q.labels.join(",");
+ if (q.author) params.creator = q.author;
+ if (q.assignee) params.assignee = q.assignee;
+ if (q.mentions) params.mentioned = q.mentions;
+ ({ data: items } = await github.rest.issues.listForRepo(params));
+ }
+ count += items.filter(matches).length;
+ if (items.length < perPage) return { totalCount: count, exact: true, backend: "rest" };
+ if (count >= threshold) return { totalCount: count, exact: false, backend: "rest" };
+ }
+ throw new Error(`inconclusive after ${REST_MAX_PAGES} pages (${count} matches, threshold ${threshold})`);
+}
+
+/**
+ * @param {string} searchQuery
+ * @returns {Promise}
+ */
+async function countWithSearch(searchQuery) {
+ const {
+ data: { total_count: totalCount },
+ } = await github.rest.search.issuesAndPullRequests({ q: searchQuery, per_page: 1 });
+ return { totalCount, exact: true, backend: "search" };
+}
+
+/**
+ * Counts issues/PRs matching a search query using the cheapest capable backend
+ * given current rate-limit pressure, falling back to the next backend on error.
+ * @param {string} searchQuery - Fully scoped search query
+ * @param {number} threshold - Count at which the gate decision is settled
+ * @returns {Promise}
+ */
+async function countSearchMatches(searchQuery, threshold) {
+ const parseResult = parseSearchQuery(searchQuery);
+ if (!parseResult.ok) {
+ core.info(`Query requires the search API (${parseResult.reason})`);
+ return countWithSearch(searchQuery);
+ }
+
+ const resources = await fetchRateLimitResources();
+ const backends = orderBackendsByPressure(getCapableBackends(parseResult), resources);
+ core.info(`Query evaluation backends: ${backends.join(" → ")}`);
+
+ /** @type {unknown} */
+ let lastError;
+ for (const backend of backends) {
+ try {
+ if (backend === "graphql") return await countWithGraphQL(parseResult.query);
+ if (backend === "rest") return await countWithRest(parseResult.query, threshold);
+ return await countWithSearch(searchQuery);
+ } catch (error) {
+ lastError = error;
+ core.info(`${backend} evaluation failed: ${getErrorMessage(error)}`);
+ }
+ }
+ throw lastError;
+}
+
+module.exports = {
+ tokenizeSearchQuery,
+ parseSearchQuery,
+ getCapableBackends,
+ orderBackendsByPressure,
+ countSearchMatches,
+};
diff --git a/actions/setup/js/skip_if_query.test.cjs b/actions/setup/js/skip_if_query.test.cjs
new file mode 100644
index 00000000000..05081f959c8
--- /dev/null
+++ b/actions/setup/js/skip_if_query.test.cjs
@@ -0,0 +1,153 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+const mockCore = { info: vi.fn(), debug: vi.fn(), warning: vi.fn() };
+global.core = mockCore;
+
+const { parseSearchQuery, getCapableBackends, orderBackendsByPressure, countSearchMatches } = await import("./skip_if_query.cjs");
+
+const REPO = "repo:octo/demo";
+
+describe("skip_if_query.cjs - parseSearchQuery", () => {
+ it("parses simple repo-scoped list queries", () => {
+ const result = parseSearchQuery(`is:issue is:open label:bug label:"needs triage" author:octocat sort:created-desc ${REPO}`);
+ expect(result).toEqual({
+ ok: true,
+ query: { type: "issue", state: "open", labels: ["bug", "needs triage"], repo: { owner: "octo", repo: "demo" }, author: "octocat", assignee: null, mentions: null },
+ });
+ });
+
+ it("treats is:merged and is:pull-request as pull request filters", () => {
+ const result = parseSearchQuery(`is:pull-request is:merged ${REPO}`);
+ expect(result.ok && result.query).toMatchObject({ type: "pr", state: "merged" });
+ });
+
+ it.each([
+ [`is:issue in:title "[daily-report]" ${REPO}`, "unsupported qualifier"],
+ [`is:issue "[daily-report]" ${REPO}`, "free-text"],
+ [`is:issue -label:bug ${REPO}`, "negated"],
+ [`is:issue label:bug,urgent ${REPO}`, "OR label list"],
+ [`is:issue is:pr ${REPO}`, "conflicting type"],
+ [`is:issue is:merged ${REPO}`, "conflicting type"],
+ [`is:issue ${REPO} repo:octo/other`, "multiple repo"],
+ [`is:issue assignee:@me ${REPO}`, "unsupported assignee"],
+ ["org:octo is:issue label:bug", "unsupported qualifier"],
+ ["is:issue label:bug", "not scoped"],
+ [`is:issue label:"unterminated ${REPO}`, "unbalanced quotes"],
+ ])("rejects %s", (query, reason) => {
+ const result = parseSearchQuery(query);
+ expect(result.ok).toBe(false);
+ expect(!result.ok && result.reason).toContain(reason);
+ });
+});
+
+describe("skip_if_query.cjs - backend selection", () => {
+ it("excludes GraphQL when label or user filters cannot be expressed exactly", () => {
+ expect(getCapableBackends(parseSearchQuery(`is:issue label:bug ${REPO}`))).toEqual(["graphql", "rest", "search"]);
+ expect(getCapableBackends(parseSearchQuery(`is:issue label:a label:b ${REPO}`))).toEqual(["rest", "search"]);
+ expect(getCapableBackends(parseSearchQuery(`is:pr author:octocat ${REPO}`))).toEqual(["rest", "search"]);
+ expect(getCapableBackends(parseSearchQuery(`is:issue in:title x ${REPO}`))).toEqual(["search"]);
+ });
+
+ it("demotes backends whose quota is under pressure", () => {
+ const resources = {
+ graphql: { limit: 5000, remaining: 100 },
+ core: { limit: 5000, remaining: 4000 },
+ search: { limit: 30, remaining: 30 },
+ };
+ expect(orderBackendsByPressure(["graphql", "rest", "search"], resources)).toEqual(["rest", "search", "graphql"]);
+ expect(orderBackendsByPressure(["graphql", "rest", "search"], { ...resources, core: { limit: 5000, remaining: 0 } })).toEqual(["search", "graphql", "rest"]);
+ expect(orderBackendsByPressure(["graphql", "rest", "search"], null)).toEqual(["graphql", "rest", "search"]);
+ });
+});
+
+describe("skip_if_query.cjs - countSearchMatches", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ global.github = {
+ graphql: vi.fn(),
+ rest: {
+ rateLimit: { get: vi.fn().mockResolvedValue({ data: { resources: {} } }) },
+ issues: { listForRepo: vi.fn() },
+ pulls: { list: vi.fn() },
+ search: { issuesAndPullRequests: vi.fn() },
+ },
+ };
+ });
+
+ it("counts simple queries through GraphQL without using search", async () => {
+ global.github.graphql.mockResolvedValue({ repository: { issues: { totalCount: 3 } } });
+
+ const result = await countSearchMatches(`is:issue is:open label:bug ${REPO}`, 1);
+
+ expect(result).toEqual({ totalCount: 3, exact: true, backend: "graphql" });
+ const [query, variables] = global.github.graphql.mock.calls[0];
+ expect(query).toContain("issues(");
+ expect(query).not.toContain("pullRequests(");
+ expect(query).not.toContain("$prStates");
+ expect(variables).toMatchObject({ owner: "octo", repo: "demo", labels: ["bug"], issueStates: ["OPEN"] });
+ // A null assignee would mean "unassigned" in GraphQL, so unset filters must be omitted.
+ expect(variables.filterBy).toEqual({});
+ expect(global.github.rest.search.issuesAndPullRequests).not.toHaveBeenCalled();
+ });
+
+ it("sums issues and pull requests for untyped queries and maps closed PRs to closed+merged", async () => {
+ global.github.graphql.mockResolvedValue({ repository: { issues: { totalCount: 2 }, pullRequests: { totalCount: 5 } } });
+
+ const result = await countSearchMatches(`is:closed ${REPO}`, 1);
+
+ expect(result.totalCount).toBe(7);
+ expect(global.github.graphql.mock.calls[0][1]).toMatchObject({ issueStates: ["CLOSED"], prStates: ["CLOSED", "MERGED"] });
+ });
+
+ it("falls back to REST when GraphQL fails and stops paging at the threshold", async () => {
+ global.github.graphql.mockRejectedValue(new Error("boom"));
+ const page = Array.from({ length: 100 }, (_, i) => (i % 2 ? { pull_request: {} } : {}));
+ global.github.rest.issues.listForRepo.mockResolvedValue({ data: page });
+
+ const result = await countSearchMatches(`is:issue is:open label:bug ${REPO}`, 60);
+
+ expect(result).toEqual({ totalCount: 100, exact: false, backend: "rest" });
+ expect(global.github.rest.issues.listForRepo).toHaveBeenCalledTimes(2);
+ expect(global.github.rest.issues.listForRepo).toHaveBeenCalledWith({ owner: "octo", repo: "demo", state: "open", labels: "bug", per_page: 100, page: 1 });
+ expect(global.github.rest.search.issuesAndPullRequests).not.toHaveBeenCalled();
+ });
+
+ it("uses REST with AND label semantics when GraphQL cannot express the query", async () => {
+ global.github.rest.issues.listForRepo.mockResolvedValue({ data: [{}] });
+
+ const result = await countSearchMatches(`label:a label:b assignee:octocat ${REPO}`, 2);
+
+ expect(result).toEqual({ totalCount: 1, exact: true, backend: "rest" });
+ expect(global.github.rest.issues.listForRepo).toHaveBeenCalledWith({ owner: "octo", repo: "demo", state: "all", labels: "a,b", assignee: "octocat", per_page: 2, page: 1 });
+ expect(global.github.graphql).not.toHaveBeenCalled();
+ });
+
+ it("counts merged pull requests through the pulls endpoint", async () => {
+ global.github.rest.rateLimit.get.mockResolvedValue({ data: { resources: { graphql: { limit: 5000, remaining: 0 } } } });
+ global.github.rest.pulls.list.mockResolvedValue({ data: [{ merged_at: "2026-01-01" }, { merged_at: null }] });
+
+ const result = await countSearchMatches(`is:pr is:merged ${REPO}`, 5);
+
+ expect(result).toEqual({ totalCount: 1, exact: true, backend: "rest" });
+ expect(global.github.rest.pulls.list).toHaveBeenCalledWith({ owner: "octo", repo: "demo", state: "closed", per_page: 100, page: 1 });
+ });
+
+ it("uses search directly for queries the parser cannot translate", async () => {
+ global.github.rest.search.issuesAndPullRequests.mockResolvedValue({ data: { total_count: 4 } });
+ const query = `is:issue in:title "[daily-report]" ${REPO}`;
+
+ const result = await countSearchMatches(query, 1);
+
+ expect(result).toEqual({ totalCount: 4, exact: true, backend: "search" });
+ expect(global.github.rest.search.issuesAndPullRequests).toHaveBeenCalledWith({ q: query, per_page: 1 });
+ expect(global.github.rest.rateLimit.get).not.toHaveBeenCalled();
+ });
+
+ it("rethrows the last backend error when every backend fails", async () => {
+ global.github.graphql.mockRejectedValue(new Error("graphql down"));
+ global.github.rest.issues.listForRepo.mockRejectedValue(new Error("rest down"));
+ global.github.rest.search.issuesAndPullRequests.mockRejectedValue(new Error("search down"));
+
+ await expect(countSearchMatches(`is:issue ${REPO}`, 1)).rejects.toThrow("search down");
+ });
+});
diff --git a/docs/src/content/docs/reference/triggers.md b/docs/src/content/docs/reference/triggers.md
index 644dc3d70b2..5c64b97c91f 100644
--- a/docs/src/content/docs/reference/triggers.md
+++ b/docs/src/content/docs/reference/triggers.md
@@ -772,6 +772,8 @@ on: weekly on monday
A pre-activation check runs the query against the current repository. If matches reach or exceed the threshold (default `max: 1`), the workflow is skipped. All standard GitHub search qualifiers are supported (`is:`, `label:`, `in:title`, `author:`, etc.).
+To spare the search API's low rate limit, simple single-repository queries are evaluated with GraphQL or REST list endpoints instead. A query qualifies when it uses only `is:`/`type:`/`state:` (`issue`, `pr`, `open`, `closed`, `merged`), `label:` (no comma lists), `author:`, `assignee:`, `mentions:`, `sort:`, and one `repo:`. The check reads current rate limits, prefers GraphQL, then REST, then search, demotes any API with less than 10% quota remaining, and falls back to the next API on error. Free text, negations, `in:`, `org:`, and other qualifiers always use the search API.
+
Use `scope: none` to remove the automatic repo qualifier and search org-wide. For cross-repo or org-wide searches that need elevated permissions, configure `github-token` or `github-app` at the top-level `on:` section — the same token is shared across all skip-if checks and the activation job:
```yaml wrap
From cf9bdc2c68095f1b9516ea79039fd63a5b33e468 Mon Sep 17 00:00:00 2001
From: pelikhan <4175913+pelikhan@users.noreply.github.com>
Date: Mon, 23 Nov 2026 17:52:14 +0000
Subject: [PATCH 2/4] Document the efficient skip-if query subset in agent
instructions and schema
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
---
.github/aw/syntax-core.md | 5 +++++
.../src/content/docs/reference/frontmatter-full.md | 14 ++++++++++----
pkg/parser/schemas/main_workflow_schema.json | 4 ++--
3 files changed, 17 insertions(+), 6 deletions(-)
diff --git a/.github/aw/syntax-core.md b/.github/aw/syntax-core.md
index 2834b1ff55d..99d2d1b27fe 100644
--- a/.github/aw/syntax-core.md
+++ b/.github/aw/syntax-core.md
@@ -57,6 +57,11 @@ The YAML frontmatter supports these fields:
- Query is automatically scoped to the current repository (use `scope: none` for cross-repo queries)
- Use to gate workflows on preconditions (e.g., only run if open PRs exist)
+ - **Efficient skip-if queries**: prefer the subset evaluated via GraphQL/REST instead of the rate-limited search API (30 req/min):
+ - Allowed: `is:`/`type:`/`state:` (`issue`, `pr`, `open`, `closed`, `merged`), `label:` (one or more, AND), `author:`, `assignee:`, `mentions:` (plain logins), `sort:`
+ - Must stay scoped to one repository (default scope; not `scope: none`)
+ - Falls back to search: free text, `in:title`/`in:body`, negation (`-label:`), comma label lists (`label:a,b`), `org:`, `@me`, other qualifiers
+ - Prefer a marker label (`is:issue is:open label:my-workflow`) over title/body text matching when designing dedup gates
- **`skip-if-check-failing:`** - Skip workflow execution when CI checks are failing on the triggering ref (boolean or object)
- Boolean format: `skip-if-check-failing: true` (skip if any check is failing or pending)
- Object format with filtering:
diff --git a/docs/src/content/docs/reference/frontmatter-full.md b/docs/src/content/docs/reference/frontmatter-full.md
index cd0fdd66963..741e4774fb9 100644
--- a/docs/src/content/docs/reference/frontmatter-full.md
+++ b/docs/src/content/docs/reference/frontmatter-full.md
@@ -1383,8 +1383,11 @@ on:
# Format 1: GitHub search query string to check before running workflow (implies
# max=1). If the search returns any results, the workflow will be skipped. Query
- # is automatically scoped to the current repository. Example: 'is:issue is:open
- # label:bug'
+ # is automatically scoped to the current repository. Simple queries using only
+ # is:/type:/state:, label:, author:, assignee:, mentions:, and sort: qualifiers
+ # are evaluated via GraphQL/REST instead of the rate-limited search API; free
+ # text, in:, negation, and comma label lists require search. Example: 'is:issue
+ # is:open label:bug'
skip-if-match: "example-value"
# Format 2: Skip-if-match configuration object with query, maximum match count,
@@ -1421,8 +1424,11 @@ on:
# Format 1: GitHub search query string to check before running workflow (implies
# min=1). If the search returns no results, the workflow will be skipped. Query is
- # automatically scoped to the current repository. Example: 'is:pr is:open
- # label:ready-to-deploy'
+ # automatically scoped to the current repository. Simple queries using only
+ # is:/type:/state:, label:, author:, assignee:, mentions:, and sort: qualifiers
+ # are evaluated via GraphQL/REST instead of the rate-limited search API; free
+ # text, in:, negation, and comma label lists require search. Example: 'is:pr
+ # is:open label:ready-to-deploy'
skip-if-no-match: "example-value"
# Format 2: Skip-if-no-match configuration object with query, minimum match count,
diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json
index d7c959603a5..1335c99b6e4 100644
--- a/pkg/parser/schemas/main_workflow_schema.json
+++ b/pkg/parser/schemas/main_workflow_schema.json
@@ -2362,7 +2362,7 @@
"oneOf": [
{
"type": "string",
- "description": "GitHub search query string to check before running workflow (implies max=1). If the search returns any results, the workflow will be skipped. Query is automatically scoped to the current repository. Example: 'is:issue is:open label:bug'"
+ "description": "GitHub search query string to check before running workflow (implies max=1). If the search returns any results, the workflow will be skipped. Query is automatically scoped to the current repository. Simple queries using only is:/type:/state:, label:, author:, assignee:, mentions:, and sort: qualifiers are evaluated via GraphQL/REST instead of the rate-limited search API; free text, in:, negation, and comma label lists require search. Example: 'is:issue is:open label:bug'"
},
{
"type": "object",
@@ -2402,7 +2402,7 @@
"oneOf": [
{
"type": "string",
- "description": "GitHub search query string to check before running workflow (implies min=1). If the search returns no results, the workflow will be skipped. Query is automatically scoped to the current repository. Example: 'is:pr is:open label:ready-to-deploy'"
+ "description": "GitHub search query string to check before running workflow (implies min=1). If the search returns no results, the workflow will be skipped. Query is automatically scoped to the current repository. Simple queries using only is:/type:/state:, label:, author:, assignee:, mentions:, and sort: qualifiers are evaluated via GraphQL/REST instead of the rate-limited search API; free text, in:, negation, and comma label lists require search. Example: 'is:pr is:open label:ready-to-deploy'"
},
{
"type": "object",
From c24a536f333eccafbead658024273f72cfbc1e73 Mon Sep 17 00:00:00 2001
From: pelikhan <4175913+pelikhan@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:15:35 +0000
Subject: [PATCH 3/4] Use backend-neutral skip-if log and dedupe REST
pagination counts
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
---
actions/setup/js/check_skip_if_helpers.cjs | 3 +--
.../setup/js/check_skip_if_no_match.test.cjs | 2 +-
actions/setup/js/skip_if_query.cjs | 15 +++++++----
actions/setup/js/skip_if_query.test.cjs | 27 ++++++++++++++++---
4 files changed, 35 insertions(+), 12 deletions(-)
diff --git a/actions/setup/js/check_skip_if_helpers.cjs b/actions/setup/js/check_skip_if_helpers.cjs
index 9375e9ad255..e49c05d8f29 100644
--- a/actions/setup/js/check_skip_if_helpers.cjs
+++ b/actions/setup/js/check_skip_if_helpers.cjs
@@ -77,8 +77,7 @@ async function runSkipQueryGate(options) {
try {
const { totalCount, exact, backend } = await countSearchMatches(searchQuery, threshold);
- core.info(`Evaluated query via ${backend} API`);
- core.info(`Search found ${exact ? "" : "at least "}${totalCount} matching items`);
+ core.info(`Query matched ${exact ? "" : "at least "}${totalCount} items (via ${backend} API)`);
if (shouldSkip(totalCount, threshold)) {
core.warning(warningMessage(totalCount, threshold));
diff --git a/actions/setup/js/check_skip_if_no_match.test.cjs b/actions/setup/js/check_skip_if_no_match.test.cjs
index 5642a48f17a..1fb8e326164 100644
--- a/actions/setup/js/check_skip_if_no_match.test.cjs
+++ b/actions/setup/js/check_skip_if_no_match.test.cjs
@@ -217,7 +217,7 @@ describe("check_skip_if_no_match", () => {
expect(mockCore.infos).toContain("Checking skip-if-no-match query: is:open is:issue label:enhancement");
expect(mockCore.infos).toContain("Minimum matches threshold: 5");
expect(mockCore.infos).toContain("Scoped query: is:open is:issue label:enhancement repo:test-owner/test-repo");
- expect(mockCore.infos).toContain("Search found 8 matching items");
+ expect(mockCore.infos).toContain("Query matched 8 items (via search API)");
});
it("should use raw query when GH_AW_SKIP_SCOPE is 'none'", async () => {
diff --git a/actions/setup/js/skip_if_query.cjs b/actions/setup/js/skip_if_query.cjs
index 8257c8c3536..985592fcf0d 100644
--- a/actions/setup/js/skip_if_query.cjs
+++ b/actions/setup/js/skip_if_query.cjs
@@ -304,7 +304,10 @@ async function countWithRest(q, threshold) {
return true;
};
- let count = 0;
+ // Page-number pagination can shift items across pages when new issues/PRs
+ // arrive mid-scan, so count distinct ids rather than raw matches.
+ /** @type {Set} */
+ const seen = new Set();
for (let page = 1; page <= REST_MAX_PAGES; page++) {
/** @type {any[]} */
let items;
@@ -319,11 +322,13 @@ async function countWithRest(q, threshold) {
if (q.mentions) params.mentioned = q.mentions;
({ data: items } = await github.rest.issues.listForRepo(params));
}
- count += items.filter(matches).length;
- if (items.length < perPage) return { totalCount: count, exact: true, backend: "rest" };
- if (count >= threshold) return { totalCount: count, exact: false, backend: "rest" };
+ for (const item of items) {
+ if (matches(item)) seen.add(item.id);
+ }
+ if (items.length < perPage) return { totalCount: seen.size, exact: true, backend: "rest" };
+ if (seen.size >= threshold) return { totalCount: seen.size, exact: false, backend: "rest" };
}
- throw new Error(`inconclusive after ${REST_MAX_PAGES} pages (${count} matches, threshold ${threshold})`);
+ throw new Error(`inconclusive after ${REST_MAX_PAGES} pages (${seen.size} matches, threshold ${threshold})`);
}
/**
diff --git a/actions/setup/js/skip_if_query.test.cjs b/actions/setup/js/skip_if_query.test.cjs
index 05081f959c8..f15fd54c926 100644
--- a/actions/setup/js/skip_if_query.test.cjs
+++ b/actions/setup/js/skip_if_query.test.cjs
@@ -101,8 +101,8 @@ describe("skip_if_query.cjs - countSearchMatches", () => {
it("falls back to REST when GraphQL fails and stops paging at the threshold", async () => {
global.github.graphql.mockRejectedValue(new Error("boom"));
- const page = Array.from({ length: 100 }, (_, i) => (i % 2 ? { pull_request: {} } : {}));
- global.github.rest.issues.listForRepo.mockResolvedValue({ data: page });
+ const page = offset => Array.from({ length: 100 }, (_, i) => (i % 2 ? { id: offset + i, pull_request: {} } : { id: offset + i }));
+ global.github.rest.issues.listForRepo.mockResolvedValueOnce({ data: page(0) }).mockResolvedValueOnce({ data: page(100) });
const result = await countSearchMatches(`is:issue is:open label:bug ${REPO}`, 60);
@@ -112,8 +112,22 @@ describe("skip_if_query.cjs - countSearchMatches", () => {
expect(global.github.rest.search.issuesAndPullRequests).not.toHaveBeenCalled();
});
+ it("does not double count items repeated across overlapping REST pages", async () => {
+ global.github.graphql.mockRejectedValue(new Error("boom"));
+ const ids = start => Array.from({ length: 100 }, (_, i) => ({ id: start + i }));
+ global.github.rest.issues.listForRepo
+ .mockResolvedValueOnce({ data: ids(1) })
+ .mockResolvedValueOnce({ data: ids(100) })
+ .mockResolvedValueOnce({ data: [] });
+
+ const result = await countSearchMatches(`is:issue is:open label:bug ${REPO}`, 200);
+
+ expect(result).toEqual({ totalCount: 199, exact: true, backend: "rest" });
+ expect(global.github.rest.issues.listForRepo).toHaveBeenCalledTimes(3);
+ });
+
it("uses REST with AND label semantics when GraphQL cannot express the query", async () => {
- global.github.rest.issues.listForRepo.mockResolvedValue({ data: [{}] });
+ global.github.rest.issues.listForRepo.mockResolvedValue({ data: [{ id: 1 }] });
const result = await countSearchMatches(`label:a label:b assignee:octocat ${REPO}`, 2);
@@ -124,7 +138,12 @@ describe("skip_if_query.cjs - countSearchMatches", () => {
it("counts merged pull requests through the pulls endpoint", async () => {
global.github.rest.rateLimit.get.mockResolvedValue({ data: { resources: { graphql: { limit: 5000, remaining: 0 } } } });
- global.github.rest.pulls.list.mockResolvedValue({ data: [{ merged_at: "2026-01-01" }, { merged_at: null }] });
+ global.github.rest.pulls.list.mockResolvedValue({
+ data: [
+ { id: 1, merged_at: "2026-01-01" },
+ { id: 2, merged_at: null },
+ ],
+ });
const result = await countSearchMatches(`is:pr is:merged ${REPO}`, 5);
From fe55dc739afa6d225bd9686b5558cb1f0465d069 Mon Sep 17 00:00:00 2001
From: pelikhan <4175913+pelikhan@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:59:05 +0000
Subject: [PATCH 4/4] Add fuzz tests for the skip-if query parser
Adds a shared invariant harness (JS), a seeded property test (vitest), and a
Go FuzzSkipIfQueryParser driver registered in make fuzz and CI. Fuzzing found
that partially quoted values (label:"a b"c) were accepted with literal quotes;
these now fall back to the search API.
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
---
.github/workflows/cgo.yml | 1 +
Makefile | 1 +
.../setup/js/fuzz_skip_if_query_harness.cjs | 204 ++++++++++++++++++
.../js/fuzz_skip_if_query_harness.test.cjs | 83 +++++++
actions/setup/js/skip_if_query.cjs | 1 +
pkg/workflow/skip_if_query_fuzz_test.go | 80 +++++++
6 files changed, 370 insertions(+)
create mode 100644 actions/setup/js/fuzz_skip_if_query_harness.cjs
create mode 100644 actions/setup/js/fuzz_skip_if_query_harness.test.cjs
create mode 100644 pkg/workflow/skip_if_query_fuzz_test.go
diff --git a/.github/workflows/cgo.yml b/.github/workflows/cgo.yml
index cd19688b13b..8592469c39d 100644
--- a/.github/workflows/cgo.yml
+++ b/.github/workflows/cgo.yml
@@ -1867,6 +1867,7 @@ jobs:
tests: >-
FuzzExpressionParser:./pkg/workflow/
FuzzBashCommandParserModel:./pkg/workflow/
+ FuzzSkipIfQueryParser:./pkg/workflow/
FuzzMentionsFiltering:./pkg/workflow/
FuzzSanitizeOutput:./pkg/workflow/
FuzzSanitizeIncomingText:./pkg/workflow/
diff --git a/Makefile b/Makefile
index f8ee0e07895..ebd6cf76509 100644
--- a/Makefile
+++ b/Makefile
@@ -275,6 +275,7 @@ fuzz:
go test -fuzz=FuzzParseFrontmatter -fuzztime=30s ./pkg/parser/
go test -fuzz=FuzzExpressionParser -fuzztime=30s ./pkg/workflow/
go test -run='^$$' -fuzz=FuzzBashCommandParserModel -fuzztime=30s ./pkg/workflow/
+ go test -run='^$$' -fuzz=FuzzSkipIfQueryParser -fuzztime=30s ./pkg/workflow/
# Run security regression tests
.PHONY: test-security
diff --git a/actions/setup/js/fuzz_skip_if_query_harness.cjs b/actions/setup/js/fuzz_skip_if_query_harness.cjs
new file mode 100644
index 00000000000..8cdcdeeff0f
--- /dev/null
+++ b/actions/setup/js/fuzz_skip_if_query_harness.cjs
@@ -0,0 +1,204 @@
+// @ts-check
+/**
+ * Fuzz harness for the skip-if search query parser in skip_if_query.cjs.
+ *
+ * Checks parser and backend-selection invariants for arbitrary queries:
+ * - parsing never throws and is deterministic
+ * - accepted queries are fully structured (single repo, valid enums, no OR label lists)
+ * - unsupported queries route only to search; supported ones always keep search as fallback
+ * - GraphQL is offered only when it is exact (<= 1 label, user filters only on issues)
+ * - acceptance is invariant to token order, extra whitespace, and sort: qualifiers
+ * - appending free text or a negated qualifier always forces the search API
+ * - pressure ordering is always a permutation of the capable backends
+ *
+ * Used by vitest and by Go's fuzzing framework when run as main module via stdin.
+ */
+
+const { tokenizeSearchQuery, parseSearchQuery, getCapableBackends, orderBackendsByPressure } = require("./skip_if_query.cjs");
+const { getErrorMessage } = require("./error_helpers.cjs");
+
+const TYPES = [null, "issue", "pr"];
+const STATES = [null, "open", "closed", "merged"];
+const LOGIN_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
+
+/**
+ * Rate-limit scenarios exercised for every query.
+ * @type {(Record | null)[]}
+ */
+const RESOURCE_SCENARIOS = [
+ null,
+ {},
+ { graphql: { limit: 5000, remaining: 5000 }, core: { limit: 5000, remaining: 5000 }, search: { limit: 30, remaining: 30 } },
+ { graphql: { limit: 5000, remaining: 10 }, core: { limit: 5000, remaining: 4000 }, search: { limit: 30, remaining: 30 } },
+ { graphql: { limit: 5000, remaining: 0 }, core: { limit: 5000, remaining: 0 }, search: { limit: 30, remaining: 1 } },
+ { graphql: { limit: 0, remaining: 0 }, core: { limit: 5000, remaining: 499 }, search: { limit: 30, remaining: 0 } },
+];
+
+/**
+ * Normalizes a parse result for comparisons that must ignore token order and casing.
+ * @param {ReturnType} result
+ * @returns {string}
+ */
+function normalize(result) {
+ if (!result.ok) return "unsupported";
+ const q = result.query;
+ const lower = (/** @type {string | null} */ v) => (v === null ? null : v.toLowerCase());
+ return JSON.stringify({
+ type: q.type,
+ state: q.state,
+ labels: [...q.labels].sort(),
+ repo: q.repo && `${q.repo.owner}/${q.repo.repo}`.toLowerCase(),
+ author: lower(q.author),
+ assignee: lower(q.assignee),
+ mentions: lower(q.mentions),
+ });
+}
+
+/**
+ * Returns all invariant violations for a query. Never throws.
+ * @param {string} query
+ * @returns {string[]}
+ */
+function checkSkipIfQueryInvariants(query) {
+ /** @type {string[]} */
+ const violations = [];
+ try {
+ const result = parseSearchQuery(query);
+ if (JSON.stringify(parseSearchQuery(query)) !== JSON.stringify(result)) violations.push("parse is not deterministic");
+
+ const backends = getCapableBackends(result);
+ if (!result.ok) {
+ if (typeof result.reason !== "string" || !result.reason) violations.push("rejection has no reason");
+ if (JSON.stringify(backends) !== '["search"]') violations.push(`unsupported query offered ${backends.join(",")}`);
+ } else {
+ const q = result.query;
+ if (!q.repo || !q.repo.owner || !q.repo.repo) violations.push("accepted query without repository");
+ if (!TYPES.includes(q.type)) violations.push(`invalid type ${q.type}`);
+ if (!STATES.includes(q.state)) violations.push(`invalid state ${q.state}`);
+ if (q.state === "merged" && q.type !== "pr") violations.push("merged state without pr type");
+ if (q.labels.some(l => !l || l.includes(","))) violations.push("empty or OR label accepted");
+ if ([...q.labels, q.author, q.assignee, q.mentions, q.repo?.owner, q.repo?.repo].some(v => v?.includes('"'))) violations.push("value with stray quote accepted");
+ if (new Set(q.labels).size !== q.labels.length) violations.push("duplicate labels");
+ for (const login of [q.author, q.assignee, q.mentions]) {
+ if (login !== null && !LOGIN_PATTERN.test(login)) violations.push(`invalid login ${login}`);
+ }
+
+ if (backends[backends.length - 1] !== "search") violations.push("search is not the final fallback");
+ if (!backends.includes("rest")) violations.push("REST not offered for supported query");
+ const graphqlExact = q.labels.length <= 1 && (q.type === "issue" || !(q.author || q.assignee || q.mentions));
+ if (backends.includes("graphql") !== graphqlExact) violations.push(`graphql offered=${backends.includes("graphql")} exact=${graphqlExact}`);
+
+ for (const suffix of [" zzfreetext", " -label:x", ' "quoted text"', " in:title"]) {
+ if (parseSearchQuery(query + suffix).ok) violations.push(`suffix ${JSON.stringify(suffix)} did not force search`);
+ }
+ }
+
+ for (const resources of RESOURCE_SCENARIOS) {
+ const ordered = orderBackendsByPressure(backends, resources);
+ if (ordered.length !== backends.length || [...ordered].sort().join() !== [...backends].sort().join()) {
+ violations.push(`pressure ordering ${ordered.join(",")} is not a permutation of ${backends.join(",")}`);
+ }
+ }
+
+ const tokens = tokenizeSearchQuery(query);
+ if (tokens === null) {
+ if (result.ok) violations.push("accepted query with unbalanced quotes");
+ } else {
+ const expected = normalize(result);
+ const variants = {
+ reordered: [...tokens].reverse().join(" "),
+ "extra whitespace": ` \t${tokens.join(" \n\t ")} `,
+ "sort qualifier": [...tokens, "sort:updated-desc"].join(" "),
+ };
+ for (const [name, variant] of Object.entries(variants)) {
+ if (normalize(parseSearchQuery(variant)) !== expected) violations.push(`${name} variant changed result`);
+ }
+ }
+ } catch (err) {
+ violations.push(`threw: ${getErrorMessage(err)}`);
+ }
+ return violations;
+}
+
+const FRAGMENTS = [
+ "is:issue",
+ "is:pr",
+ "is:pull-request",
+ "IS:Open",
+ "is:open",
+ "is:closed",
+ "is:merged",
+ "is:draft",
+ "type:issue",
+ "type:pr",
+ "state:open",
+ "state:closed",
+ "state:merged",
+ "label:bug",
+ "label:Bug",
+ 'label:"needs triage"',
+ "label:a,b",
+ 'label:""',
+ "label:",
+ "-label:bug",
+ "repo:octo/demo",
+ "repo:Octo/Demo",
+ "repo:octo/other",
+ "repo:bad",
+ "author:octocat",
+ "author:app/bot",
+ "assignee:@me",
+ "assignee:octocat",
+ "mentions:hubot",
+ "sort:created-desc",
+ "org:octo",
+ "in:title",
+ "no:assignee",
+ '"[daily-report]"',
+ "free",
+ '"unterminated',
+ ":",
+ "-",
+];
+
+/**
+ * Builds a query from a byte choice stream and a free-form payload.
+ * @param {number[]} bytes
+ * @param {string} payload
+ * @returns {string}
+ */
+function buildModelQuery(bytes, payload) {
+ const parts = [];
+ for (const b of bytes.slice(0, 64)) {
+ const pick = b % (FRAGMENTS.length + 4);
+ if (pick < FRAGMENTS.length) parts.push(FRAGMENTS[pick]);
+ else if (pick === FRAGMENTS.length) parts.push(`label:${payload}`);
+ else if (pick === FRAGMENTS.length + 1) parts.push(`author:${payload}`);
+ else if (pick === FRAGMENTS.length + 2) parts.push(`repo:${payload}`);
+ else parts.push(payload);
+ }
+ return parts.join((bytes[0] ?? 0) % 3 === 0 ? " \t " : " ");
+}
+
+// Read input from stdin for Go-driven fuzzing
+if (require.main === module) {
+ let input = "";
+ process.stdin.on("data", chunk => {
+ input += chunk;
+ });
+ process.stdin.on("end", () => {
+ try {
+ // Expected JSON: { query?: string, bytes?: number[], payload?: string }
+ const { query, bytes, payload } = JSON.parse(input);
+ const text = Array.isArray(bytes) ? buildModelQuery(bytes, payload ?? "") : (query ?? "");
+ const violations = checkSkipIfQueryInvariants(text);
+ process.stdout.write(JSON.stringify({ ok: violations.length === 0, query: text, violations }));
+ process.exit(0);
+ } catch (err) {
+ process.stdout.write(JSON.stringify({ ok: false, violations: [getErrorMessage(err)] }));
+ process.exit(1);
+ }
+ });
+}
+
+module.exports = { checkSkipIfQueryInvariants, buildModelQuery, FRAGMENTS };
diff --git a/actions/setup/js/fuzz_skip_if_query_harness.test.cjs b/actions/setup/js/fuzz_skip_if_query_harness.test.cjs
new file mode 100644
index 00000000000..629b295067b
--- /dev/null
+++ b/actions/setup/js/fuzz_skip_if_query_harness.test.cjs
@@ -0,0 +1,83 @@
+// @ts-check
+/**
+ * Property-based fuzz tests for the skip-if search query parser.
+ * Invariants live in fuzz_skip_if_query_harness.cjs and are shared with the Go fuzzer
+ * (pkg/workflow/skip_if_query_fuzz_test.go).
+ */
+import { describe, it, expect } from "vitest";
+
+const { checkSkipIfQueryInvariants, buildModelQuery, FRAGMENTS } = require("./fuzz_skip_if_query_harness.cjs");
+const { parseSearchQuery } = require("./skip_if_query.cjs");
+
+/**
+ * Deterministic mulberry32 PRNG so failures are reproducible.
+ * @param {number} seed
+ */
+function prng(seed) {
+ return () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const PAYLOADS = ["", "x", "octo/demo", "a,b", '"', '"quoted"', "-neg", "with space", "日本語", "\u00a0", "a:b", "@me", "Bug"];
+
+describe("fuzz_skip_if_query - seed corpus", () => {
+ it.each([
+ "is:issue is:open label:bug repo:octo/demo",
+ 'is:pr is:merged label:"needs triage" repo:octo/demo sort:created-desc',
+ "label:a label:b assignee:octocat repo:octo/demo",
+ 'is:issue in:title "[daily-report]" repo:octo/demo',
+ 'label:"a b"c repo:octo/demo',
+ 'label:a"b c" repo:octo/demo',
+ "repo:octo/demo repo:Octo/Demo author:A author:a",
+ "is:issue is:merged repo:octo/demo",
+ "",
+ '"',
+ "\t\n ",
+ ])("holds invariants for %j", query => {
+ expect(checkSkipIfQueryInvariants(query)).toEqual([]);
+ });
+
+ it("rejects values with partial quoting so they fall back to search", () => {
+ expect(parseSearchQuery('label:"a b"c repo:octo/demo').ok).toBe(false);
+ expect(parseSearchQuery('label:a"b c" repo:octo/demo').ok).toBe(false);
+ });
+});
+
+describe("fuzz_skip_if_query - generated queries", () => {
+ it("holds invariants for grammar-generated queries", () => {
+ const rand = prng(0x5eed);
+ let accepted = 0;
+ for (let i = 0; i < 3000; i++) {
+ const bytes = Array.from({ length: 1 + Math.floor(rand() * 8) }, () => Math.floor(rand() * 256));
+ const payload = PAYLOADS[Math.floor(rand() * PAYLOADS.length)];
+ // Most generated queries need a repo qualifier to exercise the accepted path.
+ const query = `${buildModelQuery(bytes, payload)}${rand() < 0.7 ? " repo:octo/demo" : ""}`;
+ const violations = checkSkipIfQueryInvariants(query);
+ if (violations.length) throw new Error(`invariants failed for ${JSON.stringify(query)}: ${violations.join("; ")}`);
+ if (parseSearchQuery(query).ok) accepted++;
+ }
+ // Guard against a generator that only produces rejected queries.
+ expect(accepted).toBeGreaterThan(100);
+ });
+
+ it("holds invariants for random character soup", () => {
+ const rand = prng(42);
+ const alphabet = 'abc:/-," \t@isrepolabe';
+ for (let i = 0; i < 2000; i++) {
+ const length = Math.floor(rand() * 40);
+ const query = Array.from({ length }, () => alphabet[Math.floor(rand() * alphabet.length)]).join("");
+ const violations = checkSkipIfQueryInvariants(query);
+ if (violations.length) throw new Error(`invariants failed for ${JSON.stringify(query)}: ${violations.join("; ")}`);
+ }
+ });
+
+ it("covers every fragment in the generator vocabulary", () => {
+ for (const fragment of FRAGMENTS) {
+ expect(checkSkipIfQueryInvariants(`${fragment} repo:octo/demo`)).toEqual([]);
+ }
+ });
+});
diff --git a/actions/setup/js/skip_if_query.cjs b/actions/setup/js/skip_if_query.cjs
index 985592fcf0d..40ede7b71da 100644
--- a/actions/setup/js/skip_if_query.cjs
+++ b/actions/setup/js/skip_if_query.cjs
@@ -122,6 +122,7 @@ function parseSearchQuery(query) {
const rawValue = unquote(token.slice(colon + 1));
const value = rawValue.toLowerCase();
if (!rawValue) return { ok: false, reason: `empty qualifier "${token}"` };
+ if (rawValue.includes('"')) return { ok: false, reason: `unsupported quoting "${token}"` };
/** @type {string | null} */
let conflict = null;
diff --git a/pkg/workflow/skip_if_query_fuzz_test.go b/pkg/workflow/skip_if_query_fuzz_test.go
new file mode 100644
index 00000000000..38e3addaf3c
--- /dev/null
+++ b/pkg/workflow/skip_if_query_fuzz_test.go
@@ -0,0 +1,80 @@
+//go:build !integration
+
+package workflow
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// FuzzSkipIfQueryParser checks the skip-if search query parser in
+// actions/setup/js/skip_if_query.cjs. Each input is checked both as a raw
+// query and as a choice stream for the harness's qualifier grammar. The
+// harness asserts the parser and backend-selection invariants; queries are
+// only parsed, never sent to GitHub.
+//
+// go test -run='^$' -fuzz=FuzzSkipIfQueryParser -fuzztime=30s ./pkg/workflow
+func FuzzSkipIfQueryParser(f *testing.F) {
+ node, err := exec.LookPath("node")
+ if err != nil {
+ f.Skip("Node.js is required for the skip-if query fuzz harness")
+ }
+ harness, err := filepath.Abs("../../actions/setup/js/fuzz_skip_if_query_harness.cjs")
+ if err != nil {
+ f.Fatal(err)
+ }
+ f.Add("is:issue is:open label:bug repo:octo/demo", []byte{0, 4, 13}, "bug")
+ f.Add(`is:pr is:merged label:"needs triage" repo:octo/demo`, []byte{1, 6, 20}, "octo/demo")
+ f.Add(`is:issue in:title "[daily-report]" repo:octo/demo`, []byte{33, 34}, `"`)
+ f.Add(`label:"a b"c repo:octo/demo`, []byte{15, 16, 17}, "a,b")
+ f.Add("label:a label:b assignee:octocat repo:octo/demo", []byte{25, 26, 27}, "@me")
+ f.Add("", []byte{}, "")
+ f.Fuzz(func(t *testing.T, query string, choices []byte, payload string) {
+ if len(query) > 4096 || len(choices) > 256 || len(payload) > 1024 {
+ t.Skip("Input too large")
+ }
+ // JSON encodes []byte as base64; use integers for the JS choice stream.
+ ints := make([]int, len(choices))
+ for i, value := range choices {
+ ints[i] = int(value)
+ }
+ for _, request := range []map[string]any{
+ {"query": query},
+ {"bytes": ints, "payload": payload},
+ } {
+ runSkipIfQueryHarness(t, node, harness, request)
+ }
+ })
+}
+
+func runSkipIfQueryHarness(t *testing.T, node, harness string, request map[string]any) {
+ t.Helper()
+ input, err := json.Marshal(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, node, harness)
+ cmd.Stdin = bytes.NewReader(input)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("skip-if query harness failed: %v\nrequest=%s\n%s", err, input, output)
+ }
+ var result struct {
+ OK bool `json:"ok"`
+ Query string `json:"query"`
+ Violations []string `json:"violations"`
+ }
+ if err := json.Unmarshal(output, &result); err != nil {
+ t.Fatalf("invalid harness response: %s (error: %v)", output, err)
+ }
+ if !result.OK {
+ t.Fatalf("skip-if query invariants violated for %q: %v", result.Query, result.Violations)
+ }
+}