Compare commits

...

9 Commits

7 changed files with 409 additions and 320 deletions

View File

@ -5,176 +5,178 @@
*/ */
module.exports = async ({ github, context, core }) => { module.exports = async ({ github, context, core }) => {
const rawLabels = process.env.LABELS_OUTPUT; const extractJson = (raw) => {
core.info(`Raw labels JSON: ${rawLabels}`); if (!raw || raw === '[]' || raw === '') return [];
let parsedLabels; try {
try { // First, try to parse the raw output as JSON.
// First, try to parse the raw output as JSON. return JSON.parse(raw);
parsedLabels = JSON.parse(rawLabels); } catch (jsonError) {
} catch (jsonError) { // If that fails, check for a markdown code block.
// If that fails, check for a markdown code block. core.info('Direct JSON parsing failed. Trying to extract from a markdown block.');
core.warning( const jsonMatch = raw.match(/```json\s*([\s\S]*?)\s*```/);
`Direct JSON parsing failed: ${jsonError.message}. Trying to extract from a markdown block.`, if (jsonMatch && jsonMatch[1]) {
); try {
const jsonMatch = rawLabels.match(/```json\s*([\s\S]*?)\s*```/); return JSON.parse(jsonMatch[1].trim());
if (jsonMatch && jsonMatch[1]) { } catch (markdownError) {
try { core.warning(`Failed to parse extracted JSON from markdown block: ${markdownError.message}`);
parsedLabels = JSON.parse(jsonMatch[1].trim()); }
} catch (markdownError) {
core.setFailed(
`Failed to parse JSON even after extracting from markdown block: ${markdownError.message}\nRaw output: ${rawLabels}`,
);
return;
} }
} else {
// If no markdown block, try to find a raw JSON array in the output. // Try to find a raw JSON array in the output.
// The CLI may include debug/log lines (e.g. telemetry init, YOLO mode) const jsonArrayMatch = raw.match(/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/);
// before the actual JSON response.
const jsonArrayMatch = rawLabels.match(
/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/,
);
if (jsonArrayMatch) { if (jsonArrayMatch) {
try { try {
parsedLabels = JSON.parse(jsonArrayMatch[0]); return JSON.parse(jsonArrayMatch[0]);
} catch (extractError) { } catch (extractError) {
// It's possible the regex matched from a `[STARTUP]` log all the way to the end const fallbackMatch = raw.match(/(\[\s*\{\s*"issue_number"[\s\S]*)/);
// of the JSON array. We need to be more aggressive and find the FIRST `[ { "issue_number"`
core.warning(
`Strict array match failed: ${extractError.message}. Attempting to clean leading noisy brackets.`,
);
const fallbackMatch = rawLabels.match(
/(\[\s*\{\s*"issue_number"[\s\S]*)/,
);
if (fallbackMatch) { if (fallbackMatch) {
try { try {
// We might have grabbed trailing noise too, so we find the last closing bracket const cleaned = fallbackMatch[0].substring(0, fallbackMatch[0].lastIndexOf(']') + 1);
const cleaned = fallbackMatch[0].substring( return JSON.parse(cleaned);
0,
fallbackMatch[0].lastIndexOf(']') + 1,
);
parsedLabels = JSON.parse(cleaned);
} catch (fallbackError) { } catch (fallbackError) {
core.setFailed( core.warning(`Failed to parse extracted JSON using fallback regex: ${fallbackError.message}`);
`Found JSON-like content but failed to parse: ${fallbackError.message}\nRaw output: ${rawLabels}`,
);
return;
} }
} else {
core.setFailed(
`Found JSON-like content but failed to parse: ${extractError.message}\nRaw output: ${rawLabels}`,
);
return;
} }
} }
} else {
core.setFailed(
`Output is not valid JSON and does not contain extractable JSON.\nRaw output: ${rawLabels}`,
);
return;
} }
} }
} core.warning('No valid JSON could be extracted from input.');
core.info(`Parsed labels JSON: ${JSON.stringify(parsedLabels)}`); return [];
};
for (const entry of parsedLabels) { // Collect all outputs from environment variables
const issueNumber = entry.issue_number; // Prioritize EFFORT results over STANDARD results by processing Effort FIRST
if (!issueNumber) { // so that its labels appear first in the merged arrays (and thus win in mutually exclusive logic)
core.info( const effortRaw = process.env.LABELS_OUTPUT_EFFORT;
`Skipping entry with no issue number: ${JSON.stringify(entry)}`, const standardRaw = process.env.LABELS_OUTPUT_STANDARD;
); const genericRaw = process.env.LABELS_OUTPUT;
continue;
const resultsByIssue = new Map();
const processResults = (results, sourceName) => {
for (const entry of results) {
const issueNumber = entry.issue_number;
if (!issueNumber) continue;
if (!resultsByIssue.has(issueNumber)) {
resultsByIssue.set(issueNumber, {
issue_number: issueNumber,
labels_to_add: [...(entry.labels_to_add || [])],
labels_to_remove: [...(entry.labels_to_remove || [])],
explanation: entry.explanation || '',
effort_analysis: entry.effort_analysis || '',
});
} else {
const existing = resultsByIssue.get(issueNumber);
// Combine labels
existing.labels_to_add = [...new Set([...existing.labels_to_add, ...(entry.labels_to_add || [])])];
existing.labels_to_remove = [...new Set([...existing.labels_to_remove, ...(entry.labels_to_remove || [])])];
// Combine explanations (if different)
if (entry.explanation && !existing.explanation.includes(entry.explanation)) {
existing.explanation = existing.explanation
? `${existing.explanation}\n\n${entry.explanation}`
: entry.explanation;
}
// Take effort analysis if present
if (entry.effort_analysis && !existing.effort_analysis) {
existing.effort_analysis = entry.effort_analysis;
}
}
} }
};
// Order matters: Effort first so its labels win in conflict resolution
processResults(extractJson(effortRaw), 'EFFORT');
processResults(extractJson(standardRaw), 'STANDARD');
processResults(extractJson(genericRaw), 'GENERIC');
const finalResults = Array.from(resultsByIssue.values());
core.info(`Aggregated triage results for ${finalResults.length} issues.`);
for (const entry of finalResults) {
const issueNumber = entry.issue_number;
let labelsToAdd = entry.labels_to_add || []; let labelsToAdd = entry.labels_to_add || [];
let labelsToRemove = entry.labels_to_remove || []; let labelsToRemove = entry.labels_to_remove || [];
let existingLabels = [];
labelsToRemove.push('status/need-triage'); // Fetch existing labels early
if (labelsToAdd.includes('status/manual-triage')) {
// If the AI flagged it for manual triage, remove bot-triaged if it exists
labelsToRemove.push('status/bot-triaged');
// Ensure we don't accidentally try to add bot-triaged if the AI returned it
labelsToAdd = labelsToAdd.filter((l) => l !== 'status/bot-triaged');
} else {
// Standard successful bot triage
labelsToAdd.push('status/bot-triaged');
}
// Deduplicate arrays
labelsToAdd = [...new Set(labelsToAdd)];
labelsToRemove = [...new Set(labelsToRemove)];
// Fetch existing labels to auto-resolve conflicts
try { try {
const { data: issueData } = await github.rest.issues.get({ const { data: issueData } = await github.rest.issues.get({
owner: context.repo.owner, owner: context.repo.owner,
repo: context.repo.repo, repo: context.repo.repo,
issue_number: issueNumber, issue_number: issueNumber,
}); });
const existingLabels = issueData.labels.map((l) => existingLabels = issueData.labels.map((l) =>
typeof l === 'string' ? l : l.name, typeof l === 'string' ? l : l.name,
); );
const hasNewArea = labelsToAdd.some((l) => l.startsWith('area/'));
if (hasNewArea) {
const existingAreas = existingLabels.filter((l) =>
l.startsWith('area/'),
);
labelsToRemove.push(...existingAreas);
}
const hasNewPriority = labelsToAdd.some((l) => l.startsWith('priority/'));
if (hasNewPriority) {
const existingPriorities = existingLabels.filter((l) =>
l.startsWith('priority/'),
);
labelsToRemove.push(...existingPriorities);
}
const hasNewKind = labelsToAdd.some((l) => l.startsWith('kind/'));
if (hasNewKind) {
const existingKinds = existingLabels.filter((l) =>
l.startsWith('kind/'),
);
labelsToRemove.push(...existingKinds);
}
// Re-deduplicate and filter out labels we are trying to add
labelsToRemove = [...new Set(labelsToRemove)].filter(
(l) => !labelsToAdd.includes(l),
);
} catch (e) { } catch (e) {
core.warning( core.warning(
`Failed to fetch existing labels for #${issueNumber}: ${e.message}`, `Failed to fetch existing labels for #${issueNumber}: ${e.message}`,
); );
} }
// Enforce mutually exclusive area labels // Programmatic Priority Downgrade Logic
const areaLabelsToAdd = labelsToAdd.filter((l) => l.startsWith('area/')); if (labelsToAdd.includes('status/need-information')) {
if (areaLabelsToAdd.length > 1) { const targetPriority = labelsToAdd.find((l) => l.startsWith('priority/'));
core.warning( if (targetPriority) {
`Issue #${issueNumber} has multiple area labels to add: ${areaLabelsToAdd.join(', ')}. Keeping only the first one.`, let downgradedPriority = null;
); if (targetPriority === 'priority/p0') downgradedPriority = 'priority/p1';
const firstArea = areaLabelsToAdd[0]; if (targetPriority === 'priority/p1') downgradedPriority = 'priority/p2';
labelsToAdd = labelsToAdd.filter(
(l) => !l.startsWith('area/') || l === firstArea, if (downgradedPriority) {
); core.info(`Programmatically downgrading ${targetPriority} to ${downgradedPriority} due to status/need-information`);
labelsToAdd = labelsToAdd.filter((l) => l !== targetPriority);
labelsToAdd.push(downgradedPriority);
}
}
} }
// Enforce mutually exclusive priority labels labelsToRemove.push('status/need-triage');
const priorityLabelsToAdd = labelsToAdd.filter((l) =>
l.startsWith('priority/'), if (
labelsToAdd.includes('status/manual-triage') ||
existingLabels.includes('status/manual-triage')
) {
labelsToRemove.push('status/bot-triaged');
labelsToAdd = labelsToAdd.filter((l) => l !== 'status/bot-triaged');
} else {
labelsToAdd.push('status/bot-triaged');
}
// Resolve internal conflicts (e.g., adding P1 and P2)
// We already resolved these by putting Effort first in the combined list
// Resolve external conflicts with existing labels
if (labelsToAdd.some((l) => l.startsWith('area/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('area/')));
}
if (labelsToAdd.some((l) => l.startsWith('priority/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('priority/')));
}
if (labelsToAdd.some((l) => l.startsWith('kind/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('kind/')));
}
// Enforce mutual exclusivity in the TO-ADD list (Architect wins)
const exclusivePrefixes = ['area/', 'priority/', 'kind/'];
for (const prefix of exclusivePrefixes) {
const filtered = labelsToAdd.filter(l => l.startsWith(prefix));
if (filtered.length > 1) {
const winner = filtered[0]; // First one wins
core.info(`Issue #${issueNumber} has multiple ${prefix} labels suggested. Keeping "${winner}" and discarding others.`);
labelsToAdd = labelsToAdd.filter(l => !l.startsWith(prefix) || l === winner);
}
}
// Final deduplication and cleanup
labelsToRemove = [...new Set(labelsToRemove)].filter(
(l) => !labelsToAdd.includes(l) && existingLabels.includes(l),
); );
if (priorityLabelsToAdd.length > 1) { labelsToAdd = [...new Set(labelsToAdd)].filter((l) => !existingLabels.includes(l));
core.warning(
`Issue #${issueNumber} has multiple priority labels to add: ${priorityLabelsToAdd.join(', ')}. Keeping only the first one.`,
);
const firstPriority = priorityLabelsToAdd[0];
labelsToAdd = labelsToAdd.filter(
(l) => !l.startsWith('priority/') || l === firstPriority,
);
}
// Batch label operations
if (labelsToAdd.length > 0) { if (labelsToAdd.length > 0) {
await github.rest.issues.addLabels({ await github.rest.issues.addLabels({
owner: context.repo.owner, owner: context.repo.owner,
@ -182,11 +184,7 @@ module.exports = async ({ github, context, core }) => {
issue_number: issueNumber, issue_number: issueNumber,
labels: labelsToAdd, labels: labelsToAdd,
}); });
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`);
const explanation = entry.explanation ? ` - ${entry.explanation}` : '';
core.info(
`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}${explanation}`,
);
} }
if (labelsToRemove.length > 0) { if (labelsToRemove.length > 0) {
@ -199,46 +197,33 @@ module.exports = async ({ github, context, core }) => {
name: label, name: label,
}); });
} catch (e) { } catch (e) {
if (e.status !== 404) { if (e.status !== 404) core.warning(`Failed to remove label ${label} from #${issueNumber}: ${e.message}`);
core.warning(
`Failed to remove label ${label} from #${issueNumber}: ${e.message}`,
);
}
} }
} }
core.info( core.info(`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`);
`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`,
);
} }
if ( // Post comment if needed
(entry.explanation && process.env.SUPPRESS_COMMENT !== 'true') || const needsInfoAdded = labelsToAdd.includes('status/need-information') && !existingLabels.includes('status/need-information');
entry.effort_analysis const hasEffortAnalysis = !!entry.effort_analysis;
) {
if (needsInfoAdded || hasEffortAnalysis) {
let commentBody = ''; let commentBody = '';
if (entry.explanation && process.env.SUPPRESS_COMMENT !== 'true') { if (needsInfoAdded && entry.explanation) commentBody += entry.explanation;
commentBody += entry.explanation; if (hasEffortAnalysis) {
}
if (entry.effort_analysis) {
if (commentBody) commentBody += '\n\n'; if (commentBody) commentBody += '\n\n';
commentBody += `**Effort Analysis:**\n${entry.effort_analysis}`; commentBody += `**Effort Analysis:**\n${entry.effort_analysis}`;
} }
await github.rest.issues.createComment({ if (commentBody) {
owner: context.repo.owner, await github.rest.issues.createComment({
repo: context.repo.repo, owner: context.repo.owner,
issue_number: issueNumber, repo: context.repo.repo,
body: commentBody, issue_number: issueNumber,
}); body: commentBody,
} });
core.info(`Posted required comment for #${issueNumber}`);
if ( }
(!entry.labels_to_add || entry.labels_to_add.length === 0) &&
(!entry.labels_to_remove || entry.labels_to_remove.length === 0)
) {
core.info(
`No labels to add or remove for #${issueNumber}, leaving as is`,
);
} }
} }
}; };

View File

@ -22,29 +22,53 @@ module.exports = async ({ github, context, core }) => {
for (const issue of issuesToCleanup) { for (const issue of issuesToCleanup) {
try { try {
await github.rest.issues.removeLabel({ const { data: issueData } = await github.rest.issues.get({
owner: context.repo.owner, owner: context.repo.owner,
repo: context.repo.repo, repo: context.repo.repo,
issue_number: issue.number, issue_number: issue.number,
name: 'status/need-triage',
}); });
core.info(
`Successfully removed status/need-triage from #${issue.number}`, const labels = issueData.labels.map((l) =>
typeof l === 'string' ? l : l.name,
); );
} catch (error) {
if (error.status === 404) { if (
labels.includes('status/bot-triaged') &&
labels.includes('status/need-triage')
) {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
name: 'status/need-triage',
});
core.info( core.info(
`Label status/need-triage not found on #${issue.number}, skipping.`, `Successfully removed status/need-triage from #${issue.number}`,
);
} else {
core.warning(
`Failed to remove label from #${issue.number}: ${error.message}`,
); );
} }
if (
labels.includes('status/bot-triaged') &&
labels.includes('status/manual-triage')
) {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
name: 'status/bot-triaged',
});
core.info(
`Successfully removed status/bot-triaged from #${issue.number} because it requires manual triage`,
);
}
} catch (error) {
core.warning(
`Failed to clean up labels for #${issue.number}: ${error.message}`,
);
} }
} }
core.info( core.info(
`Cleaned up status/need-triage from ${issuesToCleanup.length} issues.`, `Cleaned up conflicting labels from ${issuesToCleanup.length} issues.`,
); );
}; };

View File

@ -1,60 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
const fs = require('node:fs');
module.exports = async ({ github, context, core }) => {
core.info('Fetching open issues to check for conflicting labels...');
const issues = await github.paginate(github.rest.issues.listForRepo, {
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
per_page: 100,
});
const conflictingLabelIssues = [];
for (const issue of issues) {
if (issue.pull_request) continue;
const areaLabels = issue.labels
.filter((l) => l.name && l.name.startsWith('area/'))
.map((l) => l.name);
const priorityLabels = issue.labels
.filter((l) => l.name && l.name.startsWith('priority/'))
.map((l) => l.name);
if (areaLabels.length > 1 || priorityLabels.length > 1) {
let message = `Issue #${issue.number} has conflicting labels:`;
if (areaLabels.length > 1)
message += ` multiple areas (${areaLabels.join(', ')}).`;
if (priorityLabels.length > 1)
message += ` multiple priorities (${priorityLabels.join(', ')}).`;
core.info(message);
conflictingLabelIssues.push({
number: issue.number,
title: issue.title,
body: issue.body || '',
});
}
}
// Limit to 50 to avoid overwhelming the AI in a single run
const issuesToProcess = conflictingLabelIssues.slice(0, 50);
fs.writeFileSync(
'conflicting_labels_issues.json',
JSON.stringify(issuesToProcess, null, 2),
);
core.info(
`Found ${conflictingLabelIssues.length} issues with conflicting labels. Wrote ${issuesToProcess.length} to conflicting_labels_issues.json`,
);
};

