@se-studio/skills 1.9.20 → 1.10.2

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,37 @@
1
1
  # @se-studio/skills
2
2
 
3
+ ## 1.10.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 473a462: Customer code-review template cites R5.13: grid items snap to the grid within 8px (replacing eagle's 4px), any horizontal offset faked with padding, margin, transform, position or a wrapper is covered, and an off-grid width or offset is a BLOCKER unless an explicit approval comment (anyone, author included, naming the node and giving the reason, in the PR or a code comment at the node) or the node's (or its frame's) Figma annotation says it is intentionally off grid. `se-exception:` on the layout lint is no substitute. A repo override is recorded as a deviation.
8
+
9
+ ## 1.10.1
10
+
11
+ ### Patch Changes
12
+
13
+ - ce25bc8: Customer AGENTS block no longer pins a Next.js minor; the customer code-review template takes eagle's more precise arbitrary-layout bullet; the guardrail README requires `packageManager`.
14
+
15
+ ## 1.10.0
16
+
17
+ ### Minor Changes
18
+
19
+ - ba0f3ef: Ship the agent guard as the `se-agent-guard` bin (`commit`, `push`, `claude-pretool`, `merge-gate`, `worktrees-clean`) and add the customer guardrail templates (`customer-guardrails/`). The customer AGENTS block (v2) now states the merge gate, merge commits only, the clean-worktree rule and cleanup after merge.
20
+
21
+ No customer repo changes until it opts in: the hooks, Claude settings and audit workflow are copies a repo adds by hand (`customer-guardrails/`). Sites affected: none yet (eagle first).
22
+
23
+ ## 1.9.22
24
+
25
+ ### Patch Changes
26
+
27
+ - 10d7629: Add the `architecture-review` skill: a PHILOSOPHY-based design review any agent or human can run, posted as `## Design review`.
28
+
29
+ ## 1.9.21
30
+
31
+ ### Patch Changes
32
+
33
+ - 3d095db: Fix the eagle `worktreesRoot` in the agent-session projects registry (`~/source/customers/eaglecap/worktrees`, where the repo and its worktrees live).
34
+
3
35
  ## 1.9.20
4
36
 
5
37
  ### Patch Changes
