@se-studio/skills 1.13.1 → 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.
@@ -0,0 +1,95 @@
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 a human sets
9
+ * SE_ALLOW_PRODUCTION_MERGE=1 in the process environment.
10
+ */
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import {
14
+ defaultExec,
15
+ describeLookupError,
16
+ evaluateMergeGate,
17
+ fetchPr,
18
+ formatProblems,
19
+ parseArgs,
20
+ TEMPLATE_HINT,
21
+ } from './merge-gate.mjs';
22
+
23
+ export const OVERRIDE_PRODUCTION_MERGE = 'SE_ALLOW_PRODUCTION_MERGE';
24
+
25
+ export const SAFE_MERGE_USAGE =
26
+ 'usage: se-agent-guard safe-merge <pr number|url|branch> [-R OWNER/REPO] [--dry-run]';
27
+
28
+ const PRODUCTION_BASES = ['main', 'production'];
29
+
30
+ /**
31
+ * @returns {number} exit code: 0 merged (or dry run ok), 1 refused or merge failed, 2 usage or lookup error
32
+ */
33
+ export function safeMerge(
34
+ argv,
35
+ { exec = defaultExec, out = console.log, err = console.error, env = process.env, cwd } = {},
36
+ ) {
37
+ const parsed = parseArgs(argv, ['--dry-run']);
38
+ if (parsed.error || !parsed.target) {
39
+ err(
40
+ `safe-merge: ${parsed.error ?? 'a PR number, URL or branch is required.'}\n${SAFE_MERGE_USAGE}`,
41
+ );
42
+ return 2;
43
+ }
44
+ const { target, repo, flags } = parsed;
45
+ let pr;
46
+ try {
47
+ pr = fetchPr(target, { cwd, repo, exec });
48
+ } catch (e) {
49
+ err(`safe-merge: ${describeLookupError(e, target, repo)}`);
50
+ return 2;
51
+ }
52
+ const head = pr.headRefOid ?? '';
53
+ const result = evaluateMergeGate(pr, { requireOpen: true });
54
+ if (!result.ok) {
55
+ err(
56
+ `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}`,
57
+ );
58
+ return 1;
59
+ }
60
+ if (PRODUCTION_BASES.includes(pr.baseRefName) && env[OVERRIDE_PRODUCTION_MERGE] !== '1') {
61
+ 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.`,
63
+ );
64
+ return 1;
65
+ }
66
+ const args = [
67
+ 'pr',
68
+ 'merge',
69
+ String(pr.number),
70
+ ...(repo ? ['-R', repo] : []),
71
+ '--merge',
72
+ '--match-head-commit',
73
+ head,
74
+ ];
75
+ if (flags.has('--dry-run')) {
76
+ out(
77
+ `safe-merge: dry run, PR #${pr.number} passed the gate at ${head.slice(0, 12)}. Would run: gh ${args.join(' ')}`,
78
+ );
79
+ return 0;
80
+ }
81
+ try {
82
+ exec('gh', args, { cwd, stdio: 'inherit' });
83
+ } catch (e) {
84
+ err(
85
+ `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.`,
86
+ );
87
+ return 1;
88
+ }
89
+ out(`safe-merge: merged PR #${pr.number} at ${head.slice(0, 12)}.`);
90
+ return 0;
91
+ }
92
+
93
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
94
+ process.exit(safeMerge(process.argv.slice(2)));
95
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/skills",
3
- "version": "1.13.1",
3
+ "version": "1.14.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
 
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Fallback merge guard for Claude Code (PreToolUse, matcher `Bash|mcp__.*`). Zero dependencies, node >= 20.
4
+ * Copy to `.claude/hooks/merge-guard.mjs` in a customer repo (see customer-guardrails/README.md).
5
+ *
6
+ * Why it exists: the full adapter (`@se-studio/skills` `claude-pretool.mjs`) lives in node_modules, so with no
7
+ * `pnpm install` it is missing and Claude Code's hook fails open. This file is committed, so a merge is still checked.
8
+ *
9
+ * - MCP merge tools (e.g. `mcp__github__merge_pull_request`): deny.
10
+ * - `gh pr merge`, `gh api .../pulls/N/merge`, `mergePullRequest`: if the full adapter is installed, exit 0 (it decides);
11
+ * otherwise run the pinned merge gate (`se-agent-guard merge-gate <pr> --check`) and allow only on exit 0.
12
+ * - Any error while checking: deny (fail closed), naming what failed.
13
+ * - Anything else: exit 0, silent.
14
+ */
15
+ import { spawnSync } from 'node:child_process';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ /** Used when package.json has no exact pin. Keep equal to the `@se-studio/skills` version that ships `--check`. */
21
+ export const FALLBACK_VERSION = '1.14.0';
22
+ /** First version with `merge-gate --check`. Older versions run the same non-writing check without the flag. */
23
+ export const CHECK_FLAG_VERSION = '1.14.0';
24
+
25
+ /** Keep identical to MCP_MERGE_TOOL in agent-guard/rules.mjs: deny merge verbs, allow get_/list_/read_/search_ tools. */
26
+ export const MCP_MERGE_TOOL = /^mcp__(?!.*?__(?:get|list|read|search)_).*?__.*merge/i;
27
+ export const MCP_MERGE_REASON =
28
+ '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.';
29
+
30
+ const GH_PR_MERGE =
31
+ /\bgh\b[^;&|\n]*?\bpr\b(?:\s+(?:-R|--repo)\s+\S+|\s+--repo=\S+)*\s+merge\b[^;&|\n)"'`]*/g;
32
+ const API_MERGE = /\bgh\b[^;&|\n]*\bapi\b[^;&|\n]*pulls\/[^\s/]+\/merge|mergePullRequest/;
33
+ /** Flags of `gh pr merge` that take a value, so the value is not mistaken for the PR. */
34
+ const VALUE_FLAGS = new Set([
35
+ '-R',
36
+ '--repo',
37
+ '-t',
38
+ '--subject',
39
+ '-b',
40
+ '--body',
41
+ '-F',
42
+ '--body-file',
43
+ '-A',
44
+ '--author-email',
45
+ '--match-head-commit',
46
+ ]);
47
+
48
+ /**
49
+ * Every `gh pr merge` in a command: the PR argument (undefined = current branch) and repo.
50
+ * @returns {{ target?: string, repo?: string }[]}
51
+ */
52
+ export function parseMerges(command) {
53
+ const merges = [];
54
+ for (const match of command.matchAll(GH_PR_MERGE)) {
55
+ const tokens = match[0].split(/\s+/).filter(Boolean);
56
+ let repo;
57
+ const ghIndex = tokens.indexOf('gh');
58
+ const prIndex = tokens.findIndex((t, i) => i > ghIndex && t === 'pr');
59
+ for (let i = ghIndex + 1; i < prIndex; i++) {
60
+ if (tokens[i] === '-R' || tokens[i] === '--repo') repo = tokens[i + 1];
61
+ else if (tokens[i].startsWith('--repo=')) repo = tokens[i].slice('--repo='.length);
62
+ }
63
+ let target;
64
+ let seenMerge = false;
65
+ for (let i = prIndex + 1; i < tokens.length; i++) {
66
+ const t = tokens[i].replace(/^["']|["']$/g, '');
67
+ if (!seenMerge && t === 'merge') {
68
+ seenMerge = true;
69
+ } else if (t === '-R' || t === '--repo') {
70
+ repo = tokens[++i];
71
+ } else if (t.startsWith('--repo=')) {
72
+ repo = t.slice('--repo='.length);
73
+ } else if (t.startsWith('--')) {
74
+ if (VALUE_FLAGS.has(t.split('=')[0]) && !t.includes('=')) i++;
75
+ } else if (t.startsWith('-')) {
76
+ if (/[RtbFA]$/.test(t)) i++;
77
+ } else if (target === undefined) {
78
+ target = t;
79
+ }
80
+ }
81
+ merges.push({ target, repo });
82
+ }
83
+ return merges;
84
+ }
85
+
86
+ export const isApiMerge = (command) => API_MERGE.test(command);
87
+
88
+ /** `1.13.1` -> [1, 13, 1]; null when it is not an exact x.y.z (ranges, tags, workspace links). */
89
+ export function parseVersion(spec) {
90
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(String(spec ?? '').trim());
91
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
92
+ }
93
+
94
+ export function compareVersions(a, b) {
95
+ const x = parseVersion(a);
96
+ const y = parseVersion(b);
97
+ if (!x || !y) return 0;
98
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
99
+ return 0;
100
+ }
101
+
102
+ /** The exact pinned version of @se-studio/skills in a package.json text, or FALLBACK_VERSION. */
103
+ export function pinnedVersion(packageJsonText) {
104
+ try {
105
+ const pkg = JSON.parse(packageJsonText);
106
+ const spec =
107
+ pkg.devDependencies?.['@se-studio/skills'] ?? pkg.dependencies?.['@se-studio/skills'];
108
+ if (parseVersion(spec)) return spec.trim();
109
+ } catch {
110
+ // fall through to the constant
111
+ }
112
+ return FALLBACK_VERSION;
113
+ }
114
+
115
+ /** The npx invocation that runs the pinned merge gate. */
116
+ export function gateCommand({ version, target, repo }) {
117
+ const check = compareVersions(version, CHECK_FLAG_VERSION) >= 0 ? ['--check'] : [];
118
+ return {
119
+ cmd: 'npx',
120
+ args: [
121
+ '-y',
122
+ '-p',
123
+ `@se-studio/skills@${version}`,
124
+ 'se-agent-guard',
125
+ 'merge-gate',
126
+ ...(target ? [target] : []),
127
+ ...check,
128
+ ...(repo ? ['-R', repo] : []),
129
+ ],
130
+ };
131
+ }
132
+
133
+ const defaultRunner = (cmd, args, opts) =>
134
+ spawnSync(cmd, args, { encoding: 'utf8', timeout: 180_000, ...opts });
135
+
136
+ /**
137
+ * Decide one hook payload. Pure apart from the injected `runner` and `fsx` (exists, read).
138
+ * @returns {{ decision: 'allow' | 'deny', reason?: string }}
139
+ */
140
+ export function decide(payload, { env = process.env, runner = defaultRunner, fsx = fs } = {}) {
141
+ const tool = String(payload?.tool_name ?? '');
142
+ if (MCP_MERGE_TOOL.test(tool)) return { decision: 'deny', reason: MCP_MERGE_REASON };
143
+ if (tool !== 'Bash') return { decision: 'allow' };
144
+
145
+ const command = String(payload?.tool_input?.command ?? '');
146
+ const merges = parseMerges(command);
147
+ const api = isApiMerge(command);
148
+ if (merges.length === 0 && !api) return { decision: 'allow' };
149
+
150
+ const project = env.CLAUDE_PROJECT_DIR || payload.cwd || process.cwd();
151
+ const adapter = path.join(
152
+ project,
153
+ 'node_modules',
154
+ '@se-studio',
155
+ 'skills',
156
+ 'agent-guard',
157
+ 'claude-pretool.mjs',
158
+ );
159
+ if (fsx.existsSync(adapter)) return { decision: 'allow' }; // the full adapter decides
160
+
161
+ if (api) {
162
+ return {
163
+ decision: 'deny',
164
+ reason:
165
+ 'merge-guard: a direct merge API call skips the merge gate. Merge through `gh pr merge <n> --merge --match-head-commit <sha>` or `se-agent-guard safe-merge <n>` after `se-agent-guard merge-gate <n> --check` passes.',
166
+ };
167
+ }
168
+ let version = FALLBACK_VERSION;
169
+ try {
170
+ version = pinnedVersion(fsx.readFileSync(path.join(project, 'package.json'), 'utf8'));
171
+ } catch {
172
+ // no readable package.json: use the fallback version
173
+ }
174
+ for (const { target, repo } of merges) {
175
+ const { cmd, args } = gateCommand({ version, target, repo });
176
+ const label = `${target ?? 'the current branch'}`;
177
+ let res;
178
+ try {
179
+ res = runner(cmd, args, { cwd: payload.cwd || project });
180
+ } catch (e) {
181
+ return {
182
+ decision: 'deny',
183
+ reason: `merge-guard: could not run the merge gate for ${label} (${e?.message ?? e}). Run \`pnpm install\`, then \`pnpm exec se-agent-guard merge-gate <pr> --check\`. Merge denied (fail closed).`,
184
+ };
185
+ }
186
+ if (res?.error || res?.status === null || res?.status === undefined) {
187
+ return {
188
+ decision: 'deny',
189
+ reason: `merge-guard: could not run \`${cmd} ${args.join(' ')}\` (${res?.error?.message ?? 'no exit status'}). Install dependencies with \`pnpm install\` and make sure npx, node and gh work, then run \`pnpm exec se-agent-guard merge-gate <pr> --check\`. Merge denied (fail closed).`,
190
+ };
191
+ }
192
+ if (res.status !== 0) {
193
+ const output = `${res.stderr ?? ''}${res.stdout ?? ''}`.trim();
194
+ return {
195
+ decision: 'deny',
196
+ reason: `merge-guard: the merge gate refused ${label} (exit ${res.status}), do not merge:\n${output || '(no output)'}\nFix exactly what is named, then run \`pnpm exec se-agent-guard merge-gate <pr> --check\`.`,
197
+ };
198
+ }
199
+ }
200
+ return { decision: 'allow' };
201
+ }
202
+
203
+ function main() {
204
+ let payload;
205
+ try {
206
+ payload = JSON.parse(fs.readFileSync(0, 'utf8'));
207
+ } catch (e) {
208
+ emit({
209
+ decision: 'deny',
210
+ reason: `merge-guard: could not read the hook payload (${e?.message ?? e}). Denied (fail closed).`,
211
+ });
212
+ return;
213
+ }
214
+ let result;
215
+ try {
216
+ result = decide(payload);
217
+ } catch (e) {
218
+ result = {
219
+ decision: 'deny',
220
+ reason: `merge-guard: unexpected error (${e?.message ?? e}). Merge denied (fail closed).`,
221
+ };
222
+ }
223
+ emit(result);
224
+ }
225
+
226
+ function emit({ decision, reason }) {
227
+ if (decision === 'allow') return;
228
+ process.stdout.write(
229
+ JSON.stringify({
230
+ hookSpecificOutput: {
231
+ hookEventName: 'PreToolUse',
232
+ permissionDecision: 'deny',
233
+ permissionDecisionReason: reason,
234
+ },
235
+ }),
236
+ );
237
+ }
238
+
239
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
@@ -2,13 +2,22 @@
2
2
  "hooks": {
3
3
  "PreToolUse": [
4
4
  {
5
- "matcher": "Bash|Edit|Write|NotebookEdit",
5
+ "matcher": "Bash|Edit|Write|NotebookEdit|mcp__.*",
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
9
  "command": "node \"$CLAUDE_PROJECT_DIR/node_modules/@se-studio/skills/agent-guard/claude-pretool.mjs\""
10
10
  }
11
11
  ]
12
+ },
13
+ {
14
+ "matcher": "Bash|mcp__.*",
15
+ "hooks": [
16
+ {
17
+ "type": "command",
18
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/merge-guard.mjs\""
19
+ }
20
+ ]
12
21
  }
13
22
  ]
14
23
  }