View File

@ -16,6 +16,8 @@ module.exports = async ({ github, context, core }) => {
const owner = context.repo.owner; const owner = context.repo.owner;
const repo = context.repo.repo; const repo = context.repo.repo;
core.info(`Running in ${dryRun ? 'DRY RUN' : 'PRODUCTION'} mode.`);
const STALE_LABEL = 'stale'; const STALE_LABEL = 'stale';
const NEED_INFO_LABEL = 'status/need-information'; const NEED_INFO_LABEL = 'status/need-information';
const EXEMPT_LABELS = [ const EXEMPT_LABELS = [
@ -79,14 +81,16 @@ module.exports = async ({ github, context, core }) => {
async function processItems(query, callback) { async function processItems(query, callback) {
core.info(`Searching: ${query}`); core.info(`Searching: ${query}`);
try { try {
const response = await github.rest.search.issuesAndPullRequests({ let items = await github.paginate(
q: query, github.rest.search.issuesAndPullRequests,
per_page: 100, {
sort: 'updated', q: query,
order: 'asc', per_page: 100,
}); sort: 'updated',
const items = response.data.items; order: 'asc',
core.info(`Found ${items.length} items (batch limited).`); },
);
core.info(`Found ${items.length} items.`);
for (const item of items) { for (const item of items) {
try { try {
await callback(item); await callback(item);
@ -114,16 +118,21 @@ module.exports = async ({ github, context, core }) => {
per_page: 5, per_page: 5,
}); });
// Check if the last comment is from a non-maintainer // Check if the last comment is from a non-maintainer and not a bot
const lastComment = comments[0]; const lastComment = comments[0];
if ( if (
lastComment && lastComment &&
lastComment.user?.type !== 'Bot' &&
!(await isMaintainer(lastComment.user, lastComment.author_association)) !(await isMaintainer(lastComment.user, lastComment.author_association))
) { ) {
core.info( if (dryRun) {
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`, core.info(
); `[DRY RUN] Would remove ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
if (!dryRun) { );
} else {
core.info(
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
);
await github.rest.issues await github.rest.issues
.removeLabel({ .removeLabel({
owner, owner,
@ -141,10 +150,14 @@ module.exports = async ({ github, context, core }) => {
await processItems( await processItems(
`repo:${owner}/${repo} is:open label:"${NEED_INFO_LABEL}" updated:<${noResponseThreshold.toISOString()}`, `repo:${owner}/${repo} is:open label:"${NEED_INFO_LABEL}" updated:<${noResponseThreshold.toISOString()}`,
async (item) => { async (item) => {
core.info( if (dryRun) {
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`, core.info(
); `[DRY RUN] Would close #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
if (!dryRun) { );
} else {
core.info(
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
);
await github.rest.issues.createComment({ await github.rest.issues.createComment({
owner, owner,
repo, repo,
@ -156,6 +169,7 @@ module.exports = async ({ github, context, core }) => {
repo, repo,
issue_number: item.number, issue_number: item.number,
state: 'closed', state: 'closed',
state_reason: 'not_planned',
}); });
} }
}, },
@ -163,11 +177,21 @@ module.exports = async ({ github, context, core }) => {
// 2. Handle Stale Mark (60 days inactivity, no stale label) // 2. Handle Stale Mark (60 days inactivity, no stale label)
const exemptQuery = EXEMPT_LABELS.map((l) => `-label:"${l}"`).join(' '); const exemptQuery = EXEMPT_LABELS.map((l) => `-label:"${l}"`).join(' ');
await processItems( await processItems(
`repo:${owner}/${repo} is:open -label:"${STALE_LABEL}" ${exemptQuery} updated:<${staleThreshold.toISOString()}`, `repo:${owner}/${repo} is:open -label:"${STALE_LABEL}" ${exemptQuery} updated:<${staleThreshold.toISOString()}`,
async (item) => { async (item) => {
core.info(`Marking #${item.number} as stale.`); const isBug = item.labels.some((l) =>
if (!dryRun) { (typeof l === 'string' ? l : l.name).toLowerCase().includes('bug'),
);
const bodyText = isBug
? `This bug report has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. Many issues are resolved in newer releases. Please verify if the issue persists in the latest Gemini CLI version. If it does, please leave a comment to keep this open. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`
: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`;
if (dryRun) {
core.info(`[DRY RUN] Would mark #${item.number} as stale.`);
} else {
core.info(`Marking #${item.number} as stale.`);
await github.rest.issues.addLabels({ await github.rest.issues.addLabels({
owner, owner,
repo, repo,
@ -178,18 +202,97 @@ module.exports = async ({ github, context, core }) => {
owner, owner,
repo, repo,
issue_number: item.number, issue_number: item.number,
body: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`, body: bodyText,
}); });
} }
}, },
); );
// 3. Handle Stale Close (14 days with stale label) // 3. Handle Stale Removal & Close
await processItems( await processItems(
`repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery} updated:<${closeThreshold.toISOString()}`, `repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery}`,
async (item) => { async (item) => {
core.info(`Closing stale item #${item.number}.`); // Fetch full timeline to see events and comments
if (!dryRun) { const timeline = await github.paginate(
github.rest.issues.listEventsForTimeline,
{
owner,
repo,
issue_number: item.number,
per_page: 100,
},
);
// Find exactly when the Stale label was added
// We look for the last 'labeled' event for STALE_LABEL
const staleEventIndex = timeline.findLastIndex(
(e) =>
e.event === 'labeled' &&
e.label?.name?.toLowerCase() === STALE_LABEL.toLowerCase(),
);
if (staleEventIndex === -1) return; // Fallback if no event found
const staleEvent = timeline[staleEventIndex];
const eventsAfterStale = timeline.slice(staleEventIndex + 1);
// Check for meaningful activity after the Stale label was applied
const meaningfulEvents = eventsAfterStale.filter((e) => {
const actor = e.actor?.login || '';
const isBot =
actor.includes('[bot]') || actor.includes('github-actions');
if (isBot) return false;
// Explicit whitelist of meaningful events for humans
if (
[
'commented',
'cross-referenced',
'connected',
'reopened',
'assigned',
].includes(e.event)
) {
return true;
}
return false;
});
if (meaningfulEvents.length > 0) {
// Activity detected, remove Stale label
if (dryRun) {
core.info(
`[DRY RUN] Would remove ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
);
} else {
core.info(
`Removing ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
);
await github.rest.issues
.removeLabel({
owner,
repo,
issue_number: item.number,
name: STALE_LABEL,
})
.catch(() => {});
}
return;
}
// No meaningful activity. Check if 14 days have passed.
const labeledDate = new Date(staleEvent.created_at);
if (labeledDate > closeThreshold) {
// Has not been 14 days since it was ACTUALLY marked stale
return;
}
if (dryRun) {
core.info(`[DRY RUN] Would close stale item #${item.number}.`);
} else {
core.info(`Closing stale item #${item.number}.`);
await github.rest.issues.createComment({ await github.rest.issues.createComment({
owner, owner,
repo, repo,
@ -201,6 +304,7 @@ module.exports = async ({ github, context, core }) => {
repo, repo,
issue_number: item.number, issue_number: item.number,
state: 'closed', state: 'closed',
state_reason: 'not_planned',
}); });
} }
}, },
@ -222,8 +326,12 @@ module.exports = async ({ github, context, core }) => {
async (pr) => { async (pr) => {
if (await isMaintainer(pr.user, pr.author_association)) return; if (await isMaintainer(pr.user, pr.author_association)) return;
core.info(`Nudging PR #${pr.number} for contribution policy.`); if (dryRun) {
if (!dryRun) { core.info(
`[DRY RUN] Would nudge PR #${pr.number} for contribution policy.`,
);
} else {
core.info(`Nudging PR #${pr.number} for contribution policy.`);
await github.rest.issues.addLabels({ await github.rest.issues.addLabels({
owner, owner,
repo, repo,
@ -246,10 +354,14 @@ module.exports = async ({ github, context, core }) => {
async (pr) => { async (pr) => {
if (await isMaintainer(pr.user, pr.author_association)) return; if (await isMaintainer(pr.user, pr.author_association)) return;
core.info( if (dryRun) {
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`, core.info(
); `[DRY RUN] Would close PR #${pr.number} per contribution policy (no 'help wanted').`,
if (!dryRun) { );
} else {
core.info(
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`,
);
await github.rest.issues.createComment({ await github.rest.issues.createComment({
owner, owner,
repo, repo,

View File

@ -68,6 +68,7 @@ jobs:
ISSUE_NUMBER: '${{ github.event.issue.number }}' ISSUE_NUMBER: '${{ github.event.issue.number }}'
REPOSITORY: '${{ github.repository }}' REPOSITORY: '${{ github.repository }}'
FIRESTORE_PROJECT: '${{ vars.FIRESTORE_PROJECT }}' FIRESTORE_PROJECT: '${{ vars.FIRESTORE_PROJECT }}'
GEMINI_CLI_TRUST_WORKSPACE: 'true'
with: with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}' gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}' gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'

View File

@ -335,14 +335,41 @@ jobs:
return; return;
} }
const newAreaLabel = labelsToAdd[0];
// Get current labels to resolve conflicts
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
const currentLabelNames = currentLabels.map(l => l.name);
const currentAreaLabels = currentLabelNames.filter(name => name.startsWith('area/'));
const labelsToRemove = currentAreaLabels.filter(name => name !== newAreaLabel);
for (const label of labelsToRemove) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label
});
core.info(`Removed conflicting area label: ${label}`);
} catch (e) {
core.warning(`Failed to remove label ${label}: ${e.message}`);
}
}
// Set labels based on triage result // Set labels based on triage result
await github.rest.issues.addLabels({ await github.rest.issues.addLabels({
owner: context.repo.owner, owner: context.repo.owner,
repo: context.repo.repo, repo: context.repo.repo,
issue_number: issueNumber, issue_number: issueNumber,
labels: labelsToAdd labels: [newAreaLabel]
}); });
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`); core.info(`Successfully added labels for #${issueNumber}: ${newAreaLabel}`);
- name: 'Post Issue Analysis Failure Comment' - name: 'Post Issue Analysis Failure Comment'
if: |- if: |-

View File

@ -62,12 +62,20 @@ jobs:
- name: 'Find Issues with Conflicting Labels' - name: 'Find Issues with Conflicting Labels'
if: |- if: |-
${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea' env:
with: GITHUB_TOKEN: '${{ steps.generate_token.outputs.token }}'
github-token: '${{ steps.generate_token.outputs.token }}' GITHUB_REPOSITORY: '${{ github.repository }}'
script: |- run: |-
const findConflictingLabels = require('./.github/scripts/find-conflicting-labels.cjs'); set -euo pipefail
await findConflictingLabels({ github, context, core }); echo '🔍 Fetching open issues to find conflicts...'
# Fetch up to 2000 open issues in one quick GraphQL-backed query
gh issue list --repo "${GITHUB_REPOSITORY}" --search "is:issue is:open" --limit 2000 --json number,title,body,labels > all_open_issues.json
echo '🧹 Filtering issues with multiple area/ or priority/ labels...'
jq -c '[ .[] | select( (.labels | map(select(.name | startswith("area/"))) | length) > 1 or (.labels | map(select(.name | startswith("priority/"))) | length) > 1 ) ] | .[0:50]' all_open_issues.json > conflicting_labels_issues.json
CONFLICT_COUNT=$(jq 'length' conflicting_labels_issues.json)
echo "Found ${CONFLICT_COUNT} issues with conflicting labels (capped at 50 for processing)."
- name: 'Find untriaged issues' - name: 'Find untriaged issues'
if: |- if: |-
@ -81,19 +89,19 @@ jobs:
echo '🔍 Finding issues missing area labels...' echo '🔍 Finding issues missing area labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \ gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:status/bot-triaged -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body > no_area_issues.json --search 'is:open is:issue -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body,labels > no_area_issues.json
echo '🔍 Finding issues missing kind labels...' echo '🔍 Finding issues missing kind labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \ gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:status/bot-triaged -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body > no_kind_issues.json --search 'is:open is:issue -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body,labels > no_kind_issues.json
echo '🏷️ Finding issues missing priority labels...' echo '🏷️ Finding issues missing priority labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \ gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body > no_priority_issues.json --search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body,labels > no_priority_issues.json
echo '📏 Finding issues missing effort labels...' echo '📏 Finding issues missing effort labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \ gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 5 --json number,title,body > no_effort_issues.json --search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 20 --json number,title,body,labels > no_effort_issues.json
echo '🔄 Merging and deduplicating standard triage issues...' echo '🔄 Merging and deduplicating standard triage issues...'
if [ ! -f conflicting_labels_issues.json ]; then echo "[]" > conflicting_labels_issues.json; fi if [ ! -f conflicting_labels_issues.json ]; then echo "[]" > conflicting_labels_issues.json; fi
@ -158,6 +166,7 @@ jobs:
GEMINI_CLI_TRUST_WORKSPACE: 'true' GEMINI_CLI_TRUST_WORKSPACE: 'true'
GEMINI_EXP: 'gemini_exp.json' GEMINI_EXP: 'gemini_exp.json'
GEMINI_STRICT_TELEMETRY_LIMITS: 'true' GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
GEMINI_MODEL: 'gemini-3-flash-preview'
with: with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}' gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}' gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
@ -174,7 +183,7 @@ jobs:
"read_file" "read_file"
], ],
"telemetry": { "telemetry": {
"enabled": true, "enabled": false,
"target": "gcp" "target": "gcp"
} }
} }
@ -188,12 +197,12 @@ jobs:
## Steps ## Steps
1. You are only able to use the echo and read_file commands. Review the available labels in the environment variable: "${AVAILABLE_LABELS}". 1. You are only able to use the echo and read_file commands. Review the available labels in the environment variable: "${AVAILABLE_LABELS}".
2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage. 2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage (including their current labels).
3. Review the issue title, body and any comments provided in the JSON file. 3. Review the issue title, body, current labels, and any comments provided in the JSON file.
4. Identify the most relevant labels from the existing labels, specifically focusing on area/*, kind/*, and priority/*. 4. Identify the most relevant labels from the existing labels, specifically focusing on area/*, kind/*, and priority/*.
5. Label Policy: 5. Label Policy:
- If the issue already has a kind/ label, do not change it. - If the issue already has a kind/ label, do not change it.
- If the issue has exactly ONE priority/ label, do not change it. - If the issue has exactly ONE priority/ label, do not change it (unless you are explicitly re-evaluating an ambiguous priority).
- If the issue is missing a priority/ label, OR if the issue currently has MULTIPLE priority/ labels, you must evaluate the issue's impact to determine exactly ONE priority level (priority/p0, priority/p1, priority/p2, priority/p3, or priority/unknown) based the guidelines. If you are fixing an issue with multiple priority/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`. - If the issue is missing a priority/ label, OR if the issue currently has MULTIPLE priority/ labels, you must evaluate the issue's impact to determine exactly ONE priority level (priority/p0, priority/p1, priority/p2, priority/p3, or priority/unknown) based the guidelines. If you are fixing an issue with multiple priority/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
- If the issue has exactly ONE area/ label, do not change it. - If the issue has exactly ONE area/ label, do not change it.
- If the issue is missing an area/ label, OR if the issue currently has MULTIPLE area/ labels, select exactly ONE area/ label that best fits the issue. Issues MUST NOT have multiple area/ labels. If you are fixing an issue with multiple area/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`. - If the issue is missing an area/ label, OR if the issue currently has MULTIPLE area/ labels, select exactly ONE area/ label that best fits the issue. Issues MUST NOT have multiple area/ labels. If you are fixing an issue with multiple area/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
@ -213,11 +222,12 @@ jobs:
] ]
``` ```
If an issue cannot be classified, do not include it in the output array. If an issue cannot be classified, do not include it in the output array.
9. For each issue please check if CLI version is present, this is usually in the output of the /about command and will look like 0.1.5 9. For each issue, carefully check if the CLI version is present. It is usually found under the "### Client information" header, as a bullet point (e.g., "• CLI Version: 0.33.1"), or in the output of the `/about` command.
- Anything more than 6 versions older than the most recent should add the status/need-retesting label - If the version is provided but is more than 6 minor versions older than the most recent release, apply the status/need-information label and leave a comment politely asking the user to verify if the issue persists in the latest version.
10. If you see that the issue doesn't look like it has sufficient information recommend the status/need-information label and leave a comment politely requesting the relevant information, eg.. if repro steps are missing request for repro steps. if version information is missing request for version information into the explanation section below. 10. If the issue does not have sufficient information, recommend the status/need-information label and leave a comment politely requesting the missing details. For example, if repro steps are missing, ask for them; if the CLI version is completely missing, ask for the version information in the explanation section below. Do not ask for version info if it is already in the issue body.
11. If you think an issue might be a Priority/P0 do not apply the priority/p0 label. Instead apply a status/manual-triage label and include a note in your explanation. 11. If you think an issue is a Priority/P0, you MUST apply the priority/p1 label AND the status/manual-triage label, and include a note in your explanation that it likely requires P0 escalation.
12. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label. 12. If the issue is highly ambiguous, completely lacks a description, or you are torn between two lower priorities (like P2 vs P3), you MUST retain the existing priority label if one is already present. Do not toggle the priority if you do not have enough information to make a definitive change.
13. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label.
## Guidelines ## Guidelines
@ -230,12 +240,14 @@ jobs:
- Identify exactly ONE area/ label. Do NOT assign multiple area/ labels to a single issue. - Identify exactly ONE area/ label. Do NOT assign multiple area/ labels to a single issue.
- Identify only one kind/ label (Do not apply kind/duplicate or kind/parent-issue) - Identify only one kind/ label (Do not apply kind/duplicate or kind/parent-issue)
- Identify exactly ONE priority/ label. Do NOT assign multiple priority/ labels to a single issue. - Identify exactly ONE priority/ label. Do NOT assign multiple priority/ labels to a single issue.
- Once you categorize the issue if it needs information bump down the priority by 1 eg.. a p0 would become a p1 a p1 would become a p2. P2 and P3 can stay as is in this scenario. - **Do not manually downgrade the priority.** Always assign the true priority based on the guidelines. The system will handle downgrades programmatically if information is missing.
- **NEVER mention label names, label removals, or label additions in your `explanation`.** The explanation must be purely written for the user (e.g., "Please provide your CLI version.") without exposing internal triage mechanics (e.g., do NOT say "Removing area/unknown to leave only area/core").
Categorization Guidelines (Priority): Categorization Guidelines (Priority):
P0 - Urgent Blocking Issues: P0 - Urgent Blocking Issues:
- DO NOT APPLY THE priority/p0 LABEL AUTOMATICALLY. Instead apply priority/p1 and status/manual-triage.
- Definition: Critical failures breaking core functionality for a large portion of users. Examples: CLI fails to launch globally, core commands (gemini run) crash on valid input, unhandled promise rejections on boot, critical security vulnerability. - Definition: Critical failures breaking core functionality for a large portion of users. Examples: CLI fails to launch globally, core commands (gemini run) crash on valid input, unhandled promise rejections on boot, critical security vulnerability.
- Note: You must apply status/manual-triage instead of priority/p0. - Note: You must apply priority/p1 and status/manual-triage instead of priority/p0.
P1 - Critical but Workable: P1 - Critical but Workable:
- Definition: Severe issues without a reasonable workaround, significantly degrading the developer experience but not globally blocking. Examples: Specific tools failing consistently (e.g., `web_search` returns 500s), persistent PTY streaming hangs, memory leaks leading to OOM after short use. - Definition: Severe issues without a reasonable workaround, significantly degrading the developer experience but not globally blocking. Examples: Specific tools failing consistently (e.g., `web_search` returns 500s), persistent PTY streaming hangs, memory leaks leading to OOM after short use.
P2 - Significant Issues: P2 - Significant Issues:
@ -275,6 +287,7 @@ jobs:
GEMINI_CLI_TRUST_WORKSPACE: 'true' GEMINI_CLI_TRUST_WORKSPACE: 'true'
GEMINI_EXP: 'gemini_exp.json' GEMINI_EXP: 'gemini_exp.json'
GEMINI_STRICT_TELEMETRY_LIMITS: 'true' GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
GEMINI_MODEL: 'gemini-3-flash-preview'
with: with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}' gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}' gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
@ -293,7 +306,7 @@ jobs:
"read_file" "read_file"
], ],
"telemetry": { "telemetry": {
"enabled": true, "enabled": false,
"target": "gcp" "target": "gcp"
} }
} }
@ -379,30 +392,14 @@ jobs:
- This product is designed to use different models eg.. using pro, downgrading to flash etc. - This product is designed to use different models eg.. using pro, downgrading to flash etc.
- When users report that they dont expect the model to change those would be categorized as feature requests. - When users report that they dont expect the model to change those would be categorized as feature requests.
- name: 'Apply Standard Labels to Issues' - name: 'Apply Triaged Labels'
if: |- if: |-
${{ steps.gemini_standard_issue_analysis.outcome == 'success' && always() &&
steps.gemini_standard_issue_analysis.outputs.summary != '[]' && ( (steps.gemini_standard_issue_analysis.outcome == 'success' && steps.gemini_standard_issue_analysis.outputs.summary != '[]' && steps.gemini_standard_issue_analysis.outputs.summary != '') ||
steps.gemini_standard_issue_analysis.outputs.summary != '' }} (steps.gemini_effort_issue_analysis.outcome == 'success' && steps.gemini_effort_issue_analysis.outputs.summary != '[]' && steps.gemini_effort_issue_analysis.outputs.summary != '') )
env: env:
REPOSITORY: '${{ github.repository }}' LABELS_OUTPUT_STANDARD: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}'
LABELS_OUTPUT: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}' LABELS_OUTPUT_EFFORT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
SUPPRESS_COMMENT: 'true'
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
with:
github-token: '${{ steps.generate_token.outputs.token }}'
script: |-
const applyLabels = require('./.github/scripts/apply-issue-labels.cjs');
await applyLabels({ github, context, core });
- name: 'Apply Effort Labels to Issues'
if: |-
${{ steps.gemini_effort_issue_analysis.outcome == 'success' &&
steps.gemini_effort_issue_analysis.outputs.summary != '[]' &&
steps.gemini_effort_issue_analysis.outputs.summary != '' }}
env:
REPOSITORY: '${{ github.repository }}'
LABELS_OUTPUT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea' uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
with: with:
github-token: '${{ steps.generate_token.outputs.token }}' github-token: '${{ steps.generate_token.outputs.token }}'
@ -428,9 +425,12 @@ jobs:
GITHUB_REPOSITORY: '${{ github.repository }}' GITHUB_REPOSITORY: '${{ github.repository }}'
run: |- run: |-
set -euo pipefail set -euo pipefail
echo '🧹 Finding issues that have both bot-triaged and need-triage labels...' echo '🧹 Finding issues that have conflicting status labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \ gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > issues_to_cleanup.json --search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > cleanup_1.json
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue label:status/bot-triaged label:status/manual-triage' --limit 50 --json number > cleanup_2.json
jq -c -s 'add | unique_by(.number)' cleanup_1.json cleanup_2.json > issues_to_cleanup.json
- name: 'Clean Up Triage Labels' - name: 'Clean Up Triage Labels'
if: |- if: |-