@openora/create 0.4.1-canary.40 → 0.4.1-canary.403

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.
Files changed (104) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/generated/versions.d.ts +11 -0
  3. package/dist/generated/versions.d.ts.map +1 -0
  4. package/dist/generated/versions.js +11 -0
  5. package/dist/generated/versions.js.map +1 -0
  6. package/dist/index.js +48 -93
  7. package/dist/index.js.map +1 -1
  8. package/dist/render.d.ts +15 -0
  9. package/dist/render.d.ts.map +1 -0
  10. package/dist/render.js +125 -0
  11. package/dist/render.js.map +1 -0
  12. package/package.json +8 -6
  13. package/template/README.md.tpl +12 -7
  14. package/template/__dot__claude/settings.json.tpl +30 -12
  15. package/template/__dot__env.example +16 -0
  16. package/template/__dot__gitignore +5 -5
  17. package/template/__dot__rulesync/commands/check.md +11 -10
  18. package/template/__dot__rulesync/commands/doctor.md.tpl +17 -0
  19. package/template/__dot__rulesync/commands/scaffold-module.md +3 -2
  20. package/template/__dot__rulesync/commands/scaffold-plugin.md +23 -4
  21. package/template/__dot__rulesync/commands/scaffold-route.md +1 -0
  22. package/template/__dot__rulesync/commands/start.md +2 -2
  23. package/template/__dot__rulesync/hooks/_shared.mjs +25 -34
  24. package/template/__dot__rulesync/hooks/guard-core.mjs.tpl +98 -28
  25. package/template/__dot__rulesync/hooks/guard-generated.mjs +15 -16
  26. package/template/__dot__rulesync/hooks/guard-mr.mjs +143 -0
  27. package/template/__dot__rulesync/hooks/guard-review.mjs +280 -0
  28. package/template/__dot__rulesync/hooks/guard-stack.mjs +35 -0
  29. package/template/__dot__rulesync/hooks/guard-subagent.mjs +22 -6
  30. package/template/__dot__rulesync/hooks/post-edit.mjs.tpl +116 -0
  31. package/template/__dot__rulesync/hooks.json +37 -4
  32. package/template/__dot__rulesync/rules/conventions.md +99 -119
  33. package/template/__dot__rulesync/rules/db-conventions.md +6 -72
  34. package/template/__dot__rulesync/rules/e2e-conventions.md +33 -7
  35. package/template/__dot__rulesync/rules/frontend-conventions.md.tpl +35 -0
  36. package/template/__dot__rulesync/rules/oss-boundaries.md.tpl +78 -0
  37. package/template/__dot__rulesync/rules/overview.md +19 -82
  38. package/template/__dot__rulesync/skills/agent-retro/SKILL.md.tpl +81 -0
  39. package/template/__dot__rulesync/skills/agent-retro/scan.mjs +420 -0
  40. package/template/__dot__rulesync/skills/create-plugin/{SKILL.md → SKILL.md.tpl} +12 -23
  41. package/template/__dot__rulesync/skills/create-pr/SKILL.md.tpl +37 -0
  42. package/template/__dot__rulesync/skills/create-task/SKILL.md.tpl +96 -0
  43. package/template/__dot__rulesync/skills/create-ui-module/{SKILL.md → SKILL.md.tpl} +12 -10
  44. package/template/__dot__rulesync/skills/enhance-prompt/{SKILL.md → SKILL.md.tpl} +4 -4
  45. package/template/__dot__rulesync/skills/handoff/SKILL.md +4 -3
  46. package/template/__dot__rulesync/skills/review/SKILL.md.tpl +278 -0
  47. package/template/__dot__rulesync/skills/ship/SKILL.md.tpl +157 -0
  48. package/template/__dot__rulesync/skills/ship/handoff.md.tpl +48 -0
  49. package/template/__dot__rulesync/skills/ship/watch-pr.mjs +189 -0
  50. package/template/__dot__rulesync/skills/ui-verify/SKILL.md.tpl +120 -0
  51. package/template/__dot__rulesync/skills/ui-verify/layout-check.check.sh +58 -0
  52. package/template/__dot__rulesync/skills/ui-verify/layout-check.js +163 -0
  53. package/template/__dot__rulesync/subagents/builder.md.tpl +116 -0
  54. package/template/__dot__rulesync/subagents/compliance-reviewer.md +79 -0
  55. package/template/__dot__rulesync/subagents/debugger.md.tpl +89 -0
  56. package/template/__dot__rulesync/subagents/deployer.md.tpl +55 -0
  57. package/template/__dot__rulesync/subagents/expert.md +29 -34
  58. package/template/__dot__rulesync/subagents/planner.md.tpl +40 -0
  59. package/template/__dot__rulesync/subagents/quality-reviewer.md.tpl +113 -0
  60. package/template/__dot__rulesync/subagents/security-reviewer.md.tpl +86 -0
  61. package/template/__dot__rulesync/subagents/tester.md.tpl +103 -0
  62. package/template/__dot__rulesync/sync.json.tpl +26 -0
  63. package/template/apps/api/package.json.tpl +2 -2
  64. package/template/apps/api/src/extensions.config.ts.tpl +12 -0
  65. package/template/apps/api/src/main.ts.tpl +1 -4
  66. package/template/apps/api/src/seed.ts.tpl +24 -17
  67. package/template/docker-compose.yml +13 -0
  68. package/template/docs/agents/cross-repo.md.tpl +36 -0
  69. package/template/docs/agents/forge.md.tpl +56 -0
  70. package/template/docs/agents/issue-tracker.md.tpl +42 -0
  71. package/template/docs/standards/comments.md +16 -0
  72. package/template/docs/standards/database.md +77 -0
  73. package/template/docs/standards/enforcement.md +12 -0
  74. package/template/docs/standards/errors.md +30 -0
  75. package/template/docs/standards/frontend.md +60 -0
  76. package/template/docs/standards/functions.md +38 -0
  77. package/template/docs/standards/git-delivery.md +33 -0
  78. package/template/docs/standards/module-structure.md +37 -0
  79. package/template/docs/standards/testing.md +91 -0
  80. package/template/docs/standards/types.md +31 -0
  81. package/template/package.json.tpl +16 -10
  82. package/template/pnpm-workspace.yaml.tpl +6 -0
  83. package/template/rulesync.jsonc +4 -5
  84. package/template/tools/oss-worktree.mjs.tpl +105 -0
  85. package/template/tools/review-precheck.mjs +575 -0
  86. package/template/tools/sync-agents.mjs +273 -0
  87. package/dist/generated/core-version.d.ts +0 -2
  88. package/dist/generated/core-version.d.ts.map +0 -1
  89. package/dist/generated/core-version.js +0 -2
  90. package/dist/generated/core-version.js.map +0 -1
  91. package/template/__dot__rulesync/commands/doctor.md +0 -16
  92. package/template/__dot__rulesync/hooks/post-edit.mjs +0 -57
  93. package/template/__dot__rulesync/rules/oss-boundaries.md +0 -31
  94. package/template/__dot__rulesync/skills/add-feature/SKILL.md +0 -113
  95. package/template/__dot__rulesync/skills/add-feature/handoff.md +0 -58
  96. package/template/__dot__rulesync/skills/create-pr/SKILL.md +0 -55
  97. package/template/__dot__rulesync/skills/create-task/SKILL.md +0 -77
  98. package/template/__dot__rulesync/skills/review/SKILL.md +0 -110
  99. package/template/__dot__rulesync/subagents/builder.md +0 -93
  100. package/template/__dot__rulesync/subagents/debugger.md +0 -82
  101. package/template/__dot__rulesync/subagents/deployer.md +0 -66
  102. package/template/__dot__rulesync/subagents/qa.md +0 -88
  103. package/template/__dot__rulesync/subagents/quality-reviewer.md +0 -67
  104. package/template/__dot__rulesync/subagents/security-reviewer.md +0 -54
