@ryusenkei/conventions 0.7.0 → 0.8.1

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/README.md CHANGED
@@ -55,7 +55,7 @@ The PreToolUse hook blocks the call and tells Claude why, so Claude can fix it a
55
55
  | PR title = squash commit message | Checks `gh pr create` / `gh pr edit` titles with prose-lint's commit rules |
56
56
  | No AI signature | `attribution` is empty, and the hook blocks PR bodies with an AI signature |
57
57
  | Squash merge | Blocks `gh pr merge --rebase`, and `--merge` except for a `dev/*` → `main` PR with the epic flow, which must use `--merge` |
58
- | Merge only after CI passes | Blocks `gh pr merge` unless every check of the PR has passed (`gh pr checks`). Pending, failed, missing, or unreadable checks are blocked, also with `--auto` (with the epic flow, a PR into `dev/*` may have no checks) |
58
+ | Merge only after CI passes | Blocks `gh pr merge` unless every check of the PR has passed (`gh pr checks`). Pending, failed, missing, or unreadable checks are blocked, also with `--auto`. A PR may have no checks only when the repository has no enabled workflow that runs on `pull_request` (workflows disabled on GitHub with `gh workflow disable` don't count; the pre-push `pnpm check` is the gate), or with the epic flow when it targets `dev/*`. Right after a push, the checks may not be registered yet, so the hook points to `gh pr checks --watch` |
59
59
  | Epic flow (opt-in) | See [Epic flow](#epic-flow) |
60
60
  | Do not edit `node_modules` | Blocks Edit and Write under `node_modules` |
61
61
  | Secrets | `permissions.deny` blocks reading `.env` and `.dev.vars` with Claude's file tools (not Bash) |
@@ -87,6 +87,7 @@ Opt in per repository in the root `package.json`:
87
87
  `sync` writes these files and `check` compares them, ignoring line endings:
88
88
 
89
89
  - `.editorconfig`, `.gitattributes`, `.gitignore`, `.gitleaks.toml`, `mise.toml`, `.github/dependabot.yaml`, `.githooks/commit-msg`, `.githooks/pre-push`
90
+ - Skills in `.claude/skills/`: `stacked-pr` (cleaning up a stacked PR after its parent is squash-merged). Only these names are managed; other skills in the repository are kept
90
91
  - `.github/dependabot.yaml` updates npm and GitHub Actions. When the repository has a `go.mod` at the root, a `gomod` entry is appended (same schedule, rebase strategy and cooldown, minor and patch grouped). Without one it is left out, because Dependabot fails on a missing `go.mod`
91
92
  - When the repository has a `Cargo.toml` at the root, a `cargo` entry is appended to `.github/dependabot.yaml` after any `gomod` entry (same settings as `gomod`, covering workspace members), and `target/` is appended to `.gitignore`. `Cargo.lock` stays tracked
92
93
  - `.claude/settings.json`: only the hooks, `attribution`, `permissions.deny`, and the writing plugins are managed. Other settings, hooks, and plugins are kept
@@ -106,6 +107,90 @@ When the `rules.md` import is present, `sync` adds the missing ones right after
106
107
 
107
108
  Dependabot runs monthly with `rebase-strategy: disabled` to save GitHub Actions minutes, so rebase a Dependabot PR (`@dependabot rebase`) before merging it. The `cooldown` excludes `@ryusenkei/*`. To pick up a new version sooner, run `pnpm update "@ryusenkei/*"`. After an update, `check` fails until `sync` is run.
108
109
 
110
+ ## Dependency direction
111
+
112
+ `runDepsCheck` checks imports in the sources and the dependencies in each `package.json` against the layer rules of the repository. Each repository keeps only its rules:
113
+
114
+ ```ts
115
+ // scripts/deps.ts
116
+ import { runDepsCheck } from '@ryusenkei/conventions';
117
+ import { EXCEPTIONS, RULES } from './lib/deps-rules.ts';
118
+
119
+ runDepsCheck({ rules: RULES, exceptions: EXCEPTIONS });
120
+ ```
121
+
122
+ ```ts
123
+ // scripts/lib/deps-rules.ts
124
+ import type { Exception, Rule } from '@ryusenkei/conventions';
125
+
126
+ export const RULES: Rule[] = [
127
+ { name: 'core', paths: ['packages/core'], allow: [], deny: ['cloudflare:', 'node:', '@vercel/'] },
128
+ { name: 'adapters', paths: ['packages/adapter-*'], allow: ['packages/core'] },
129
+ { name: 'app', paths: ['apps/*'], allow: ['packages/core', 'packages/adapter-*'] },
130
+ ];
131
+ export const EXCEPTIONS: Exception[] = [];
132
+ ```
133
+
134
+ | Field | Meaning |
135
+ | --- | --- |
136
+ | `paths` | Paths the rule covers, from the repository root. `*` matches within one path segment. The most specific match wins |
137
+ | `allow` | Paths the covered files may import. The same rule and the same package are always allowed |
138
+ | `deny` | Prefixes of external modules the covered files may not import |
139
+ | `EXCEPTIONS` | `{ from, to }` pairs allowed despite the rules |
140
+
141
+ It reads tracked and unignored files, `.ts`/`.js` variants and `.astro` (front matter and `<script>`), and fails when a workspace package has no rule. It needs `typescript` (a peer dependency), which only this check loads.
142
+
143
+ ## CI
144
+
145
+ The CI lives in toolkit as reusable workflows, so each repository only keeps the triggers:
146
+
147
+ ```yaml
148
+ # .github/workflows/ci.yaml
149
+ name: CI
150
+ on:
151
+ pull_request:
152
+ branches: [main]
153
+ types: [opened, synchronize, reopened]
154
+ concurrency:
155
+ group: ci-${{ github.ref }}
156
+ cancel-in-progress: true
157
+ permissions:
158
+ contents: read
159
+ jobs:
160
+ ci:
161
+ uses: ryusenkei-inc/toolkit/.github/workflows/reusable-ci.yaml@main
162
+ with:
163
+ checks: |
164
+ pnpm lint:deps
165
+ ```
166
+
167
+ ```yaml
168
+ # .github/workflows/pr-title.yaml
169
+ name: PR title
170
+ on:
171
+ pull_request:
172
+ branches: [main]
173
+ types: [edited]
174
+ concurrency:
175
+ group: pr-title-${{ github.ref }}
176
+ cancel-in-progress: true
177
+ permissions:
178
+ contents: read
179
+ jobs:
180
+ title:
181
+ uses: ryusenkei-inc/toolkit/.github/workflows/reusable-pr-title.yaml@main
182
+ ```
183
+
184
+ | Workflow | Steps |
185
+ | --- | --- |
186
+ | `reusable-ci.yaml` | Checkout (full history), mise, pnpm, `pnpm install --frozen-lockfile`, `pnpm typecheck`, `pnpm test`, `pnpm lint:prose`, the `checks` input, the PR title with prose-lint's commit rules (not for Dependabot), and a gitleaks scan with `.gitleaks.toml` |
187
+ | `reusable-pr-title.yaml` | Re-checks the PR title when it is edited, with the `@ryusenkei/prose-lint` version from `package.json` and no install |
188
+
189
+ - `terraform`: space-separated directories to check with `terraform fmt -check` and `validate` (no backend, so no credentials). Terraform comes from the caller's `mise.toml`.
190
+ - Language jobs (Go, Rust) stay in the calling workflow as extra jobs.
191
+ - PR title edits run in their own workflow. In the same workflow, the later `edited` run would overwrite the `ci` job's result with "skipped" and hide a failure.
192
+ - `@main` follows toolkit's `main`, so fixes reach every repository at once. A breaking change gets a new file name instead of changing these.
193
+
109
194
  ## Versioning
110
195
 
111
196
  - major: a rule is removed or reversed, or a synced file changes incompatibly
@@ -0,0 +1,12 @@
1
+ import { type Exception, type Rule } from './deps.ts';
2
+ /** ワークスペースのパッケージのディレクトリ(pnpm-workspace.yaml の packages、リポのルートから `/` 区切り) */
3
+ export declare function workspaceDirs(): string[];
4
+ /**
5
+ * リポのルートで依存の向きを検査し、結果を出力して終了コードを設定
6
+ * @param options.rulesFile 案内に出す規則のファイル
7
+ */
8
+ export declare function runDepsCheck(options: {
9
+ rules: Rule[];
10
+ exceptions?: Exception[];
11
+ rulesFile?: string;
12
+ }): void;
@@ -0,0 +1,50 @@
1
+ // 依存の向きの検査の実行(各リポの scripts/deps.ts から規則を渡して呼ぶ)
2
+ // - 対象: ソースの import と package.json の依存(git が追跡するファイルと、無視されていない未追跡のファイル)
3
+ // - 違反・規則のないワークスペースのパッケージがあれば終了コード1
4
+ import { spawnSync } from 'node:child_process';
5
+ import { existsSync, globSync, readFileSync } from 'node:fs';
6
+ import { posix } from 'node:path';
7
+ import { checkManifest, checkSource, uncovered } from "./deps.js";
8
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
9
+ const dependenciesOf = (pkg) => Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies });
10
+ /** ワークスペースのパッケージのディレクトリ(pnpm-workspace.yaml の packages、リポのルートから `/` 区切り) */
11
+ export function workspaceDirs() {
12
+ const packagesBlock = /^packages:\r?\n((?:[ \t]+.*\r?\n?)+)/m.exec(readFileSync('pnpm-workspace.yaml', 'utf8'))?.[1] ?? '';
13
+ const patterns = [...packagesBlock.matchAll(/-\s+["']?([^"'\s#]+)/g)].map((m) => m[1]);
14
+ return patterns.flatMap((p) => globSync(`${p}/package.json`)).map((f) => posix.dirname(f.replaceAll('\\', '/')));
15
+ }
16
+ // サブパスの export: 指定子 `名前/サブパス` をファイルに解決(パッケージの中で規則が分かれる場合の照合、`.` とパターンはディレクトリのまま)
17
+ const entriesOf = (dir) => {
18
+ const pkg = readJson(`${dir}/package.json`);
19
+ const name = pkg.name ?? dir;
20
+ const subpaths = Object.entries(pkg.exports ?? {}).flatMap(([key, value]) => (key !== '.' && !key.includes('*') && typeof value === 'string' ? [[`${name}/${key.slice(2)}`, posix.join(dir, value)]] : []));
21
+ return [[name, dir], ...subpaths];
22
+ };
23
+ /**
24
+ * リポのルートで依存の向きを検査し、結果を出力して終了コードを設定
25
+ * @param options.rulesFile 案内に出す規則のファイル
26
+ */
27
+ export function runDepsCheck(options) {
28
+ const { rules, exceptions = [], rulesFile = 'scripts/lib/deps-rules.ts' } = options;
29
+ const dirs = workspaceDirs();
30
+ const workspace = new Map(dirs.flatMap(entriesOf));
31
+ const manifests = [{ dir: '', ruleAt: 'scripts', dependencies: dependenciesOf(readJson('package.json')) }, ...dirs.map((dir) => ({ dir, ruleAt: dir, dependencies: dependenciesOf(readJson(`${dir}/package.json`)) }))];
32
+ const listed = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8' });
33
+ if (listed.status !== 0) {
34
+ console.error(listed.stderr);
35
+ process.exitCode = 1;
36
+ return;
37
+ }
38
+ const files = listed.stdout.split('\n').filter((f) => f && existsSync(f));
39
+ const violations = [...manifests.flatMap((m) => checkManifest(rules, workspace, exceptions, m)), ...files.flatMap((f) => checkSource(rules, workspace, exceptions, f, readFileSync(f, 'utf8')))];
40
+ const missing = uncovered(rules, workspace);
41
+ for (const dir of missing)
42
+ console.error(`${dir}: 依存の規則がない(${rulesFile} に追加)`);
43
+ for (const v of violations)
44
+ console.error(`${v.file}: '${v.specifier}'(${v.rule})→ ${v.reason}`);
45
+ if (missing.length > 0 || violations.length > 0) {
46
+ process.exitCode = 1;
47
+ return;
48
+ }
49
+ console.log('依存の向き: 問題なし');
50
+ }
package/dist/deps.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /** 依存の向きの規則: paths のファイル・パッケージが依存してよい先 */
2
+ export type Rule = {
3
+ /** 表示名(層) */
4
+ name: string;
5
+ /** 対象のパス(リポのルートから、`*` は区画内の任意の文字列) */
6
+ paths: string[];
7
+ /** 依存してよい先のパス(その下で別の規則を持つ、より具体的なパスは含まない) */
8
+ allow: string[];
9
+ /** 依存を禁止する外部のモジュールの接頭辞 */
10
+ deny?: string[];
11
+ };
12
+ /** 規則の例外: from のファイルから to のパスへの依存を許可 */
13
+ export type Exception = {
14
+ from: string;
15
+ to: string;
16
+ };
17
+ /** 規則に反する依存 */
18
+ export type Violation = {
19
+ file: string;
20
+ specifier: string;
21
+ rule: string;
22
+ reason: string;
23
+ };
24
+ /** ワークスペースのパッケージ(名前 → ディレクトリ、`名前/サブパス` の export → ファイル) */
25
+ export type Workspace = Map<string, string>;
26
+ /** package.json の依存(dependencies・devDependencies・peerDependencies の名前) */
27
+ export type Manifest = {
28
+ /** パッケージのディレクトリ(ルートは空文字列) */
29
+ dir: string;
30
+ /** 規則を引くパス(ルートの package.json はスクリプトの依存のため scripts) */
31
+ ruleAt: string;
32
+ dependencies: string[];
33
+ };
34
+ /** パスがパターン(またはその下)に該当するか */
35
+ export declare function matches(path: string, pattern: string): boolean;
36
+ /** パスに該当する規則(最も具体的なパターン、なければ undefined) */
37
+ export declare function ruleOf(rules: Rule[], path: string): Rule | undefined;
38
+ /** パターンがディレクトリの下にあるか(`*` は区画内の任意の文字列) */
39
+ export declare function under(pattern: string, dir: string): boolean;
40
+ /** ソースの import・export from・動的 import・require の指定子(コメントと文字列の中は対象外) */
41
+ export declare function specifiersOf(text: string, file: string): string[];
42
+ /** ソースの import の検査 */
43
+ export declare function checkSource(rules: Rule[], workspace: Workspace, exceptions: Exception[], file: string, text: string): Violation[];
44
+ /** package.json の依存の検査(規則: パッケージ自体と、中にある組み立てのファイルの和) */
45
+ export declare function checkManifest(rules: Rule[], workspace: Workspace, exceptions: Exception[], manifest: Manifest): Violation[];
46
+ /** 規則に該当しないワークスペースのパッケージ(新しいパッケージは規則の追加が必要) */
47
+ export declare function uncovered(rules: Rule[], workspace: Workspace): string[];
package/dist/deps.js ADDED
@@ -0,0 +1,115 @@
1
+ // 依存の向きの検査の本体(規則は各リポの scripts/lib/deps-rules.ts)
2
+ import { createRequire } from 'node:module';
3
+ import { posix } from 'node:path';
4
+ // typescript は peerDependency。依存の向きの検査を使うときだけ読み込む(sync・check は typescript なしで動かす)
5
+ let tsModule;
6
+ const typescript = () => (tsModule ??= createRequire(import.meta.url)('typescript'));
7
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|astro)$/;
8
+ function patternRegExp(pattern) {
9
+ const body = pattern.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*');
10
+ return new RegExp(`^${body}(?:/|$)`);
11
+ }
12
+ /** パスがパターン(またはその下)に該当するか */
13
+ export function matches(path, pattern) {
14
+ return patternRegExp(pattern).test(path);
15
+ }
16
+ function bestRuleOf(rules, path) {
17
+ let best;
18
+ for (const rule of rules) {
19
+ for (const p of rule.paths) {
20
+ if (matches(path, p) && (!best || p.length > best.pattern.length))
21
+ best = { rule, pattern: p };
22
+ }
23
+ }
24
+ return best;
25
+ }
26
+ /** パスに該当する規則(最も具体的なパターン、なければ undefined) */
27
+ export function ruleOf(rules, path) {
28
+ return bestRuleOf(rules, path)?.rule;
29
+ }
30
+ /** パターンがディレクトリの下にあるか(`*` は区画内の任意の文字列) */
31
+ export function under(pattern, dir) {
32
+ const ps = pattern.split('/');
33
+ const ds = dir.split('/');
34
+ return ps.length > ds.length && ds.every((d, i) => patternRegExp(ps[i]).test(d));
35
+ }
36
+ const packageNameOf = (specifier) => {
37
+ const parts = specifier.split('/');
38
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
39
+ };
40
+ const packageDirs = (workspace) => [...workspace].filter(([name]) => packageNameOf(name) === name).map(([, dir]) => dir);
41
+ function packageDirOf(workspace, path) {
42
+ let best;
43
+ for (const dir of packageDirs(workspace)) {
44
+ if (matches(path, dir) && (!best || dir.length > best.length))
45
+ best = dir;
46
+ }
47
+ return best;
48
+ }
49
+ function astroScripts(text) {
50
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? '';
51
+ const scripts = [...text.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
52
+ return [frontmatter, ...scripts].join('\n');
53
+ }
54
+ /** ソースの import・export from・動的 import・require の指定子(コメントと文字列の中は対象外) */
55
+ export function specifiersOf(text, file) {
56
+ const code = file.endsWith('.astro') ? astroScripts(text) : text;
57
+ const info = typescript().preProcessFile(code, true, true);
58
+ return [...info.importedFiles, ...info.typeReferenceDirectives].map((f) => f.fileName);
59
+ }
60
+ function targetOf(workspace, file, specifier) {
61
+ if (specifier.startsWith('.')) {
62
+ return { kind: 'path', path: posix.normalize(posix.join(posix.dirname(file), specifier.replace(/\?.*$/, ''))) };
63
+ }
64
+ const dir = workspace.get(specifier) ?? workspace.get(packageNameOf(specifier));
65
+ return dir ? { kind: 'path', path: dir } : { kind: 'external', name: specifier };
66
+ }
67
+ function verdict(rules, workspace, exceptions, from, fromRules, target) {
68
+ const deny = fromRules.flatMap((r) => r.deny ?? []);
69
+ if (target.kind === 'external') {
70
+ const hit = deny.find((d) => target.name.startsWith(d));
71
+ return hit ? `${hit} は依存不可` : undefined;
72
+ }
73
+ const fromPackage = packageDirOf(workspace, from);
74
+ if (fromPackage && fromPackage === packageDirOf(workspace, target.path))
75
+ return undefined;
76
+ const to = bestRuleOf(rules, target.path);
77
+ if (!to)
78
+ return undefined;
79
+ const toRule = to.rule;
80
+ if (fromRules.includes(toRule))
81
+ return undefined;
82
+ if (fromRules.some((r) => r.allow.some((a) => matches(target.path, a) && a.length >= to.pattern.length)))
83
+ return undefined;
84
+ if (exceptions.some((e) => matches(from, e.from) && matches(target.path, e.to)))
85
+ return undefined;
86
+ return `${toRule.name}(${target.path})は依存不可`;
87
+ }
88
+ /** ソースの import の検査 */
89
+ export function checkSource(rules, workspace, exceptions, file, text) {
90
+ if (!SOURCE_EXT.test(file))
91
+ return [];
92
+ const rule = ruleOf(rules, file);
93
+ if (!rule)
94
+ return [];
95
+ return specifiersOf(text, file).flatMap((specifier) => {
96
+ const reason = verdict(rules, workspace, exceptions, file, [rule], targetOf(workspace, file, specifier));
97
+ return reason ? [{ file, specifier, rule: rule.name, reason }] : [];
98
+ });
99
+ }
100
+ /** package.json の依存の検査(規則: パッケージ自体と、中にある組み立てのファイルの和) */
101
+ export function checkManifest(rules, workspace, exceptions, manifest) {
102
+ const own = ruleOf(rules, manifest.ruleAt);
103
+ if (!own)
104
+ return [];
105
+ const inner = manifest.dir === '' ? [] : rules.filter((r) => r !== own && r.paths.some((p) => matches(p, manifest.dir) || under(p, manifest.dir)));
106
+ const file = posix.join(manifest.dir, 'package.json');
107
+ return manifest.dependencies.flatMap((name) => {
108
+ const reason = verdict(rules, workspace, exceptions, file, [own, ...inner], targetOf(workspace, file, name));
109
+ return reason ? [{ file, specifier: name, rule: own.name, reason }] : [];
110
+ });
111
+ }
112
+ /** 規則に該当しないワークスペースのパッケージ(新しいパッケージは規則の追加が必要) */
113
+ export function uncovered(rules, workspace) {
114
+ return packageDirs(workspace).filter((dir) => !ruleOf(rules, dir));
115
+ }
package/dist/files.js CHANGED
@@ -21,6 +21,8 @@ const FILES = [
21
21
  },
22
22
  { from: 'commit-msg', to: '.githooks/commit-msg', mode: 0o755 },
23
23
  { from: 'pre-push', to: '.githooks/pre-push', mode: 0o755 },
24
+ // スキル: 管理するのはこの一覧の名前だけ(リポ独自のスキルは維持)
25
+ { from: 'skills/stacked-pr/SKILL.md', to: '.claude/skills/stacked-pr/SKILL.md' },
24
26
  ];
25
27
  const SETTINGS = '.claude/settings.json';
26
28
  const WORKSPACE = 'pnpm-workspace.yaml';
package/dist/hook.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // - Stop: 変更があれば `pnpm lint`・`pnpm test` を実行し、失敗時は完了を差し戻し
5
5
  // - hook 自体の失敗は終了コード1(拒否にしない → 作業を継続)
6
6
  import { spawnSync } from 'node:child_process';
7
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { homedir, tmpdir } from 'node:os';
9
9
  import { isAbsolute, join, resolve } from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
@@ -14,7 +14,7 @@ const root = process.env.CLAUDE_PROJECT_DIR ?? input.cwd ?? process.cwd();
14
14
  // Windows の `pnpm` は `.cmd` → シェル経由でのみ起動可能
15
15
  const shell = process.platform === 'win32';
16
16
  if (input.hook_event_name === 'PreToolUse') {
17
- const reason = denyReason(input, { root, repoRoot, resolveDir, titleIssues, readFile, currentBranch, prHead, prBase, prChecks });
17
+ const reason = denyReason(input, { root, repoRoot, resolveDir, titleIssues, readFile, currentBranch, prHead, prBase, hasPrWorkflow, prChecks });
18
18
  if (reason) {
19
19
  process.stderr.write(`${reason}\n`);
20
20
  process.exit(2);
@@ -70,6 +70,29 @@ function prBase(pr, cwd) {
70
70
  const r = spawnSync('gh', ['pr', 'view', ...(pr ? [pr] : []), '--json', 'baseRefName', '--jq', '.baseRefName'], { cwd: cwd ?? root, encoding: 'utf8' });
71
71
  return (r.status === 0 && r.stdout.trim()) || undefined;
72
72
  }
73
+ // GitHub で無効にしたワークフローはチェックを出さない → 有効なものだけを数える
74
+ // 読めなければ「ある」とみなす(チェックなしのマージを許可しない側に倒す)
75
+ function hasPrWorkflow(cwd) {
76
+ const dir = join(repoRoot(cwd) ?? root, '.github', 'workflows');
77
+ let files;
78
+ try {
79
+ files = readdirSync(dir).filter((f) => /\.ya?ml$/.test(f) && /^\s*pull_request(_target)?\s*:|^on:.*\bpull_request/m.test(readFileSync(join(dir, f), 'utf8')));
80
+ }
81
+ catch (e) {
82
+ return e.code !== 'ENOENT';
83
+ }
84
+ if (files.length === 0)
85
+ return false;
86
+ const r = spawnSync('gh', ['workflow', 'list', '--all', '--json', 'path,state'], { cwd: cwd ?? root, encoding: 'utf8' });
87
+ try {
88
+ const states = new Map(JSON.parse(r.stdout).map((w) => [w.path, w.state]));
89
+ // GitHub にまだないファイル(未 push)は有効とみなす
90
+ return files.some((f) => (states.get(`.github/workflows/${f}`) ?? 'active') === 'active');
91
+ }
92
+ catch {
93
+ return true;
94
+ }
95
+ }
73
96
  // `gh pr checks` は実行中・失敗で終了コードが0以外(8・1)→ 終了コードではなく出力で判定
74
97
  function prChecks(pr, cwd) {
75
98
  const r = spawnSync('gh', ['pr', 'checks', ...(pr ? [pr] : []), '--json', 'bucket'], { cwd: cwd ?? root, encoding: 'utf8' });
package/dist/index.d.ts CHANGED
@@ -1 +1,3 @@
1
1
  export { drifts, sync, IMPORT, type Drift } from './files.ts';
2
+ export { runDepsCheck } from './deps-check.ts';
3
+ export type { Exception, Rule } from './deps.ts';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export { drifts, sync, IMPORT } from "./files.js";
2
+ export { runDepsCheck } from "./deps-check.js";
package/dist/policy.d.ts CHANGED
@@ -24,6 +24,8 @@ export type Context = {
24
24
  prHead: (pr: string | undefined, cwd: string | undefined) => string | undefined;
25
25
  /** PR の base のブランチ(`pr` の省略時は現在のブランチの PR) */
26
26
  prBase: (pr: string | undefined, cwd: string | undefined) => string | undefined;
27
+ /** PR で動くワークフロー(`pull_request`)のうち、GitHub で有効なものがリポにあるか */
28
+ hasPrWorkflow: (cwd: string | undefined) => boolean;
27
29
  /** PR のチェックの集計(`pr` の省略時は現在のブランチの PR) */
28
30
  prChecks: (pr: string | undefined, cwd: string | undefined) => Checks;
29
31
  };
package/dist/policy.js CHANGED
@@ -31,7 +31,7 @@ const BRANCH_RULE = `\`<type>/<内容>\`(type = ${TYPES.join('・')}、内容
31
31
  const CHECKS_REASON = {
32
32
  pending: 'CI が実行中。全チェックの成功を確認してからマージ(`gh pr checks --watch`)',
33
33
  fail: 'CI が失敗。修正して全チェックが成功してからマージ',
34
- none: 'PR にチェックがない。CI の成功を確認できない PR はマージしない',
34
+ none: 'PR にチェックがない。push の直後ならチェックの登録を待ち、`gh pr checks --watch` で全チェックの成功を確認してからマージ',
35
35
  unknown: 'CI の結果を取得できない(`gh pr checks` が失敗)。全チェックの成功を確認してからマージ',
36
36
  };
37
37
  /** 拒否の理由(許可する場合は `undefined`) */
@@ -251,6 +251,9 @@ function mergeReasons(args, st, ctx) {
251
251
  const checks = ctx.prChecks(pr, cwd);
252
252
  if (checks === 'pass')
253
253
  return [];
254
+ // PR で動く有効なワークフローがないリポ: CI の代わりに pre-push の `pnpm check` が関門
255
+ if (checks === 'none' && !ctx.hasPrWorkflow(cwd))
256
+ return [];
254
257
  if (checks === 'none' && epicFlow(st, ctx)) {
255
258
  const base = ctx.prBase(pr, cwd);
256
259
  if (base !== undefined && DEV_BRANCH.test(base))
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: stacked-pr
3
+ description: 前の PR のブランチから作った PR(スタックした PR)を、前の PR のマージの後に整理する手順。親の PR を squash でマージした後、子の PR のベースの付け替え、rebase、親のブランチの削除をするときに使う
4
+ ---
5
+
6
+ # スタックした PR の整理
7
+
8
+ 親の PR(`feat/a` → `main`)の上に、子の PR(`feat/b` → `feat/a`)を重ねている場合の手順。親を squash でマージすると、親のコミットは `main` 上の別のコミットになる。そのため、子のブランチには親の元のコミットが残り、そのままだと子の差分に親の変更が混ざる
9
+
10
+ ## 手順
11
+
12
+ 親の PR をマージした直後に、子の PR ごとに次を行う
13
+
14
+ 1. 親の PR を squash でマージする。このとき `--delete-branch` は付けない。親のブランチは手順4で `rebase --onto` の基準に使う
15
+
16
+ ```sh
17
+ gh pr merge <親の番号> --squash
18
+ ```
19
+
20
+ 2. 子の PR のベースを、親のベース(`main`、epic のフローなら `dev/...`)に付け替える
21
+
22
+ ```sh
23
+ gh pr edit <子の番号> --base main
24
+ ```
25
+
26
+ 3. 最新のベースを取得する
27
+
28
+ ```sh
29
+ git fetch origin
30
+ ```
31
+
32
+ 4. 子のブランチから親の元のコミットを外し、ベースの上に載せ直す。`feat/a` は親のブランチの、マージの前の先端を指している必要がある(手元のブランチを消していなければそのまま使える)
33
+
34
+ ```sh
35
+ git rebase --onto origin/main feat/a feat/b
36
+ ```
37
+
38
+ 5. 子のブランチを push する。履歴を書き換えたので `--force-with-lease` を使う(`main` への force push はフックで止まる)
39
+
40
+ ```sh
41
+ git push --force-with-lease origin feat/b
42
+ ```
43
+
44
+ 6. 親のブランチを消す
45
+
46
+ ```sh
47
+ git branch -D feat/a
48
+ git push origin --delete feat/a
49
+ ```
50
+
51
+ ## 多段のスタック
52
+
53
+ `feat/a` ← `feat/b` ← `feat/c` のように重ねている場合は、下から順に1段ずつ行う。`feat/b` を整理してマージしたら、`feat/c` について同じ手順を `feat/b` を親として繰り返す
54
+
55
+ ## 確認
56
+
57
+ - 子の PR の差分に、子の変更だけが出ている(`gh pr diff <子の番号>`)
58
+ - 子の PR の CI が通っている(`gh pr checks <子の番号> --watch`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryusenkei/conventions",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "RYUSENKEI のモノリポの共通の規約(Claude Code の規約・hook、共通ファイルの同期)",
5
5
  "license": "MIT",
6
6
  "author": "RYUSENKEI",
@@ -40,6 +40,14 @@
40
40
  "@types/node": "^26.6.1",
41
41
  "typescript": "^5.9.3"
42
42
  },
43
+ "peerDependencies": {
44
+ "typescript": ">=5.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "typescript": {
48
+ "optional": true
49
+ }
50
+ },
43
51
  "scripts": {
44
52
  "build": "tsc -p tsconfig.build.json",
45
53
  "typecheck": "tsc --noEmit"
package/rules-ts.md CHANGED
@@ -3,7 +3,8 @@
3
3
  - エントリポイントはパッケージごとの `src/index.ts`
4
4
  - TypeScript はビルドせず、Node で直接実行する(`node scripts/x.ts`)
5
5
  - テストは Vitest で書き、対象と同じディレクトリに `*.test.ts` を置く
6
- - 子プロセスは `scripts/lib/exec.ts` の `exec` で起動する。Windows の `.cmd` に対応するため
6
+ - 子プロセスは `@ryusenkei/scripts` の `exec` で起動する。Windows の `.cmd` に対応するため
7
+ - 層の依存の向きは `scripts/lib/deps-rules.ts` に規則を書き、`@ryusenkei/conventions` の `runDepsCheck` で検査する(`pnpm lint` に含める)
7
8
 
8
9
  ## 定数
9
10
 
package/rules.md CHANGED
@@ -10,7 +10,8 @@
10
10
 
11
11
  - 秘密値はルートの `.env` にまとめ、配信は `pnpm env:push` だけで行う
12
12
  - `*.tfvars` と Terraform の state はコミットしない
13
- - `.env.example` に変数を足したら、`scripts/env.ts` の `TARGETS` にも定義する
13
+ - `.env.example` に変数を足したら、`scripts/env.ts` の `targets` にも定義する。`scripts/env.ts` は `@ryusenkei/scripts` の `envCli` に配信先を渡すだけにする
14
+ - Cloudflare のトークンはデプロイ用と Terraform 用に分ける。CI でデプロイしないなら、どちらも GitHub に配信しない
14
15
  - 環境変数を付けて実行するときは `node scripts/env.ts run NAME=value <cmd>` を使う。`NAME=value cmd` は Windows で動かない
15
16
  - YAML の拡張子は `.yaml` にする(pnpm のファイルに合わせる)
16
17
  - 共通ファイル(`.editorconfig`、`.github/dependabot.yaml`、`.claude/settings.json` など)は `@ryusenkei/conventions` から同期するので、直接編集しない。変えるときは toolkit で直し、`ryusenkei-conventions sync` で反映する
@@ -55,6 +56,7 @@
55
56
  - add は変更・追加したファイルをパスで指定する。一括の add はフックで止まる
56
57
  - push の前に `pnpm check` を通す。`check` を持つリポでは pre-push で強制される
57
58
  - PR の本文は背景、変更、検証の順に書く
59
+ - 前の PR のブランチから PR を重ねた場合は、親のマージの後にスキル `stacked-pr` の手順で整理する
58
60
  - マージは squash で、CI の全チェックの成功を確かめてから行う(フックで強制)
59
61
  - epic のフロー(有効にしたリポだけ)
60
62
  - epic ごとに `dev/<issue の番号>-<内容>` を作り、sub-issue の PR は dev のブランチに向ける
@@ -64,6 +66,8 @@
64
66
 
65
67
  ## CI(GitHub Actions)
66
68
 
69
+ - CI は toolkit の再利用可能なワークフロー(`reusable-ci.yaml`、`reusable-pr-title.yaml`)を呼ぶ。リポ独自の検査は入力の `checks` に書き、言語ごとのジョブ(Go、Rust)は呼ぶ側に足す。呼び方は `@ryusenkei/conventions` の README
70
+
67
71
  非公開のリポでは GitHub Free の時間を節約する(上限は組織の合計で月2,000分、ジョブごとに分単位で切り上げて計上)
68
72
 
69
73
  - 実行するのは `main` 行きの PR だけ。マージの結果の ref は PR で検査済みなので、`main` への push では実行しない