@ryusenkei/conventions 0.9.0 → 0.10.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.1
4
+
5
+ - `runAffectedCheck` failed every step on Windows when `npm_execpath` pointed at a standalone `pnpm.exe` (it was started with `node`). It now starts `.js`, `.cjs`, and `.mjs` with `node`, and `.exe` directly.
6
+
7
+ ## 0.10.0
8
+
9
+ - `runAffectedCheck`: the pre-push `pnpm check` from `scripts/check.ts`. It type checks the changed packages and their dependents and runs the tests that import a changed file, against the nearest of `origin/main` and `origin/dev/*`; `--all` checks everything. The type check and the tests run one after the other to keep the peak memory low. See [Pre-push check](README.md#pre-push-check).
10
+ - The `check` script that `check` asks for is now `node scripts/check.ts` with `runAffectedCheck`. Repositories with their own `scripts/check.ts` (zrgn, pcpalette.com) can replace the shared part with it.
11
+ - `pnpm check` records each passing commit in the common git directory, and the hook lets `gh pr merge` through without passing checks when the PR's head passed `pnpm check --base origin/<base>` (or `--all`). A PR doesn't get stuck when CI doesn't run.
12
+ - `reusable-ci.yaml` skips draft PRs, caches the pnpm store, and takes `affected: true` to run `pnpm check --base origin/<base>` instead of the full check. Add `ready_for_review` to the caller's `types` so a PR is checked when it's marked ready.
13
+ - `rules.md`: open PRs to `main` as drafts and mark them ready before merging; run `pnpm check --all` locally before deploying.
14
+
3
15
  ## 0.9.0
4
16
 
5
17
  - `TEST_EXCLUDE` (`.claude/**`, `**/.terraform/**`): patterns to add to Vitest's default `exclude`.
package/README.md CHANGED
@@ -10,6 +10,7 @@ Shared conventions for RYUSENKEI monorepos created from monorepo-template. Rules
10
10
  | `files/` | Master copies of the shared files, synced into each repository |
11
11
  | `ryusenkei-conventions` | CLI: `sync` writes the shared files, `check` reports drift |
12
12
  | `TEST_EXCLUDE` | Patterns to add to Vitest's default `exclude` |
13
+ | `runAffectedCheck` | The pre-push `pnpm check`: type checks and tests only what the change affects |
13
14
 
14
15
  ## Install
15
16
 
@@ -57,7 +58,7 @@ The PreToolUse hook blocks the call and tells Claude why, so Claude can fix it a
57
58
  | PR title = squash commit message | Checks `gh pr create` / `gh pr edit` titles with prose-lint's commit rules |
58
59
  | No AI signature | `attribution` is empty, and the hook blocks PR bodies with an AI signature |
59
60
  | Squash merge | Blocks `gh pr merge --rebase` and `--merge`, also for a `dev/*` → `main` PR with the epic flow |
60
- | 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` |
61
+ | Merge only after CI passes | Blocks `gh pr merge` unless every check of the PR has passed (`gh pr checks`), or the PR's head commit passed the local `pnpm check` against the PR's base (see [Pre-push check](#pre-push-check)). 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` |
61
62
  | Epic flow (opt-in) | See [Epic flow](#epic-flow) |
62
63
  | Do not edit `node_modules` | Blocks Edit and Write under `node_modules` |
63
64
  | Secrets | `permissions.deny` blocks reading `.env` and `.dev.vars` with Claude's file tools (not Bash) |
@@ -108,7 +109,7 @@ Opt in per repository in the root `package.json`:
108
109
 
109
110
  When the `rules.md` import is present, `sync` adds the missing ones right after it.
110
111
 
111
- `check` also reports a missing or incomplete root Vitest config when the root `package.json` depends on `vitest` (see [Vitest](#vitest)), and a root `package.json` without a `check` script, since the pre-push hook runs `pnpm check` and pushes unchecked without one. Add it by hand (for example `pnpm typecheck && pnpm test && pnpm lint:prose && ryusenkei-conventions check`).
112
+ `check` also reports a missing or incomplete root Vitest config when the root `package.json` depends on `vitest` (see [Vitest](#vitest)), and a root `package.json` without a `check` script, since the pre-push hook runs `pnpm check` and pushes unchecked without one. Add it by hand, as `node scripts/check.ts` with [`runAffectedCheck`](#pre-push-check).
112
113
 
113
114
  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.
114
115
 
@@ -137,6 +138,40 @@ export default defineConfig({
137
138
 
138
139
  `ryusenkei-conventions` exits with 0 when nothing drifts, 1 when something does, and 2 for a usage error; `--help` exits with 0.
139
140
 
141
+ ## Pre-push check
142
+
143
+ `runAffectedCheck` runs the type checks and tests a change affects, so a push doesn't wait for the whole repository. Each repository passes its own fast checks:
144
+
145
+ ```ts
146
+ // scripts/check.ts (package.json: "check": "node scripts/check.ts")
147
+ import { runAffectedCheck } from '@ryusenkei/conventions';
148
+
149
+ const results = await runAffectedCheck({
150
+ steps: () => [
151
+ { name: 'prose-lint', command: 'pnpm', args: ['exec', 'prose-lint'] },
152
+ { name: 'conventions', command: 'pnpm', args: ['exec', 'ryusenkei-conventions', 'check'] },
153
+ { name: 'deps', command: 'node', args: ['scripts/deps.ts'] },
154
+ ],
155
+ });
156
+ process.exitCode = results.every((r) => r.ok) ? 0 : 1;
157
+ ```
158
+
159
+ | Scope | What runs |
160
+ | --- | --- |
161
+ | Base | The merge base with the nearest of `origin/main` and `origin/dev/*` (fewest commits to `HEAD`), excluding the branch's own remote. A sub-issue branch is checked against its epic's `dev/*`, and a `dev/*` branch against `main` |
162
+ | Changes | Committed, uncommitted and untracked files since the base. Markdown doesn't count |
163
+ | Type check | `typecheck` of the changed packages and their dependents (`pnpm -r --filter ...<name>`), and the root `tsc` when a `.ts` file outside the packages changed. Packages that import the root `scripts/` count as changed with it |
164
+ | Tests | `vitest run --changed <base>` (tests that import a changed file) |
165
+ | Everything | `pnpm typecheck` and all tests, with `--all`, without a base, or when a root config changed (`package.json`, `pnpm-workspace.yaml`, `tsconfig*.json`, `vitest.config.*`, `mise.toml`, `.npmrc`, or `pnpm-lock.yaml` without a package's `package.json`) |
166
+
167
+ - The type check and the tests run one after the other, and `steps` run beside them. This keeps the peak memory to one heavy process tree, so parallel pushes from other worktrees fit (`concurrency` sets how many packages `tsc` checks at once, default 2).
168
+ - `--base <ref>` sets the base. `globalFiles` adds files that mean everything, and `testArgs` adds Vitest arguments such as reporters.
169
+ - Run it through `pnpm` (`pnpm check`). It starts `pnpm` from `npm_execpath` (`.js` with `node`, `.exe` directly).
170
+
171
+ The whole repository is checked with `pnpm check --all` locally before deploying.
172
+
173
+ When `pnpm check` passes with a clean working tree, it records the commit and the base it checked in the common git directory (`ryusenkei-check/<sha>`). `gh pr merge` accepts a PR without passing checks when its head commit has a record for the PR's base (`origin/<base>`) or for `--all`. So when CI doesn't run (the free minutes ran out, or the workflow is disabled), run `pnpm check --base origin/main` on the PR's head and merge. A push of a `dev/*` branch is checked against `origin/main`, so it records that already.
174
+
140
175
  ## Dependency direction
141
176
 
142
177
  `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:
@@ -180,7 +215,7 @@ name: CI
180
215
  on:
181
216
  pull_request:
182
217
  branches: [main]
183
- types: [opened, synchronize, reopened]
218
+ types: [opened, synchronize, reopened, ready_for_review]
184
219
  concurrency:
185
220
  group: ci-${{ github.ref }}
186
221
  cancel-in-progress: true
@@ -194,6 +229,9 @@ jobs:
194
229
  pnpm lint:deps
195
230
  ```
196
231
 
232
+ - The job is skipped while the PR is a draft and runs when it is marked ready (`ready_for_review`), to save the free minutes.
233
+ - `affected: true` runs `pnpm check --base origin/<base>` ([Pre-push check](#pre-push-check)) instead of the full type check, tests and prose-lint. Use it where the full check takes too long for the free minutes; the full check then runs locally before deploying.
234
+
197
235
  Go, with releases on `v*` tags:
198
236
 
199
237
  ```yaml
@@ -0,0 +1,40 @@
1
+ export type CheckStep = {
2
+ name: string;
3
+ command: string;
4
+ args: string[];
5
+ };
6
+ export type CheckContext = {
7
+ base: string | undefined;
8
+ changed: string[];
9
+ full: boolean;
10
+ };
11
+ export type CheckResult = {
12
+ name: string;
13
+ ok: boolean;
14
+ output: string;
15
+ };
16
+ export type AffectedCheckOptions = {
17
+ /** GLOBAL_FILES に足す、変更されたらすべてを検査するファイル */
18
+ globalFiles?: (string | RegExp)[];
19
+ /** 型検査・テストと並列に実行する軽い検査(数秒で終わる、全体にかかるもの) */
20
+ steps?: (ctx: CheckContext) => CheckStep[];
21
+ /** vitest に足す引数(reporter など) */
22
+ testArgs?: string[];
23
+ /** 型検査で同時に動かすパッケージの数(`pnpm -r --workspace-concurrency`) */
24
+ concurrency?: number;
25
+ };
26
+ /**
27
+ * 起動するファイルと引数(pnpm は実行中の pnpm の npm_execpath から)
28
+ * - .js・.cjs・.mjs は node で起動、.exe は直接、.cmd・.bat はシェル経由(単体の pnpm.exe を指す場合があるため)
29
+ */
30
+ export declare function spawnTarget(command: string, args: string[], execpath?: string | undefined): {
31
+ file: string;
32
+ argv: string[];
33
+ shell: boolean;
34
+ };
35
+ /**
36
+ * リポのルートで push の前の検査を実行し、結果を返す(終了コードは呼ぶ側が設定)
37
+ * - 引数: `--all` ですべて、`--base <ref>` で基準を指定(省略時は origin/main と origin/dev/* のうち最も近いもの)
38
+ * - 成功し、作業ツリーに変更がなければ HEAD の検査の記録を書く(check-record.ts)
39
+ */
40
+ export declare function runAffectedCheck(options?: AffectedCheckOptions, argv?: string[]): Promise<CheckResult[]>;
@@ -0,0 +1,128 @@
1
+ // push の前の検査の実行(各リポの scripts/check.ts から呼ぶ、範囲の決定は affected.ts)
2
+ // - pnpm check: 基準(PR の向き先との分岐点)からの変更(コミット済み・作業中・未追跡)に絞って型検査とテスト
3
+ // - pnpm check --all: すべて(デプロイの前)
4
+ // - 重い検査(型検査・テスト)は順に、軽い検査はそれと並列に実行(push の前のメモリのピークを1つの重い検査に抑えるため)
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { GLOBAL_FILES, nearestBase, scopeOf } from "./affected.js";
8
+ import { writeCheckRecord } from "./check-record.js";
9
+ import { workspaceDirs } from "./deps-check.js";
10
+ const git = (args) => {
11
+ const r = spawnSync('git', ['-c', 'core.quotepath=off', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
12
+ return r.status === 0 ? r.stdout.trim() : null;
13
+ };
14
+ const lines = (text) => (text ?? '').split('\n').filter(Boolean);
15
+ const nameOf = (dir) => JSON.parse(readFileSync(`${dir}/package.json`, 'utf8')).name;
16
+ function candidates() {
17
+ const branch = git(['branch', '--show-current']);
18
+ const refs = ['origin/main', ...lines(git(['for-each-ref', '--format=%(refname:short)', 'refs/remotes/origin/dev/'])).filter((r) => r !== `origin/${branch}`)];
19
+ return refs.flatMap((ref) => {
20
+ const mergeBase = git(['merge-base', 'HEAD', ref]);
21
+ const ahead = mergeBase === null ? null : git(['rev-list', '--count', `${mergeBase}..HEAD`]);
22
+ return mergeBase === null || ahead === null ? [] : [{ ref, mergeBase, ahead: Number(ahead) }];
23
+ });
24
+ }
25
+ function baseOf(argv) {
26
+ const i = argv.indexOf('--base');
27
+ if (i === -1)
28
+ return nearestBase(candidates());
29
+ const ref = argv[i + 1];
30
+ const mergeBase = git(['merge-base', 'HEAD', ref]);
31
+ return mergeBase === null ? undefined : { ref, mergeBase };
32
+ }
33
+ /** 検査の計画(表示する行と、重い検査・軽い検査) */
34
+ function planOf(options, argv) {
35
+ const { globalFiles = [], testArgs = [], concurrency = 2 } = options;
36
+ const all = argv.includes('--all');
37
+ const base = all ? undefined : baseOf(argv);
38
+ const changed = base === undefined ? [] : [...new Set([...lines(git(['diff', '--name-only', base.mergeBase])), ...lines(git(['ls-files', '--others', '--exclude-standard']))])];
39
+ const dirs = workspaceDirs();
40
+ const scriptsChanged = changed.some((f) => f.startsWith('scripts/'));
41
+ // ルートの scripts/ を相対パスで import するパッケージ(apps/api/scripts など)は、scripts/ の変更で型の検査の結果に影響
42
+ const importers = scriptsChanged && dirs.length > 0 ? lines(git(['grep', '-l', '-E', String.raw `from '(\.\./)+scripts/`, '--', ...dirs])) : [];
43
+ const scope = base === undefined ? { full: true, reason: all ? '--all' : 'no base (origin/main or origin/dev/*)' } : scopeOf(changed, dirs, importers, [...GLOBAL_FILES, ...globalFiles]);
44
+ const vitest = (args) => ({ name: 'test', command: 'pnpm', args: ['exec', 'vitest', 'run', '--passWithNoTests', ...args, ...testArgs] });
45
+ const ctx = { base: base?.mergeBase, changed, full: scope.full };
46
+ if (scope.full)
47
+ return { plan: [`all (${scope.reason})`], heavy: [{ name: 'typecheck', command: 'pnpm', args: ['typecheck'] }, vitest([])], ctx, covered: 'all' };
48
+ const sha = base.mergeBase.slice(0, 7);
49
+ const plan = [`base: ${base.ref} (merge base ${sha}), ${changed.length} changed files`];
50
+ const heavy = [];
51
+ const names = scope.dirs.map(nameOf).sort();
52
+ if (names.length > 0) {
53
+ plan.push(`typecheck: ${names.join(', ')} and dependents`);
54
+ heavy.push({ name: 'typecheck (packages)', command: 'pnpm', args: ['-r', '--if-present', `--workspace-concurrency=${concurrency}`, ...names.flatMap((n) => ['--filter', `...${n}`]), 'typecheck'] });
55
+ }
56
+ if (scope.root && existsSync('tsconfig.json')) {
57
+ plan.push('typecheck: root (tsc)');
58
+ heavy.push({ name: 'typecheck (root)', command: 'pnpm', args: ['exec', 'tsc'] });
59
+ }
60
+ if (heavy.length === 0)
61
+ plan.push('typecheck: none');
62
+ if (scope.tests) {
63
+ plan.push(`test: related to changes (vitest --changed ${sha})`);
64
+ heavy.push(vitest(['--changed', base.mergeBase]));
65
+ }
66
+ else
67
+ plan.push('test: none (Markdown only)');
68
+ return { plan, heavy, ctx, covered: base.ref };
69
+ }
70
+ const seconds = (from) => `${((Date.now() - from) / 1000).toFixed(1)}s`;
71
+ /**
72
+ * 起動するファイルと引数(pnpm は実行中の pnpm の npm_execpath から)
73
+ * - .js・.cjs・.mjs は node で起動、.exe は直接、.cmd・.bat はシェル経由(単体の pnpm.exe を指す場合があるため)
74
+ */
75
+ export function spawnTarget(command, args, execpath = process.env.npm_execpath) {
76
+ if (command !== 'pnpm' || !execpath)
77
+ return { file: command, argv: args, shell: false };
78
+ if (/\.[cm]?js$/i.test(execpath))
79
+ return { file: process.execPath, argv: [execpath, ...args], shell: false };
80
+ return { file: execpath, argv: args, shell: /\.(cmd|bat)$/i.test(execpath) };
81
+ }
82
+ function capture(command, args) {
83
+ const { file, argv, shell } = spawnTarget(command, args);
84
+ return new Promise((resolve) => {
85
+ const child = spawn(file, argv, { stdio: ['ignore', 'pipe', 'pipe'], shell });
86
+ let output = '';
87
+ child.stdout.on('data', (chunk) => (output += chunk.toString()));
88
+ child.stderr.on('data', (chunk) => (output += chunk.toString()));
89
+ child.on('close', (status) => resolve({ status: status ?? 1, output }));
90
+ child.on('error', (error) => resolve({ status: 1, output: `${output}${error.message}\n` }));
91
+ });
92
+ }
93
+ async function run(step) {
94
+ const from = Date.now();
95
+ const { status, output } = await capture(step.command, step.args);
96
+ console.log(`\n${status === 0 ? '[ok]' : '[failed]'} ${step.name} (${seconds(from)})`);
97
+ if (status !== 0)
98
+ console.log(output.trimEnd());
99
+ return { name: step.name, ok: status === 0, output };
100
+ }
101
+ /**
102
+ * リポのルートで push の前の検査を実行し、結果を返す(終了コードは呼ぶ側が設定)
103
+ * - 引数: `--all` ですべて、`--base <ref>` で基準を指定(省略時は origin/main と origin/dev/* のうち最も近いもの)
104
+ * - 成功し、作業ツリーに変更がなければ HEAD の検査の記録を書く(check-record.ts)
105
+ */
106
+ export async function runAffectedCheck(options = {}, argv = process.argv.slice(2)) {
107
+ const { plan, heavy, ctx, covered } = planOf(options, argv);
108
+ const light = options.steps?.(ctx) ?? [];
109
+ if (light.length > 0)
110
+ plan.push(`${light.map((s) => s.name).join(', ')}: all`);
111
+ console.log(['pnpm check', ...plan.map((p) => `- ${p}`)].join('\n'));
112
+ const started = Date.now();
113
+ const sequential = async () => {
114
+ const results = [];
115
+ for (const step of heavy)
116
+ results.push(await run(step));
117
+ return results;
118
+ };
119
+ const [heavyResults, lightResults] = await Promise.all([sequential(), Promise.all(light.map(run))]);
120
+ const results = [...heavyResults, ...lightResults];
121
+ const failed = results.filter((r) => !r.ok).length;
122
+ console.log(`\n${failed === 0 ? 'all passed' : `${failed} check(s) failed`} (${seconds(started)})`);
123
+ const commonDir = git(['rev-parse', '--path-format=absolute', '--git-common-dir']);
124
+ const head = git(['rev-parse', 'HEAD']);
125
+ if (failed === 0 && commonDir && head && git(['status', '--porcelain']) === '')
126
+ writeCheckRecord(commonDir, head, covered);
127
+ return results;
128
+ }
@@ -0,0 +1,32 @@
1
+ /** 変更されたらすべてを検査するルートのファイル(依存の解決・テスト・TypeScript の設定など、影響の範囲を辿れないもの) */
2
+ export declare const GLOBAL_FILES: (string | RegExp)[];
3
+ export type Candidate = {
4
+ ref: string;
5
+ mergeBase: string;
6
+ ahead: number;
7
+ };
8
+ /**
9
+ * 基準: PR の向き先として最も近いもの(分岐点から HEAD までのコミットが最も少ない候補、同数なら先の候補)
10
+ * 候補は origin/main と epic の origin/dev/*。sub-issue のブランチは dev のブランチが、dev のブランチ自体は main が基準になる
11
+ */
12
+ export declare function nearestBase(candidates: Candidate[]): Candidate | undefined;
13
+ export type Scope = {
14
+ full: true;
15
+ reason: string;
16
+ } | {
17
+ full: false;
18
+ dirs: string[];
19
+ root: boolean;
20
+ tests: boolean;
21
+ };
22
+ /**
23
+ * 変更から検査の範囲を決定
24
+ * @param dirs ワークスペースのパッケージのディレクトリ
25
+ * @param importers ルートの scripts/ を import するファイル(scripts/ の変更で型の検査の結果が変わる)
26
+ * - pnpm-lock.yaml: package.json を変えたパッケージの依存の追加として扱い、どのパッケージの package.json も変わっていなければすべて
27
+ * - root: パッケージの外の .ts の変更(ルートの tsc の対象)
28
+ * - Markdown の変更は型検査・テストの対象にしない
29
+ */
30
+ export declare function scopeOf(changed: string[], dirs: string[], importers: string[], globalFiles: (string | RegExp)[]): Scope;
31
+ /** ファイルを含むワークスペースのパッケージ(最も深いディレクトリ、どれにも含まれなければ undefined) */
32
+ export declare function packageDirOf(dirs: string[], file: string): string | undefined;
@@ -0,0 +1,38 @@
1
+ // push の前の検査の範囲の決定(純粋な関数、実行は affected-check.ts)
2
+ /** 変更されたらすべてを検査するルートのファイル(依存の解決・テスト・TypeScript の設定など、影響の範囲を辿れないもの) */
3
+ export const GLOBAL_FILES = ['package.json', 'pnpm-workspace.yaml', 'mise.toml', '.npmrc', /^vitest\.config\.[cm]?[jt]s$/, /^tsconfig(\.[\w-]+)?\.json$/];
4
+ /**
5
+ * 基準: PR の向き先として最も近いもの(分岐点から HEAD までのコミットが最も少ない候補、同数なら先の候補)
6
+ * 候補は origin/main と epic の origin/dev/*。sub-issue のブランチは dev のブランチが、dev のブランチ自体は main が基準になる
7
+ */
8
+ export function nearestBase(candidates) {
9
+ return candidates.reduce((best, c) => (best === undefined || c.ahead < best.ahead ? c : best), undefined);
10
+ }
11
+ /**
12
+ * 変更から検査の範囲を決定
13
+ * @param dirs ワークスペースのパッケージのディレクトリ
14
+ * @param importers ルートの scripts/ を import するファイル(scripts/ の変更で型の検査の結果が変わる)
15
+ * - pnpm-lock.yaml: package.json を変えたパッケージの依存の追加として扱い、どのパッケージの package.json も変わっていなければすべて
16
+ * - root: パッケージの外の .ts の変更(ルートの tsc の対象)
17
+ * - Markdown の変更は型検査・テストの対象にしない
18
+ */
19
+ export function scopeOf(changed, dirs, importers, globalFiles) {
20
+ const hit = changed.find((f) => globalFiles.some((g) => (typeof g === 'string' ? f === g : g.test(f))));
21
+ if (hit !== undefined)
22
+ return { full: true, reason: `${hit} changed` };
23
+ const manifests = changed.filter((f) => dirs.some((d) => f === `${d}/package.json`));
24
+ if (changed.includes('pnpm-lock.yaml') && manifests.length === 0)
25
+ return { full: true, reason: 'pnpm-lock.yaml changed without a package.json' };
26
+ const code = changed.filter((f) => !f.endsWith('.md'));
27
+ const affected = [...code, ...importers].map((f) => packageDirOf(dirs, f)).filter((d) => d !== undefined);
28
+ return {
29
+ full: false,
30
+ dirs: [...new Set(affected)].sort(),
31
+ root: code.some((f) => packageDirOf(dirs, f) === undefined && /\.[cm]?tsx?$/.test(f)),
32
+ tests: code.length > 0,
33
+ };
34
+ }
35
+ /** ファイルを含むワークスペースのパッケージ(最も深いディレクトリ、どれにも含まれなければ undefined) */
36
+ export function packageDirOf(dirs, file) {
37
+ return dirs.filter((dir) => file.startsWith(`${dir}/`)).sort((a, b) => b.length - a.length)[0];
38
+ }
@@ -0,0 +1,4 @@
1
+ export declare function writeCheckRecord(commonDir: string, sha: string, covered: string): void;
2
+ export declare function readCheckRecord(commonDir: string, sha: string): string | undefined;
3
+ /** PR の base に向けた検査として足りるか(`origin/<base>` を基準にした検査か、すべての検査) */
4
+ export declare const coversBase: (covered: string | undefined, base: string) => boolean;
@@ -0,0 +1,20 @@
1
+ // 手元の検査の記録(CI が走らない・止まったときに、gh pr merge の関門を手元の検査で通すため)
2
+ // - pnpm check が成功し、作業ツリーに変更がないときに HEAD のコミットごとに書く。中身は検査した範囲(基準の ref、すべてなら `all`)
3
+ // - 置き場は git の共通のディレクトリ(worktree をまたいで1つ、追跡しない)
4
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ const dirOf = (commonDir) => join(commonDir, 'ryusenkei-check');
7
+ export function writeCheckRecord(commonDir, sha, covered) {
8
+ mkdirSync(dirOf(commonDir), { recursive: true });
9
+ writeFileSync(join(dirOf(commonDir), sha), `${covered}\n`);
10
+ }
11
+ export function readCheckRecord(commonDir, sha) {
12
+ try {
13
+ return readFileSync(join(dirOf(commonDir), sha), 'utf8').trim();
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ /** PR の base に向けた検査として足りるか(`origin/<base>` を基準にした検査か、すべての検査) */
20
+ export const coversBase = (covered, base) => covered === 'all' || covered === `origin/${base}`;
package/dist/hook.js CHANGED
@@ -8,13 +8,14 @@ import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'n
8
8
  import { homedir, tmpdir } from 'node:os';
9
9
  import { isAbsolute, join, resolve } from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
+ import { readCheckRecord } from "./check-record.js";
11
12
  import { denyReason } from "./policy.js";
12
13
  const input = JSON.parse(readFileSync(0, 'utf8'));
13
14
  const root = process.env.CLAUDE_PROJECT_DIR ?? input.cwd ?? process.cwd();
14
15
  // Windows の `pnpm` は `.cmd` → シェル経由でのみ起動可能
15
16
  const shell = process.platform === 'win32';
16
17
  if (input.hook_event_name === 'PreToolUse') {
17
- const reason = denyReason(input, { root, repoRoot, resolveDir, titleIssues, readFile, currentBranch, prHead, prBase, hasPrWorkflow, prChecks });
18
+ const reason = denyReason(input, { root, repoRoot, resolveDir, titleIssues, readFile, currentBranch, prHead, prBase, hasPrWorkflow, prChecks, localCheck });
18
19
  if (reason) {
19
20
  process.stderr.write(`${reason}\n`);
20
21
  process.exit(2);
@@ -70,6 +71,11 @@ function prBase(pr, cwd) {
70
71
  const r = spawnSync('gh', ['pr', 'view', ...(pr ? [pr] : []), '--json', 'baseRefName', '--jq', '.baseRefName'], { cwd: cwd ?? root, encoding: 'utf8' });
71
72
  return (r.status === 0 && r.stdout.trim()) || undefined;
72
73
  }
74
+ function localCheck(pr, cwd) {
75
+ const sha = spawnSync('gh', ['pr', 'view', ...(pr ? [pr] : []), '--json', 'headRefOid', '--jq', '.headRefOid'], { cwd: cwd ?? root, encoding: 'utf8' }).stdout?.trim();
76
+ const commonDir = spawnSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: cwd ?? root, encoding: 'utf8' }).stdout?.trim();
77
+ return sha && commonDir ? readCheckRecord(commonDir, sha) : undefined;
78
+ }
73
79
  // GitHub で無効にしたワークフローはチェックを出さない → 有効なものだけを数える
74
80
  // 読めなければ「ある」とみなす(チェックなしのマージを許可しない側に倒す)
75
81
  function hasPrWorkflow(cwd) {
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ export { drifts, sync, IMPORT, type Drift } from './files.ts';
2
2
  export { runDepsCheck } from './deps-check.ts';
3
3
  export type { Exception, Rule } from './deps.ts';
4
4
  export { TEST_EXCLUDE } from './test-exclude.ts';
5
+ export { runAffectedCheck, type AffectedCheckOptions, type CheckContext, type CheckResult, type CheckStep } from './affected-check.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { drifts, sync, IMPORT } from "./files.js";
2
2
  export { runDepsCheck } from "./deps-check.js";
3
3
  export { TEST_EXCLUDE } from "./test-exclude.js";
4
+ export { runAffectedCheck } from "./affected-check.js";
package/dist/policy.d.ts CHANGED
@@ -28,6 +28,8 @@ export type Context = {
28
28
  hasPrWorkflow: (cwd: string | undefined) => boolean;
29
29
  /** PR のチェックの集計(`pr` の省略時は現在のブランチの PR) */
30
30
  prChecks: (pr: string | undefined, cwd: string | undefined) => Checks;
31
+ /** PR の head のコミットで手元の `pnpm check` が通った範囲(check-record.ts、記録がなければ `undefined`) */
32
+ localCheck: (pr: string | undefined, cwd: string | undefined) => string | undefined;
31
33
  };
32
34
  /** 拒否の理由(許可する場合は `undefined`) */
33
35
  export declare function denyReason(use: ToolUse, ctx: Context): string | undefined;
package/dist/policy.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // - 拒否の理由は Claude に返却 → Claude が修正して再実行
4
4
  // - 対象のリポ・ブランチはコマンドから解決: `cd`・`git -C` の後はその git のルート、ブランチの切り替えの後はその先のブランチ
5
5
  import { isAbsolute, join } from 'node:path';
6
+ import { coversBase } from "./check-record.js";
6
7
  import { commands, option } from "./shell.js";
7
8
  const TYPES = ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'];
8
9
  const BRANCH = new RegExp(`^(${TYPES.join('|')})/[a-z0-9][a-z0-9._-]*$`);
@@ -236,6 +237,7 @@ function prReasons(sub, args, st, ctx) {
236
237
  // `--auto` も対象(必須のチェックがないリポでは即時にマージされる)
237
238
  // - マージは常に squash(org のリポの設定が squash だけを許可。epic のフローの dev/* から main へも同じ)
238
239
  // - epic のフローの dev/* への PR: チェックなしを許可(CI を実行せず pre-push の `pnpm check` が関門)
240
+ // - CI が通っていなくても、PR の head で base に向けた手元の `pnpm check` が通っていれば許可(無料枠の超過などで CI が走らないときに詰まらないため)
239
241
  function mergeReasons(args, st, ctx) {
240
242
  const { cwd } = st;
241
243
  if (args.some((a) => a === '--rebase' || a === '-r'))
@@ -249,12 +251,12 @@ function mergeReasons(args, st, ctx) {
249
251
  // PR で動く有効なワークフローがないリポ: CI の代わりに pre-push の `pnpm check` が関門
250
252
  if (checks === 'none' && !ctx.hasPrWorkflow(cwd))
251
253
  return [];
252
- if (checks === 'none' && epicFlow(st, ctx)) {
253
- const base = ctx.prBase(pr, cwd);
254
- if (base !== undefined && DEV_BRANCH.test(base))
255
- return [];
256
- }
257
- return [CHECKS_REASON[checks]];
254
+ const base = ctx.prBase(pr, cwd);
255
+ if (checks === 'none' && epicFlow(st, ctx) && base !== undefined && DEV_BRANCH.test(base))
256
+ return [];
257
+ if (base !== undefined && coversBase(ctx.localCheck(pr, cwd), base))
258
+ return [];
259
+ return [`${CHECKS_REASON[checks]}。CI が走らない・止まったときは、PR の head のコミットで手元の \`pnpm check --base origin/${base ?? 'main'}\` を通すとマージできる`];
258
260
  }
259
261
  // epic のフロー: main への PR は dev/* から、それ以外のブランチの PR は dev/* へ
260
262
  // - `gh pr create` の base の省略 = main(既定のブランチ)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryusenkei/conventions",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "RYUSENKEI のモノリポの共通の規約(Claude Code の規約・hook、共通ファイルの同期)",
5
5
  "license": "MIT",
6
6
  "author": "RYUSENKEI",
package/rules.md CHANGED
@@ -57,9 +57,12 @@
57
57
 
58
58
  - add は変更・追加したファイルをパスで指定する。一括の add はフックで止まる
59
59
  - push の前に `pnpm check` を通す。pre-push で強制される(`check` の script はどのリポにも置く)
60
+ - `pnpm check` は PR の向き先(`origin/main` か epic の `origin/dev/*`)からの変更の影響の範囲だけを検査する。全体の検査の `pnpm check --all` はデプロイの前に手元で回す
60
61
  - PR の本文は背景、変更、検証の順に書く
61
62
  - 前の PR のブランチから PR を重ねた場合は、親のマージの後にスキル `stacked-pr` の手順で整理する
62
63
  - マージは squash で、CI の全チェックの成功を確かめてから行う(フックで強制)
64
+ - `main` 行きの PR は draft で作り、マージの前に ready にする。CI は ready の PR だけで回る(GitHub Actions の無料枠の節約)
65
+ - CI が走らない・止まったとき(無料枠の超過など)は、PR の head のコミットで手元の `pnpm check --base origin/<base>` を通せばマージできる
63
66
  - epic のフロー(有効にしたリポだけ)
64
67
  - epic ごとに `dev/<issue の番号>-<内容>` を作り、sub-issue の PR は dev のブランチに向ける
65
68
  - dev のブランチへのマージに CI は使わず、pre-push の `pnpm check` を関門にする。チェックがある場合は成功が必要