@@ -1,44 +1,114 @@
1
1
  #!/usr/bin/env node
2
- // PreToolUse guard (Claude / Copilot CLI / Codex CLI / Gemini CLI).
3
- // Enforces the HARD RULE: never modify OSS core. Blocks shell write-primitives
4
- // and direct file edits that target the linked OSS checkout or node_modules.
5
- // Reads/blocks are allowed; only writes into protected paths are denied.
2
+ // PreToolUse guard (Claude / Codex CLI / Gemini CLI - rulesync renders the same
3
+ // script for every hook target, so the rule below holds identically in each tool).
4
+ // Enforces the HARD RULE: the linked OSS checkout and node_modules are read-only. The one
5
+ // exception is a git worktree under <oss>/.worktrees/ - the sanctioned place to change OSS
6
+ // code from this repo (oss-boundaries rule, `pnpm oss:worktree`). Reads are always allowed.
6
7
 
7
- import { extractCommand, extractFilePath, readPayload, deny } from './_shared.mjs';
8
+ import { readFileSync, realpathSync } from 'node:fs';
9
+ import { basename, dirname, join, resolve, sep } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { extractCommand, extractFilePaths, readPayload, deny } from './_shared.mjs';
8
12
 
9
13
  const payload = readPayload();
10
14
 
11
- // The linked OSS core checkout (baked in at generation time) plus any node_modules.
12
- const ossPath = String.raw`{{ossFromRoot}}`;
13
- const escapedOss = ossPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
14
- const PROTECTED = `(?:${escapedOss}|node_modules\\b)`;
15
+ // Paths resolve from the repo root (this file lives in <root>/.rulesync/hooks/), so an
16
+ // absolute path - what most tools send - is caught as well as the relative form.
17
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
18
+ const OSS_RELATIVE = String.raw`{{ossFromRoot}}`;
19
+ // This repo is often checked out as a git worktree, whose `.git` is a file pointing at
20
+ // <main>/.git/worktrees/<name>. The OSS checkout is a sibling of the MAIN checkout, so without
21
+ // this the guard would resolve it inside the worktree, match nothing, and let core writes pass.
22
+ const mainCheckoutOf = (dir) => {
23
+ try {
24
+ const pointer = readFileSync(join(dir, '.git'), 'utf8');
25
+ const gitdir = pointer.match(/^gitdir:\s*(.*[/\\]worktrees[/\\][^/\\]+?)\s*$/m)?.[1];
26
+ return gitdir ? resolve(dir, gitdir, '..', '..', '..') : dir;
27
+ } catch {
28
+ return dir; // `.git` is a directory (the main checkout) or missing
29
+ }
30
+ };
31
+ const OSS = resolve(mainCheckoutOf(ROOT), OSS_RELATIVE);
32
+
33
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
34
+ const OSS_PATH = `(?:${escape(OSS)}|${escape(OSS_RELATIVE)})`;
35
+ const PROTECTED = `(?:${OSS_PATH}|node_modules\\b)`;
36
+ // A path into a worktree with no `..` hop and no node_modules segment is sanctioned; it is
37
+ // masked out before the write checks run, so the rest of the command is still judged. The mask
38
+ // takes plain path characters only and needs a worktree name: a `>`, `$(`, `{a,b}` or a bare
39
+ // `.worktrees/` (where git resolves to the main repo) is left for the checks to see.
40
+ const WORKTREE_TOKEN = new RegExp(
41
+ String.raw`${OSS_PATH}/\.worktrees/(?![^\s'"|;&]*(?:\.\.|node_modules))[\w+@%=:-][\w.+@%=:/-]*`,
42
+ 'g',
43
+ );
44
+ // cp, install, and rsync write only to their last argument, so copying out of core stays a read.
45
+ const LAST_ARG = String.raw`\s['"]?[^'"\s|;&]*${PROTECTED}[^'"\s|;&]*['"]?(?:\s+\d?>\S*)*\s*(?:[|;&]|$)`;
46
+ const GIT_WRITES = 'apply|am|checkout|restore|reset|clean|stash|merge|rebase|pull|switch|cherry-pick|revert|rm|mv';
47
+
48
+ const HOW_TO_CHANGE_OSS =
49
+ 'To change OSS code, run `pnpm oss:worktree <branch>` and edit inside ' +
50
+ `${OSS_RELATIVE}/.worktrees/ (rule: oss-boundaries). Otherwise extend from the OUTSIDE ` +
51
+ '(overlay plugin, adapter rebinding, UI plugin, config).';
52
+
53
+ // The path on disk, symlinks followed, so a link in this repo that points into the checkout
54
+ // does not pass as a local path. A file not yet created resolves through its nearest existing
55
+ // ancestor.
56
+ const physical = (path) => {
57
+ try {
58
+ return realpathSync(path);
59
+ } catch {
60
+ const parent = dirname(path);
61
+ return parent === path ? path : join(physical(parent), basename(path));
62
+ }
63
+ };
15
64
 
