@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,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 `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
+
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.
@@ -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: