@se-studio/skills 1.13.1 → 1.15.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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Production-merge approval check (Nick, 19 Nov 2026: "Charlie can approve or the individual can
3
+ * approve ... production promotes must not happen randomly").
4
+ *
5
+ * An agent may merge a PR whose base is `main` or `production` only when ALL hold:
6
+ * 1. a live `## Merge approval` comment has a `Head SHA:` line equal to the PR's current head SHA,
7
+ * 2. that comment's `Who:` line is an approver in merge-approvers.json (Nick or Charlie),
8
+ * 3. a live `## Code review of <sha>` comment names that head and has a passing verdict.
9
+ * Pure functions, no I/O except loadApprovers. This reads comment text: it cannot authenticate who
10
+ * typed it (agents post with the human's gh token), so it stops accidents, not forgery.
11
+ */
12
+ import fs from 'node:fs';
13
+ import { approvalComments, citesSha, live } from './merge-gate.mjs';
14
+
15
+ export const PRODUCTION_BASES = ['main', 'master', 'production'];
16
+ export const OVERRIDE_PRODUCTION_MERGE = 'SE_ALLOW_PRODUCTION_MERGE';
17
+
18
+ /** Loads and validates the approver allowlist. Throws on a missing or malformed file (callers fail closed). */
19
+ export function loadApprovers(file = new URL('./merge-approvers.json', import.meta.url)) {
20
+ const { approvers } = JSON.parse(fs.readFileSync(file, 'utf8'));
21
+ const valid =
22
+ Array.isArray(approvers) &&
23
+ approvers.length > 0 &&
24
+ approvers.every(
25
+ (a) =>
26
+ typeof a?.name === 'string' &&
27
+ Array.isArray(a.aliases) &&
28
+ a.aliases.length > 0 &&
29
+ a.aliases.every((x) => typeof x === 'string' && x.trim()),
30
+ );
31
+ if (!valid) throw new Error('merge-approvers.json must list approvers with a name and aliases.');
32
+ return approvers;
33
+ }
34
+
35
+ /** A merge command names a specific PR only by number or PR URL, never by branch or by the current branch. */
36
+ export function isSpecificPr(target) {
37
+ return (
38
+ typeof target === 'string' &&
39
+ (/^\d+$/.test(target) ||
40
+ /^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+(?:[/?#]\S*)?$/.test(target))
41
+ );
42
+ }
43
+
44
+ const normalize = (text) =>
45
+ text
46
+ .toLowerCase()
47
+ .replace(/[*`_]/g, '')
48
+ .replace(/[.\s]+$/, '')
49
+ .replace(/\s+/g, ' ')
50
+ .trim();
51
+
52
+ const lineValue = (body, label) =>
53
+ new RegExp(`^[ \\t]*(?:[-*][ \\t]+)?\\**${label}\\**[ \\t]*:[ \\t]*(.+?)[ \\t]*$`, 'im').exec(
54
+ body ?? '',
55
+ )?.[1];
56
+
57
+ const PASSING = /^(?:pass|nits?|lgtm|approved?)$/i;
58
+ const BLOCKING = /^blockers?$/i;
59
+ const REVIEW_HEADING = /^\s*#{1,6}\s+(?:Code review|Review \(no code change\))\b/i;
60
+
61
+ /**
62
+ * @param {{ headRefOid: string, number?: number, comments?: object[] }} pr
63
+ * @param {{ name: string, aliases: string[] }[]} approvers
64
+ * @returns {{ ok: boolean, problems: { id: string, message: string }[] }}
65
+ */
66
+ export function checkProductionApproval(pr, approvers) {
67
+ const head = (pr.headRefOid ?? '').toLowerCase();
68
+ const head12 = head.slice(0, 12);
69
+ const problems = [];
70
+ const fail = (id, message) => problems.push({ id, message });
71
+
72
+ const approvals = approvalComments(pr.comments ?? []);
73
+ if (approvals.length === 0) {
74
+ fail(
75
+ 'production-approval-missing',
76
+ 'Missing approval: no `## Merge approval` comment on the PR. A production merge needs one from Nick or Charlie at the current head.',
77
+ );
78
+ } else {
79
+ const headOf = (c) => lineValue(c.body, 'Head SHA')?.match(/^\W*([0-9a-f]{7,40})\b/i)?.[1];
80
+ const atHead = approvals.filter((c) => headOf(c)?.toLowerCase() === head);
81
+ if (atHead.length === 0) {
82
+ const cited = [
83
+ ...new Set(approvals.map((c) => headOf(c)?.slice(0, 12) ?? 'no `Head SHA:` line')),
84
+ ];
85
+ fail(
86
+ 'production-approval-sha-mismatch',
87
+ `SHA mismatch: the \`## Merge approval\` names ${cited.join(', ')} but the PR head is ${head}. The approval's \`Head SHA:\` line must be the full current head; new commits need a fresh approval.`,
88
+ );
89
+ } else {
90
+ const names = (list) => list.map((a) => `${a.name} (${a.aliases.join(' / ')})`).join('; ');
91
+ const allowed = (c) => {
92
+ const who = lineValue(c.body, 'Who');
93
+ return (
94
+ who !== undefined &&
95
+ approvers.some((a) => a.aliases.some((x) => normalize(x) === normalize(who)))
96
+ );
97
+ };
98
+ if (!atHead.some(allowed)) {
99
+ const whos = atHead.map((c) => `"${lineValue(c.body, 'Who') ?? 'no Who line'}"`).join(', ');
100
+ fail(
101
+ 'production-approval-unapproved-approver',
102
+ `Unapproved approver: the approval at ${head12} has Who: ${whos}. A production merge needs Who to be one of: ${names(approvers)}. The list is merge-approvers.json in @se-studio/skills.`,
103
+ );
104
+ }
105
+ }
106
+ }
107
+
108
+ // A review is at the head when its heading or its `Head SHA:` line names it (not a mention in the body).
109
+ const atHead = (c) => {
110
+ const body = c.body ?? '';
111
+ const heading = body.split('\n').find((l) => /^\s*#{1,6}\s/.test(l)) ?? '';
112
+ return citesSha(heading, head) || citesSha(lineValue(body, 'Head SHA') ?? '', head);
113
+ };
114
+ const reviews = live(pr.comments ?? []).filter(
115
+ (c) => REVIEW_HEADING.test(c.body ?? '') && atHead(c),
116
+ );
117
+ const verdictOf = (c) => lineValue(c.body, 'Verdict')?.match(/^\W*([A-Za-z]+)\W*$/)?.[1];
118
+ // The newest review at the head decides: a later BLOCKER overrides an earlier PASS.
119
+ const newest = reviews.reduce(
120
+ (a, c) => ((c.createdAt ?? '') >= (a.createdAt ?? '') ? c : a),
121
+ reviews[0],
122
+ );
123
+ const verdict = newest && verdictOf(newest);
124
+ if (reviews.length === 0) {
125
+ fail(
126
+ 'production-review-missing',
127
+ `No review: no live \`## Code review of ${head12}…\` comment names the current head. Post a review at this head (Head SHA, Verdict, Findings) before the approval.`,
128
+ );
129
+ } else if (!(verdict && PASSING.test(verdict) && !BLOCKING.test(verdict))) {
130
+ fail(
131
+ 'production-review-not-passing',
132
+ `No passing review: the newest review at ${head12} has verdict ${verdict ?? 'no single-word Verdict line'}. It needs a \`Verdict:\` of exactly PASS, NITS or LGTM at the current head.`,
133
+ );
134
+ }
135
+ return { ok: problems.length === 0, problems };
136
+ }
137
+
138
+ export const formatApprovalProblems = (problems) =>
139
+ problems.map((p) => `[${p.id}] ${p.message}`).join(' ');
@@ -4,6 +4,8 @@
4
4
  *
5
5
  * Overrides are read only from the *human's* environment (never from the command
6
6
  * text an agent writes), so an agent cannot unlock a guard by prefixing a variable.
7
+ * The one exception is SE_ALLOW_PRODUCTION_MERGE, which an agent may prefix on a merge command:
8
+ * it unlocks nothing by itself, the hook then checks the named PR (production-approval.mjs).
7
9
  *
8
10
  * Enforcement vs advice: checkCommit/checkPush run in git hooks and are the real
9
11
  * guard (CI audits the rest). classifyShellCommand runs in an agent hook before a
@@ -23,6 +25,10 @@ export const PROTECTED_PUSH_BRANCHES = ['main', 'master', 'production'];
23
25
  export const OVERRIDE_COMMIT = 'SE_ALLOW_PROTECTED_COMMIT';
24
26
  export const OVERRIDE_PUSH = 'SE_ALLOW_PROTECTED_PUSH';
25
27
  export const OVERRIDE_PRIMARY_EDIT = 'SE_ALLOW_PRIMARY_EDIT';
28
+ const OVERRIDE_PRODUCTION_MERGE = 'SE_ALLOW_PRODUCTION_MERGE';
29
+ /** An inline assignment (`VAR=1 cmd`, `env VAR=1 cmd`) or `export VAR` of the production-merge override. */
30
+ const OVERRIDE_PRODUCTION_MERGE_USE = /^SE_ALLOW_PRODUCTION_MERGE(?:=\S*)?$/;
31
+ const OVERRIDE_SCOPE_REASON = `${OVERRIDE_PRODUCTION_MERGE} may only be set inline on the merge command itself, e.g. \`${OVERRIDE_PRODUCTION_MERGE}=1 se-agent-guard safe-merge <pr number>\`, and only for a production PR whose \`## Merge approval\` is from an approver in merge-approvers.json. Not via export, a separate assignment, or a command that merges no named PR.`;
26
32
 
27
33
  const ZERO_SHA = /^0+$/;
28
34
  const MAX_DEPTH = 5;
@@ -102,6 +108,13 @@ const WRAPPERS = {
102
108
  xargs: ['-I', '-n', '-L', '-P', '-s', '-d', '-E', '-a', '-R', '-S'],
103
109
  npx: ['-p', '--package'],
104
110
  bunx: [],
111
+ setsid: [],
112
+ ionice: ['-c', '-n', '-p'],
113
+ };
114
+ /** Wrappers whose first non-flag word is not the command (a duration, a lock file). */
115
+ const WRAPPERS_WITH_OPERAND = {
116
+ timeout: ['-s', '--signal', '-k', '--kill-after'],
117
+ flock: ['-w', '--timeout', '-E'],
105
118
  };
106
119
  const GIT_GLOBAL_VALUE_FLAGS = [
107
120
  '-C',
@@ -153,7 +166,16 @@ function unwrap(argv, nested, notes) {
153
166
  args.splice(0, REDIRECTION_ONLY.test(args[0]) ? 2 : 1);
154
167
  if (args.length === 0) return args;
155
168
  const bin = path.basename(args[0]);
156
- if (bin in WRAPPERS) {
169
+ if (bin === 'env' && args.some((a) => a === '-S' || a === '--split-string' || /^-S./.test(a))) {
170
+ // `env -S 'gh pr merge 5'` runs a string: analyse it as a nested command.
171
+ const at = args.findIndex((a) => a === '-S' || a === '--split-string' || /^-S./.test(a));
172
+ nested.push(
173
+ args[at].length > 2 && args[at].startsWith('-S') ? args[at].slice(2) : (args[at + 1] ?? ''),
174
+ );
175
+ return [];
176
+ } else if (bin in WRAPPERS_WITH_OPERAND) {
177
+ args = skipFlags(args.slice(1), WRAPPERS_WITH_OPERAND[bin]).slice(1);
178
+ } else if (bin in WRAPPERS) {
157
179
  args = skipFlags(args.slice(1), WRAPPERS[bin]);
158
180
  } else if ((bin === 'pnpm' || bin === 'yarn') && ['dlx', 'exec'].includes(args[1])) {
159
181
  args = skipFlags(args.slice(2), []);
@@ -278,25 +300,51 @@ function classifyGh(argv, merges, escalate) {
278
300
  if (argv[i] === '-R' || argv[i] === '--repo') repo = argv[i + 1];
279
301
  i += ['-R', '--repo'].includes(argv[i]) ? 2 : 1;
280
302
  }
281
- const [area, action, ...rest] = argv.slice(i);
303
+ const tail = argv.slice(i);
304
+ // `gh pr -R o/r merge 5`: flags (and the value of -R/--repo) may sit between `pr` and the action.
305
+ let k = 1;
306
+ while (tail[0] === 'pr' && k < tail.length && tail[k].startsWith('-')) {
307
+ if (tail[k] === '-R' || tail[k] === '--repo') {
308
+ repo = tail[k + 1];
309
+ k += 2;
310
+ } else {
311
+ if (tail[k].startsWith('--repo=')) repo = tail[k].slice('--repo='.length);
312
+ k += 1;
313
+ }
314
+ }
315
+ const area = tail[0];
316
+ const action = tail[k];
317
+ const rest = tail.slice(k + 1);
282
318
  if (area === 'pr' && action === 'merge') {
283
319
  let target;
320
+ let matchHead;
321
+ let admin = false;
284
322
  let strategy = false;
285
323
  for (let j = 0; j < rest.length; j++) {
286
324
  const arg = rest[j];
287
325
  if (arg.startsWith('--')) {
288
326
  const name = arg.split('=')[0];
327
+ if (name === '--match-head-commit')
328
+ matchHead = arg.includes('=') ? arg.split('=')[1] : rest[j + 1];
289
329
  if (name === '--squash' || name === '--rebase') strategy = true;
330
+ if (name === '--admin') admin = true;
290
331
  if (name === '--repo' || name === '-R')
291
332
  repo = arg.includes('=') ? arg.split('=')[1] : rest[j + 1];
292
333
  if (MERGE_VALUE_FLAGS.includes(name) && !arg.includes('=')) j++;
293
- } else if (/^-[A-Za-z]+$/.test(arg)) {
334
+ } else if (/^-[A-Za-z]/.test(arg)) {
294
335
  // A short cluster such as -sd: scan until a flag that takes a value, which ends the cluster.
295
- for (const ch of arg.slice(1)) {
336
+ // `-Ra/b` carries the repo attached to R; `-bRelease` is a body, not a repo.
337
+ const chars = arg.slice(1);
338
+ for (let k = 0; k < chars.length; k++) {
339
+ const ch = chars[k];
296
340
  if (ch === 's' || ch === 'r') strategy = true;
297
341
  if (MERGE_VALUE_FLAGS.includes(`-${ch}`)) {
298
- if (ch === 'R' && arg.endsWith('R')) repo = rest[j + 1];
299
- if (arg.endsWith(ch)) j++;
342
+ if (k < chars.length - 1) {
343
+ if (ch === 'R') repo = chars.slice(k + 1);
344
+ } else {
345
+ if (ch === 'R') repo = rest[j + 1];
346
+ j++;
347
+ }
300
348
  break;
301
349
  }
302
350
  }
@@ -304,7 +352,13 @@ function classifyGh(argv, merges, escalate) {
304
352
  target = arg;
305
353
  }
306
354
  }
307
- merges.push({ target, repo });
355
+ merges.push({ target, repo, ...(matchHead ? { matchHead } : {}) });
356
+ if (admin) {
357
+ escalate(
358
+ 'deny',
359
+ 'No admin merges: `gh pr merge --admin` skips the checks. Fix what the merge gate names instead.',
360
+ );
361
+ }
308
362
  if (strategy) {
309
363
  escalate(
310
364
  'deny',
@@ -323,9 +377,57 @@ function classifyGh(argv, merges, escalate) {
323
377
  }
324
378
  }
325
379
 
380
+ const SAFE_MERGE_VALUE_FLAGS = ['-R', '--repo'];
381
+ const REPO_SLUG = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
382
+
383
+ /**
384
+ * `se-agent-guard safe-merge <pr> [-R repo]`, `node .../safe-merge.mjs ...`, or the wrapper
385
+ * `safe-merge <owner/repo> <pr>`. Returns the PR it names, or null when argv is not a safe-merge.
386
+ */
387
+ function parseSafeMerge(argv) {
388
+ const bin = path.basename(argv[0]);
389
+ let at = -1;
390
+ if (bin === 'safe-merge') at = 0;
391
+ else if (bin === 'se-agent-guard' && argv[1] === 'safe-merge') at = 1;
392
+ else if (bin === 'node') {
393
+ const script = argv.findIndex((a) => /(^|\/)safe-merge\.mjs$/.test(a));
394
+ const cli = argv.findIndex((a) => /(^|\/)agent-guard\/bin\.mjs$/.test(a));
395
+ if (script > 0) at = script;
396
+ else if (cli > 0 && argv[cli + 1] === 'safe-merge') at = cli + 1;
397
+ }
398
+ if (at < 0) return null;
399
+ const positional = [];
400
+ let repo;
401
+ let dryRun = false;
402
+ const rest = argv.slice(at + 1);
403
+ for (let j = 0; j < rest.length; j++) {
404
+ const arg = rest[j];
405
+ if (arg === '--dry-run' || arg === '-n') dryRun = true;
406
+ else if (arg.startsWith('--repo=')) repo = arg.slice('--repo='.length);
407
+ else if (SAFE_MERGE_VALUE_FLAGS.includes(arg)) repo = rest[++j];
408
+ else if (!arg.startsWith('-')) positional.push(arg);
409
+ }
410
+ if (positional.length >= 2 && REPO_SLUG.test(positional[0])) {
411
+ return { target: positional[1], repo: positional[0], dryRun };
412
+ }
413
+ return { target: positional[0], repo, dryRun };
414
+ }
415
+
416
+ const GH_API_WRITE = /^(?:-X|--method(?:=.*)?|-f|-F|--field|--raw-field|--input)$/;
417
+ /** Commands that can change which PR, base or head a later merge in the same line would hit. */
418
+ function mutatesPr(argv) {
419
+ const bin = path.basename(argv[0]);
420
+ if (bin === 'git') return argv.includes('push');
421
+ if (bin !== 'gh') return false;
422
+ if (argv[1] === 'pr' && argv[2] === 'edit') {
423
+ return argv.some((a) => a === '-B' || a === '--base' || a.startsWith('--base='));
424
+ }
425
+ return argv[1] === 'api' && argv.some((a) => GH_API_WRITE.test(a));
426
+ }
427
+
326
428
  /**
327
429
  * Classify a shell command an agent is about to run.
328
- * @returns {{ decision: 'allow' | 'ask' | 'deny', reason?: string, merges: { target?: string, repo?: string }[] }}
430
+ * @returns {{ decision: 'allow' | 'ask' | 'deny', reason?: string, merges: { target?: string, repo?: string, matchHead?: string, via?: 'safe-merge', dryRun?: boolean, productionOverride?: boolean }[] }}
329
431
  */
330
432
  export function classifyShellCommand(command, { currentBranch = null, env = {} } = {}, depth = 0) {
331
433
  const ctx = { currentBranch, env };
@@ -342,9 +444,18 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
342
444
 
343
445
  const nested = [];
344
446
  const notes = [];
447
+ let mutatesBeforeMerge = false; // `gh pr edit --base`, `gh api` writes, `git push`: the PR may change before the merge
448
+ let redirectsRepo = false; // GH_REPO= or cd: the PR the hook looks up may not be the one gh merges
345
449
  for (const raw of scan(command, nested)) {
450
+ if (raw.some((tok) => /^GH_REPO(?:=|$)/.test(tok))) redirectsRepo = true;
451
+ if (['cd', 'pushd'].includes(path.basename(raw[0] ?? ''))) redirectsRepo = true;
346
452
  const argv = unwrap(raw, nested, notes);
347
- if (argv.length === 0) continue;
453
+ const usesOverride = raw.some((tok) => OVERRIDE_PRODUCTION_MERGE_USE.test(tok));
454
+ if (argv.length === 0) {
455
+ // A bare assignment (`VAR=1;`) or one on a wrapper around a nested shell is unscoped.
456
+ if (usesOverride) escalate('deny', OVERRIDE_SCOPE_REASON);
457
+ continue;
458
+ }
348
459
  const bin = path.basename(argv[0]);
349
460
 
350
461
  if (argv.some((tok) => DEPLOY_SCRIPT.test(tok))) {
@@ -369,7 +480,35 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
369
480
  }
370
481
  }
371
482
  if (bin === 'git') classifyGit(argv, ctx, escalate);
483
+ const before = merges.length;
372
484
  if (bin === 'gh') classifyGh(argv, merges, escalate);
485
+ const safeMerge = parseSafeMerge(argv);
486
+ if (safeMerge) {
487
+ merges.push({ ...safeMerge, via: 'safe-merge' });
488
+ if (!safeMerge.dryRun) {
489
+ escalate(
490
+ 'ask',
491
+ 'Merging needs a `## Merge approval` PR comment at the head SHA and a real review (AGENTS.md). Confirm both exist.',
492
+ );
493
+ }
494
+ }
495
+ // The production override is allowed only inline on the merge command that uses it. The hook
496
+ // then checks the named PR (production-approval.mjs); export, a bare assignment, or a wrapper
497
+ // around a nested shell leave it unscoped, so they are refused.
498
+ if (merges.length > before && raw.some((tok) => path.basename(tok) === 'xargs')) {
499
+ escalate(
500
+ 'deny',
501
+ 'A merge run through xargs takes its PR number from input the guard cannot see. Name the PR on the merge command itself.',
502
+ );
503
+ }
504
+ if (mutatesPr(argv)) mutatesBeforeMerge = true;
505
+ if (usesOverride) {
506
+ if (merges.length > before) {
507
+ for (const m of merges.slice(before)) m.productionOverride = true;
508
+ } else {
509
+ escalate('deny', OVERRIDE_SCOPE_REASON);
510
+ }
511
+ }
373
512
  }
374
513
 
375
514
  for (const note of notes) escalate('ask', note);
@@ -378,6 +517,19 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
378
517
  merges.push(...r.merges);
379
518
  escalate(r.decision, r.reason);
380
519
  }
520
+ // After the nested commands, so a merge inside `bash -c` or `eval` is seen.
521
+ if (redirectsRepo && merges.length > 0) {
522
+ escalate(
523
+ 'deny',
524
+ 'A merge command that also sets GH_REPO or changes directory (cd, pushd) cannot be checked: the PR looked up may not be the PR merged. Run the merge on its own with -R owner/repo or a PR URL.',
525
+ );
526
+ }
527
+ if (mutatesBeforeMerge && merges.length > 0) {
528
+ escalate(
529
+ 'deny',
530
+ 'Do not combine a merge with a command that can change the PR first (`gh pr edit --base`, a `gh api` write, `git push`): the guard checks the PR as it is now. Run them as separate commands.',
531
+ );
532
+ }
381
533
  return { ...result, merges };
382
534
  }
383
535
 
@@ -397,3 +549,13 @@ export function classifyEdit({ isPrimaryCheckout, branch, env = {} }) {
397
549
  }
398
550
  return { decision: 'allow' };
399
551
  }
552
+
553
+ /**
554
+ * MCP tools that merge a PR (`merge_pull_request`, `merge_pr`, `pull_request_merge`, `enable_auto_merge`,
555
+ * `mergePullRequest`) skip `gh pr merge`, so skip the gate. Read-only tools named `get_`, `list_`, `read_`
556
+ * or `search_` after the `mcp__<server>__` prefix are not merges. Keep identical to claude-merge-guard.mjs.
557
+ */
558
+ export const MCP_MERGE_TOOL = /^mcp__(?!.*?__(?:get|list|read|search)_).*?__.*merge/i;
559
+
560
+ export const MCP_MERGE_REASON =
561
+ '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.';
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `se-agent-guard safe-merge <pr> [-R owner/repo] [--dry-run]`
4
+ *
5
+ * Runs the merge gate (check mode, no writes). Only when it passes does it run
6
+ * gh pr merge <n> [-R repo] --merge --match-head-commit <the head it checked>
7
+ * so a push between the check and the merge makes the merge fail. Merge commits only.
8
+ * A production promote (base `main` or `production`) is refused unless SE_ALLOW_PRODUCTION_MERGE=1
9
+ * is set AND the PR has a `## Merge approval` at the current head from an approver in
10
+ * merge-approvers.json (Nick or Charlie) plus a passing review at that head. Whoever sets the
11
+ * variable, a human or an agent, is held to that approval.
12
+ */
13
+ import path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import {
16
+ defaultExec,
17
+ describeLookupError,
18
+ evaluateMergeGate,
19
+ fetchPr,
20
+ formatProblems,
21
+ parseArgs,
22
+ TEMPLATE_HINT,
23
+ } from './merge-gate.mjs';
24
+ import {
25
+ checkProductionApproval,
26
+ formatApprovalProblems,
27
+ isSpecificPr,
28
+ loadApprovers,
29
+ OVERRIDE_PRODUCTION_MERGE,
30
+ PRODUCTION_BASES,
31
+ } from './production-approval.mjs';
32
+
33
+ export { OVERRIDE_PRODUCTION_MERGE };
34
+
35
+ export const SAFE_MERGE_USAGE =
36
+ 'usage: se-agent-guard safe-merge <pr number|url|branch> [-R OWNER/REPO] [--dry-run]';
37
+
38
+ /**
39
+ * @returns {number} exit code: 0 merged (or dry run ok), 1 refused or merge failed, 2 usage or lookup error
40
+ */
41
+ export function safeMerge(
42
+ argv,
43
+ { exec = defaultExec, out = console.log, err = console.error, env = process.env, cwd } = {},
44
+ ) {
45
+ const parsed = parseArgs(argv, ['--dry-run']);
46
+ if (parsed.error || !parsed.target) {
47
+ err(
48
+ `safe-merge: ${parsed.error ?? 'a PR number, URL or branch is required.'}\n${SAFE_MERGE_USAGE}`,
49
+ );
50
+ return 2;
51
+ }
52
+ const { target, repo, flags } = parsed;
53
+ let pr;
54
+ try {
55
+ pr = fetchPr(target, { cwd, repo, exec });
56
+ } catch (e) {
57
+ err(`safe-merge: ${describeLookupError(e, target, repo)}`);
58
+ return 2;
59
+ }
60
+ const head = pr.headRefOid ?? '';
61
+ const result = evaluateMergeGate(pr, { requireOpen: true });
62
+ if (!result.ok) {
63
+ err(
64
+ `safe-merge: PR #${pr.number} is NOT mergeable at ${head.slice(0, 12)}, nothing was merged:\n${formatProblems(result)}\nDo NOT merge. Fix exactly what is named above, then run safe-merge again.\n${TEMPLATE_HINT}`,
65
+ );
66
+ return 1;
67
+ }
68
+ if (PRODUCTION_BASES.includes(pr.baseRefName) && env[OVERRIDE_PRODUCTION_MERGE] !== '1') {
69
+ err(
70
+ `safe-merge: PR #${pr.number} targets ${pr.baseRefName}, a production promote. safe-merge refuses it: a production merge needs the ask + confirm gate (production-merge.md) and ${OVERRIDE_PRODUCTION_MERGE}=1 on the command (an agent may set it inline only when the approval is from Nick or Charlie at the current head; that is then checked). Nothing was merged.`,
71
+ );
72
+ return 1;
73
+ }
74
+ if (PRODUCTION_BASES.includes(pr.baseRefName)) {
75
+ if (!isSpecificPr(target)) {
76
+ err(
77
+ `safe-merge: PR #${pr.number} targets ${pr.baseRefName}. A production merge must name the PR by number or URL, not "${target}". Nothing was merged.`,
78
+ );
79
+ return 1;
80
+ }
81
+ let approvers;
82
+ try {
83
+ approvers = loadApprovers();
84
+ } catch (e) {
85
+ err(`safe-merge: cannot read merge-approvers.json (${e.message}). Nothing was merged.`);
86
+ return 1;
87
+ }
88
+ const approval = checkProductionApproval(pr, approvers);
89
+ if (!approval.ok) {
90
+ err(
91
+ `safe-merge: PR #${pr.number} targets ${pr.baseRefName} and is not approved for a production merge at ${head.slice(0, 12)}. Nothing was merged.\n${formatApprovalProblems(approval.problems)}`,
92
+ );
93
+ return 1;
94
+ }
95
+ }
96
+ const args = [
97
+ 'pr',
98
+ 'merge',
99
+ String(pr.number),
100
+ ...(repo ? ['-R', repo] : []),
101
+ '--merge',
102
+ '--match-head-commit',
103
+ head,
104
+ ];
105
+ if (flags.has('--dry-run')) {
106
+ out(
107
+ `safe-merge: dry run, PR #${pr.number} passed the gate at ${head.slice(0, 12)}. Would run: gh ${args.join(' ')}`,
108
+ );
109
+ return 0;
110
+ }
111
+ try {
112
+ exec('gh', args, { cwd, stdio: 'inherit' });
113
+ } catch (e) {
114
+ err(
115
+ `safe-merge: gh pr merge failed (${e?.message ?? e}). If the head moved since the check, re-run the gate and approve the new head.`,
116
+ );
117
+ return 1;
118
+ }
119
+ out(`safe-merge: merged PR #${pr.number} at ${head.slice(0, 12)}.`);
120
+ return 0;
121
+ }
122
+
123
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
124
+ process.exit(safeMerge(process.argv.slice(2)));
125
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/skills",
3
- "version": "1.13.1",
3
+ "version": "1.15.0",
4
4
  "description": "SE Studio agent skills for marketing site development with Contentful CMS",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,4 +1,4 @@
1
- <!-- BEGIN:se-core-agents-block v4 -->
1
+ <!-- BEGIN:se-core-agents-block v5 -->
2
2
  ## Next.js docs (version-matched)
3
3
 
4
4
  This site runs **Next.js 16** (the minor is in `package.json`). Before writing Next.js code, read the relevant guide in `node_modules/next/dist/docs/` (in monorepos, resolve from the app that depends on `next`). Keep the managed `<!-- BEGIN:nextjs-agent-rules -->` block in `AGENTS.md`. Do **not** use `npx @next/codemod agents-md`, `.next-docs`, or `NEXT-AGENTS-MD-START` (Next 15 index: Pages Router, `middleware.ts`).
@@ -74,9 +74,19 @@ The review, design-review triggers and merge steps are in **Review and merge** b
74
74
 
75
75
  ### Review and merge
76
76
 
77
- 1. **Review.** One review (an agent or a human), when the work is finished. Post it as a PR comment under a heading that says "review", name the **final head SHA** (the full SHA, or a prefix of at least 12 hex characters), and give a verdict (PASS, BLOCKERS, NITs, LGTM or approved). Lint, typecheck and tests are CI (the shared site CI workflow). A change to schema, forms, analytics, caching or security (auth, secrets, headers, access control) also gets a design review in that same review: use skill `architecture-review` and post `## Design review` (PASS / BLOCKERS). Do not re-review on every push. A later commit that changes schema, forms, analytics, caching, or security gets a review of that delta only. Anything else is CI and needs no new code review, but post a one-line `## Review (no code change)` comment at the new head (`PASS at <head SHA, at least 12 hex characters>. Only lint/typecheck/tests/format since <link to earlier review>.`) and link that from the approval. A different hex string does not count.
78
- 2. **Approve.** Nick's go in chat (or another human the owner has authorised) is the approval; an agent records it but is never the approver. The agent records it as a PR comment headed `## Merge approval`: who, where, when (Europe/London), the head SHA, and a link to the review comment (`#issuecomment-N` on this PR). Post the review before the approval. Never merge a PR marked **do not merge**.
79
- Template, one comment:
77
+ The template below is **mandatory** (Nick, 19 Nov 2026). The canonical copy, with the reasons, is `node_modules/@se-studio/skills/references/agent-session/merge-review-template.md`. It binds every bot, agent, tool and script that merges (Claude, Cursor, Grok Bot, Codex, local scripts): run the check first, stop if it fails.
78
+
79
+ 1. **Review.** One review (an agent or a human), when the work is finished. Post it as a PR comment (never a GitHub "PR review") **before** the approval, in exactly this shape:
80
+
81
+ ```markdown
82
+ ## Code review of <full head SHA>
83
+ - Head SHA: <full head SHA>
84
+ - Verdict: PASS
85
+ - Findings: <none, or one line per finding prefixed BLOCKER: or NIT:>
86
+ ```
87
+
88
+ Verdict is exactly one of PASS, NITS, BLOCKER. Lint, typecheck and tests are CI (the shared site CI workflow). A change to schema, forms, analytics, caching or security (auth, secrets, headers, access control) also gets a design review in that same review: use skill `architecture-review` and post `## Design review` (PASS / BLOCKERS). Do not re-review on every push. A later commit that changes schema, forms, analytics, caching, or security gets a review of that delta only. Anything else is CI and needs no new code review, but post `## Review (no code change) of <full head SHA>` at the new head (verdict PASS, plus `- Since: <link to the earlier review>`) and link that from the approval.
89
+ 2. **Approve.** Nick's go in chat (or another human the owner has authorised) is the approval; an agent records it but is never the approver. Record it as one PR comment after the review. Never merge a PR marked **do not merge**.
80
90
 
81
91
  ```markdown
82
92
  ## Merge approval
@@ -84,12 +94,12 @@ The review, design-review triggers and merge steps are in **Review and merge** b
84
94
  - Where: <chat or agent session, or "GitHub">
85
95
  - When: <Europe/London, from `TZ=Europe/London date '+%Y-%m-%d %H:%M %Z'`>
86
96
  - Head SHA: <full head SHA>
87
- - Review: <link to the review comment>
97
+ - Review: <link to the review comment, https://github.com/<owner>/<repo>/pull/<n>#issuecomment-N>
88
98
  ```
89
99
 
90
100
  A production promote may use a line that is exactly `CI covers the changes since` instead of the review link; `none, Nick override` or `none, approver override` stands alone on a line. To hold a PR, make it a draft or label it `do not merge`: body prose holds nothing.
91
- 3. **Check.** `pnpm exec se-agent-guard merge-gate <number>` runs the same gate the Claude hook and the post-merge audit use. Run it before merging; fix what it names.
92
- 4. **Merge.** `gh pr merge <number> --merge --match-head-commit <approved head sha>`. Merge commits only: never `--squash` or `--rebase`. To undo a merge, `git revert -m 1 <merge commit>`. A merge that skipped the gate is labelled `pushed-through`. That label is the guardrail. It does not start a post-merge AI review.
101
+ 3. **Check, and stop if it fails.** `pnpm exec se-agent-guard merge-gate <number> --check` runs the same gate the Claude hook and the post-merge audit use, on the open PR's current head, and writes nothing. Each failure names the check and a `Fix:`. Fix exactly that. Never merge anyway.
102
+ 4. **Merge.** `pnpm exec se-agent-guard safe-merge <number>` (it runs the check, then merges with `--match-head-commit`), or `gh pr merge <number> --merge --match-head-commit <approved head sha>` after the check passed. Merge commits only: never `--squash` or `--rebase`, and no MCP merge tool or `gh api .../merge`. To undo a merge, `git revert -m 1 <merge commit>`. A merge that skipped the gate is labelled `pushed-through`. That label is the guardrail. It does not start a post-merge AI review.
93
103
  5. **Clean up** (see "Parallel features").
94
104
 
95
105
  Production merges (integration → `main`/`production`) need ask + confirm (`production-merge.md`) and a `## Merge approval` whose review line is `CI covers the changes since`. They do not get a second AI review.
@@ -120,4 +130,4 @@ When **marketing** work is ready, agents **stop** and hand off. Merge `develop`
120
130
 
121
131
  When the promote depends on new/changed Contentful content, complete **release verification** (`release-verification.md` in `@se-studio/skills`): publish state (CDA vs CPA), content smoke (not HTTP-only), preview compare (≥3 pages on published-only build), and no unresolved failed production build. Nick override never skips publish-state or content smoke.
122
132
 
123
- <!-- END:se-core-agents-block v4 -->
133
+ <!-- END:se-core-agents-block v5 -->
@@ -6,7 +6,8 @@ Thin files a customer repo copies once. The hook, Claude settings, and merge-gat
6
6
  |------|----|---------|
7
7
  | `pre-commit` | `.githooks/pre-commit` or `.husky/pre-commit` | refuse commits on `main`/`develop`/`production`; then the repo's own staged checks |
8
8
  | `pre-push` | `.githooks/pre-push` or `.husky/pre-push` | refuse pushes to `main`/`production`; type-check non-delete pushes |
9
- | `claude-settings.json` | `.claude/settings.json` | Claude Code pre-tool guard (denies `vercel deploy`, `--no-verify`, ungated `gh pr merge`, and so on) |
9
+ | `claude-settings.json` | `.claude/settings.json` | Claude Code pre-tool guard (denies `vercel deploy`, `--no-verify`, ungated `gh pr merge`, MCP merge tools, and so on). The matcher includes `mcp__.*`, and a second hook runs `merge-guard.mjs` |
10
+ | `claude-merge-guard.mjs` | `.claude/hooks/merge-guard.mjs` | committed fallback for the Claude hook (matcher `Bash|mcp__.*`, no dependencies). Denies MCP merge tools; for `gh pr merge` it defers to the full adapter when installed, otherwise runs the pinned `merge-gate --check` via `npx` and allows only on exit 0. Any error denies. `doctor` and `fleet-audit` warn when it is missing |
10
11
  | `merge-gate-audit.yml` | `.github/workflows/merge-gate-audit.yml` | labels `pushed-through` when a merge skipped the approval. The label is the guardrail; it does not start an AI review |
11
12
  | `site-ci.yml` | `.github/workflows/ci.yml` | calls the shared site CI workflow. Lint, typecheck, and tests always run. Set `run_prettier`, `run_lychee`, or `run_lighthouse` to adopt those checks |
12
13
 
@@ -18,7 +19,7 @@ Requirements:
18
19
  - `.claude/settings.json` must contain no tokens, and no allowlisted URL with an `access_token`.
19
20
  - GitHub Actions runs the shared site CI workflow (`site-ci.yml`: lint, typecheck, and tests), the deployment smoke (a Vercel Deployment Check with `targets` `["production"]` — feature previews are not gated, and new projects omit the skip job that posts a passing status on other branches), the audit above, and any publish job. Prettier, lychee link checking, and Lighthouse CI are inputs on that workflow; turn on the ones this repo uses. Lighthouse URLs are public origins with no bypass token. The shared workflow strips the query and fragment before upload and does not publish reports to temporary public storage. The caller job grants `actions: write` so that upload can succeed; only the Lighthouse job uses it. Vercel is still the production build. The repo's `validate` script also runs locally. If it needs the Contentful tokens (`validate:routes` does), it reads them from the repo's `.env.local`, and `DRAFT_ONLY` picks the preview or delivery token.
20
21
  - Link the package's skills into `.agents/skills` with `skills-npm --yes` in `prepare` (skipped on Vercel and CI). Do not run `skills update` or `skills@latest`. Keep the linked skill directories out of git: ignore everything under `.agents/skills`, `.claude/skills`, `.cursor/skills` and `.grok/skills` except the repo's own authored skills (use the `dir/*` form with `!dir/<name>` exceptions, as eagle-website does), and track `skills-npm-lock.json`.
21
- - Run `pnpm install` in every worktree. The git hooks fail closed without it (the commit is refused). The Claude hook cannot: Claude Code only blocks a tool call on exit code 2, so with no `node_modules` it fails open. The git hooks are the enforcement; the Claude hook is advice earlier.
22
+ - Run `pnpm install` in every worktree. The git hooks fail closed without it (the commit is refused). The Claude hook cannot: Claude Code only blocks a tool call on exit code 2, so with no `node_modules` it fails open. That is what `.claude/hooks/merge-guard.mjs` is for: it is committed, so a merge is still checked. The git hooks are the enforcement; the Claude hook is advice earlier.
22
23
  - The `pre-push` template runs `pnpm run type-check`: the repo needs that script (or edit the line).
23
24
  - Repo setting: merge commits only, squash and rebase off, delete branch on merge on.
24
25