16
- // 1) Shell command writing into a protected path (sed -i, redirect, tee, rm, ...).
17
- const command = extractCommand(payload);
65
+ // The checkout itself may sit behind a symlink (a linked home or projects folder).
66
+ const oss = physical(OSS);
67
+
68
+ // 1) Shell command writing into a protected path (sed -i, redirect, tee, cp, rm, git, ...).
69
+ const rawCommand = extractCommand(payload);
70
+ // A symlink planted in a worktree would carry later shell writes into the main checkout, and no
71
+ // worktree needs one, so `ln` is judged before the worktree mask, against the whole command and
72
+ // the cwd: `cd <oss>/.worktrees/x && ln -s ../../packages p` names no protected path itself.
73
+ const insideOss = (dir) => {
74
+ try {
75
+ const real = realpathSync(dir);
76
+ return real === oss || real.startsWith(oss + sep);
77
+ } catch {
78
+ return false;
79
+ }
80
+ };
81
+ if (
82
+ /(?<![\w-])ln\s/.test(rawCommand) &&
83
+ (new RegExp(PROTECTED).test(rawCommand) || (payload.cwd && insideOss(payload.cwd)))
84
+ ) {
85
+ deny(`Blocked: this symlink points into or lives in the OSS checkout or node_modules. ${HOW_TO_CHANGE_OSS}`);
86
+ }
87
+ const command = rawCommand.replace(WORKTREE_TOKEN, '<oss-worktree>');
18
88
  if (command) {
19
89
  const writeToCore = [
20
- [new RegExp(String.raw`\b(?:sed|perl)\b[^|;&]*\s-\w*i\w*\b[^|;&]*(?:${PROTECTED})`), 'in-place edit (sed/perl -i)'],
21
- [new RegExp(String.raw`(?:>>?|>\|)\s*['"]?[^'"\s|;&]*(?:${PROTECTED})`), 'shell redirection'],
22
- [new RegExp(String.raw`\btee\b\s+(?:-a\s+)?['"]?[^'"\s|;&]*(?:${PROTECTED})`), 'tee'],
23
- [new RegExp(String.raw`\b(?:rm|truncate|dd|chmod|chown|unlink|shred|mv)\b[^|;&]*(?:${PROTECTED})`), 'destructive file op'],
90
+ [new RegExp(String.raw`\b(?:sed|perl)\b[^|;&]*\s-\w*i\w*\b[^|;&]*${PROTECTED}`), 'in-place edit (sed/perl -i)'],
91
+ [new RegExp(String.raw`(?:>>?|>\|)\s*['"]?[^'"\s|;&]*${PROTECTED}`), 'shell redirection'],
92
+ [new RegExp(String.raw`\btee\b\s+(?:-a\s+)?['"]?[^'"\s|;&]*${PROTECTED}`), 'tee'],
93
+ [new RegExp(String.raw`(?<![\w-])(?:cp|install|rsync)\b[^|;&]*${LAST_ARG}`), 'copy'],
94
+ [new RegExp(String.raw`(?<![\w-])(?:rm|truncate|dd|chmod|chown|unlink|shred|mv|ln|patch)\b[^|;&]*${PROTECTED}`), 'destructive file op'],
95
+ [new RegExp(String.raw`\bgit\b[^|;&]*${PROTECTED}[^|;&]*\s(?:${GIT_WRITES})\b`), 'git command'],
24
96
  ];
25
- const hit = writeToCore.find(([re]) => re.test(command));
97
+ const hit = writeToCore.find(([pattern]) => pattern.test(command));
26
98
  if (hit) {
27
- deny(
28
- `Blocked: this ${hit[1]} writes into OSS core / node_modules, which is read-only here. ` +
29
- 'Extend the platform from the OUTSIDE (overlay plugin, adapter rebinding, UI plugin, config). ' +
30
- 'If it can only be fixed in core, STOP and report it as an upstream OSS issue.',
31
- );
99
+ deny(`Blocked: this ${hit[1]} writes into the OSS checkout or node_modules, which are read-only here. ${HOW_TO_CHANGE_OSS}`);
32
100
  }
33
101
  }
34
102
 
