@se-studio/skills 1.14.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @se-studio/skills
2
2
 
3
+ ## 1.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 798701a: Production-merge guard loosened from "never" to "only with a Nick or Charlie approval at the current head" (Nick, 19 Nov 2026: Charlie or the individual can approve, but production promotes must not happen randomly).
8
+
9
+ - **Agents may set `SE_ALLOW_PRODUCTION_MERGE=1`**, inline on the merge command (`SE_ALLOW_PRODUCTION_MERGE=1 se-agent-guard safe-merge <pr>`, `gh pr merge`, or the `safe-merge <owner/repo> <pr>` wrapper), but only when the PR (base `main` or `production`) has all of: a `## Merge approval` whose `Head SHA:` is the current full head, a `Who:` line that is Nick (`Nick`, `Nick Randell`, `nrandell`) or Charlie (chief of staff bot), and a passing `## Code review of <sha>` at that head. Otherwise the hook denies with a message naming the failed check (`production-approval-missing`, `-sha-mismatch`, `-unapproved-approver`, `production-review-missing`, `-not-passing`).
10
+ - **One allowlist:** `agent-guard/merge-approvers.json`, shipped in the package, so changing who may approve is a core PR and customer repos pick it up with the next `@se-studio/skills` bump.
11
+ - **Never without a named PR:** the command must name the PR by number or URL (not the current branch or a branch name). A `gh pr merge` into production must pin `--match-head-commit <full head>`. No admin bypass, no `pushed-through` shortcut; `none, Nick override` and `CI covers the changes since` do not replace the review on this path. The hook fails closed when `gh` cannot read the PR.
12
+ - **Applies to every production merge** the hook sees, with or without the variable. `safe-merge` runs the same check itself, so a script or a human shell is held to it too. `export SE_ALLOW_PRODUCTION_MERGE=...`, a bare assignment, a prefix on a nested shell, or a command that merges no PR is still denied.
13
+ - **Limit:** the check reads comment text and cannot authenticate who wrote `Who: Nick` (agents post with the human's `gh` login). It stops accidental promotes, not forgery.
14
+ - **Behaviour change:** `safe-merge` and the hook now require the approval above for a production merge even when a human sets the variable.
15
+ - **Hardening found in review:** `gh pr merge --admin` is denied; a merge in a command that also sets `GH_REPO` or runs `cd`/`pushd` is denied (the PR looked up could differ from the PR merged); an attached `-Ra/b` repo is read; the newest review at the head decides (a later BLOCKER overrides an earlier PASS); the review's SHA must be in its heading or `Head SHA:` line, and the verdict must be one word.
16
+ - **More hardening:** a merge combined with `GH_REPO`/`cd` is denied even inside `bash -c`/`eval`; a merge behind `xargs` is denied; a merge combined with `gh pr edit --base`, a `gh api` write or `git push` is denied; `timeout`, `flock`, `setsid`, `ionice` and `env -S` no longer hide a merge; `master` counts as a production base.
17
+
3
18
  ## 1.14.0
4
19
 
5
20
  ### Minor Changes
@@ -58,7 +58,17 @@ The skills checks are skipped when `CI` is set (anything but `false`, the same r
58
58
 
59
59
  **Check mode (run this before any merge, by any bot, agent, tool or script).** `se-agent-guard merge-gate <pr> --check` (alias `--pre-merge`; running with neither `--check` nor `--audit` is the same) reads the open PR's current head and **writes nothing**. It prints `merge-gate: PR #N OK at <head 12> — safe to merge with: gh pr merge N --merge --match-head-commit <full head>` and exits 0, or exits 1 with one bullet per failed check, ` - [check-id] <what failed> Fix: <what to do>`, then a line pointing at the templates. Exit 2 means it could not run (usage error, `gh` missing, not authenticated, PR not found) and says which. `-R OWNER/REPO` picks the repository when not run inside it; `--json` prints `{ ok, pr, head, checks, problems }` (`checks` is `{ id, ok, message, fix? }[]` for every check that ran). `--check` with `--audit` is a usage error. Check ids: `state`, `draft`, `do-not-merge-title`, `do-not-merge-label`, `approval-missing`, `approval-head`, `approval-review-link`, `review-link-target`, `review-pr-review`, `review-exists`, `review-self`, `review-heading`, `review-verdict`, `review-sha`, `review-order`. When an approval links several reviews, every candidate's failure is reported; with several approvals at the head, the newest is diagnosed.
60
60
 
61
- **`se-agent-guard safe-merge <pr> [-R owner/repo] [--dry-run]`** runs that check and, only if it passes, `gh pr merge <n> [-R repo] --merge --match-head-commit <the head it checked>`: merge commits only, and a push between the check and the merge makes the merge fail. It refuses a production promote (base `main` or `production`) unless a human set `SE_ALLOW_PRODUCTION_MERGE=1` in the process environment. `--dry-run` prints the command and does not run it.
61
+ **`se-agent-guard safe-merge <pr> [-R owner/repo] [--dry-run]`** runs that check and, only if it passes, `gh pr merge <n> [-R repo] --merge --match-head-commit <the head it checked>`: merge commits only, and a push between the check and the merge makes the merge fail. It refuses a production merge (base `main` or `production`) unless `SE_ALLOW_PRODUCTION_MERGE=1` is set **and** the PR passes the production approval check below. `--dry-run` prints the command and does not run it.
62
+
63
+ **Production merge by an agent (Nick, 19 Nov 2026: "Charlie can approve or the individual can approve ... production promotes must not happen randomly").** An agent may merge a PR whose base is `main` or `production` only when the command names that PR by number or URL (never the current branch or a branch name) and all of these hold; each failure is denied with a message that names which one:
64
+
65
+ 1. **Approval:** a live `## Merge approval` comment whose `Head SHA:` line is the PR's full current head SHA (`production-approval-missing`, `production-approval-sha-mismatch`).
66
+ 2. **Approver:** that comment's `Who:` line equals, whole and case-insensitively, an alias of an approver in `agent-guard/merge-approvers.json`: Nick (`Nick`, `Nick Randell`, `nrandell`) or Charlie (`Charlie`, `Charlie (chief of staff bot)`, ...) (`production-approval-unapproved-approver`). This file is the one allowlist; changing it is a core PR and customer repos get it with the next `@se-studio/skills` bump.
67
+ 3. **Review:** a live `## Code review of <sha>` (or `## Review (no code change) of <sha>`) comment naming the same head with `Verdict:` PASS, NITS or LGTM (`production-review-missing`, `production-review-not-passing`). `none, Nick override` and `CI covers the changes since` do **not** stand in for it on this path; the existing merge-gate rules (not a draft, not "do not merge", the approval links a review before it) still apply on top.
68
+
69
+ The hook runs this for every production merge (`gh pr merge` and `safe-merge`, with or without the variable in the command or the environment). The variable goes inline on the merge command only (`SE_ALLOW_PRODUCTION_MERGE=1 se-agent-guard safe-merge <pr>`); `export`, a bare assignment, a wrapper around a nested shell, or a command that merges no PR is denied. A `gh pr merge` into production must also pin `--match-head-commit <full head>`. `safe-merge` runs the same check itself, so a script or a human shell is held to it too. There is no admin bypass and no `pushed-through` shortcut: a failed check is fixed on the PR, then the merge runs again. The hook fails closed when `gh` cannot read the PR.
70
+
71
+ Limits: the check reads comment text. Agents post with the human's own `gh` login (every `## Merge approval` on this repo shows the author `nrandell`), so it cannot authenticate who wrote `Who: Nick`; it stops accidental and lazy production merges, not a deliberate forgery. Real separation would need Charlie to post under its own GitHub identity. The hook also reads command text, so a merge hidden behind something it cannot see (a `gh alias`, an unlisted wrapper such as `sg -c`, a script that runs `gh`) is not checked by the hook; `safe-merge` still checks for itself.
62
72
 
63
73
  The review comment and approval templates are in `references/agent-session/merge-review-template.md` (mandatory, Nick, 19 Nov 2026).
64
74
 
@@ -68,11 +78,11 @@ What the gate checks: the PR needs a `## Merge approval` comment that names the
68
78
 
69
79
  ## Overrides (human only)
70
80
 
71
- Read from the environment of the process that runs the hook, never from command text, so an agent cannot unlock a guard by prefixing a variable.
81
+ Read from the environment of the process that runs the hook, never from command text, so an agent cannot unlock a guard by prefixing a variable. The one exception is `SE_ALLOW_PRODUCTION_MERGE`, which an agent may prefix on a merge command; it unlocks nothing by itself, because the hook then checks the named PR's approval (see Merge gate).
72
82
 
73
83
  - `SE_ALLOW_PROTECTED_COMMIT=1` commit on an integration branch (explicit "work in place")
74
84
  - `SE_ALLOW_PROTECTED_PUSH=1` push to a production branch (after ask + confirm)
75
85
  - `SE_ALLOW_PRIMARY_EDIT=1` stop Claude asking before edits on a primary checkout
76
- - `SE_ALLOW_PRODUCTION_MERGE=1` let `safe-merge` merge into `main` or `production` (after the ask + confirm gate in `production-merge.md`)
86
+ - `SE_ALLOW_PRODUCTION_MERGE=1` let `safe-merge` merge into `main` or `production` (after the ask + confirm gate in `production-merge.md`). An agent may also put it inline on the merge command, but only for a named PR that passes the production approval check above
77
87
 
78
88
  `CI` set to anything but `false` skips the commit and push hooks.
@@ -8,6 +8,14 @@ import { execFileSync } from 'node:child_process';
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { describeLookupError, evaluateMergeGate, fetchPr } from './merge-gate.mjs';
11
+ import {
12
+ checkProductionApproval,
13
+ formatApprovalProblems,
14
+ isSpecificPr,
15
+ loadApprovers,
16
+ OVERRIDE_PRODUCTION_MERGE,
17
+ PRODUCTION_BASES,
18
+ } from './production-approval.mjs';
11
19
  import { classifyEdit, classifyShellCommand, MCP_MERGE_REASON, MCP_MERGE_TOOL } from './rules.mjs';
12
20
 
13
21
  function git(cwd, args) {
@@ -53,23 +61,77 @@ try {
53
61
  const cwd = payload.cwd || process.cwd();
54
62
  const input = payload.tool_input || {};
55
63
 
64
+ const deny = (reason) => ({ decision: 'deny', reason });
65
+
66
+ /**
67
+ * Production base (main/production), Nick 19 Nov 2026: the PR must be named by number or URL, a
68
+ * `gh pr merge` must pin the head, `safe-merge` needs the override on the command, and the PR needs a
69
+ * `## Merge approval` at the current head from an approver in merge-approvers.json plus a passing
70
+ * review at that head. Runs for every production merge, with or without the override.
71
+ * @returns {{ decision: 'deny', reason: string } | null} null when the production checks pass
72
+ */
73
+ function productionDecision(merge, pr, label) {
74
+ const refused = (why) =>
75
+ deny(`Production merge refused (${label}, base ${pr.baseRefName}): ${why}`);
76
+ if (!isSpecificPr(merge.target)) {
77
+ return refused(
78
+ 'the command must name the PR by number or URL, never "the current branch" or a branch name.',
79
+ );
80
+ }
81
+ const overridden = merge.productionOverride || process.env[OVERRIDE_PRODUCTION_MERGE] === '1';
82
+ if (merge.via === 'safe-merge' && !overridden) {
83
+ return refused(
84
+ `safe-merge refuses a production merge without ${OVERRIDE_PRODUCTION_MERGE}=1 on the command. Set it inline only when the approval is from Nick or Charlie at the current head; the guard checks that.`,
85
+ );
86
+ }
87
+ if (!merge.via) {
88
+ const pinned = (merge.matchHead ?? '').toLowerCase();
89
+ if (pinned !== (pr.headRefOid ?? '').toLowerCase()) {
90
+ return refused(
91
+ `pin the head with \`--match-head-commit ${pr.headRefOid}\` (the full current head) so a push after this check cannot slip in.${pinned ? ` The command pins ${pinned}.` : ''}`,
92
+ );
93
+ }
94
+ }
95
+ let approvers;
96
+ try {
97
+ approvers = loadApprovers();
98
+ } catch (e) {
99
+ return refused(`cannot read merge-approvers.json (${e.message}).`);
100
+ }
101
+ const approval = checkProductionApproval(pr, approvers);
102
+ return approval.ok ? null : refused(formatApprovalProblems(approval.problems));
103
+ }
104
+
56
105
  /**
57
106
  * Every merge in the command must pass the gate; any failure denies. Fail closed: when the gate
58
107
  * cannot run (gh missing, offline, not authenticated) the merge is denied too, never left to a prompt.
59
108
  */
60
109
  function mergeDecision(merges) {
61
110
  const lookupFailures = [];
62
- for (const { target, repo } of merges) {
111
+ for (const merge of merges) {
112
+ const { target, repo } = merge;
113
+ const label = target ?? 'current branch';
114
+ if (merge.productionOverride && !isSpecificPr(target)) {
115
+ return deny(
116
+ `${OVERRIDE_PRODUCTION_MERGE} is refused: the command does not name a specific PR (${label}). Name the PR by number or URL.`,
117
+ );
118
+ }
119
+ if (merge.dryRun) continue; // a dry run writes nothing
63
120
  try {
64
- const gate = evaluateMergeGate(fetchPr(target, { cwd, repo }), { requireOpen: true });
121
+ const pr = fetchPr(target, { cwd, repo });
122
+ if (PRODUCTION_BASES.includes(pr.baseRefName)) {
123
+ const refused = productionDecision(merge, pr, label);
124
+ if (refused) return refused;
125
+ }
126
+ const gate = evaluateMergeGate(pr, { requireOpen: true });
65
127
  if (!gate.ok) {
66
128
  return {
67
129
  decision: 'deny',
68
- reason: `Not mergeable yet (${target ?? 'current branch'}), do not merge:\n${gate.problems.map((p) => `- ${p}`).join('\n')}\nFix exactly what is named, then run \`se-agent-guard merge-gate ${target ?? '<pr>'} --check\` before merging.`,
130
+ reason: `Not mergeable yet (${label}), do not merge:\n${gate.problems.map((p) => `- ${p}`).join('\n')}\nFix exactly what is named, then run \`se-agent-guard merge-gate ${target ?? '<pr>'} --check\` before merging.`,
69
131
  };
70
132
  }
71
133
  } catch (e) {
72
- lookupFailures.push(`${target ?? 'current branch'}: ${describeLookupError(e, target, repo)}`);
134
+ lookupFailures.push(`${label}: ${describeLookupError(e, target, repo)}`);
73
135
  }
74
136
  }
75
137
  if (lookupFailures.length === 0) return { decision: 'allow' };
@@ -0,0 +1,15 @@
1
+ {
2
+ "description": "Who may approve a production merge (base main or production) that an agent runs with SE_ALLOW_PRODUCTION_MERGE=1. A `## Merge approval` comment at the PR's current head SHA must have a `Who:` line whose whole value equals one of these aliases (case-insensitive). Nick, 19 Nov 2026: Charlie or the individual can approve. Changing this list is a core PR; customer repos pick it up with the next @se-studio/skills bump.",
3
+ "approvers": [
4
+ { "name": "Nick", "aliases": ["Nick", "Nick Randell", "nrandell"] },
5
+ {
6
+ "name": "Charlie",
7
+ "aliases": [
8
+ "Charlie",
9
+ "Charlie (chief of staff)",
10
+ "Charlie (chief of staff bot)",
11
+ "chief of staff"
12
+ ]
13
+ }
14
+ ]
15
+ }
@@ -18,16 +18,16 @@ export const BREACH_LABEL = 'pushed-through';
18
18
 
19
19
  const DO_NOT_MERGE = /do[\s-]*not[\s-]*merge/i;
20
20
 
21
- const live = (comments) => comments.filter((c) => !c.isMinimized);
21
+ export const live = (comments) => comments.filter((c) => !c.isMinimized);
22
22
 
23
- function approvalComments(comments) {
23
+ export function approvalComments(comments) {
24
24
  return live(comments).filter((c) => /^\s*##\s+Merge approval\b/i.test(c.body ?? ''));
25
25
  }
26
26
 
27
27
  /** A head citation is the full SHA or a prefix of it. Seven characters is too easy to share by accident. */
28
28
  const MIN_HEAD_SHA = 12;
29
29
 
30
- function citesSha(body, headSha) {
30
+ export function citesSha(body, headSha) {
31
31
  if (!headSha) return false;
32
32
  const head = headSha.toLowerCase();
33
33
  return (body.match(new RegExp(`\\b[0-9a-f]{${MIN_HEAD_SHA},40}\\b`, 'gi')) ?? []).some((sha) =>
@@ -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,8 +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';
26
29
  /** 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(?:=|$)/;
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.`;
28
32
 
29
33
  const ZERO_SHA = /^0+$/;
30
34
  const MAX_DEPTH = 5;
@@ -104,6 +108,13 @@ const WRAPPERS = {
104
108
  xargs: ['-I', '-n', '-L', '-P', '-s', '-d', '-E', '-a', '-R', '-S'],
105
109
  npx: ['-p', '--package'],
106
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'],
107
118
  };
108
119
  const GIT_GLOBAL_VALUE_FLAGS = [
109
120
  '-C',
@@ -155,7 +166,16 @@ function unwrap(argv, nested, notes) {
155
166
  args.splice(0, REDIRECTION_ONLY.test(args[0]) ? 2 : 1);
156
167
  if (args.length === 0) return args;
157
168
  const bin = path.basename(args[0]);
158
- 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) {
159
179
  args = skipFlags(args.slice(1), WRAPPERS[bin]);
160
180
  } else if ((bin === 'pnpm' || bin === 'yarn') && ['dlx', 'exec'].includes(args[1])) {
161
181
  args = skipFlags(args.slice(2), []);
@@ -297,22 +317,34 @@ function classifyGh(argv, merges, escalate) {
297
317
  const rest = tail.slice(k + 1);
298
318
  if (area === 'pr' && action === 'merge') {
299
319
  let target;
320
+ let matchHead;
321
+ let admin = false;
300
322
  let strategy = false;
301
323
  for (let j = 0; j < rest.length; j++) {
302
324
  const arg = rest[j];
303
325
  if (arg.startsWith('--')) {
304
326
  const name = arg.split('=')[0];
327
+ if (name === '--match-head-commit')
328
+ matchHead = arg.includes('=') ? arg.split('=')[1] : rest[j + 1];
305
329
  if (name === '--squash' || name === '--rebase') strategy = true;
330
+ if (name === '--admin') admin = true;
306
331
  if (name === '--repo' || name === '-R')
307
332
  repo = arg.includes('=') ? arg.split('=')[1] : rest[j + 1];
308
333
  if (MERGE_VALUE_FLAGS.includes(name) && !arg.includes('=')) j++;
309
- } else if (/^-[A-Za-z]+$/.test(arg)) {
334
+ } else if (/^-[A-Za-z]/.test(arg)) {
310
335
  // A short cluster such as -sd: scan until a flag that takes a value, which ends the cluster.
311
- 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];
312
340
  if (ch === 's' || ch === 'r') strategy = true;
313
341
  if (MERGE_VALUE_FLAGS.includes(`-${ch}`)) {
314
- if (ch === 'R' && arg.endsWith('R')) repo = rest[j + 1];
315
- 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
+ }
316
348
  break;
317
349
  }
318
350
  }
@@ -320,7 +352,13 @@ function classifyGh(argv, merges, escalate) {
320
352
  target = arg;
321
353
  }
322
354
  }
323
- 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
+ }
324
362
  if (strategy) {
325
363
  escalate(
326
364
  'deny',
@@ -339,9 +377,57 @@ function classifyGh(argv, merges, escalate) {
339
377
  }
340
378
  }
341
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
+
342
428
  /**
343
429
  * Classify a shell command an agent is about to run.
344
- * @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 }[] }}
345
431
  */
346
432
  export function classifyShellCommand(command, { currentBranch = null, env = {} } = {}, depth = 0) {
347
433
  const ctx = { currentBranch, env };
@@ -358,9 +444,18 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
358
444
 
359
445
  const nested = [];
360
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
361
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;
362
452
  const argv = unwrap(raw, nested, notes);
363
- 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
+ }
364
459
  const bin = path.basename(argv[0]);
365
460
 
366
461
  if (argv.some((tok) => DEPLOY_SCRIPT.test(tok))) {
@@ -384,14 +479,36 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
384
479
  );
385
480
  }
386
481
  }
387
- if (raw.some((tok) => OVERRIDE_PRODUCTION_MERGE_USE.test(tok))) {
482
+ if (bin === 'git') classifyGit(argv, ctx, escalate);
483
+ const before = merges.length;
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')) {
388
499
  escalate(
389
500
  'deny',
390
- "SE_ALLOW_PRODUCTION_MERGE is for a human's own shell after Nick's explicit ask; agents may not set it.",
501
+ 'A merge run through xargs takes its PR number from input the guard cannot see. Name the PR on the merge command itself.',
391
502
  );
392
503
  }
393
- if (bin === 'git') classifyGit(argv, ctx, escalate);
394
- if (bin === 'gh') classifyGh(argv, merges, escalate);
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
+ }
395
512
  }
396
513
 
397
514
  for (const note of notes) escalate('ask', note);
@@ -400,6 +517,19 @@ export function classifyShellCommand(command, { currentBranch = null, env = {} }
400
517
  merges.push(...r.merges);
401
518
  escalate(r.decision, r.reason);
402
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
+ }
403
533
  return { ...result, merges };
404
534
  }
405
535
 
@@ -5,8 +5,10 @@
5
5
  * Runs the merge gate (check mode, no writes). Only when it passes does it run
6
6
  * gh pr merge <n> [-R repo] --merge --match-head-commit <the head it checked>
7
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 a human sets
9
- * SE_ALLOW_PRODUCTION_MERGE=1 in the process environment.
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.
10
12
  */
11
13
  import path from 'node:path';
12
14
  import { fileURLToPath } from 'node:url';
@@ -19,14 +21,20 @@ import {
19
21
  parseArgs,
20
22
  TEMPLATE_HINT,
21
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';
22
32
 
23
- export const OVERRIDE_PRODUCTION_MERGE = 'SE_ALLOW_PRODUCTION_MERGE';
33
+ export { OVERRIDE_PRODUCTION_MERGE };
24
34
 
25
35
  export const SAFE_MERGE_USAGE =
26
36
  'usage: se-agent-guard safe-merge <pr number|url|branch> [-R OWNER/REPO] [--dry-run]';
27
37
 
28
- const PRODUCTION_BASES = ['main', 'production'];
29
-
30
38
  /**
31
39
  * @returns {number} exit code: 0 merged (or dry run ok), 1 refused or merge failed, 2 usage or lookup error
32
40
  */
@@ -59,10 +67,32 @@ export function safeMerge(
59
67
  }
60
68
  if (PRODUCTION_BASES.includes(pr.baseRefName) && env[OVERRIDE_PRODUCTION_MERGE] !== '1') {
61
69
  err(
62
- `safe-merge: PR #${pr.number} targets ${pr.baseRefName}, a production promote. safe-merge refuses it: a production merge needs the human ask + confirm gate (production-merge.md). A human sets ${OVERRIDE_PRODUCTION_MERGE}=1 in the environment of the process that runs this; an agent must not. Nothing was merged.`,
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.`,
63
71
  );
64
72
  return 1;
65
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
+ }
66
96
  const args = [
67
97
  'pr',
68
98
  'merge',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/skills",
3
- "version": "1.14.0",
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",
@@ -15,7 +15,7 @@ This applies to Claude, Cursor, Grok Bot fleet bots, Codex, local scripts, and p
15
15
  3. Merge only with `se-agent-guard safe-merge <n>` (it runs the check, then merges with `--match-head-commit`), or `gh pr merge <n> --merge --match-head-commit <head>` after the check passed.
16
16
  4. If the check fails: **STOP.** Fix exactly what it names. Never merge anyway, and never use an MCP merge tool or `gh api .../merge`.
17
17
 
18
- A production promote (`main` or `production` as the base) also needs the human ask + confirm gate (`production-merge.md`); `safe-merge` refuses it unless a human set `SE_ALLOW_PRODUCTION_MERGE=1`.
18
+ A production promote (`main` or `production` as the base) also needs the human ask + confirm gate (`production-merge.md`); `safe-merge` refuses it unless `SE_ALLOW_PRODUCTION_MERGE=1` is set. An agent may set it inline on a merge command that names the PR, but only when the PR has a `## Merge approval` whose `Head SHA:` is the current head and whose `Who:` is Nick or Charlie (`merge-approvers.json`), plus a passing `## Code review of <sha>` at that head. On this path `none, Nick override` and `CI covers the changes since` do not replace the review. A failed check names itself; fix it on the PR and run the merge again.
19
19
 
20
20
  ## Review comment
21
21
 
@@ -29,6 +29,16 @@ Never ship customer production from a registry `productionPath` checkout. Merge
29
29
  5. **Prerequisites (core promote).** Version bumps must already be on `dev` (pending `.changeset/*.md` consumed by CI Dev). Do not promote while changesets remain. Post `## Merge approval` on the promote PR (who, where, when Europe/London, head SHA). The review line is a whole line `CI covers the changes since` (nothing after it). It applies to `dev` → `main` and to customer `develop` → `main` or `production`, when the head branch is in this repository. Do not run a second AI review of the promote. Merge approval is **in addition to** ask + confirm — not a substitute. The same CI line applies to a customer production promote.
30
30
  6. **Release verification (customer).** When the customer promote depends on new or changed Contentful entries, complete [`release-verification.md`](./release-verification.md) (publish state via CDA vs CPA, content smoke, preview compare, no unresolved failed production build). Record results on the promote PR. A Nick override never skips publish-state or content smoke.
31
31
 
32
+ ### Agent-run production merge (Nick, 19 Nov 2026)
33
+
34
+ The ask + confirm gate above is unchanged. On top of it, the agent-guard hook decides whether the merge command may run. The agent puts `SE_ALLOW_PRODUCTION_MERGE=1` inline on the merge command (`SE_ALLOW_PRODUCTION_MERGE=1 se-agent-guard safe-merge <pr number>`), and the PR must have:
35
+
36
+ - a `## Merge approval` whose `Head SHA:` line is the PR's current full head SHA,
37
+ - a `Who:` line that is Nick (`Nick`, `Nick Randell`, `nrandell`) or Charlie (chief of staff bot); the list is `agent-guard/merge-approvers.json` in `@se-studio/skills`,
38
+ - a passing `## Code review of <sha>` at that same head (Verdict PASS, NITS or LGTM). On this path a whole line `CI covers the changes since` or `none, Nick override` does **not** stand in for it, so a promote PR needs a review comment at its head.
39
+
40
+ The command must name the PR by number or URL, and a `gh pr merge` into `main`/`production` must pin `--match-head-commit <full head>`. A missing approval, a stale head, an approver outside the list, or no passing review is denied with a message naming which. Never work around it: no admin merge, no `pushed-through` merge, no `export` of the variable. Fix the PR and run the merge again. A push after the approval changes the head, so it needs a fresh review and approval.
41
+
32
42
  ### Restatement — customer production (required before merge)
33
43
 
34
44
  Send this shape, filled in, then wait: