@openora/create 0.4.1-canary.43 → 0.4.1-canary.430

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 (112) hide show
  1. package/README.md +4 -4
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/generated/versions.d.ts +11 -0
  4. package/dist/generated/versions.d.ts.map +1 -0
  5. package/dist/generated/versions.js +11 -0
  6. package/dist/generated/versions.js.map +1 -0
  7. package/dist/index.js +50 -96
  8. package/dist/index.js.map +1 -1
  9. package/dist/render.d.ts +15 -0
  10. package/dist/render.d.ts.map +1 -0
  11. package/dist/render.js +125 -0
  12. package/dist/render.js.map +1 -0
  13. package/package.json +8 -6
  14. package/template/Dockerfile +11 -0
  15. package/template/README.md.tpl +44 -10
  16. package/template/__dot__claude/settings.json.tpl +39 -12
  17. package/template/__dot__dockerignore +8 -0
  18. package/template/__dot__env.example +42 -2
  19. package/template/__dot__gitignore +5 -5
  20. package/template/__dot__rulesync/commands/check.md +11 -10
  21. package/template/__dot__rulesync/commands/doctor.md.tpl +17 -0
  22. package/template/__dot__rulesync/commands/scaffold-module.md +3 -2
  23. package/template/__dot__rulesync/commands/scaffold-plugin.md +23 -4
  24. package/template/__dot__rulesync/commands/scaffold-route.md +1 -0
  25. package/template/__dot__rulesync/commands/start.md +3 -3
  26. package/template/__dot__rulesync/hooks/_shared.mjs +25 -34
  27. package/template/__dot__rulesync/hooks/guard-comments.mjs +82 -0
  28. package/template/__dot__rulesync/hooks/guard-core.mjs.tpl +98 -28
  29. package/template/__dot__rulesync/hooks/guard-generated.mjs +15 -16
  30. package/template/__dot__rulesync/hooks/guard-mr.mjs +199 -0
  31. package/template/__dot__rulesync/hooks/guard-review.mjs +280 -0
  32. package/template/__dot__rulesync/hooks/guard-stack.mjs +35 -0
  33. package/template/__dot__rulesync/hooks/guard-subagent.mjs +22 -6
  34. package/template/__dot__rulesync/hooks/post-edit.mjs.tpl +116 -0
  35. package/template/__dot__rulesync/hooks.json +42 -4
  36. package/template/__dot__rulesync/rules/conventions.md +99 -119
  37. package/template/__dot__rulesync/rules/db-conventions.md +6 -72
  38. package/template/__dot__rulesync/rules/e2e-conventions.md +33 -7
  39. package/template/__dot__rulesync/rules/frontend-conventions.md.tpl +35 -0
  40. package/template/__dot__rulesync/rules/oss-boundaries.md.tpl +78 -0
  41. package/template/__dot__rulesync/rules/overview.md +20 -82
  42. package/template/__dot__rulesync/skills/agent-retro/SKILL.md.tpl +81 -0
  43. package/template/__dot__rulesync/skills/agent-retro/scan.mjs +420 -0
  44. package/template/__dot__rulesync/skills/babysit/SKILL.md.tpl +48 -0
  45. package/template/__dot__rulesync/skills/babysit/babysit.mjs +290 -0
  46. package/template/__dot__rulesync/skills/create-plugin/{SKILL.md → SKILL.md.tpl} +12 -23
  47. package/template/__dot__rulesync/skills/create-pr/SKILL.md.tpl +50 -0
  48. package/template/__dot__rulesync/skills/create-task/SKILL.md.tpl +96 -0
  49. package/template/__dot__rulesync/skills/create-ui-module/{SKILL.md → SKILL.md.tpl} +12 -10
  50. package/template/__dot__rulesync/skills/enhance-prompt/{SKILL.md → SKILL.md.tpl} +4 -4
  51. package/template/__dot__rulesync/skills/handoff/SKILL.md +4 -3
  52. package/template/__dot__rulesync/skills/review/SKILL.md.tpl +274 -0
  53. package/template/__dot__rulesync/skills/ship/SKILL.md.tpl +157 -0
  54. package/template/__dot__rulesync/skills/ship/handoff.md.tpl +48 -0
  55. package/template/__dot__rulesync/skills/ui-verify/SKILL.md.tpl +129 -0
  56. package/template/__dot__rulesync/skills/ui-verify/join-video.mjs +148 -0
  57. package/template/__dot__rulesync/skills/ui-verify/layout-check.check.sh +58 -0
  58. package/template/__dot__rulesync/skills/ui-verify/layout-check.js +163 -0
  59. package/template/__dot__rulesync/subagents/builder.md.tpl +116 -0
  60. package/template/__dot__rulesync/subagents/compliance-reviewer.md +79 -0
  61. package/template/__dot__rulesync/subagents/debugger.md.tpl +89 -0
  62. package/template/__dot__rulesync/subagents/deployer.md.tpl +53 -0
  63. package/template/__dot__rulesync/subagents/expert.md +29 -34
  64. package/template/__dot__rulesync/subagents/planner.md.tpl +47 -0
  65. package/template/__dot__rulesync/subagents/quality-reviewer.md.tpl +113 -0
  66. package/template/__dot__rulesync/subagents/security-reviewer.md.tpl +86 -0
  67. package/template/__dot__rulesync/subagents/tester.md.tpl +103 -0
  68. package/template/__dot__rulesync/sync.json.tpl +26 -0
  69. package/template/apps/api/package.json.tpl +2 -2
  70. package/template/apps/api/src/extensions.config.ts.tpl +12 -0
  71. package/template/apps/api/src/main.ts.tpl +1 -4
  72. package/template/apps/api/src/seed.ts.tpl +24 -17
  73. package/template/compose.prod.yml +63 -0
  74. package/template/docker-compose.yml +15 -2
  75. package/template/docs/agents/cross-repo.md.tpl +36 -0
  76. package/template/docs/agents/forge.md.tpl +56 -0
  77. package/template/docs/agents/issue-tracker.md.tpl +42 -0
  78. package/template/docs/standards/comments.md +16 -0
  79. package/template/docs/standards/database.md +77 -0
  80. package/template/docs/standards/enforcement.md +12 -0
  81. package/template/docs/standards/errors.md +30 -0
  82. package/template/docs/standards/frontend.md +60 -0
  83. package/template/docs/standards/functions.md +38 -0
  84. package/template/docs/standards/git-delivery.md +32 -0
  85. package/template/docs/standards/module-structure.md +37 -0
  86. package/template/docs/standards/testing.md +92 -0
  87. package/template/docs/standards/types.md +31 -0
  88. package/template/package.json.tpl +17 -10
  89. package/template/pnpm-workspace.yaml.tpl +6 -0
  90. package/template/rulesync.jsonc +4 -5
  91. package/template/tools/bootstrap.mjs +73 -0
  92. package/template/tools/oss-worktree.mjs.tpl +105 -0
  93. package/template/tools/review-precheck.mjs +575 -0
  94. package/template/tools/sync-agents.mjs +279 -0
  95. package/dist/generated/core-version.d.ts +0 -2
  96. package/dist/generated/core-version.d.ts.map +0 -1
  97. package/dist/generated/core-version.js +0 -2
  98. package/dist/generated/core-version.js.map +0 -1
  99. package/template/__dot__rulesync/commands/doctor.md +0 -16
  100. package/template/__dot__rulesync/hooks/post-edit.mjs +0 -57
  101. package/template/__dot__rulesync/rules/oss-boundaries.md +0 -31
  102. package/template/__dot__rulesync/skills/add-feature/SKILL.md +0 -113
  103. package/template/__dot__rulesync/skills/add-feature/handoff.md +0 -58
  104. package/template/__dot__rulesync/skills/create-pr/SKILL.md +0 -55
  105. package/template/__dot__rulesync/skills/create-task/SKILL.md +0 -77
  106. package/template/__dot__rulesync/skills/review/SKILL.md +0 -110
  107. package/template/__dot__rulesync/subagents/builder.md +0 -93
  108. package/template/__dot__rulesync/subagents/debugger.md +0 -82
  109. package/template/__dot__rulesync/subagents/deployer.md +0 -66
  110. package/template/__dot__rulesync/subagents/qa.md +0 -88
  111. package/template/__dot__rulesync/subagents/quality-reviewer.md +0 -67
  112. package/template/__dot__rulesync/subagents/security-reviewer.md +0 -54