@@ -0,0 +1,47 @@
1
+ # agent-guard
2
+
3
+ Agent-neutral guards, published in `@se-studio/skills` as the `se-agent-guard` bin so customer repos run the version their lockfile pins instead of a copy.
4
+
5
+ ```
6
+ se-agent-guard commit | push | claude-pretool | merge-gate <pr> [--audit] | worktrees-clean [--apply] [--remote]
7
+ ```
8
+
9
+ Customer repos copy four thin files that call the bin: see `references/agent-session/customer-guardrails/`. Core uses the same code from `packages/skills/agent-guard/`.
10
+
11
+ Rules live in `rules.mjs`, `shell.mjs` and `merge-gate.mjs` (pure functions, tested in `scripts/__tests__`).
12
+
13
+ ## What enforces what
14
+
15
+ | Layer | Covers | Strength |
16
+ |-------|--------|----------|
17
+ | `cli.mjs commit` / `cli.mjs push` (husky) | every agent and human | **Enforcement.** No commits on `dev`/`develop`/`main`/`production`; no push or delete of `main`/`master`/`production`. Skipped by `--no-verify`, `-c core.hooksPath=...`, or uninstalled hooks. |
18
+ | `merge-gate-audit.yml` (CI, after every merge) | everyone, including the GitHub UI | **Detection.** Labels and comments `pushed-through` when a merge skipped the approval. Cannot undo or block a merge. |
19
+ | `claude-pretool.mjs` (Claude Code hook) | Claude only | **Advice before the command runs.** Reads the command text with a quote-aware tokenizer (`shell.mjs`): quoting, `git -C/-c`, `env`/`xargs`/`npx`/`pnpm dlx` wrappers, `sh -c`, `eval`, `$( )`, backticks, heredocs, `{ }` groups, `if`/`while`/`do`/`!` and leading redirections. It asks (rather than guesses) when a push argument contains `$( )`, backticks or a glob, and when a shell reads commands from a pipe, heredoc or process substitution. It does not follow variables, aliases, functions or scripts that run git, so treat it as a guard against honest mistakes, not a sandbox. |
20
+
21
+ GitHub branch protection and rulesets are not available on this plan (HTTP 403), so nothing stops a human merging in the GitHub UI; the audit is the backstop.
22
+
23
+ Grok and Cursor rely on the git hooks and the CI audit. Add thin adapters that call `rules.mjs` the same way if their hook APIs allow it.
24
+
25
+ ## What the Claude hook does
26
+
27
+ - Denies a push or delete of `main`/`master`/`production` (including `--all`, `--mirror`, quoted refs, `HEAD:main`), manual `vercel deploy/promote/rollback/--prod` (bare `vercel` too), `cms-edit:deploy`, `--no-verify`, and `-c`/`--config`/`--config-env` `core.hooksPath=...` (any spelling).
28
+ - Denies `gh api .../pulls/N/merge`: merge through `gh pr merge` so the gate can check it.
29
+ - Asks before a force-push and before editing on a primary checkout that is on an integration branch.
30
+ - For `gh pr merge`, checks **every** merge in the command against the merge gate. Any failure denies. If `gh` cannot be reached it asks. When all pass it allows without asking: the approval comment is the confirmation.
31
+ - A malformed hook payload exits 0 (never breaks the session).
32
+
33
+ ## Merge gate
34
+
35
+ `merge-gate.mjs <pr>`: the PR needs a `## Merge approval` comment that names the current head SHA and cites a review. **Anyone** may post it (Nick's decision, 30 Oct 2026: what matters is that the PR was reviewed, not who clicks approve), so the author is not checked. The review is: a link into this PR to a review comment (agent or human; its first heading says "review", it names the head SHA, it gives a verdict such as PASS/BLOCKERS/NITs/LGTM, and it was posted strictly before the approval), or a line that is exactly `none, Nick override`. Links to PR reviews (`#pullrequestreview-N`) are not accepted because `gh` returns no numeric review id to match them to; post the review as a comment. A bare "reviewed", an external link, a link to a comment that does not exist, a review of an older SHA, a `#pullrequestreview-` link, a minimized comment, or the approval citing itself all fail. Also: not a draft, not "do not merge". `--audit` labels `pushed-through` after a breach.
36
+
37
+ `gh` returns no `updatedAt` for comments, so a review comment edited after the approval (to add the SHA, say) cannot be detected. It cannot tell that the review was any good, or that the approver is Nick; someone determined can fabricate a review comment. It makes the honest path easy and the lazy fake fail. It reads comments through `gh pr view --json comments`; very long threads rely on `gh` paging them.
38
+
39
+ ## Overrides (human only)
40
+
41
+ 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.
42
+
43
+ - `SE_ALLOW_PROTECTED_COMMIT=1` commit on an integration branch (explicit "work in place")
44
+ - `SE_ALLOW_PROTECTED_PUSH=1` push to a production branch (after ask + confirm)
45
+ - `SE_ALLOW_PRIMARY_EDIT=1` stop Claude asking before edits on a primary checkout
46
+
47
+ `CI` set to anything but `false` skips the commit and push hooks.
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `se-agent-guard`: one entry point so a repo that depends on @se-studio/skills runs the
4
+ * pinned guard instead of carrying a copy of it.
5
+ * se-agent-guard commit git pre-commit hook
6
+ * se-agent-guard push git pre-push hook (ref lines on stdin)
7
+ * se-agent-guard claude-pretool Claude Code PreToolUse hook (payload on stdin)
8
+ * se-agent-guard merge-gate <pr> [--audit]
9
+ * se-agent-guard worktrees-clean [--apply] [--remote] remove merged worktrees and branches
10
+ */
11
+ import { spawnSync } from 'node:child_process';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ const SUBCOMMANDS = {
16
+ commit: ['cli.mjs', ['commit']],
17
+ push: ['cli.mjs', ['push']],
18
+ 'claude-pretool': ['claude-pretool.mjs', []],
19
+ 'merge-gate': ['merge-gate.mjs', []],
20
+ 'worktrees-clean': ['worktrees-clean.mjs', []],
21
+ };
22
+
23
+ const [sub, ...rest] = process.argv.slice(2);
24
+ const entry = SUBCOMMANDS[sub];
25
+ if (!entry) {
26
+ console.error(`usage: se-agent-guard ${Object.keys(SUBCOMMANDS).join('|')} [args]`);
27
+ process.exit(2);
28
+ }
29
+ const [file, fixed] = entry;
30
+ const script = path.join(path.dirname(fileURLToPath(import.meta.url)), file);
31
+ const { status, signal } = spawnSync(process.execPath, [script, ...fixed, ...rest], {
32
+ stdio: 'inherit',
33
+ });
34
+ process.exit(signal ? 1 : (status ?? 1));
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Claude Code PreToolUse adapter. Thin: parses the hook payload, asks rules.mjs,
4
+ * prints the permission decision. The enforcement that covers every agent lives in
5
+ * the git hooks (cli.mjs) and CI; this only stops the command earlier with a reason.
6
+ */
7
+ import { execFileSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { evaluateMergeGate, fetchPr } from './merge-gate.mjs';
11
+ import { classifyEdit, classifyShellCommand } from './rules.mjs';
12
+
13
+ function git(cwd, args) {
14
+ try {
15
+ return execFileSync('git', ['-C', cwd, ...args], {
16
+ encoding: 'utf8',
17
+ stdio: ['ignore', 'pipe', 'ignore'],
18
+ }).trim();
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ function repoState(cwd) {
25
+ const gitDir = git(cwd, ['rev-parse', '--absolute-git-dir']);
26
+ const commonDir = git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
27
+ return {
28
+ branch: git(cwd, ['symbolic-ref', '--short', '-q', 'HEAD']),
29
+ isPrimaryCheckout: Boolean(gitDir) && gitDir === commonDir,
30
+ };
31
+ }
32
+
33
+ function respond(decision, reason) {
34
+ if (decision === 'allow') return;
35
+ process.stdout.write(
36
+ JSON.stringify({
37
+ hookSpecificOutput: {
38
+ hookEventName: 'PreToolUse',
39
+ permissionDecision: decision,
40
+ permissionDecisionReason: `agent-guard: ${reason}`,
41
+ },
42
+ }),
43
+ );
44
+ }
45
+
46
+ let payload;
47
+ try {
48
+ payload = JSON.parse(fs.readFileSync(0, 'utf8'));
49
+ } catch {
50
+ process.exit(0); // never break the session on a malformed payload
51
+ }
52
+
53
+ const cwd = payload.cwd || process.cwd();
54
+ const input = payload.tool_input || {};
55
+
56
+ /** Every merge in the command must pass the gate; any failure denies, any lookup error asks. */
57
+ function mergeDecision(merges) {
58
+ let lookupFailed = false;
59
+ for (const { target, repo } of merges) {
60
+ try {
61
+ const gate = evaluateMergeGate(fetchPr(target, { cwd, repo }));
62
+ if (!gate.ok) {
63
+ return {
64
+ decision: 'deny',
65
+ reason: `Not mergeable yet (${target ?? 'current branch'}): ${gate.problems.join(' ')}`,
66
+ };
67
+ }
68
+ } catch {
69
+ lookupFailed = true; // gh missing, offline, or not authenticated
70
+ }
71
+ }
72
+ return lookupFailed ? null : { decision: 'allow' };
73
+ }
74
+
75
+ if (payload.tool_name === 'Bash') {
76
+ const shell = classifyShellCommand(String(input.command || ''), {
77
+ currentBranch: repoState(cwd).branch,
78
+ env: process.env,
79
+ });
80
+ // A hard deny wins. Otherwise a merge is decided by the real state of every PR it names;
81
+ // when all pass the human confirm is intentionally skipped (the approval comment is the confirm).
82
+ const { decision, reason } =
83
+ shell.decision === 'deny' || shell.merges.length === 0
84
+ ? shell
85
+ : (mergeDecision(shell.merges) ?? shell);
86
+ respond(decision, reason);
87
+ } else {
88
+ const target = input.file_path || input.notebook_path;
89
+ if (target) {
90
+ const dir = path.dirname(path.resolve(cwd, target));
91
+ const { decision, reason } = classifyEdit({
92
+ ...repoState(fs.existsSync(dir) ? dir : cwd),
93
+ env: process.env,
94
+ });
95
+ respond(decision, reason);
96
+ }
97
+ }
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Git-hook entry for the agent guard. Works for every agent (Claude, Cursor, Grok, humans).
4
+ * node packages/skills/agent-guard/cli.mjs commit # .husky/pre-commit
5
+ * node packages/skills/agent-guard/cli.mjs push # .husky/pre-push (reads ref lines on stdin)
6
+ */
7
+ import { execFileSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import { checkCommit, checkPush } from './rules.mjs';
10
+
11
+ function currentBranch() {
12
+ try {
13
+ return execFileSync('git', ['symbolic-ref', '--short', '-q', 'HEAD'], {
14
+ encoding: 'utf8',
15
+ }).trim();
16
+ } catch {
17
+ return null; // detached HEAD
18
+ }
19
+ }
20
+
21
+ function fail(reason) {
22
+ console.error(`\nagent-guard: ${reason}\n`);
23
+ process.exit(1);
24
+ }
25
+
26
+ const mode = process.argv[2];
27
+ if (mode === 'commit') {
28
+ const result = checkCommit({ branch: currentBranch(), env: process.env });
29
+ if (!result.ok) fail(result.reason);
30
+ } else if (mode === 'push') {
31
+ const stdin = fs.readFileSync(0, 'utf8');
32
+ const result = checkPush({ stdin, env: process.env });
33
+ if (!result.ok) fail(result.reason);
34
+ } else {
35
+ console.error('usage: cli.mjs commit|push');
36
+ process.exit(2);
37
+ }
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Merge gate (AGENTS.md: "Merge approval comment", "Review before merge").
4
+ * node packages/skills/agent-guard/merge-gate.mjs <pr number|url|branch> # exit 1 when not mergeable
5
+ * node packages/skills/agent-guard/merge-gate.mjs <pr> --audit # after a merge: label + comment on a breach
6
+ *
7
+ * GitHub cannot enforce this as a required check on this plan, so it is checked
8
+ * (1) before an agent runs `gh pr merge` (Claude adapter) and (2) after any merge (audit workflow).
9
+ */
10
+ import { execFileSync } from 'node:child_process';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ export const BREACH_LABEL = 'pushed-through';
15
+
16
+ const DO_NOT_MERGE = /do[\s-]*not[\s-]*merge/i;
17
+
18
+ const live = (comments) => comments.filter((c) => !c.isMinimized);
19
+
20
+ function approvalComments(comments) {
21
+ return live(comments).filter((c) => /^\s*##\s+Merge approval\b/i.test(c.body ?? ''));
22
+ }
23
+
24
+ function citesSha(body, headSha) {
25
+ const head = headSha.toLowerCase();
26
+ return (body.match(/\b[0-9a-f]{7,40}\b/gi) ?? []).some((sha) =>
27
+ head.startsWith(sha.toLowerCase()),
28
+ );
29
+ }
30
+
31
+ /** A verdict is what makes a comment a review rather than a note that mentions the word. */
32
+ const VERDICT = /\b(BLOCKERS?|NITs?|PASS|LGTM|approved?)\b/i;
33
+
34
+ /**
35
+ * A comment that is itself a review: its first heading says "review", it names the head SHA,
36
+ * and it gives a verdict. A heading may follow a short preamble.
37
+ */
38
+ function isReviewComment(comment, headSha) {
39
+ const body = comment.body ?? '';
40
+ const heading = body.split('\n').find((l) => /^\s*#{1,6}\s/.test(l)) ?? '';
41
+ return (
42
+ /\breview/i.test(heading) &&
43
+ !/merge approval/i.test(heading) &&
44
+ citesSha(body, headSha) &&
45
+ VERDICT.test(body)
46
+ );
47
+ }
48
+
49
+ /** Strictly before: a missing or equal timestamp cannot prove the review came first. */
50
+ const postedBefore = (review, approval) =>
51
+ Boolean(review.createdAt && approval.createdAt && review.createdAt < approval.createdAt);
52
+
53
+ const fragmentId = (url) => /#((?:issuecomment|pullrequestreview)-\d+)$/.exec(url)?.[1];
54
+
55
+ /** Links in the approval, trimmed of markdown and sentence punctuation. */
56
+ function linksIn(body) {
57
+ return (body.match(/https?:\/\/[^\s)>\]"'*`]+/g) ?? []).map((u) =>
58
+ u.replace(/[.,;:!?]+$/, '').replace(/\?[^#]*(?=#|$)/, ''),
59
+ );
60
+ }
61
+
62
+ /** The approval line `none, Nick override` must stand alone, not sit in a quote or a negation. */
63
+ const OVERRIDE_LINE = /^\s*(?:\d+[.)]\s*)?none,\s*nick override\.?\s*$/im;
64
+
65
+ /**
66
+ * Anyone may approve, but the approval has to point at a review that really exists on this PR
67
+ * at the current head: a review comment (agent or human) naming the head SHA, with a verdict, posted
68
+ * before the approval. `none, Nick override` skips it. Links to PR reviews (#pullrequestreview-N) are
69
+ * not accepted: gh returns no numeric review id, so such a link cannot be tied to a review.
70
+ * Cannot detect a review comment edited after the approval (gh returns no updatedAt).
71
+ */
72
+ function citedReview(approval, pr) {
73
+ if (OVERRIDE_LINE.test(approval.body)) return true;
74
+ const prUrl = (pr.url ?? '').replace(/\/$/, '');
75
+ for (const url of linksIn(approval.body)) {
76
+ const id = fragmentId(url);
77
+ if (!id || !prUrl || !url.startsWith(`${prUrl}#`)) continue; // must point into this PR
78
+ if (id.startsWith('issuecomment-')) {
79
+ const comment = live(pr.comments ?? []).find(
80
+ (c) => c !== approval && fragmentId(c.url ?? '') === id,
81
+ );
82
+ if (comment && isReviewComment(comment, pr.headRefOid) && postedBefore(comment, approval))
83
+ return true;
84
+ }
85
+ }
86
+ return false;
87
+ }
88
+
89
+ /**
90
+ * @param {{ headRefOid: string, isDraft?: boolean, title?: string, labels?: {name:string}[],
91
+ * url?: string, comments?: {body:string, url?:string, createdAt?:string, isMinimized?:boolean}[],
92
+ * }} pr
93
+ * @returns {{ ok: boolean, problems: string[] }}
94
+ */
95
+ export function evaluateMergeGate(pr, { ignoreDraft = false } = {}) {
96
+ const problems = [];
97
+ const labels = (pr.labels ?? []).map((l) => l.name);
98
+ if (!ignoreDraft && pr.isDraft) problems.push('PR is still a draft.');
99
+ if (DO_NOT_MERGE.test(pr.title ?? '') || labels.some((l) => DO_NOT_MERGE.test(l))) {
100
+ problems.push('PR is marked "do not merge".');
101
+ }
102
+
103
+ const approvals = approvalComments(pr.comments ?? []);
104
+ if (approvals.length === 0) {
105
+ problems.push('No `## Merge approval` comment on the PR.');
106
+ } else {
107
+ const atHead = approvals.filter((c) => citesSha(c.body, pr.headRefOid));
108
+ if (atHead.length === 0) {
109
+ problems.push(
110
+ `No \`## Merge approval\` comment names the current head SHA (${pr.headRefOid.slice(0, 7)}). ` +
111
+ 'New commits since the approval need a fresh one.',
112
+ );
113
+ } else if (!atHead.some((c) => citedReview(c, pr))) {
114
+ problems.push(
115
+ 'The `## Merge approval` comment must link a review on this PR (an agent or human review comment ' +
116
+ 'naming the current head SHA with a verdict, posted before the approval), or have a line saying `none, Nick override`.',
117
+ );
118
+ }
119
+ }
120
+ return { ok: problems.length === 0, problems };
121
+ }
122
+
123
+ const PR_FIELDS = 'isDraft,title,labels,headRefOid,comments,number,url';
124
+
125
+ export function fetchPr(target, { cwd, repo } = {}) {
126
+ const args = [
127
+ 'pr',
128
+ 'view',
129
+ ...(target ? [target] : []),
130
+ ...(repo ? ['-R', repo] : []),
131
+ '--json',
132
+ PR_FIELDS,
133
+ ];
134
+ return JSON.parse(
135
+ execFileSync('gh', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }),
136
+ );
137
+ }
138
+
139
+ function audit(pr, problems) {
140
+ const gh = (...args) => execFileSync('gh', args, { stdio: 'inherit' });
141
+ gh(
142
+ 'label',
143
+ 'create',
144
+ BREACH_LABEL,
145
+ '--force',
146
+ '--color',
147
+ 'B60205',
148
+ '--description',
149
+ 'Merged without the required approval/review',
150
+ );
151
+ gh('pr', 'edit', String(pr.number), '--add-label', BREACH_LABEL);
152
+ gh(
153
+ 'pr',
154
+ 'comment',
155
+ String(pr.number),
156
+ '--body',
157
+ `## Merge gate breach\n\nThis PR was merged without meeting AGENTS.md "Merge approval comment" / "Review before merge":\n\n${problems
158
+ .map((p) => `- ${p}`)
159
+ .join('\n')}\n\nLabelled \`${BREACH_LABEL}\` for review after the fact.`,
160
+ );
161
+ }
162
+
163
+ function main() {
164
+ const args = process.argv.slice(2);
165
+ const doAudit = args.includes('--audit');
166
+ const target = args.find((a) => !a.startsWith('--'));
167
+ const pr = fetchPr(target);
168
+ // After a merge the PR is no longer a draft in any meaningful sense.
169
+ const result = evaluateMergeGate(pr, { ignoreDraft: doAudit });
170
+ if (result.ok) {
171
+ console.log(`merge-gate: PR #${pr.number} ok at ${pr.headRefOid.slice(0, 7)}`);
172
+ return;
173
+ }
174
+ console.error(
175
+ `merge-gate: PR #${pr.number} is not mergeable:\n${result.problems.map((p) => ` - ${p}`).join('\n')}`,
176
+ );
177
+ if (doAudit) audit(pr, result.problems);
178
+ process.exit(1);
179
+ }
180
+
181
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();