@se-studio/skills 1.10.27 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/agent-guard/README.md +34 -3
- package/agent-guard/bin.mjs +5 -1
- package/agent-guard/claude-pretool.mjs +21 -12
- package/agent-guard/doctor.mjs +369 -0
- package/agent-guard/merge-gate.mjs +416 -77
- package/agent-guard/rules.mjs +34 -2
- package/agent-guard/safe-merge.mjs +95 -0
- package/agent-guard/skill-links.mjs +130 -0
- package/package.json +1 -1
- package/references/agent-session/customer-agents-block.md +18 -8
- package/references/agent-session/customer-guardrails/README.md +4 -3
- package/references/agent-session/customer-guardrails/claude-merge-guard.mjs +239 -0
- package/references/agent-session/customer-guardrails/claude-settings.json +10 -1
- package/references/agent-session/fleet-audit.mjs +122 -22
- package/references/agent-session/merge-review-template.md +48 -0
- package/skills/coding-discipline/SKILL.md +17 -17
- package/skills/contentful-cms-generate-cms-guidelines/SKILL.md +1 -1
- package/skills/contentful-cms-schema-audit/SKILL.md +2 -2
- package/skills/contentful-cms-update-cms-guidelines/SKILL.md +1 -1
- package/skills/se-marketing-sites-customer-simplicity/SKILL.md +1 -0
- package/skills/se-marketing-sites-markdown-accuracy-review/SKILL.md +2 -2
- package/skills/se-marketing-sites-redirects/SKILL.md +67 -7
- package/skills/se-marketing-sites-smoke-test-setup/SKILL.md +1 -1
- package/skills/site-workflows-agent-session/SKILL.md +1 -1
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* Merge gate (AGENTS.md: "Merge approval comment", "Review before merge").
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* merge-gate.mjs <pr number|url|branch> [--check] [-R owner/repo] [--json]
|
|
5
|
+
* Pre-merge check of the open PR's current head. Writes nothing. Exit 0 ok, 1 not mergeable,
|
|
6
|
+
* 2 usage or lookup error (gh missing, not authenticated, PR not found). `--pre-merge` is an alias.
|
|
7
|
+
* merge-gate.mjs <pr> --audit After a merge: label `pushed-through` on a breach (no AI review).
|
|
6
8
|
*
|
|
7
9
|
* GitHub cannot enforce this as a required check on this plan, so it is checked
|
|
8
|
-
* (1) before an agent runs `gh pr merge` (Claude adapter) and (2) after any merge (audit workflow).
|
|
10
|
+
* (1) before an agent runs `gh pr merge` (Claude adapter, `safe-merge`) and (2) after any merge (audit workflow).
|
|
11
|
+
* Canonical review and approval templates: references/agent-session/merge-review-template.md.
|
|
9
12
|
*/
|
|
10
13
|
import { execFileSync } from 'node:child_process';
|
|
11
14
|
import path from 'node:path';
|
|
@@ -35,21 +38,6 @@ function citesSha(body, headSha) {
|
|
|
35
38
|
/** A verdict is what makes a comment a review rather than a note that mentions the word. */
|
|
36
39
|
const VERDICT = /\b(BLOCKERS?|NITs?|PASS|LGTM|approved?)\b/i;
|
|
37
40
|
|
|
38
|
-
/**
|
|
39
|
-
* A comment that is itself a review: its first heading says "review", it gives a verdict,
|
|
40
|
-
* and it names the current head (the full SHA, or a prefix of at least 12 hex characters).
|
|
41
|
-
* A heading may follow a short preamble. A hex string that is not that prefix does not count,
|
|
42
|
-
* including one shared with a `CI covers the changes since` line.
|
|
43
|
-
*/
|
|
44
|
-
function isReviewComment(comment, headSha) {
|
|
45
|
-
const body = comment.body ?? '';
|
|
46
|
-
const heading = body.split('\n').find((l) => /^\s*#{1,6}\s/.test(l)) ?? '';
|
|
47
|
-
if (!/\breview/i.test(heading) || /merge approval/i.test(heading) || !VERDICT.test(body)) {
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
return citesSha(body, headSha);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
41
|
/** Strictly before: a missing or equal timestamp cannot prove the review came first. */
|
|
54
42
|
const postedBefore = (review, approval) =>
|
|
55
43
|
Boolean(review.createdAt && approval.createdAt && review.createdAt < approval.createdAt);
|
|
@@ -88,6 +76,142 @@ export function isProductionPromote(pr) {
|
|
|
88
76
|
const CI_COVERS_LINE =
|
|
89
77
|
/^\s*(?:\d+[.)]\s*)?CI covers the changes since(?:\s+[0-9a-f]{12,40})?\.?\s*$/im;
|
|
90
78
|
|
|
79
|
+
/** The 12-character prefixes of every commit-looking hex string in a body, in order, without repeats. */
|
|
80
|
+
function citedShas(body) {
|
|
81
|
+
const found = (body ?? '').match(new RegExp(`\\b[0-9a-f]{${MIN_HEAD_SHA},40}\\b`, 'gi')) ?? [];
|
|
82
|
+
return [...new Set(found.map((s) => s.slice(0, MIN_HEAD_SHA).toLowerCase()))];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const firstHeading = (body) =>
|
|
86
|
+
(body ?? '')
|
|
87
|
+
.split('\n')
|
|
88
|
+
.find((l) => /^\s*#{1,6}\s/.test(l))
|
|
89
|
+
?.replace(/^\s*#{1,6}\s+/, '')
|
|
90
|
+
.trim();
|
|
91
|
+
|
|
92
|
+
const truncate = (text, n = 80) => (text.length > n ? `${text.slice(0, n - 1)}…` : text);
|
|
93
|
+
|
|
94
|
+
/** The newest comment by `createdAt`; without timestamps, the last one listed. */
|
|
95
|
+
function newest(list) {
|
|
96
|
+
return list.reduce((a, b) => ((b.createdAt ?? '') >= (a.createdAt ?? '') ? b : a));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Diagnose one linked candidate review, stopping at the first failing check.
|
|
101
|
+
* @returns {{ id: string, ok: boolean, message: string, fix?: string }[]}
|
|
102
|
+
*/
|
|
103
|
+
function diagnoseCandidate(url, approval, pr) {
|
|
104
|
+
const head = pr.headRefOid ?? '';
|
|
105
|
+
const head12 = head.slice(0, MIN_HEAD_SHA);
|
|
106
|
+
const id = fragmentId(url);
|
|
107
|
+
const checks = [];
|
|
108
|
+
const pass = (checkId, message) => {
|
|
109
|
+
checks.push({ id: checkId, ok: true, message });
|
|
110
|
+
return true;
|
|
111
|
+
};
|
|
112
|
+
const fail = (checkId, message, fix) => {
|
|
113
|
+
checks.push({ id: checkId, ok: false, message, fix });
|
|
114
|
+
return false;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
if (id.startsWith('pullrequestreview-')) {
|
|
118
|
+
fail(
|
|
119
|
+
'review-pr-review',
|
|
120
|
+
`Linked review ${url} is a GitHub PR review (#pullrequestreview-); the gate cannot read those.`,
|
|
121
|
+
'post the review as a PR comment and link #issuecomment-N.',
|
|
122
|
+
);
|
|
123
|
+
return checks;
|
|
124
|
+
}
|
|
125
|
+
const found = (pr.comments ?? []).find((c) => fragmentId(c.url ?? '') === id);
|
|
126
|
+
if (found === approval || (approval.url && fragmentId(approval.url) === id)) {
|
|
127
|
+
fail(
|
|
128
|
+
'review-self',
|
|
129
|
+
`Linked review ${url} is the "## Merge approval" comment itself, not a review.`,
|
|
130
|
+
`post the review as its own comment headed "## Code review of ${head}" before the approval and link that.`,
|
|
131
|
+
);
|
|
132
|
+
return checks;
|
|
133
|
+
}
|
|
134
|
+
if (!found || found.isMinimized) {
|
|
135
|
+
fail(
|
|
136
|
+
'review-exists',
|
|
137
|
+
`Linked review ${url} is not a live comment on this PR (deleted, minimized, or wrong id).`,
|
|
138
|
+
`link the review comment's own #issuecomment-N (the review must be unminimized, on this PR).`,
|
|
139
|
+
);
|
|
140
|
+
return checks;
|
|
141
|
+
}
|
|
142
|
+
pass('review-exists', `Linked review ${url} is a live comment on this PR.`);
|
|
143
|
+
|
|
144
|
+
const body = found.body ?? '';
|
|
145
|
+
const heading = firstHeading(body);
|
|
146
|
+
if (heading === undefined) {
|
|
147
|
+
fail(
|
|
148
|
+
'review-heading',
|
|
149
|
+
`Linked review ${url} has no markdown heading.`,
|
|
150
|
+
`start it with "## Code review of ${head}".`,
|
|
151
|
+
);
|
|
152
|
+
return checks;
|
|
153
|
+
}
|
|
154
|
+
if (/merge approval/i.test(heading)) {
|
|
155
|
+
fail(
|
|
156
|
+
'review-heading',
|
|
157
|
+
`Linked review ${url} is headed "${truncate(heading)}", a merge approval heading, not a review.`,
|
|
158
|
+
`post the review as its own comment headed "## Code review of ${head}" and link that.`,
|
|
159
|
+
);
|
|
160
|
+
return checks;
|
|
161
|
+
}
|
|
162
|
+
if (!/\breview/i.test(heading)) {
|
|
163
|
+
fail(
|
|
164
|
+
'review-heading',
|
|
165
|
+
`Linked review ${url} has no markdown heading containing "review" (first heading: "${truncate(heading)}").`,
|
|
166
|
+
`change the heading to "## Code review of ${head}".`,
|
|
167
|
+
);
|
|
168
|
+
return checks;
|
|
169
|
+
}
|
|
170
|
+
pass('review-heading', `Linked review ${url} has a review heading.`);
|
|
171
|
+
|
|
172
|
+
if (!VERDICT.test(body)) {
|
|
173
|
+
fail(
|
|
174
|
+
'review-verdict',
|
|
175
|
+
`Linked review ${url} has no verdict word (need PASS, LGTM, NITS/NIT, BLOCKER/BLOCKERS, or approved).`,
|
|
176
|
+
'add a line "Verdict: PASS".',
|
|
177
|
+
);
|
|
178
|
+
return checks;
|
|
179
|
+
}
|
|
180
|
+
pass('review-verdict', `Linked review ${url} gives a verdict.`);
|
|
181
|
+
|
|
182
|
+
if (!citesSha(body, head)) {
|
|
183
|
+
const cited = citedShas(body);
|
|
184
|
+
if (cited.length === 0) {
|
|
185
|
+
fail(
|
|
186
|
+
'review-sha',
|
|
187
|
+
`Linked review ${url} names no commit SHA (need the head SHA, full or >=12 hex chars).`,
|
|
188
|
+
`add "- Head SHA: ${head}".`,
|
|
189
|
+
);
|
|
190
|
+
} else {
|
|
191
|
+
fail(
|
|
192
|
+
'review-sha',
|
|
193
|
+
`Linked review ${url} names ${cited.join(', ')} but the PR head is ${head12}.`,
|
|
194
|
+
`re-review at the head, or if only lint/typecheck/tests/format changed post "## Review (no code change)" naming ${head12}.`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return checks;
|
|
198
|
+
}
|
|
199
|
+
pass('review-sha', `Linked review ${url} names the PR head ${head12}.`);
|
|
200
|
+
|
|
201
|
+
if (!postedBefore(found, approval)) {
|
|
202
|
+
const when = found.createdAt ?? 'no timestamp';
|
|
203
|
+
const then = approval.createdAt ?? 'no timestamp';
|
|
204
|
+
fail(
|
|
205
|
+
'review-order',
|
|
206
|
+
`Linked review ${url} was posted at ${when}, not strictly before the approval (${then}).`,
|
|
207
|
+
'post the review first, then a fresh "## Merge approval" that links it.',
|
|
208
|
+
);
|
|
209
|
+
return checks;
|
|
210
|
+
}
|
|
211
|
+
pass('review-order', `Linked review ${url} was posted before the approval.`);
|
|
212
|
+
return checks;
|
|
213
|
+
}
|
|
214
|
+
|
|
91
215
|
/**
|
|
92
216
|
* Anyone may approve, but the approval has to point at a review that really exists on this PR
|
|
93
217
|
* at the current head: a review comment (agent or human) naming the head SHA (full, or a
|
|
@@ -96,69 +220,175 @@ const CI_COVERS_LINE =
|
|
|
96
220
|
* Links to PR reviews (#pullrequestreview-N) are
|
|
97
221
|
* not accepted: gh returns no numeric review id, so such a link cannot be tied to a review.
|
|
98
222
|
* Cannot detect a review comment edited after the approval (gh returns no updatedAt).
|
|
223
|
+
* @returns {{ ok: boolean, checks: { id: string, ok: boolean, message: string, fix?: string }[] }}
|
|
99
224
|
*/
|
|
100
|
-
function
|
|
101
|
-
|
|
102
|
-
|
|
225
|
+
function diagnoseApproval(approval, pr) {
|
|
226
|
+
const body = approval.body ?? '';
|
|
227
|
+
const aUrl = approval.url ?? 'comment';
|
|
228
|
+
const head = pr.headRefOid ?? '';
|
|
229
|
+
if (OVERRIDE_LINE.test(body)) {
|
|
230
|
+
return {
|
|
231
|
+
ok: true,
|
|
232
|
+
checks: [{ id: 'approval-review', ok: true, message: `${aUrl} carries an override line.` }],
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
const promote = isProductionPromote(pr);
|
|
236
|
+
if (promote && CI_COVERS_LINE.test(body)) {
|
|
237
|
+
return {
|
|
238
|
+
ok: true,
|
|
239
|
+
checks: [
|
|
240
|
+
{ id: 'approval-review', ok: true, message: `${aUrl} uses "CI covers the changes since".` },
|
|
241
|
+
],
|
|
242
|
+
};
|
|
243
|
+
}
|
|
103
244
|
const prUrl = (pr.url ?? '').replace(/\/$/, '');
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
245
|
+
const links = [...new Set(linksIn(body))];
|
|
246
|
+
const mine = links.filter((u) => prUrl && u.startsWith(`${prUrl}#`) && fragmentId(u));
|
|
247
|
+
if (mine.length === 0) {
|
|
248
|
+
const checks = [
|
|
249
|
+
{
|
|
250
|
+
id: 'approval-review-link',
|
|
251
|
+
ok: false,
|
|
252
|
+
message: `"## Merge approval" ${aUrl} links no review comment on this PR (no #issuecomment- link into ${prUrl || 'this PR'}, and no "none, Nick override" line).`,
|
|
253
|
+
fix:
|
|
254
|
+
`add "- Review: <link to the review comment>" (post the review first, headed "## Code review of ${head}" with a verdict, see the template in AGENTS.md).` +
|
|
255
|
+
(promote
|
|
256
|
+
? ' This is a production promote: a whole line `CI covers the changes since` also works, with no review on this PR.'
|
|
257
|
+
: ''),
|
|
258
|
+
},
|
|
259
|
+
];
|
|
260
|
+
for (const url of links) {
|
|
261
|
+
checks.push({
|
|
262
|
+
id: 'review-link-target',
|
|
263
|
+
ok: false,
|
|
264
|
+
message: `Link ${url} in the approval points at another PR, an external page, or something that is not a #issuecomment-N on ${prUrl || 'this PR'}.`,
|
|
265
|
+
fix: 'link the review comment on this PR (https://github.com/<owner>/<repo>/pull/<n>#issuecomment-N).',
|
|
266
|
+
});
|
|
113
267
|
}
|
|
268
|
+
return { ok: false, checks };
|
|
269
|
+
}
|
|
270
|
+
const all = [];
|
|
271
|
+
for (const url of mine) {
|
|
272
|
+
const checks = diagnoseCandidate(url, approval, pr);
|
|
273
|
+
if (checks.every((c) => c.ok)) return { ok: true, checks };
|
|
274
|
+
all.push(...checks);
|
|
114
275
|
}
|
|
115
|
-
return false;
|
|
276
|
+
return { ok: false, checks: all };
|
|
116
277
|
}
|
|
117
278
|
|
|
279
|
+
export const problemText = (c) => (c.fix ? `${c.message} Fix: ${c.fix}` : c.message);
|
|
280
|
+
|
|
118
281
|
/**
|
|
119
282
|
* @param {{ headRefOid: string, isDraft?: boolean, title?: string, labels?: {name:string}[],
|
|
283
|
+
* state?: string, number?: number,
|
|
120
284
|
* url?: string, comments?: {body:string, url?:string, createdAt?:string, isMinimized?:boolean}[],
|
|
121
285
|
* }} pr
|
|
122
|
-
* @
|
|
286
|
+
* @param {{ ignoreDraft?: boolean, requireOpen?: boolean }} [options] `requireOpen` is for the pre-merge check
|
|
287
|
+
* (an audit runs on a merged PR).
|
|
288
|
+
* @returns {{ ok: boolean, problems: string[], checks: { id: string, ok: boolean, message: string, fix?: string }[] }}
|
|
289
|
+
* `problems[i]` belongs to the i-th failed check, so `problems` can be printed with check ids.
|
|
123
290
|
*/
|
|
124
|
-
export function evaluateMergeGate(pr, { ignoreDraft = false } = {}) {
|
|
125
|
-
const
|
|
291
|
+
export function evaluateMergeGate(pr, { ignoreDraft = false, requireOpen = false } = {}) {
|
|
292
|
+
const checks = [];
|
|
293
|
+
const add = (id, ok, message, fix) => checks.push({ id, ok, message, ...(fix ? { fix } : {}) });
|
|
294
|
+
const n = pr.number ?? '<n>';
|
|
295
|
+
const head = pr.headRefOid ?? '';
|
|
296
|
+
const head12 = head.slice(0, MIN_HEAD_SHA);
|
|
126
297
|
const labels = (pr.labels ?? []).map((l) => l.name);
|
|
127
|
-
|
|
128
|
-
if (
|
|
129
|
-
|
|
298
|
+
|
|
299
|
+
if (requireOpen && pr.state) {
|
|
300
|
+
const state = String(pr.state).toUpperCase();
|
|
301
|
+
add(
|
|
302
|
+
'state',
|
|
303
|
+
state === 'OPEN',
|
|
304
|
+
state === 'OPEN' ? `PR #${n} is open.` : `PR #${n} is ${state}, not open.`,
|
|
305
|
+
state === 'OPEN'
|
|
306
|
+
? undefined
|
|
307
|
+
: 'merge only an open PR (reopen it, or open a new PR for the work).',
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
if (!ignoreDraft) {
|
|
311
|
+
add(
|
|
312
|
+
'draft',
|
|
313
|
+
!pr.isDraft,
|
|
314
|
+
pr.isDraft ? 'PR is still a draft.' : 'PR is ready for review.',
|
|
315
|
+
pr.isDraft ? `mark it ready for review (gh pr ready ${n}).` : undefined,
|
|
316
|
+
);
|
|
130
317
|
}
|
|
318
|
+
const titleHit = DO_NOT_MERGE.test(pr.title ?? '');
|
|
319
|
+
add(
|
|
320
|
+
'do-not-merge-title',
|
|
321
|
+
!titleHit,
|
|
322
|
+
titleHit ? 'PR title says "do not merge".' : 'PR title does not say "do not merge".',
|
|
323
|
+
titleHit ? 'rename the PR once it is cleared to merge, or leave it unmerged.' : undefined,
|
|
324
|
+
);
|
|
325
|
+
const labelHit = labels.find((l) => DO_NOT_MERGE.test(l));
|
|
326
|
+
add(
|
|
327
|
+
'do-not-merge-label',
|
|
328
|
+
labelHit === undefined,
|
|
329
|
+
labelHit === undefined
|
|
330
|
+
? 'PR has no "do not merge" label.'
|
|
331
|
+
: `PR has the label "${labelHit}" (do not merge).`,
|
|
332
|
+
labelHit === undefined
|
|
333
|
+
? undefined
|
|
334
|
+
: `remove the label "${labelHit}" once the PR is cleared to merge, or leave it unmerged.`,
|
|
335
|
+
);
|
|
131
336
|
|
|
132
337
|
const approvals = approvalComments(pr.comments ?? []);
|
|
133
338
|
if (approvals.length === 0) {
|
|
134
|
-
|
|
339
|
+
add(
|
|
340
|
+
'approval-missing',
|
|
341
|
+
false,
|
|
342
|
+
'No "## Merge approval" comment on the PR.',
|
|
343
|
+
'post one using the template in AGENTS.md (Review and merge).',
|
|
344
|
+
);
|
|
135
345
|
} else {
|
|
136
|
-
const atHead = approvals.filter((c) => citesSha(c.body,
|
|
346
|
+
const atHead = approvals.filter((c) => citesSha(c.body, head));
|
|
137
347
|
if (atHead.length === 0) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
'The `## Merge approval` comment must link a review on this PR (an agent or human review comment ' +
|
|
146
|
-
'naming the current head SHA — the full SHA or a prefix of at least 12 hex characters — with a verdict, posted before the approval), or have a line saying `none, Nick override` (or `none, approver override`). ' +
|
|
147
|
-
'A hex string that is not that prefix does not count. ' +
|
|
148
|
-
(isProductionPromote(pr)
|
|
149
|
-
? 'This is a production promote: a whole line `CI covers the changes since` also works, with no review on this PR. '
|
|
150
|
-
: '') +
|
|
151
|
-
`Fix: post a review comment headed "## Code review" that names ${head} and gives a verdict (PASS, BLOCKERS, NITs, LGTM or approved), then a \`## Merge approval\` with the line \`Review: <link to that comment>\` (see the template in AGENTS.md).`,
|
|
348
|
+
const latest = newest(approvals);
|
|
349
|
+
const cited = citedShas(latest.body);
|
|
350
|
+
add(
|
|
351
|
+
'approval-head',
|
|
352
|
+
false,
|
|
353
|
+
`"## Merge approval" ${latest.url ?? 'comment'} names ${cited.length ? cited.join(', ') : 'no SHA'} but the PR head is ${head12}.`,
|
|
354
|
+
`post a fresh approval naming ${head}.`,
|
|
152
355
|
);
|
|
356
|
+
} else {
|
|
357
|
+
add('approval-head', true, `A "## Merge approval" names the PR head ${head12}.`);
|
|
358
|
+
let accepted;
|
|
359
|
+
for (const approval of atHead) {
|
|
360
|
+
const result = diagnoseApproval(approval, pr);
|
|
361
|
+
if (result.ok) {
|
|
362
|
+
accepted = result;
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (accepted) {
|
|
367
|
+
checks.push(...accepted.checks);
|
|
368
|
+
} else {
|
|
369
|
+
// Several approvals at the head: explain the newest, the one the approver most likely meant.
|
|
370
|
+
checks.push(...diagnoseApproval(newest(atHead), pr).checks);
|
|
371
|
+
}
|
|
153
372
|
}
|
|
154
373
|
}
|
|
155
|
-
|
|
374
|
+
const problems = checks.filter((c) => !c.ok).map(problemText);
|
|
375
|
+
return { ok: problems.length === 0, problems, checks };
|
|
156
376
|
}
|
|
157
377
|
|
|
158
378
|
const PR_FIELDS =
|
|
159
|
-
'isDraft,title,labels,headRefOid,baseRefName,headRefName,isCrossRepository,comments,number,url';
|
|
379
|
+
'isDraft,title,labels,headRefOid,baseRefName,headRefName,isCrossRepository,comments,number,url,state';
|
|
380
|
+
|
|
381
|
+
/** Default command runner: returns stdout, throws on a non-zero exit. */
|
|
382
|
+
export function defaultExec(cmd, args, opts = {}) {
|
|
383
|
+
const out = execFileSync(cmd, args, {
|
|
384
|
+
encoding: 'utf8',
|
|
385
|
+
stdio: opts.stdio ?? ['ignore', 'pipe', 'pipe'],
|
|
386
|
+
cwd: opts.cwd,
|
|
387
|
+
});
|
|
388
|
+
return out ?? '';
|
|
389
|
+
}
|
|
160
390
|
|
|
161
|
-
export function fetchPr(target, { cwd, repo } = {}) {
|
|
391
|
+
export function fetchPr(target, { cwd, repo, exec = defaultExec } = {}) {
|
|
162
392
|
const args = [
|
|
163
393
|
'pr',
|
|
164
394
|
'view',
|
|
@@ -167,13 +397,40 @@ export function fetchPr(target, { cwd, repo } = {}) {
|
|
|
167
397
|
'--json',
|
|
168
398
|
PR_FIELDS,
|
|
169
399
|
];
|
|
170
|
-
return JSON.parse(
|
|
171
|
-
|
|
172
|
-
|
|
400
|
+
return JSON.parse(exec('gh', args, { cwd }));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** A clear, one-line reason for a failed `gh pr view`, for exit 2 and for deny reasons. */
|
|
404
|
+
export function describeLookupError(err, target, repo) {
|
|
405
|
+
const text = `${err?.stderr ?? ''}\n${err?.message ?? ''}`;
|
|
406
|
+
const which = `${target ? `PR ${target}` : 'the PR for the current branch'}${repo ? ` in ${repo}` : ''}`;
|
|
407
|
+
if (err?.code === 'ENOENT') {
|
|
408
|
+
return 'gh (the GitHub CLI) is not installed or not on PATH. Install it (https://cli.github.com), run `gh auth login`, then retry.';
|
|
409
|
+
}
|
|
410
|
+
if (/gh auth login|not logged in|authentication|GH_TOKEN|HTTP 401|bad credentials/i.test(text)) {
|
|
411
|
+
return 'gh is not authenticated. Run `gh auth login` (or set GH_TOKEN), then retry.';
|
|
412
|
+
}
|
|
413
|
+
if (/could not resolve to a pullrequest|no pull requests found|HTTP 404|not found/i.test(text)) {
|
|
414
|
+
return `${which} was not found. Check the number, URL or branch${repo ? '' : ' (and pass -R OWNER/REPO outside the repository)'}.`;
|
|
415
|
+
}
|
|
416
|
+
if (err instanceof SyntaxError) return `gh returned output that is not JSON for ${which}.`;
|
|
417
|
+
const line = text.split('\n').find((l) => l.trim());
|
|
418
|
+
return `could not read ${which} with gh${line ? `: ${line.trim()}` : ''}.`;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export const TEMPLATE_HINT =
|
|
422
|
+
'Review and approval templates: AGENTS.md "Review and merge", or packages/skills/references/agent-session/merge-review-template.md (shipped in @se-studio/skills under references/agent-session/).';
|
|
423
|
+
|
|
424
|
+
/** The failed checks as ` - [id] problem` bullets. */
|
|
425
|
+
export function formatProblems(result) {
|
|
426
|
+
return result.checks
|
|
427
|
+
.filter((c) => !c.ok)
|
|
428
|
+
.map((c) => ` - [${c.id}] ${problemText(c)}`)
|
|
429
|
+
.join('\n');
|
|
173
430
|
}
|
|
174
431
|
|
|
175
|
-
function audit(pr, problems) {
|
|
176
|
-
const gh = (...args) =>
|
|
432
|
+
function audit(pr, problems, exec) {
|
|
433
|
+
const gh = (...args) => exec('gh', args, { stdio: 'inherit' });
|
|
177
434
|
gh(
|
|
178
435
|
'label',
|
|
179
436
|
'create',
|
|
@@ -198,22 +455,104 @@ function audit(pr, problems) {
|
|
|
198
455
|
);
|
|
199
456
|
}
|
|
200
457
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
458
|
+
/**
|
|
459
|
+
* Parse `<target> [-R owner/repo] [flags]`. `allow` lists the boolean flags the caller accepts.
|
|
460
|
+
* @returns {{ target?: string, repo?: string, flags: Set<string>, error?: string }}
|
|
461
|
+
*/
|
|
462
|
+
export function parseArgs(argv, allow = []) {
|
|
463
|
+
const flags = new Set();
|
|
464
|
+
let target;
|
|
465
|
+
let repo;
|
|
466
|
+
const aliases = { '--pre-merge': '--check' };
|
|
467
|
+
for (let i = 0; i < argv.length; i++) {
|
|
468
|
+
const raw = argv[i];
|
|
469
|
+
const a = aliases[raw] ?? raw;
|
|
470
|
+
if (a === '-R' || a === '--repo') {
|
|
471
|
+
repo = argv[++i];
|
|
472
|
+
if (!repo || repo.startsWith('-')) return { flags, error: `${raw} needs OWNER/REPO.` };
|
|
473
|
+
} else if (a.startsWith('--repo=')) {
|
|
474
|
+
repo = a.slice('--repo='.length);
|
|
475
|
+
} else if (allow.includes(a)) {
|
|
476
|
+
flags.add(a);
|
|
477
|
+
} else if (a.startsWith('-')) {
|
|
478
|
+
return { flags, error: `unknown option ${raw}.` };
|
|
479
|
+
} else if (target === undefined) {
|
|
480
|
+
target = a;
|
|
481
|
+
} else {
|
|
482
|
+
return { flags, error: `unexpected extra argument ${raw}.` };
|
|
483
|
+
}
|
|
211
484
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
485
|
+
return { target, repo, flags };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export const USAGE =
|
|
489
|
+
'usage: se-agent-guard merge-gate <pr number|url|branch> [--check] [-R OWNER/REPO] [--json]\n se-agent-guard merge-gate <pr> --audit [-R OWNER/REPO] (after a merge; labels `pushed-through`)';
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* CLI body. Returns the exit code instead of exiting so it can be tested with an injected `exec`.
|
|
493
|
+
* 0 mergeable, 1 not mergeable, 2 usage or lookup error. Check mode (the default) performs no writes.
|
|
494
|
+
*/
|
|
495
|
+
export function run(
|
|
496
|
+
argv,
|
|
497
|
+
{ exec = defaultExec, out = console.log, err = console.error, cwd } = {},
|
|
498
|
+
) {
|
|
499
|
+
const parsed = parseArgs(argv, ['--audit', '--check', '--json']);
|
|
500
|
+
if (parsed.error) {
|
|
501
|
+
err(`merge-gate: ${parsed.error}\n${USAGE}`);
|
|
502
|
+
return 2;
|
|
503
|
+
}
|
|
504
|
+
const { target, repo, flags } = parsed;
|
|
505
|
+
const doAudit = flags.has('--audit');
|
|
506
|
+
if (doAudit && flags.has('--check')) {
|
|
507
|
+
err(
|
|
508
|
+
`merge-gate: --check (alias --pre-merge) and --audit cannot be combined: --check never writes, --audit labels a merged PR.\n${USAGE}`,
|
|
509
|
+
);
|
|
510
|
+
return 2;
|
|
511
|
+
}
|
|
512
|
+
let pr;
|
|
513
|
+
try {
|
|
514
|
+
pr = fetchPr(target, { cwd, repo, exec });
|
|
515
|
+
} catch (e) {
|
|
516
|
+
err(`merge-gate: ${describeLookupError(e, target, repo)}`);
|
|
517
|
+
return 2;
|
|
518
|
+
}
|
|
519
|
+
// After a merge the PR is no longer a draft or open in any meaningful sense.
|
|
520
|
+
const result = evaluateMergeGate(pr, { ignoreDraft: doAudit, requireOpen: !doAudit });
|
|
521
|
+
const head = pr.headRefOid ?? '';
|
|
522
|
+
const head12 = head.slice(0, MIN_HEAD_SHA);
|
|
523
|
+
if (flags.has('--json')) {
|
|
524
|
+
out(
|
|
525
|
+
JSON.stringify(
|
|
526
|
+
{ ok: result.ok, pr: pr.number, head, checks: result.checks, problems: result.problems },
|
|
527
|
+
null,
|
|
528
|
+
2,
|
|
529
|
+
),
|
|
530
|
+
);
|
|
531
|
+
} else if (result.ok) {
|
|
532
|
+
out(
|
|
533
|
+
doAudit
|
|
534
|
+
? `merge-gate: PR #${pr.number} OK at ${head12} (audit: nothing to label)`
|
|
535
|
+
: `merge-gate: PR #${pr.number} OK at ${head12} — safe to merge with: gh pr merge ${pr.number}${repo ? ` -R ${repo}` : ''} --merge --match-head-commit ${head}`,
|
|
536
|
+
);
|
|
537
|
+
} else {
|
|
538
|
+
err(
|
|
539
|
+
`merge-gate: PR #${pr.number} is NOT mergeable at ${head12}:\n${formatProblems(result)}\n` +
|
|
540
|
+
(doAudit
|
|
541
|
+
? 'Labelling the breach.'
|
|
542
|
+
: `Do NOT merge. Fix exactly what is named above, then re-run: se-agent-guard merge-gate ${pr.number} --check\n${TEMPLATE_HINT}`),
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
if (result.ok) return 0;
|
|
546
|
+
if (doAudit) {
|
|
547
|
+
try {
|
|
548
|
+
audit(pr, result.problems, exec);
|
|
549
|
+
} catch (e) {
|
|
550
|
+
err(`merge-gate: could not label the breach: ${e?.message ?? e}`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return 1;
|
|
217
554
|
}
|
|
218
555
|
|
|
219
|
-
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url))
|
|
556
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
557
|
+
process.exit(run(process.argv.slice(2)));
|
|
558
|
+
}
|
package/agent-guard/rules.mjs
CHANGED
|
@@ -23,6 +23,8 @@ export const PROTECTED_PUSH_BRANCHES = ['main', 'master', 'production'];
|
|
|
23
23
|
export const OVERRIDE_COMMIT = 'SE_ALLOW_PROTECTED_COMMIT';
|
|
24
24
|
export const OVERRIDE_PUSH = 'SE_ALLOW_PROTECTED_PUSH';
|
|
25
25
|
export const OVERRIDE_PRIMARY_EDIT = 'SE_ALLOW_PRIMARY_EDIT';
|
|
26
|
+
/** An inline assignment (`VAR=1 cmd`, `env VAR=1 cmd`) or `export VAR` of the production-merge override. */
|
|
27
|
+
const OVERRIDE_PRODUCTION_MERGE_USE = /^SE_ALLOW_PRODUCTION_MERGE(?:=|$)/;
|
|
26
28
|
|
|
27
29
|
const ZERO_SHA = /^0+$/;
|
|
28
30
|
const MAX_DEPTH = 5;
|
|
@@ -32,7 +34,7 @@ function isOn(env, name) {
|
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
/** CI runs the same checks as audits; the hooks are for local laptops. */
|
|
35
|
-
function inCi(env) {
|
|
37
|
+
export function inCi(env) {
|
|
36
38
|
return Boolean(env.CI) && env.CI !== 'false';
|
|
37
39
|
}
|
|
38
40
|
|
|
@@ -278,7 +280,21 @@ function classifyGh(argv, merges, escalate) {
|
|
|
278
280
|
if (argv[i] === '-R' || argv[i] === '--repo') repo = argv[i + 1];
|
|
279
281
|
i += ['-R', '--repo'].includes(argv[i]) ? 2 : 1;
|
|
280
282
|
}
|
|
281
|
-
const
|
|
283
|
+
const tail = argv.slice(i);
|
|
284
|
+
// `gh pr -R o/r merge 5`: flags (and the value of -R/--repo) may sit between `pr` and the action.
|
|
285
|
+
let k = 1;
|
|
286
|
+
while (tail[0] === 'pr' && k < tail.length && tail[k].startsWith('-')) {
|
|
287
|
+
if (tail[k] === '-R' || tail[k] === '--repo') {
|
|
288
|
+
repo = tail[k + 1];
|
|
289
|
+
k += 2;
|
|
290
|
+
} else {
|
|
291
|
+
if (tail[k].startsWith('--repo=')) repo = tail[k].slice('--repo='.length);
|
|
292
|
+
k += 1;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const area = tail[0];
|
|
296
|
+
const action = tail[k];
|
|
297
|
+
const rest = tail.slice(k + 1);
|
|
282
298
|
if (area === 'pr' && action === 'merge') {
|
|
283
299
|
let target;
|
|
284
300
|
let strategy = false;
|
|
@@ -368,6 +384,12 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
|
|
|
368
384
|
);
|
|
369
385
|
}
|
|
370
386
|
}
|
|
387
|
+
if (raw.some((tok) => OVERRIDE_PRODUCTION_MERGE_USE.test(tok))) {
|
|
388
|
+
escalate(
|
|
389
|
+
'deny',
|
|
390
|
+
"SE_ALLOW_PRODUCTION_MERGE is for a human's own shell after Nick's explicit ask; agents may not set it.",
|
|
391
|
+
);
|
|
392
|
+
}
|
|
371
393
|
if (bin === 'git') classifyGit(argv, ctx, escalate);
|
|
372
394
|
if (bin === 'gh') classifyGh(argv, merges, escalate);
|
|
373
395
|
}
|
|
@@ -397,3 +419,13 @@ export function classifyEdit({ isPrimaryCheckout, branch, env = {} }) {
|
|
|
397
419
|
}
|
|
398
420
|
return { decision: 'allow' };
|
|
399
421
|
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* MCP tools that merge a PR (`merge_pull_request`, `merge_pr`, `pull_request_merge`, `enable_auto_merge`,
|
|
425
|
+
* `mergePullRequest`) skip `gh pr merge`, so skip the gate. Read-only tools named `get_`, `list_`, `read_`
|
|
426
|
+
* or `search_` after the `mcp__<server>__` prefix are not merges. Keep identical to claude-merge-guard.mjs.
|
|
427
|
+
*/
|
|
428
|
+
export const MCP_MERGE_TOOL = /^mcp__(?!.*?__(?:get|list|read|search)_).*?__.*merge/i;
|
|
429
|
+
|
|
430
|
+
export const MCP_MERGE_REASON =
|
|
431
|
+
'Merge only through `gh pr merge <n> --merge --match-head-commit <sha>` or `se-agent-guard safe-merge <n>` so the merge gate runs. MCP merge tools are not allowed.';
|