@@ -1,18 +1,19 @@
1
1
  // Shared helpers for the cross-CLI hook guards.
2
2
  //
3
- // One script serves Claude Code, Copilot CLI, Codex CLI, and Gemini CLI. Each
4
- // passes the tool call as JSON on stdin but with a slightly different shape:
5
- // Claude / Codex : { tool_name, tool_input: { command?, file_path? } }
6
- // Copilot : { toolName, toolArgs: "<json-string>" | object }
7
- // Gemini : { toolName/tool_name, ... } (best-effort)
3
+ // One script serves Claude Code, Codex CLI, and Gemini CLI. Each passes the tool
4
+ // call as JSON on stdin:
5
+ // Claude / Gemini : { tool_name, tool_input: { command?, file_path? } }
6
+ // Codex : same, except an edit is { tool_name: "apply_patch", tool_input: { command: "<patch>" } },
7
+ // the paths only in its "*** Add File: <path>" style headers; an Edit|Write
8
+ // matcher matches apply_patch
8
9
  //
9
10
  // Deny is universal: exit code 2 + a message on stderr. Every other path exits 0
10
- // (allow). We FAIL OPEN on any parse error or uncertainty - Copilot's preToolUse
11
- // is fail-closed, so a crashing/slow guard would block real work; we never do
12
- // that, we only block on a positive match.
11
+ // (allow). We FAIL OPEN on any parse error or uncertainty, so a crashing guard
12
+ // never blocks real work; we only block on a positive match.
13
13
 