@@ -222,6 +222,21 @@ export function auditFiles({
222
222
  '.claude/settings.json does not run `claude-pretool.mjs` (copy customer-guardrails/claude-settings.json)',
223
223
  );
224
224
  }
225
+ const claudeSettings = files['.claude/settings.json'] ?? '';
226
+ if (/claude-pretool/.test(claudeSettings) && !/mcp__/.test(claudeSettings)) {
227
+ add(
228
+ 'claude-mcp-matcher-missing',
229
+ 'customer',
230
+ '.claude/settings.json PreToolUse matcher lacks `mcp__.*`: an MCP merge tool (mcp__github__merge_pull_request) would skip the merge gate (copy customer-guardrails/claude-settings.json)',
231
+ );
232
+ }
233
+ if (!files['.claude/hooks/merge-guard.mjs']) {
234
+ add(
235
+ 'merge-guard-missing',
236
+ 'customer',
237
+ '.claude/hooks/merge-guard.mjs is missing: without `pnpm install` the Claude hook fails open and a merge is not checked (copy customer-guardrails/claude-merge-guard.mjs and register it, see customer-guardrails/README.md)',
238
+ );
239
+ }
225
240
  if (!/merge-gate/.test(files['.github/workflows/merge-gate-audit.yml'] ?? '')) {
226
241
  add(
227
242
  'merge-audit-missing',
@@ -330,6 +345,7 @@ const GUARD_FILES = new Set([
330
345
  '.githooks/pre-commit',
331
346
  '.githooks/pre-push',
332
347
  '.claude/settings.json',
348
+ '.claude/hooks/merge-guard.mjs',
333
349
  '.github/workflows/merge-gate-audit.yml',
334
350
  ]);
335
351
 
@@ -0,0 +1,48 @@
1
+ # Merge review template (mandatory)
2
+
3
+ Nick, **19 Nov 2026**: this is the one canonical copy of the review comment, the merge approval comment, and the check that comes before any merge. `AGENTS.md` ("Merge approval comment", "Review before merge") and the customer agents block ("Review and merge") point here and show the same two comments.
4
+
5
+ ## Why
6
+
7
+ On 19 Nov 2026 OM1 #106, Pedestal #128, PointMe #165 and core #521 and #522 were labelled `pushed-through`. The linked review had no markdown heading containing "review" and/or no verdict word, and the merges were run by bots that never ran the gate first. Using the exact shapes below, and running the check before merging, makes that hard to get wrong.
8
+
9
+ ## Run the check first (binds every bot, agent, tool and human script)
10
+
11
+ This applies to Claude, Cursor, Grok Bot fleet bots, Codex, local scripts, and people. Whatever merges a PR runs the check first and stops if it fails.
12
+
13
+ 1. Post the review comment, then the merge approval comment (below).
14
+ 2. Run `se-agent-guard merge-gate <n> --check` (customer repos: `pnpm exec se-agent-guard merge-gate <n> --check`). It reads the open PR's current head, writes nothing, and names each failed check with a `Fix:`.
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
+ 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
+
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`.
19
+
20
+ ## Review comment
21
+
22
+ Post it **before** the approval, as a PR comment, never as a GitHub "PR review".
23
+
24
+ ```markdown
25
+ ## Code review of <full head SHA>
26
+ - Head SHA: <full head SHA>
27
+ - Verdict: PASS
28
+ - Findings: <none, or one line per finding prefixed BLOCKER: or NIT:>
29
+ ```
30
+
31
+ The verdict is exactly one of `PASS`, `NITS`, `BLOCKER` (the gate also accepts `LGTM`, `approved`, `NIT`, `BLOCKERS`).
32
+
33
+ After a review, a push that changes only lint, typecheck, tests or format uses the same shape with the heading `## Review (no code change) of <full head SHA>`, verdict `PASS`, and one more line: `- Since: <link to the earlier review>`.
34
+
35
+ ## Merge approval comment
36
+
37
+ Post it after the review.
38
+
39
+ ```markdown
40
+ ## Merge approval
41
+ - Who: <name of the person who said go>
42
+ - Where: <chat or agent session, or "GitHub">
43
+ - When: <Europe/London, from `TZ=Europe/London date '+%Y-%m-%d %H:%M %Z'`>
44
+ - Head SHA: <full head SHA>
45
+ - Review: <link to the review comment, https://github.com/<owner>/<repo>/pull/<n>#issuecomment-N>
46
+ ```
47
+
48
+ The `Review:` line may instead be a line of its own that reads `none, Nick override` (or `none, approver override`); on a production promote only, a line that is exactly `CI covers the changes since`. An approval that does not name the current head needs a fresh one after every new commit.