35
- // 2) Direct file edit/write whose target is inside a protected path.
36
- const filePath = extractFilePath(payload);
37
- if (filePath && new RegExp(PROTECTED).test(filePath)) {
38
- deny(
39
- `Blocked: ${filePath} is inside OSS core / node_modules, which is read-only here. ` +
40
- 'Extend from the OUTSIDE (overlay, adapter, UI plugin, config), or report an upstream OSS issue.',
41
- );
103
+ // 2) Direct file edit/write whose target resolves inside a protected path.
104
+ for (const filePath of extractFilePaths(payload)) {
105
+ const written = resolve(payload.cwd ?? process.cwd(), filePath);
106
+ const target = physical(written);
107
+ const isInside = (dir) => target.startsWith(dir + sep);
108
+ const inNodeModules = [written, target].some((path) => /(?:^|[\\/])node_modules(?:[\\/]|$)/.test(path));
109
+ if (inNodeModules || (isInside(oss) && !isInside(join(oss, '.worktrees')))) {
110
+ deny(`Blocked: ${filePath} is inside the OSS checkout or node_modules, which are read-only here. ${HOW_TO_CHANGE_OSS}`);
111
+ }
42
112
  }
43
113
 
44
114
  process.exit(0);
@@ -1,34 +1,33 @@
1
1
  #!/usr/bin/env node
2
- // PreToolUse guard (Claude / Copilot CLI / Codex CLI).
2
+ // PreToolUse guard (Claude / Codex CLI / Gemini CLI).
3
3
  // Blocks edits to files generated by rulesync (`pnpm gen:agents`). The single
4
4
  // source of truth is .rulesync/; editing a generated mirror is lost on the next
5
5
  // sync. Fail-open: only a positive match denies.
6
6
 
7
- import { extractFilePath, readPayload, deny } from './_shared.mjs';
7
+ import { extractFilePaths, readPayload, deny } from './_shared.mjs';
8
8
  import { relative, isAbsolute } from 'node:path';
9
9
 
10
- const payload = readPayload();
11
- const filePath = extractFilePath(payload);
12
- if (!filePath) process.exit(0);
13
-
14
- const rel = isAbsolute(filePath) ? relative(process.cwd(), filePath) : filePath;
15
-
10
+ // Everything rulesync generates from .rulesync/.
16
11
  const generated = [
17
12
  /^AGENTS\.md$/,
18
13
  /^CLAUDE\.md$/,
19
- /^\.github\/copilot-instructions\.md$/,
14
+ /^GEMINI\.md$/,
20
15
  /^\.mcp\.json$/,
21
- /^\.vscode\/mcp\.json$/,
22
16
  /^\.codex\/config\.toml$/,
17
+ /^\.gemini\/settings\.json$/,
23
18
  /^\.claude\/(agents|commands)\//,
24
- /^\.github\/(agents|prompts)\//,
19
+ /^\.gemini\/(agents|commands)\//,
25
20
  ];
26
21
 
27
- if (generated.some((re) => re.test(rel))) {
28
- deny(
29
- `Blocked: ${rel} is generated by rulesync (\`pnpm gen:agents\`). ` +
30
- 'Edit the source under .rulesync/ instead (rules/, subagents/, commands/, mcp.json), then run `pnpm gen:agents`.',
31
- );
22
+ for (const filePath of extractFilePaths(readPayload())) {
23
+ // Repo-relative (hooks run with cwd = repo root) - name-agnostic.
24
+ const rel = isAbsolute(filePath) ? relative(process.cwd(), filePath) : filePath;
25
+ if (generated.some((re) => re.test(rel))) {
26
+ deny(
27
+ `Blocked: ${rel} is generated by rulesync (\`pnpm gen:agents\`). ` +
28
+ 'Edit the source under .rulesync/ instead (rules/, subagents/, commands/, mcp.json), then run `pnpm gen:agents`.',
29
+ );
30
+ }
32
31
  }
33
32
 
34
33
  process.exit(0);
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse guard: no merge/pull request until `pnpm verify` passed on the commit being sent.
3
+ // A full `pnpm verify` run (no extra arguments) ends with `node .rulesync/hooks/guard-mr.mjs
4
+ // --stamp`, which records HEAD in node_modules/.cache/verify-head when the tree is clean; a
5
+ // `--stamp` outside the verify script is refused. Opening an MR/PR (CLI, push option, REST or
6
+ // GraphQL) is denied unless that record matches the commit it sends: the named source branch
7
+ // (`--source-branch`, `--head`), else HEAD of a clean tree. A promotion from a shared branch was
8
+ // verified by that branch's pipeline and passes. Every create in a chain is checked, and one that
9
+ // names two different source branches is denied. Git errors fail open, like every other guard.
10
+
11
+ import { execFileSync } from 'node:child_process';
12
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { deny, extractCommand, readPayload } from './_shared.mjs';
15
+
16
+ const SHARED = /^(?:origin\/)?(?:main|master|dev|develop|stage|staging|prod|production)$/;
17
+ // `-R <repo>` goes before or after `pr`/`mr`; `new` is an alias of `create`.
18
+ const REPO = String.raw`(?:\s+(?:-R\s*|--repo(?:=|\s+))\S+)?`;
19
+ const CLI_CREATE = new RegExp(
20
+ String.raw`\b(?:(gh)${REPO}\s+(?:pr${REPO}\s+(?:create|new)|stack\s+(?:submit|push))|(glab)${REPO}\s+mr${REPO}\s+(?:create|new))\b([^;&|\n]*)`,
21
+ 'g',
22
+ );
23
+ const PUSH_OPTION_CREATE = /merge_request\.create/;
24
+ // GraphQL mutations live in a quoted query, so they are matched on the raw command of an API call.
25
+ const GRAPHQL_CREATE = /\b(?:createPullRequest|mergeRequestCreate)\b/;
26
+ const API_CALL = /\b(?:gh|glab)\s+api\b/;
27
+ const REVIEW_COLLECTION = /\/(?:pulls|merge_requests)(?=["'\s?]|$)/;
28
+ // `gh api` and `glab api` default to POST once a field or body is passed.
29
+ const WRITES = /\s(?:(?:-X\s*|--method[=\s]+)POST\b|(?:-f|-F|--field|--raw-field|--input)\b)/i;
30
+ const READS = /\s(?:-X\s*|--method[=\s]+)GET\b/i;
31
+ // The source branch flag, glued (`-Hfeat/x`, `-dH x`) or not. glab's `-H` names the head repository.
32
+ const SOURCE_FLAG = {
33
+ gh: /\s(?:--head(?:=|\s+)|-[defw]*H(?:=|\s*))['"]?([^\s'"]+)/g,
34
+ glab: /\s(?:--source-branch(?:=|\s+)|-[fwy]*s(?:=|\s*))['"]?([^\s'"]+)/g,
35
+ };
36
+
37
+ // Quoted prose (a title, a search pattern) or a quoted separator is blanked so a command named
38
+ // inside it never counts and never cuts a flag list short; a quoted single word (a branch) is kept.
39
+ const blankProse = (command) =>
40
+ command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (quoted) =>
41
+ /[\s;&|(){}]/.test(quoted) ? '""' : quoted,
42
+ );
43
+
44
+ // A push option or an API call opens the MR/PR from HEAD.
45
+ const opensFromHead = (raw, command) =>
46
+ PUSH_OPTION_CREATE.test(command) ||
47
+ (API_CALL.test(command) &&
48
+ (GRAPHQL_CREATE.test(raw) ||
49
+ (REVIEW_COLLECTION.test(raw) && WRITES.test(command) && !READS.test(command))));
50
+
51
+ const git = (cwd, ...args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
52
+ const stampFile = (root) => join(root, 'node_modules', '.cache', 'verify-head');
53
+
54
+ const checkout = (cwd) => {
55
+ try {
56
+ const root = git(cwd, 'rev-parse', '--show-toplevel');
57
+ return {
58
+ root,
59
+ head: git(root, 'rev-parse', 'HEAD'),
60
+ isClean: git(root, 'status', '--porcelain') === '',
61
+ };
62
+ } catch {
63
+ return undefined;
64
+ }
65
+ };
66
+
67
+ const branchCommit = (root, branch) => {
68
+ for (const ref of [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]) {
69
+ try {
70
+ return git(root, 'rev-parse', '--verify', '-q', `${ref}^{commit}`);
71
+ } catch {
72
+ // try the next ref
73
+ }
74
+ }
75
+ return '';
76
+ };
77
+
78
+ if (process.argv.includes('--stamp')) {
79
+ if (process.env.npm_lifecycle_event !== 'verify') {
80
+ process.stderr.write('--stamp is recorded by `pnpm verify` only: run `pnpm verify`.\n');
81
+ process.exit(1);
82
+ }
83
+ const state = checkout(process.cwd());
84
+ if (state?.isClean) {
85
+ mkdirSync(dirname(stampFile(state.root)), { recursive: true });
86
+ writeFileSync(stampFile(state.root), state.head);
87
+ } else {
88
+ process.stderr.write(
89
+ 'verify passed on uncommitted changes: commit, then rerun `pnpm verify` before opening an MR/PR.\n',
90
+ );
91
+ }
92
+ process.exit(0);
93
+ }
94
+
95
+ const payload = readPayload();
96
+ const raw = extractCommand(payload);
97
+ const command = blankProse(raw);
98
+ // The source branch of each create in the chain, `undefined` for HEAD; `gh pr create --head
99
+ // owner:branch` names the fork too. A create naming two different ones is ambiguous.
100
+ const sources = [...command.matchAll(CLI_CREATE)].map((create) => {
101
+ const named = [
102
+ ...new Set(
103
+ [...create[3].matchAll(SOURCE_FLAG[create[1] ?? create[2]])].map((flag) =>
104
+ flag[1].replace(/^[^:]+:/, ''),
105
+ ),
106
+ ),
107
+ ];
108
+ if (named.length > 1) {
109
+ deny(
110
+ `Blocked: this command names more than one source branch (${named.join(', ')}); name one.`,
111
+ );
112
+ }
113
+ return named[0];
114
+ });
115
+ if (opensFromHead(raw, command)) {
116
+ sources.push(undefined);
117
+ }
118
+ const pending = sources.filter((source) => !source || !SHARED.test(source));
119
+ if (pending.length === 0) {
120
+ process.exit(0);
121
+ }
122
+ const state = checkout(payload.cwd ?? process.cwd());
123
+ if (!state) {
124
+ process.exit(0);
125
+ }
126
+ const readStamp = () => {
127
+ try {
128
+ return readFileSync(stampFile(state.root), 'utf8').trim();
129
+ } catch {
130
+ return '';
131
+ }
132
+ };
133
+ const stamp = readStamp();
134
+ for (const source of pending) {
135
+ const sent = source ? branchCommit(state.root, source) : state.head;
136
+ // Only the checked-out commit can carry uncommitted edits.
137
+ if (!sent || (sent === state.head && !state.isClean) || stamp !== sent) {
138
+ deny(
139
+ 'Blocked: run `pnpm verify` (no extra arguments) on a clean checkout of the commit this merge/pull request sends. It records the verified commit; this check compares it with that commit.',
140
+ );
141
+ }
142
+ }
143
+ process.exit(0);
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse guard: no push and no new merge/pull request until the `review` skill approved HEAD.
3
+ // `review` (and `ship`, which runs it) saves `.claude/reviews/<pr or branch>.json` in the main
4
+ // checkout with the reviewed `sha` and the `verdict`. A push, `gh stack submit|push`, or a new
5
+ // MR/PR is denied unless one of those files records the current HEAD as APPROVED (or GO). A
6
+ // PR/MR that names two different source branches is denied.
7
+ // Each command in a chain is judged on its own: a branch delete or a tag-only push passes, and
8
+ // so does a PR/MR opened from a shared branch (a promotion, which no branch review covers). A
9
+ // push to a shared branch and a hand merge (`gh pr|stack merge`, `glab mr merge`) are denied
10
+ // outright: the merge bot merges. Git errors fail open, like every other guard.
11
+ //
12
+ // ponytail: trusts the state file, which an agent could write by hand, and checks the checked-out
13
+ // HEAD (or a PR/MR's named source branch), not a different ref named in a push refspec. It stops
14
+ // a forgotten review, not a hostile one; the forge's own AI review is the gate an agent cannot write.
15
+
16
+ import { execFileSync } from 'node:child_process';
17
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
18
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
19
+ import { deny, extractCommand, readPayload } from './_shared.mjs';
20
+
21
+ const SHARED = /^(?:origin\/)?(?:main|master|dev|develop|stage|staging|prod|production)$/;
22
+ const PREFIX = String.raw`^(?:(?:env\s+)?\w+=\S*\s+)*(?:(?:command|env|time|nohup)\s+)?(?:\S*/)?`;
23
+ const GIT_PUSH = new RegExp(`${PREFIX}git((?:\\s+(?:-[cC]\\s+\\S+|--\\S+))*)\\s+push\\b(.*)$`);
24
+ // `-R <repo>` goes before or after `pr`/`mr`; `new` is an alias of `create`.
25
+ const REPO = String.raw`(?:\s+(?:-R\s*|--repo(?:=|\s+))\S+)?`;
26
+ const OPENS_REVIEW = new RegExp(
27
+ `${PREFIX}(?:(gh)${REPO}\\s+(?:pr${REPO}\\s+(?:create|new)|stack\\s+(?:submit|push))|(glab)${REPO}\\s+mr${REPO}\\s+(?:create|new))\\b(.*)$`,
28
+ );
29
+ // A forge CLI (`gh`/`glab`, bare, by path or behind `command`) and its words after that prefix.
30
+ const FORGE_CLI = new RegExp(`${PREFIX}(gh|glab)\\s+(.*)$`);
31
+ const MERGE_API = /\/merge(?=$|[?\s"'])/;
32
+ const API_WRITES =
33
+ /\s(?:(?:-X\s*|--method[=\s]+)(?:PUT|POST)\b|(?:-f|-F|--field|--raw-field|--input)\b)/i;
34
+ // GraphQL merges live in a quoted query, which `segments` blanks, so the raw command is checked.
35
+ const GRAPHQL_MERGE =
36
+ /\b(?:mergePullRequest|mergeRequestAccept|enqueuePullRequest|enablePullRequestAutoMerge)\b/;
37
+ const isHandMerge = (segment) => {
38
+ const cli = FORGE_CLI.exec(segment);
39
+ if (!cli) {
40
+ return false;
41
+ }
42
+ const words = cli[2].split(/\s+/);
43
+ const command = words.findIndex((word) => /^(?:pr|stack|mr)$/.test(word));
44
+ // The subcommand is the first word after `pr|stack|mr` that is no flag and no `-R` value.
45
+ const subcommand = words
46
+ .slice(command + 1)
47
+ .find((word, i, rest) => !word.startsWith('-') && !/^(?:-R|--repo)$/.test(rest[i - 1]));
48
+ return (
49
+ (command >= 0 && /^(?:merge|accept)$/.test(subcommand ?? '')) ||
50
+ (words.includes('api') && MERGE_API.test(cli[2]) && API_WRITES.test(` ${cli[2]}`))
51
+ );
52
+ };
53
+ // The source branch flag, glued (`-Hfeat/x`, `-dH x`) or not. glab's `-H` names the head repository.
54
+ const SOURCE_FLAG = {
55
+ gh: /\s(?:--head(?:=|\s+)|-[defw]*H(?:=|\s*))(\S+)/g,
56
+ glab: /\s(?:--source-branch(?:=|\s+)|-[fwy]*s(?:=|\s*))(\S+)/g,
57
+ };
58
+ // A command that can move HEAD. The hook runs before the whole command, so a push chained after
59
+ // one would be judged on the commit it starts from, not the one it sends. A stash listing and a
60
+ // new feature branch at HEAD move nothing; a new or renamed shared branch counts, since a push
61
+ // after it would be judged against the branch checked out before it.
62
+ const MOVES_HEAD = new RegExp(
63
+ `${PREFIX}(?:git(?:\\s+(?:-[cC]\\s+\\S+|--\\S+))*\\s+(?:commit|merge|rebase|reset|checkout|switch|cherry-pick|revert|pull|am|stash|update-ref|symbolic-ref\\s+(?:-m\\s+\\S+\\s+)?HEAD\\s+\\S+|bisect\\s+(?:start|good|bad|new|old|skip|reset|run|replay)|branch\\s+(?:-[mM]|--move))|gh${REPO}\\s+pr${REPO}\\s+checkout|glab${REPO}\\s+mr${REPO}\\s+checkout)\\b`,
64
+ );
65
+ const NEW_BRANCH = /\s(?:checkout\s+-[bB]|switch\s+-[cC])\s+(\S+)\s*$/;
66
+ const movesNothing = (segment) => {
67
+ const created = NEW_BRANCH.exec(segment);
68
+ return created
69
+ ? !SHARED.test(created[1].replace(/['"\\]/g, ''))
70
+ : /\sstash\s+(?:list|show)\b/.test(segment);
71
+ };
72
+ const DIR_FLAG = /\s-C\s+(\S+)/;
73
+
74
+ const git = (cwd, ...args) => {
75
+ try {
76
+ return execFileSync('git', ['-C', cwd, ...args], {
77
+ encoding: 'utf8',
78
+ stdio: ['ignore', 'pipe', 'ignore'],
79
+ }).trim();
80
+ } catch {
81
+ return '';
82
+ }
83
+ };
84
+
85
+ const unquote = (path) =>
86
+ path.replace(/^['"]|['"]$/g, '').replace(/^~(?=\/)/, process.env.HOME ?? '~');
87
+ const within = (cwd, path) => {
88
+ const dir = unquote(path);
89
+ return isAbsolute(dir) ? dir : resolve(cwd, dir);
90
+ };
91
+
92
+ // Quoted prose (commit messages, PR bodies) is blanked so a flag or command inside it never
93
+ // counts; a quoted single word (a path, a branch) is kept.
94
+ const segments = (command) =>
95
+ command
96
+ .replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (quoted) => (/[\s;&|(){}]/.test(quoted) ? '""' : quoted))
97
+ .split(/&&|\|\||(?<![>&])&(?![>&])|[;|\n(){}]/)
98
+ .map((part) => part.replace(/(?:^|\s)#.*$/, '').trim())
99
+ .filter(Boolean);
100
+
101
+ // The flags and refspecs of a push. A flag's separate value (`-o ci.skip`) is no remote, and with
102
+ // `--repo <remote>` every positional word is a refspec.
103
+ const VALUED = /^(?:-o|--push-option|--repo|--receive-pack|--exec)$/;
104
+ const pushWords = (pushArgs) => {
105
+ const args = pushArgs.trim().split(/\s+/).filter(Boolean);
106
+ const positional = args.filter((arg, i) => !arg.startsWith('-') && !VALUED.test(args[i - 1]));
107
+ const hasRepo = args.some((arg) => /^--repo(?:=|$)/.test(arg));
108
+ return { args, refs: hasRepo ? positional : positional.slice(1) };
109
+ };
110
+
111
+ const sendsNothingNew = (pushArgs) => {
112
+ const { args, refs } = pushWords(pushArgs);
113
+ return (
114
+ args.some((arg) => arg === '--delete' || arg === '-d') ||
115
+ (refs.length > 0 && refs.every((ref) => ref.startsWith(':'))) ||
116
+ (args.includes('--tags') && refs.length === 0)
117
+ );
118
+ };
119
+
120
+ // The directory to check and whether the segment opens a PR/MR, or null when it sends nothing
121
+ // that needs a review. A PR/MR opened from a shared branch is a promotion and needs none; a push
122
+ // from one does.
123
+ const reviewTarget = (segment, cwd) => {
124
+ if (/^cd\s/.test(segment)) {
125
+ return null;
126
+ }
127
+ const push = GIT_PUSH.exec(segment);
128
+ if (push) {
129
+ const dir = DIR_FLAG.exec(push[1]);
130
+ return {
131
+ dir: dir ? within(cwd, dir[1]) : cwd,
132
+ opensReview: false,
133
+ pushArgs: push[2],
134
+ sendsNothingNew: sendsNothingNew(push[2]),
135
+ };
136
+ }
137
+ const opens = OPENS_REVIEW.exec(segment);
138
+ if (!opens) {
139
+ return null;
140
+ }
141
+ // Every source branch it names; `gh pr create --head owner:branch` names the fork too.
142
+ const sources = [
143
+ ...new Set(
144
+ [...opens[3].matchAll(SOURCE_FLAG[opens[1] ?? opens[2]])].map((flag) =>
145
+ unquote(flag[1]).replace(/^[^:]+:/, ''),
146
+ ),
147
+ ),
148
+ ];
149
+ if (sources.length > 1) {
150
+ deny(
151
+ `Blocked: this command names more than one source branch (${sources.join(', ')}); name one.`,
152
+ );
153
+ }
154
+ const [source] = sources;
155
+ if (source && SHARED.test(source)) {
156
+ return null;
157
+ }
158
+ return { dir: cwd, opensReview: true, source };
159
+ };
160
+
161
+ // The commit a PR/MR sends: its named source branch (local, else the fetched remote one), or HEAD.
162
+ const sentCommit = (dir, source) =>
163
+ source
164
+ ? git(dir, 'rev-parse', '--verify', '-q', `refs/heads/${source}^{commit}`) ||
165
+ git(dir, 'rev-parse', '--verify', '-q', `refs/remotes/origin/${source}^{commit}`)
166
+ : git(dir, 'rev-parse', 'HEAD');
167
+
168
+ const isApproved = (dirs, head) =>
169
+ dirs.some((dir) => {
170
+ try {
171
+ const reviews = join(dir, '.claude', 'reviews');
172
+ if (!existsSync(reviews)) {
173
+ return false;
174
+ }
175
+ return readdirSync(reviews)
176
+ .filter((name) => name.endsWith('.json'))
177
+ .some((name) => {
178
+ try {
179
+ const state = JSON.parse(readFileSync(join(reviews, name), 'utf8'));
180
+ // The full SHA: an abbreviation could match an older reviewed commit.
181
+ return (
182
+ String(state.sha ?? '').toLowerCase() === head &&
183
+ /^(?:APPROVED|GO\b)/i.test(String(state.verdict ?? ''))
184
+ );
185
+ } catch {
186
+ return false;
187
+ }
188
+ });
189
+ } catch {
190
+ return false;
191
+ }
192
+ });
193
+
194
+ // The branches a push writes or deletes: each refspec's destination (`HEAD`/`@` is the checked-out
195
+ // branch, a glob may be any branch), or with no refspec where git sends this branch (`@{push}`,
196
+ // which follows push.default and remote.<name>.push). `--all` and `--mirror` write every branch.
197
+ const pushesShared = (dir, pushArgs, branch) => {
198
+ if (/\s--(?:all|mirror)\b/.test(pushArgs)) {
199
+ return true;
200
+ }
201
+ const { args, refs: specs } = pushWords(pushArgs);
202
+ // The shell drops every quote and backslash, and git reads `heads/dev` as `refs/heads/dev`.
203
+ const refs = specs.map((spec) => spec.replace(/['"\\]/g, ''));
204
+ if (refs.length === 0) {
205
+ if (args.includes('--tags')) {
206
+ return false;
207
+ }
208
+ const destination = git(dir, 'rev-parse', '--abbrev-ref', '@{push}').replace(/^[^/]+\//, '');
209
+ return SHARED.test(destination || branch);
210
+ }
211
+ return refs.some((spec) => {
212
+ const destination = spec.replace(/^\+/, '').split(':').pop();
213
+ return (
214
+ destination.includes('*') ||
215
+ SHARED.test(
216
+ (/^(?:HEAD|@)$/.test(destination) ? branch : destination).replace(
217
+ /^(?:refs\/)?(?:heads\/)?/,
218
+ '',
219
+ ),
220
+ )
221
+ );
222
+ });
223
+ };
224
+
225
+ const check = ({ dir, opensReview, pushArgs, sendsNothingNew, source }) => {
226
+ const branch = git(dir, 'rev-parse', '--abbrev-ref', 'HEAD');
227
+ if (pushArgs !== undefined && branch && pushesShared(dir, pushArgs, branch)) {
228
+ deny(
229
+ 'Blocked: nobody pushes to or deletes a shared branch by hand. Push a topic branch and open a merge/pull request; the merge bot merges it. A person can still push from their own terminal.',
230
+ );
231
+ }
232
+ if (sendsNothingNew) {
233
+ return;
234
+ }
235
+ const top = git(dir, 'rev-parse', '--show-toplevel');
236
+ const common = git(dir, 'rev-parse', '--git-common-dir');
237
+ const head = sentCommit(dir, source);
238
+ if (!top || !common || (opensReview && !source && SHARED.test(branch))) {
239
+ return;
240
+ }
241
+ if (!head) {
242
+ if (source) {
243
+ deny(`Blocked: \`${source}\` is not a local or fetched branch here; fetch it, then retry.`);
244
+ }
245
+ return;
246
+ }
247
+ const mainCheckout = dirname(isAbsolute(common) ? common : resolve(dir, common));
248
+ if (!isApproved([...new Set([top, mainCheckout])], head)) {
249
+ deny(
250
+ `Blocked: no APPROVED review of HEAD ${head.slice(0, 9)}. Run \`ship\` for a ticket, or the \`review\` skill on this branch until it says APPROVED, then push. A person can still push from their own terminal.`,
251
+ );
252
+ }
253
+ };
254
+
255
+ const payload = readPayload();
256
+ const rawCommand = extractCommand(payload);
257
+ let cwd = payload.cwd ?? process.cwd();
258
+ let headMoved = false;
259
+ for (const segment of segments(rawCommand)) {
260
+ const cd = /^cd\s+(\S+)$/.exec(segment);
261
+ if (cd) {
262
+ cwd = within(cwd, cd[1]);
263
+ }
264
+ if (isHandMerge(segment) || (/\b(?:gh|glab)\s/.test(segment) && GRAPHQL_MERGE.test(rawCommand))) {
265
+ deny(
266
+ 'Blocked: the merge bot merges, never an agent. Leave the merge/pull request to it; a person who has to merge by hand runs it from their own terminal (`! <command>` in Claude Code).',
267
+ );
268
+ }
269
+ const target = reviewTarget(segment, cwd);
270
+ if (target && headMoved && !target.sendsNothingNew) {
271
+ deny(
272
+ 'Blocked: an earlier command in this chain can move HEAD, and this check runs before any of it. Commit first, get the `review` skill to approve that commit, then push or open the merge/pull request as its own command.',
273
+ );
274
+ }
275
+ if (target) {
276
+ check(target);
277
+ }
278
+ headMoved ||= MOVES_HEAD.test(segment) && !movesNothing(segment);
279
+ }
280
+ process.exit(0);
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse guard: a GitHub pull request that builds on another feature branch goes up as a
3
+ // native stacked PR (`gh stack`, the github/gh-stack extension), not as a plain PR whose base is
4
+ // that branch. `gh pr create|new|edit --base <b>` is denied when <b> is not a
5
+ // shared branch. Without `--base` the PR targets the default branch and passes.
6
+ //
7
+ // ponytail: shared branches are a fixed list; a repo with another trunk name adds it here.
8
+
9
+ import { deny, extractCommand, readPayload } from './_shared.mjs';
10
+
11
+ const SHARED = /^(?:origin\/)?(?:main|master|dev|develop|stage|staging|prod|production)$/;
12
+ // Every `--base`/`-B` is judged, glued (`-Bfeat/x`) or not: a repeated flag must not hide a
13
+ // feature base behind a shared one. `-R <repo>` goes before or after `pr`; `new` aliases `create`.
14
+ const REPO = String.raw`(?:\s+(?:-R\s*|--repo(?:=|\s+))\S+)?`;
15
+ const PR_COMMAND = new RegExp(
16
+ String.raw`(?:^|[;&|\n(])\s*(?:(?:env\s+)?\w+=\S*\s+)*(?:(?:command|env|time|nohup)\s+)?(?:\S*\/)?gh${REPO}\s+pr${REPO}\s+(?:create|new|edit)\b([^;&|\n]*)`,
17
+ 'g',
18
+ );
19
+ const BASE_FLAG = /\s(?:--base(?:=|\s+)|-[defw]*B(?:=|\s*))['"]?([^\s'"]+)/g;
20
+
21
+ // Quoted prose (a title or body) or a quoted separator is blanked so a `--base` inside it never
22
+ // counts and never cuts a flag list short.
23
+ const command = extractCommand(readPayload()).replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (quoted) =>
24
+ /[\s;&|(){}]/.test(quoted) ? '""' : quoted,
25
+ );
26
+ // Every PR command in a chain is judged, not only the first.
27
+ const base = [...command.matchAll(PR_COMMAND)]
28
+ .flatMap((pr) => [...pr[1].matchAll(BASE_FLAG)].map((flag) => flag[1]))
29
+ .find((name) => !SHARED.test(name));
30
+ if (base) {
31
+ deny(
32
+ `Blocked: a PR based on \`${base}\` is a stack. Use \`gh stack\` (gh extension install github/gh-stack): \`gh stack init\` or \`gh stack init <branches...>\`, \`gh stack add <branch>\`, then \`gh stack submit --auto\` (layers open as drafts). Review each layer on its own; the merge bot merges.`,
33
+ );
34
+ }
35
+ process.exit(0);