14
14
  import { readFileSync } from 'node:fs';
15
15
 
16
+ /** Read the hook payload from stdin; {} on any error. */
16
17
  export function readPayload() {
17
18
  try {
18
19
  return JSON.parse(readFileSync(0, 'utf8') || '{}');
@@ -21,39 +22,29 @@ export function readPayload() {
21
22
  }
22
23
  }
23
24
 
24
- function toolArgsObject(payload) {
25
- const a = payload.toolArgs;
26
- if (typeof a === 'string') {
27
- try {
28
- return JSON.parse(a);
29
- } catch {
30
- return {};
31
- }
32
- }
33
- return a && typeof a === 'object' ? a : {};
34
- }
25
+ const PATCH_PATH = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm;
26
+
27
+ const rawCommand = (payload) => String(payload.tool_input?.command ?? '');
35
28
 
29
+ // Only the tool name tells a patch from a shell command: a Bash command can carry patch text too.
30
+ const isPatch = (payload) => payload.tool_name === 'apply_patch';
31
+
32
+ /** The shell command string for this tool call, across tool shapes ('' if none or a patch). */
36
33
  export function extractCommand(payload) {
37
- const ti = payload.tool_input ?? {};
38
- const ca = toolArgsObject(payload);
39
- return String(ti.command ?? ca.command ?? '');
34
+ return isPatch(payload) ? '' : rawCommand(payload);
40
35
  }
41
36
 
42
- export function extractFilePath(payload) {
37
+ /** Every file an edit/write tool call touches, across tool shapes ([] if none). */
38
+ export function extractFilePaths(payload) {
39
+ if (isPatch(payload)) {
40
+ return [...rawCommand(payload).matchAll(PATCH_PATH)].map((match) => match[1].trim());
41
+ }
43
42
  const ti = payload.tool_input ?? {};
44
- const ca = toolArgsObject(payload);
45
- return String(
46
- ti.file_path ??
47
- ti.path ??
48
- ca.path ??
49
- ca.filePath ??
50
- ca.file ??
51
- ca.targetFile ??
52
- ca.target_file ??
53
- '',
54
- );
43
+ const filePath = ti.file_path ?? ti.path;
44
+ return filePath ? [String(filePath)] : [];
55
45
  }
56
46
 
47
+ /** Deny the tool call (works on Claude, Codex, Gemini). */
57
48
  export function deny(message) {
58
49
  process.stderr.write(message.endsWith('\n') ? message : message + '\n');
59
50
  process.exit(2);
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse guard: agent sessions never post on a pull/merge request (review comments, thread
3
+ // replies, reviews, verdict notes). They draft the text and a person posts it. Resolving a thread
4
+ // stays allowed: `glab api -X PUT .../discussions/<id> -f resolved=true` and the GraphQL
5
+ // resolveReviewThread mutation. Fails open like every other guard: only a positive match denies.
6
+
7
+ import { deny, extractCommand, readPayload } from './_shared.mjs';
8
+
9
+ // A call starts its shell segment, after `(`, `{`, `!`, a loop or branch keyword, env assignments
10
+ // and wrappers (`env`, `sudo`, `eval "`, `xargs -n1`, ...), so a commit message that mentions
11
+ // `gh pr comment` is not one. An absolute path to the binary counts too.
12
+ const START = String.raw`^[\s(!{]*(?:[\w-]+\s*\(\)\s*[({]*\s*)?(?:(?:do|then|else|if|elif|while|until)\s+)?(?:(?:\w+=\S*|(?:command|env|exec|eval|nice|time|nohup|sudo|npx|pnpm\s+exec|xargs)(?:\s+-\S+)*|g?timeout(?:\s+-\S+)*\s+\S+)\s+["']?)*(?:\S*/)?`;
13
+ const COMMENT_CLI = new RegExp(
14
+ START + String.raw`(?:gh\s+(?:pr|issue)\s+comment|glab\s+(?:mr|issue)\s+(?:note|comment))\b`,
15
+ );
16
+ const GH_PR_REVIEW = new RegExp(START + String.raw`gh\s+pr\s+review\b`);
17
+ // `-b` and `-F` also match a value glued to the flag (`-bLGTM`).
18
+ const REVIEW_WITH_TEXT = /\s(?:-[cbrF]|--comment|--request-changes|--body|--body-file)/;
19
+ const API_CALL = new RegExp(START + String.raw`(?:gh|glab)\s+api\b`);
20
+ // `draft_notes` covers the draft and its `/publish` and `bulk_publish` calls.
21
+ const COMMENT_PATH = /\/(?:comments|(?:draft_)?notes|reviews)(?=[/"'\s?]|$)/;
22
+ // Reacting is allowed: `.../comments/<id>/reactions` (gh) and `.../notes/<id>/award_emoji` (glab).
23
+ const REACTION_PATH =
24
+ /\/(?:comments|notes)\/[^/\s"'?]+\/(?:reactions|award_emoji)(?:\/[^/\s"'?]*)?/g;
25
+ const DISCUSSIONS = /\/discussions\/?(?=["'\s?]|$)/;
26
+ const GRAPHQL = /\s["']?(?:\S*\/)?graphql(?=["'\s]|$)/;
27
+ // A repeated method flag is a write when any of them is, whichever one the CLI honours.
28
+ const EXPLICIT_METHODS = /\s(?:-X\s*|--method[=\s]+)["']?([A-Za-z]+)/g;
29
+ // `-R o/r`, `-Ro/r`, `--repo o/r` and `--repo=o/r` may sit before the subcommand.
30
+ const REPO_FLAG = /\s(?:-R\s*|--repo(?:=|\s+))\S+/g;
31
+ // `gh api` and `glab api` default to POST once a field or body is passed.
32
+ // `-f` and `-F` also match a value glued to the flag (`-fbody=x`).
33
+ const FIELDS = /\s(?:-[fF]|--(?:raw-)?field\b|--input\b)/;
34
+ const COMMENT_MUTATION =
35
+ /\b(?:addComment|addPullRequestReview\w*|submitPullRequestReview|updateIssueComment|updatePullRequestReview\w*|create(?:Diff|ImageDiff)?Note|createDiscussion|updateNote)\b/;
36
+ // A query read from a file, stdin, a variable or a substitution cannot be inspected, so it counts
37
+ // as a mutation. A heredoc is inline, so the mutation check already sees it.
38
+ const OPAQUE_QUERY = /query=["']?(?:@|\$(?!\(cat\s*<<)|`)|--input\b/;
39
+ // `bash -c '<script>'` runs its script as calls of its own.
40
+ const SHELL_SCRIPT = /\b(?:ba|z|da)?sh\s+-\w*c\s+(["'])([\s\S]*?)\1/g;
41
+
42
+ const methodsOf = (call) => {
43
+ const explicit = [...call.matchAll(EXPLICIT_METHODS)].map((match) => match[1].toUpperCase());
44
+ return explicit.length > 0 ? explicit : [FIELDS.test(call) ? 'POST' : 'GET'];
45
+ };
46
+
47
+ const postsComment = (call) => {
48
+ const withoutRepo = call.replace(REPO_FLAG, '');
49
+ if (
50
+ COMMENT_CLI.test(withoutRepo) ||
51
+ (GH_PR_REVIEW.test(withoutRepo) && REVIEW_WITH_TEXT.test(withoutRepo))
52
+ ) {
53
+ return true;
54
+ }
55
+ if (!API_CALL.test(call)) {
56
+ return false;
57
+ }
58
+ if (GRAPHQL.test(call)) {
59
+ // A query spans lines, variables and substitutions, so the whole command is checked.
60
+ return COMMENT_MUTATION.test(command) || OPAQUE_QUERY.test(command);
61
+ }
62
+ const methods = methodsOf(call);
63
+ const path = call.replace(REACTION_PATH, '');
64
+ return (
65
+ (methods.some((method) => ['POST', 'PUT', 'PATCH'].includes(method)) &&
66
+ COMMENT_PATH.test(path)) ||
67
+ (methods.includes('POST') && DISCUSSIONS.test(path))
68
+ );
69
+ };
70
+
71
+ // ponytail: splits on shell separators without parsing quotes; a body with `;` before the path slips
72
+ // through, a quoted `sh -c '...'` or a backticked call in a commit message is denied, and curl, `xargs -I {}` and a script
73
+ // piped into a shell are not seen
74
+ const command = extractCommand(readPayload())
75
+ .replace(/\\\r?\n/g, ' ')
76
+ .replace(SHELL_SCRIPT, '; $2 ;');
77
+ if (command.split(/\|\||\$\(|[;|&\n`]/).some(postsComment)) {
78
+ deny(
79
+ 'Blocked: agent sessions never post on a pull/merge request (comment, reply, review, verdict note). Print the drafts as `file:line` + text for the user to post by hand. Resolving a thread your fix addressed is allowed.',
80
+ );
81
+ }
82
+ process.exit(0);
@@ -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,199 @@
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. From a checkout of another repository (one
10
+ // without this guard, so no stamp) only one plain `gh pr create`/`glab mr create` passes, left to that
11
+ // repository's rules: no shell syntax, no `-R`/`--repo`, and no remote of that checkout pointing at
12
+ // this repository. Anything else there is denied, since text cannot prove where it lands. Git errors
13
+ // fail open, like every other guard.
14
+
15
+ import { execFileSync } from 'node:child_process';
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { deny, extractCommand, readPayload } from './_shared.mjs';
20
+
21
+ const SHARED = /^(?:origin\/)?(?:main|master|dev|develop|stage|staging|prod|production)$/;
22
+ // `-R <repo>` goes before or after `pr`/`mr`; `new` is an alias of `create`.
23
+ const REPO = String.raw`(?:\s+(?:-R\s*|--repo(?:=|\s+))\S+)?`;
24
+ const CLI_CREATE = new RegExp(
25
+ 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]*)`,
26
+ 'g',
27
+ );
28
+ const PUSH_OPTION_CREATE = /merge_request\.create/;
29
+ // GraphQL mutations live in a quoted query, so they are matched on the raw command of an API call.
30
+ const GRAPHQL_CREATE = /\b(?:createPullRequest|mergeRequestCreate)\b/;
31
+ const API_CALL = /\b(?:gh|glab)\s+api\b/;
32
+ const REVIEW_COLLECTION = /\/(?:pulls|merge_requests)(?=["'\s?]|$)/;
33
+ // `gh api` and `glab api` default to POST once a field or body is passed.
34
+ const WRITES = /\s(?:(?:-X\s*|--method[=\s]+)POST\b|(?:-f|-F|--field|--raw-field|--input)\b)/i;
35
+ const READS = /\s(?:-X\s*|--method[=\s]+)GET\b/i;
36
+ // The source branch flag, glued (`-Hfeat/x`, `-dH x`) or not. glab's `-H` names the head repository.
37
+ const SOURCE_FLAG = {
38
+ gh: /\s(?:--head(?:=|\s+)|-[defw]*H(?:=|\s*))['"]?([^\s'"]+)/g,
39
+ glab: /\s(?:--source-branch(?:=|\s+)|-[fwy]*s(?:=|\s*))['"]?([^\s'"]+)/g,
40
+ };
41
+
42
+ // Quoted prose (a title, a search pattern) or a quoted separator is blanked so a command named
43
+ // inside it never counts and never cuts a flag list short; a quoted single word (a branch) is kept.
44
+ const blankProse = (command) =>
45
+ command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (quoted) =>
46
+ /[\s;&|(){}]/.test(quoted) ? '""' : quoted,
47
+ );
48
+
49
+ // One create and nothing else, once each whole-token quoted value the shell keeps literal is set
50
+ // aside: no quote left, no separator, expansion, glob, escape, redirection or newline, and no
51
+ // `-R`/`--repo`. A quoted value that starts with `-` stays, so a quoted flag is never hidden.
52
+ const PLAIN_CREATE =
53
+ /^[ \t]*(?:gh[ \t]+pr|glab[ \t]+mr)[ \t]+(?:create|new)(?:[ \t]+[^\s;&|$`'"(){}[\]*?\\<>!~]+)*[ \t]*$/;
54
+ const NAMES_REPO = /[ \t](?:-\w*R|--repo)/;
55
+ const literals = (command) =>
56
+ command.replace(
57
+ /(?<=[ \t=])(?:'([^'\n]*)'|"([^"$`\\!\n]*)")(?=[ \t]|$)/g,
58
+ (quoted, single, double) => ((single ?? double).startsWith('-') ? quoted : '_'),
59
+ );
60
+ // `owner/repo` from a remote URL (ssh or https, with or without .git).
61
+ const slug = (value) =>
62
+ value
63
+ .toLowerCase()
64
+ .replace(/\/+$/, '')
65
+ .replace(/\.git$/, '')
66
+ .split(/[/:]/)
67
+ .slice(-2)
68
+ .join('/')
69
+ .toLowerCase();
70
+
71
+ // A push option or an API call opens the MR/PR from HEAD.
72
+ const opensFromHead = (raw, command) =>
73
+ PUSH_OPTION_CREATE.test(command) ||
74
+ (API_CALL.test(command) &&
75
+ (GRAPHQL_CREATE.test(raw) ||
76
+ (REVIEW_COLLECTION.test(raw) && WRITES.test(command) && !READS.test(command))));
77
+
78
+ const git = (cwd, ...args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
79
+ const stampFile = (root) => join(root, 'node_modules', '.cache', 'verify-head');
80
+
81
+ const checkout = (cwd) => {
82
+ try {
83
+ const root = git(cwd, 'rev-parse', '--show-toplevel');
84
+ return {
85
+ root,
86
+ head: git(root, 'rev-parse', 'HEAD'),
87
+ isClean: git(root, 'status', '--porcelain') === '',
88
+ };
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ };
93
+
94
+ const branchCommit = (root, branch) => {
95
+ for (const ref of [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]) {
96
+ try {
97
+ return git(root, 'rev-parse', '--verify', '-q', `${ref}^{commit}`);
98
+ } catch {
99
+ // try the next ref
100
+ }
101
+ }
102
+ return '';
103
+ };
104
+
105
+ if (process.argv.includes('--stamp')) {
106
+ if (process.env.npm_lifecycle_event !== 'verify') {
107
+ process.stderr.write('--stamp is recorded by `pnpm verify` only: run `pnpm verify`.\n');
108
+ process.exit(1);
109
+ }
110
+ const state = checkout(process.cwd());
111
+ if (state?.isClean) {
112
+ mkdirSync(dirname(stampFile(state.root)), { recursive: true });
113
+ writeFileSync(stampFile(state.root), state.head);
114
+ } else {
115
+ process.stderr.write(
116
+ 'verify passed on uncommitted changes: commit, then rerun `pnpm verify` before opening an MR/PR.\n',
117
+ );
118
+ }
119
+ process.exit(0);
120
+ }
121
+
122
+ const payload = readPayload();
123
+ const raw = extractCommand(payload);
124
+ // A command handed to a shell (`sh -c '...'`, `eval "..."`) runs its quoted text: read it unquoted.
125
+ const command = /\b(?:\w*sh\s+-\w*c|eval)\b/.test(raw)
126
+ ? raw.replace(/['"]/g, ' ')
127
+ : blankProse(raw);
128
+ // The source branch of each create in the chain, `undefined` for HEAD; `gh pr create --head
129
+ // owner:branch` names the fork too. A create naming two different ones is ambiguous.
130
+ const sources = [...command.matchAll(CLI_CREATE)].map((create) => {
131
+ const named = [
132
+ ...new Set(
133
+ [...create[3].matchAll(SOURCE_FLAG[create[1] ?? create[2]])].map((flag) =>
134
+ flag[1].replace(/^[^:]+:/, ''),
135
+ ),
136
+ ),
137
+ ];
138
+ if (named.length > 1) {
139
+ deny(
140
+ `Blocked: this command names more than one source branch (${named.join(', ')}); name one.`,
141
+ );
142
+ }
143
+ return named[0];
144
+ });
145
+ if (opensFromHead(raw, command)) {
146
+ sources.push(undefined);
147
+ }
148
+ const pending = sources.filter((source) => !source || !SHARED.test(source));
149
+ if (pending.length === 0) {
150
+ process.exit(0);
151
+ }
152
+ const state = checkout(payload.cwd ?? process.cwd());
153
+ if (!state || !existsSync(join(state.root, '.rulesync', 'hooks', 'guard-mr.mjs'))) {
154
+ // Not a checkout of this repository: it has no stamp, so its own rules apply to a plain create.
155
+ // The guarded repository is the one this hook file lives in.
156
+ let foreign = false;
157
+ try {
158
+ const origin = slug(
159
+ git(dirname(fileURLToPath(import.meta.url)), 'remote', 'get-url', 'origin'),
160
+ );
161
+ // As gh reads them: `git remote -v` applies `insteadOf` rewrites and lists push URLs too.
162
+ const urls = git(state.root, 'remote', '-v')
163
+ .split('\n')
164
+ // A URL with whitespace in it is read differently by gh (last token): it proves nothing.
165
+ .map((line) => /^\S+\t(\S+) \((?:fetch|push)\)$/.exec(line)?.[1] ?? '');
166
+ // gh parses a remote as a URL (decodes `%XX`, drops `?`/`#`, resolves dot segments), so a URL
167
+ // whose text could resolve elsewhere than it reads proves nothing.
168
+ foreign = urls.every(
169
+ (url) => url && !/[?#%]|\/\.\.?(?:\/|$)/.test(url) && slug(url) !== origin,
170
+ );
171
+ } catch {
172
+ // no git here, no origin to compare, or no remote: nothing proves where it lands
173
+ }
174
+ const flat = literals(raw);
175
+ if (!foreign || !PLAIN_CREATE.test(flat) || NAMES_REPO.test(flat)) {
176
+ deny(
177
+ 'Blocked: from a checkout of another repository only one plain `gh pr create`/`glab mr create` runs, with no shell syntax or `-R` (pass the body with `--body-file`), and none of its remotes may point here.',
178
+ );
179
+ }
180
+ process.exit(0);
181
+ }
182
+ const readStamp = () => {
183
+ try {
184
+ return readFileSync(stampFile(state.root), 'utf8').trim();
185
+ } catch {
186
+ return '';
187
+ }
188
+ };
189
+ const stamp = readStamp();
190
+ for (const source of pending) {
191
+ const sent = source ? branchCommit(state.root, source) : state.head;
192
+ // Only the checked-out commit can carry uncommitted edits.
193
+ if (!sent || (sent === state.head && !state.isClean) || stamp !== sent) {
194
+ deny(
195
+ '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.',
196
+ );
197
+ }
198
+ }
199
+ process.exit(0);