Skip to content

Commit 54a6e78

Browse files
Independently moderate newly opened issues (#2030)
## Summary Add a single independent GitHub Agentic Workflow for newly opened issues. It starts on `issues.opened`, judges the report itself, and does not wait for central `~spam` / `~info-needed` flags. There is no hourly catch-up, flag-event router, automatic backlog sweep, or automatic AI review on edits, comments, or reopening. | Independent judgment | Action | | --- | --- | | Clear gibberish, explicit tracker-only test submissions, or plainly unrelated material | Fixed polite reply, then close as `not_planned` | | Plausible extension report without enough information, including an empty extension template | Friendly template request, add only local `info-needed`, leave open | | Useful report or uncertainty | No comment, label, reaction, or state change | The information request is: > Thanks for reaching out! Could you fill out the issue template in this issue? A little more information would help us investigate and better understand how to help. Language, spelling, brevity, a new account, missing logs, or unfilled optional fields are not sufficient grounds for closure. This version creates no `moderation-review-needed` queue label. ## Follow-up responses: comments and description edits The existing reporter-comment cleanup now works for issues even without `triage-needed`; existing shared-action authorization remains, and pull requests keep their previous guard. A small deterministic `issues.edited` job also treats a genuine nonempty description update by the authenticated human issue author as a response. It removes **only plain `info-needed`**. It does not run AI, post another comment, close/reopen an issue, or remove central flags. This prevents a reporter who fills out the requested template in the description from later being closed as unanswered. - Title-only, whitespace-only, and empty-body changes do not clear a pending request. - Current body/state/author/label and timeline checks reject stale responses, unverifiable ordering, renewed requests, or newer human handling; a final reread guards intervening changes. Simultaneous events with unverifiable ordering defer conservatively. - Actual GitHub testing showed that one title-and-body update can produce separate edited webhooks. A reporter rename matching that response's actor, timestamp, and new title does not veto its body update, even when the body webhook omits `changes.title`. Later or mismatched handling remains protected. Passive mentions/subscriptions are not treated as renewed requests. - The existing seven-day closer is unchanged. Clearing the label excludes the answered issue from its information-needed path; unanswered issues retain the existing follow-up behavior. ## Independence and safeguards - The model receives a prepared JSON file containing **title and description only**. Labels, assignments, account metadata, and other bots' judgments are not classification input. Both central flags, either flag, or neither flag can be present without authorizing or vetoing a judgment. - Central automation remains untouched and may apply labels later. The moderator never adds/removes central flags, rewrites assignments, changes area/type classifications, or locks issues. Both systems may consume inference while they coexist. - A native preflight prepares content plus a trusted fingerprint before inference. Human discussion, manual triage/assignment, pins/project changes and other protected decisions, closed/locked issues, and previous workflow replies stop automatic action. Opening-payload template labels are neutral; later human label changes are not. Bot metadata churn does not create a false human override or invalidate content. - Publication rereads state before commenting and before labeling/closing. Changed content or intervening human handling backs off. A previous response prevents duplicate replies and reclosure after human reopening. Manual runs without an original opening payload conservatively defer human-origin labels, including possible template labels. - The Copilot agent has GitHub/shell/editing tools disabled, plus explicit CLI `--deny-tool shell --deny-tool write` arguments. It reads the **whole** prepared file with native `view` and `forceReadLargeFiles: true`; unavailable/incomplete input must produce a safe no-op. It emits only a classification. Fixed code chooses the issue, reply, labels and state change. - Strict threat detection must pass before the separate write-enabled publisher runs. Publication independently downloads the original preflight fingerprint; the agent's copy is not trusted. API errors propagate. Partial failure after a reply requires maintainer inspection rather than blind duplicate publication. GitHub API reads/writes are not atomic, so a small read/write race remains. ## Operation, budgets, and rollout Manual dispatch accepts one issue number with the same human-protection guards. It is **live publication, not a dry run**, not a force override, and not a backlog sweep. The committed workflow exposes no staged dispatch input. Agent execution is serialized with a 20-turn, 10-minute, 500-credit per-run limit and a separate 200-credit detector budget. The 10,000-credit daily guardrail applies to automatic runs; the pinned runtime **exempts manual dispatch**. Daily accounting can lag in-flight work. Missed events or failures require manual retry/review. The source and generated executable use gh-aw v1.2.2 and pinned runtime `53d0749e19424a918acd82b4d140264ce48f2f14`. Focused safeguard tests run in existing Linux/Windows unit CI jobs, and the large lockfile is marked generated. Repository/organization policy and billing must permit `copilot-requests: write` and the pinned Actions. Administrative upstream Actions policy could not be inspected with the available access (HTTP 403); no settings were changed. ## Review and validation Repeated manual lifecycle review and independent code review found and fixed the description-only response gap and the same-response rename edge case. The latter was tested against actual split GitHub webhooks, not just assumed payloads. The final narrow independent review found no remaining meaningful defect in the corrections. - **30 focused scenario tests passed**, including edit-only responses, actor/content validation, renewed requests, combined/split title-body events, passive timeline events, API failures, and existing moderation guards. In-memory mutation checks verified that the new regressions reject the corresponding broken behaviors. - Lint, TypeScript test compilation, and the existing unit suite passed: **3,573 passing, 9 pending**. - Pinned workflow compilation and policy lint passed with **zero compiler warnings**; final no-emit compilation passed. - Final production helper/tests, reporter-cleanup workflow, Markdown source, and executable were compared with private candidate `770d176407659ed9c39f80ef5f893a7251cafe87`. No identity substitutions were used. ### Live end-to-end checks These runs are in the private isolated fixture repository and require access. Actual content, comments, labels and states were asserted, not just green job conclusions. | Scenario | Verified result / evidence | | --- | --- | | New incomplete report | Friendly request and local `info-needed`, initially open. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44362637094) | | Author fills the requested template and clarifies the title in one update | Actual split title/body webhooks clear only local `info-needed`, leave open and add no reply. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44365652560) | | Author supplies details by editing only the description | Same cleanup, preserving existing `~spam` / `~info-needed`. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44366004911) | | Title-only / whitespace-only / empty-body edits | Pending `info-needed` retained. [Title](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44365024251), [whitespace](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44365889836), [empty](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44365939620) | | Existing author-comment path without `triage-needed` | Label removed; issue stayed open; original authorization logic retained. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44366085169) | | Answered versus unanswered information requests | Existing closer preserved the answered fixture and closed the unanswered fixture. **Only the private test copy used zero days; production remains seven days.** [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44366254849) | | 64,892-character log-heavy report with the actual problem buried in the middle | Final candidate returned the entire report in one native-view read; returned JSON was compared with the full prepared input. No shell fallback was attempted. Classified `relevant`; no comment, label, or closure. [Final run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44366880993) | | Clear junk | Fixed polite reply and closure of only its own issue. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44362649587) | | Human reopens that handled junk issue, then explicitly requests manual review | No automatic AI review on reopening. Manual run skipped inference/publication, left it open, and posted no duplicate response. [Run](https://github.com/StellaHuang95/gh-aw-trial/actions/runs/44367638093) | The earlier independent-flow checks also verified useful French reports despite misleading Bot metadata, pre-inference human-pin protection, stale-publication rejection after a body edit, and cross-issue instruction confinement. Logs and pre-cleanup outcome snapshots are retained locally. No upstream issue was created or modified. Keep this PR **draft** for maintainer inspection before making it ready for review. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent e2685bd commit 54a6e78

7 files changed

Lines changed: 3267 additions & 2 deletions

File tree

‎.gitattributes‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.github/workflows/*.lock.yml linguist-generated=true
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
const { createHash } = require('node:crypto');
5+
6+
const marker = '<!-- gh-aw-workflow-id: issue-moderation -->';
7+
const triageEvents = new Set([
8+
'labeled', 'unlabeled', 'assigned', 'unassigned', 'reopened', 'closed', 'locked', 'unlocked', 'renamed',
9+
'milestoned', 'demilestoned', 'pinned', 'unpinned', 'added_to_project', 'removed_from_project',
10+
'moved_columns_in_project', 'connected', 'disconnected', 'marked_as_duplicate', 'unmarked_as_duplicate',
11+
]);
12+
const replies = {
13+
unrelated:
14+
"Thanks for reaching out! This tracker is for bugs and feature requests about the Python Environments extension for VS Code. This report appears unrelated, so we're closing it for now. If we misunderstood, please leave a comment so a maintainer can review it.",
15+
'needs-info':
16+
'Thanks for reaching out! Could you fill out the issue template in this issue? A little more information would help us investigate and better understand how to help.',
17+
};
18+
19+
function isHuman(actor) {
20+
return actor?.type !== 'Bot';
21+
}
22+
23+
function getTarget(context, issueNumber) {
24+
const number = issueNumber ?? context.payload.issue?.number ?? context.payload.inputs?.issue_number;
25+
if (!/^[1-9]\d*$/.test(String(number)) || !Number.isSafeInteger(Number(number))) {
26+
throw new Error('A positive issue number is required.');
27+
}
28+
if (context.payload.issue && context.payload.issue.number !== Number(number)) {
29+
throw new Error('The requested issue does not match the triggering issue.');
30+
}
31+
return { ...context.repo, issue_number: Number(number) };
32+
}
33+
34+
/**
35+
* Prepare content-only input for an independent review. Bot metadata is neither
36+
* classification evidence nor an eligibility gate. Human triage/discussion,
37+
* closed/locked issues, and this workflow's previous responses take precedence.
38+
* The fingerprint binds the live report across inference and publication.
39+
*/
40+
async function inspectIssue({ github, context, issueNumber, ownCommentId }) {
41+
const target = getTarget(context, issueNumber);
42+
const skip = (reason) => ({ target, reason });
43+
if (context.eventName === 'issues' && context.payload.action !== 'opened') {
44+
return skip('Only newly opened issues are automatically reviewed.');
45+
}
46+
const { data: issue } = await github.rest.issues.get(target);
47+
if (issue.pull_request || issue.state !== 'open' || issue.locked) {
48+
return skip('The target is not an open, unlocked issue.');
49+
}
50+
const opening = context.eventName === 'issues' ? context.payload.issue : undefined;
51+
if (opening && (issue.title !== opening.title || (issue.body ?? '') !== (opening.body ?? ''))) {
52+
return skip('The report changed after opening; leave the updated report for normal triage.');
53+
}
54+
const events = await github.paginate(github.rest.issues.listEventsForTimeline, { ...target, per_page: 100 });
55+
const labelEvents = (name) =>
56+
events.filter((event) => ['labeled', 'unlabeled'].includes(event.event) && event.label?.name === name);
57+
// Only the opening payload proves creation-time labels; manual runs must not guess from timestamps.
58+
const initialLabelNames = new Set((opening?.labels ?? []).map((label) => label.name));
59+
const initialEvents = new Set();
60+
for (const name of initialLabelNames) {
61+
const history = labelEvents(name);
62+
if (history[0]?.event === 'labeled') initialEvents.add(history[0]);
63+
}
64+
for (const label of issue.labels) {
65+
const event = labelEvents(label.name).at(-1);
66+
if (!event || (isHuman(event.actor) && !initialEvents.has(event))) {
67+
return skip('A human-owned or unverifiable triage label is present.');
68+
}
69+
}
70+
for (const assignee of issue.assignees) {
71+
const event = events.findLast((entry) => entry.event === 'assigned' && entry.assignee?.login === assignee.login);
72+
if (!event || isHuman(event.actor)) {
73+
return skip('A human has assigned the issue.');
74+
}
75+
}
76+
if (
77+
events.some(
78+
(event) =>
79+
triageEvents.has(event.event) &&
80+
isHuman(event.actor) &&
81+
!initialEvents.has(event),
82+
)
83+
) {
84+
return skip('A human has already changed triage or issue state.');
85+
}
86+
const comments = (await github.paginate(github.rest.issues.listComments, { ...target, per_page: 100 })).filter(
87+
(comment) => ownCommentId === undefined || comment.id !== ownCommentId,
88+
);
89+
if (comments.some((comment) => isHuman(comment.user))) {
90+
return skip('Human discussion already exists; leave the issue for normal triage.');
91+
}
92+
if (
93+
comments.some(
94+
(comment) => comment.user?.login === 'github-actions[bot]' && (comment.body ?? '').includes(marker),
95+
)
96+
) {
97+
return skip('This workflow has already responded to the issue.');
98+
}
99+
const report = { title: issue.title, description: issue.body ?? '' };
100+
const snapshot = createHash('sha256').update(JSON.stringify({ target, report })).digest('hex');
101+
return { target, report, snapshot };
102+
}
103+
104+
/**
105+
* Apply one independent content classification to the selected issue only.
106+
* Useful/uncertain reports cause no writes. Missing details get a fixed request
107+
* and local info-needed; only clear unrelated content gets a polite closure.
108+
* Central labels and assignments are preserved. Staged mode performs no writes.
109+
*/
110+
async function applyModeration({ github, context, issueNumber, output, snapshot, staged = false }) {
111+
const items = Array.isArray(output?.items) ? output.items.filter((item) => item?.type === 'moderation_action') : [];
112+
if (items.length !== 1 || !['unrelated', 'needs-info', 'relevant'].includes(items[0].classification)) {
113+
throw new Error('Exactly one valid moderation classification is required.');
114+
}
115+
if (typeof snapshot !== 'string' || !/^[a-f0-9]{64}$/.test(snapshot)) {
116+
throw new Error('A trusted pre-inference issue snapshot is required.');
117+
}
118+
let ownCommentId;
119+
const check = async () => {
120+
const current = await inspectIssue({ github, context, issueNumber, ownCommentId });
121+
if (!current.reason && current.snapshot !== snapshot) {
122+
current.reason = 'The report changed during review.';
123+
}
124+
return current;
125+
};
126+
const current = await check();
127+
if (current.reason) return { status: 'skipped', reason: current.reason };
128+
const classification = items[0].classification;
129+
if (classification === 'relevant') {
130+
return { status: 'skipped', reason: 'The report is useful or uncertain; no changes were made.' };
131+
}
132+
const action = classification === 'unrelated'
133+
? 'Reply politely and close as not planned.'
134+
: 'Request information, add info-needed, and leave the issue open.';
135+
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
136+
const body = [
137+
replies[classification],
138+
'',
139+
`_Automated issue moderation (${classification}). [Workflow run](${runUrl})._`,
140+
'',
141+
marker,
142+
].join('\n');
143+
if (staged) return { status: 'skipped', reason: `Staged preview: ${action}`, body };
144+
const { data: comment } = await github.rest.issues.createComment({ ...current.target, body });
145+
ownCommentId = comment.id;
146+
const fresh = await check();
147+
if (fresh.reason) {
148+
return { status: 'skipped', reason: `A reply was posted; further actions were skipped: ${fresh.reason}` };
149+
}
150+
if (classification === 'needs-info') {
151+
await github.rest.issues.addLabels({ ...current.target, labels: ['info-needed'] });
152+
} else {
153+
await github.rest.issues.update({ ...current.target, state: 'closed', state_reason: 'not_planned' });
154+
}
155+
return { status: 'success', reason: action, url: comment.html_url };
156+
}
157+
158+
/**
159+
* Treat a nonempty description update by the issue author as an information
160+
* response, like an author comment. Remove only local info-needed without AI,
161+
* reopening, or comments. Stale edits and newer human requests take precedence.
162+
*/
163+
async function clearInfoNeededOnEdit({ github, context }) {
164+
const { issue: edited, sender, changes } = context.payload;
165+
const skip = (reason) => ({ status: 'skipped', reason });
166+
if (context.eventName !== 'issues' || context.payload.action !== 'edited' || !changes?.body) {
167+
return skip('Only issue-description edits can acknowledge an information response.');
168+
}
169+
if (!Number.isSafeInteger(sender?.id) || sender.id !== edited?.user?.id || sender.type !== 'User') {
170+
return skip('Only the issue author can acknowledge an information response by editing.');
171+
}
172+
const body = edited.body ?? '';
173+
if (!body.trim() || body.trim() === (changes.body.from ?? '').trim()) {
174+
return skip('The description has no nonempty content change.');
175+
}
176+
const target = getTarget(context);
177+
const { data: issue } = await github.rest.issues.get(target);
178+
if (issue.pull_request || issue.state !== 'open' || issue.locked || issue.user?.id !== sender.id ||
179+
issue.body !== body || !issue.labels.some((label) => label.name === 'info-needed')) {
180+
return skip('The response is stale or the issue is not awaiting information.');
181+
}
182+
const editedAt = Date.parse(edited.updated_at);
183+
const events = await github.paginate(github.rest.issues.listEventsForTimeline, { ...target, per_page: 100 });
184+
const label = events.findLast((event) =>
185+
['labeled', 'unlabeled'].includes(event.event) && event.label?.name === 'info-needed');
186+
const labeledAt = Date.parse(label?.created_at);
187+
if (!Number.isFinite(editedAt) || !Number.isFinite(labeledAt) ||
188+
label.event !== 'labeled' || labeledAt >= editedAt) {
189+
return skip('The information request does not verifiably precede this response.');
190+
}
191+
if (events.some((event) => {
192+
const time = Date.parse(event.created_at);
193+
// GitHub can emit separate edited payloads for one title/body update.
194+
const sameEditRename = event.event === 'renamed' && event.actor?.id === sender.id &&
195+
time === editedAt && event.rename?.to === edited.title &&
196+
(!changes.title || event.rename?.from === changes.title.from);
197+
return (triageEvents.has(event.event) || event.event === 'commented') && !sameEditRename &&
198+
isHuman(event.actor ?? event.user) && (!Number.isFinite(time) || time >= editedAt);
199+
})) {
200+
return skip('Newer human activity takes precedence over this queued response.');
201+
}
202+
const { data: fresh } = await github.rest.issues.get(target);
203+
if (fresh.updated_at !== issue.updated_at || fresh.body !== body || fresh.state !== 'open' || fresh.locked ||
204+
!fresh.labels.some((entry) => entry.name === 'info-needed')) {
205+
return skip('The issue changed while checking the response.');
206+
}
207+
await github.rest.issues.removeLabel({ ...target, name: 'info-needed' });
208+
return { status: 'success', reason: 'The issue author updated the description; local info-needed was removed.' };
209+
}
210+
211+
module.exports = { inspectIssue, applyModeration, clearInfoNeededOnEdit };

0 commit comments

Comments
 (0)