From 7883928a26b960acf0602fc3692eeb08ed485d47 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 21:04:50 +0900 Subject: [PATCH 1/5] 142: add PR diff guard for newly added Python scripts and ADR exceptions --- .github/workflows/eval-controls.yml | 5 + package.json | 1 + scripts/quality/check-new-python.mts | 298 ++++++++++++++++++ scripts/quality/check-new-python.test.mts | 139 ++++++++ skills/quality-gate/SKILL.md | 2 +- .../references/new-python-guard.md | 28 ++ 6 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 scripts/quality/check-new-python.mts create mode 100644 scripts/quality/check-new-python.test.mts create mode 100644 skills/quality-gate/references/new-python-guard.md diff --git a/.github/workflows/eval-controls.yml b/.github/workflows/eval-controls.yml index d495dc1..28f2b9f 100644 --- a/.github/workflows/eval-controls.yml +++ b/.github/workflows/eval-controls.yml @@ -10,6 +10,8 @@ jobs: contents: read steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - uses: actions/setup-node@v4 with: node-version: '22' @@ -22,6 +24,9 @@ jobs: run: shellcheck --version - name: Check whole-repository analysis and references run: bun run quality:structure + - name: Reject newly added Python scripts on PR diff + if: github.event_name == 'pull_request' + run: node scripts/quality/check-new-python.mts --base "${{ github.event.pull_request.base.sha }}" --head "${{ github.event.pull_request.head.sha }}" - name: Test quality checks and challenge executor run: bun run test:system-quality - name: Challenge actual repository checks diff --git a/package.json b/package.json index 7194fe6..0dace3e 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "delivery-status": "node scripts/delivery-status/delivery-status.mts", "test:supervisor-boundary": "node --test templates/supervisor-boundary/guard.test.mts", "quality:structure": "node scripts/quality/check.mts", + "test:new-python": "node --test scripts/quality/check-new-python.test.mts", "test:system-quality": "node --test evals/system-quality/*.test.mts evals/code-structure/*.test.mts scripts/quality/*.test.mts", "quality:challenge": "node evals/system-quality/challenge.mts" }, diff --git a/scripts/quality/check-new-python.mts b/scripts/quality/check-new-python.mts new file mode 100644 index 0000000..c826f5c --- /dev/null +++ b/scripts/quality/check-new-python.mts @@ -0,0 +1,298 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const POLICY_REFERENCE = "docs/adr/ADR-0001.md#11-tooling-conventions"; + +export interface DiffEntry { + readonly status: string; + readonly path: string; + readonly firstLine?: string; +} + +export interface PythonException { + readonly paths: readonly string[]; + readonly adr: string; + readonly reason: string; + readonly alternatives: string; + readonly sunsetCondition: string; +} + +export interface Violation { + readonly code: "NEW_PYTHON_FILE" | "NEW_PYTHON_SHEBANG" | "INVALID_EXCEPTION"; + readonly path: string; + readonly detail: string; + readonly policy: string; +} + +export interface CheckResult { + readonly status: "PASS" | "FAIL"; + readonly checkedAddedFiles: number; + readonly exemptedFiles: readonly string[]; + readonly violations: readonly Violation[]; +} + +const PYTHON_EXTENSION = /\.py[wi]?$/i; +const PYTHON_SHEBANG = + /^#!\s*(?:\/usr\/bin\/env\s+(?:-\S+\s+)*python(?:\d+(?:\.\d+)?)?|\/[^\s]*\/python(?:\d+(?:\.\d+)?)?)(?:\s|$)/; + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function nonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +export function hasPythonExtension(filePath: string): boolean { + return PYTHON_EXTENSION.test(filePath); +} + +export function hasPythonShebang(firstLine: string | undefined): boolean { + if (!firstLine) return false; + return PYTHON_SHEBANG.test(firstLine.trimEnd()); +} + +export function loadExceptions( + root: string, + exceptionsPath: string, +): { exceptions: PythonException[]; errors: Violation[] } { + const absolute = resolve(root, exceptionsPath); + if (!existsSync(absolute)) { + return { exceptions: [], errors: [] }; + } + const errors: Violation[] = []; + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(absolute, "utf8")) as unknown; + } catch (error) { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: exceptionsPath, + detail: `malformed exception manifest: ${error instanceof Error ? error.message : String(error)}`, + policy: POLICY_REFERENCE, + }, + ], + }; + } + if (!isRecord(parsed) || !Array.isArray(parsed.exceptions)) { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: exceptionsPath, + detail: 'exception manifest must contain an "exceptions" array', + policy: POLICY_REFERENCE, + }, + ], + }; + } + + const valid: PythonException[] = []; + for (const [index, raw] of parsed.exceptions.entries()) { + const label = `${exceptionsPath}#exceptions[${index}]`; + if (!isRecord(raw)) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: "exception entry must be an object", + policy: POLICY_REFERENCE, + }); + continue; + } + const paths = Array.isArray(raw.paths) + ? raw.paths.filter((p): p is string => nonEmptyString(p)) + : []; + if ( + paths.length === 0 || + paths.length !== (Array.isArray(raw.paths) ? raw.paths.length : -1) || + !nonEmptyString(raw.adr) || + !nonEmptyString(raw.reason) || + !nonEmptyString(raw.alternatives) || + !nonEmptyString(raw.sunsetCondition) + ) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: + "exception requires non-empty paths[], adr, reason, alternatives, and sunsetCondition", + policy: POLICY_REFERENCE, + }); + continue; + } + const adrAbs = resolve(root, raw.adr); + if (!existsSync(adrAbs) || !statSync(adrAbs).isFile()) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: `approved ADR file not found: ${raw.adr}`, + policy: POLICY_REFERENCE, + }); + continue; + } + valid.push({ + paths, + adr: raw.adr, + reason: raw.reason, + alternatives: raw.alternatives, + sunsetCondition: raw.sunsetCondition, + }); + } + return { exceptions: valid, errors }; +} + +export function evaluateAddedFiles( + entries: readonly DiffEntry[], + exceptions: readonly PythonException[] = [], + exceptionErrors: readonly Violation[] = [], +): CheckResult { + const violations: Violation[] = [...exceptionErrors]; + const exemptedFiles: string[] = []; + const allowedPaths = new Set(); + for (const ex of exceptions) { + for (const p of ex.paths) allowedPaths.add(p.replaceAll("\\", "/")); + } + + let checkedAddedFiles = 0; + for (const entry of entries) { + const normalizedStatus = entry.status.trim().toUpperCase(); + // Only newly added files ('A' or copy 'C*') are inspected; edits ('M') to + // pre-existing Python files are out of scope for ADR-0001 §11. + if (!normalizedStatus.startsWith("A") && !normalizedStatus.startsWith("C")) { + continue; + } + checkedAddedFiles++; + const normalizedPath = entry.path.replaceAll("\\", "/"); + const extMatch = hasPythonExtension(normalizedPath); + const shebangMatch = !extMatch && hasPythonShebang(entry.firstLine); + if (!extMatch && !shebangMatch) continue; + + if (allowedPaths.has(normalizedPath)) { + exemptedFiles.push(normalizedPath); + continue; + } + + violations.push({ + code: extMatch ? "NEW_PYTHON_FILE" : "NEW_PYTHON_SHEBANG", + path: normalizedPath, + detail: extMatch + ? "newly added Python file violates ADR-0001 §11 (new Python scripts prohibited unless backed by an approved project-local ADR exception)" + : "newly added file with Python shebang violates ADR-0001 §11 (new Python scripts prohibited unless backed by an approved project-local ADR exception)", + policy: POLICY_REFERENCE, + }); + } + + return { + status: violations.length > 0 ? "FAIL" : "PASS", + checkedAddedFiles, + exemptedFiles, + violations, + }; +} + +function readFirstLineFromGit(root: string, ref: string, path: string): string | undefined { + try { + const content = execFileSync("git", ["show", `${ref}:${path}`], { + cwd: root, + encoding: "utf8", + maxBuffer: 1024 * 1024, + stdio: ["ignore", "pipe", "pipe"], + }); + const idx = content.indexOf("\n"); + return idx === -1 ? content : content.slice(0, idx); + } catch { + return undefined; + } +} + +export function collectGitDiffEntries( + root: string, + baseRef: string, + headRef: string, +): DiffEntry[] { + const output = execFileSync( + "git", + ["diff", "--name-status", "--no-renames", `${baseRef}...${headRef}`], + { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }, + ); + const entries: DiffEntry[] = []; + for (const rawLine of output.split(/\r?\n/)) { + if (!rawLine.trim()) continue; + const parts = rawLine.split("\t"); + const status = parts[0] ?? ""; + const filePath = parts[parts.length - 1] ?? ""; + if (!filePath) continue; + const isAdded = status.startsWith("A") || status.startsWith("C"); + const firstLine = + isAdded && !hasPythonExtension(filePath) + ? readFirstLineFromGit(root, headRef, filePath) + : undefined; + entries.push({ status, path: filePath, firstLine }); + } + return entries; +} + +interface CliArgs { + root: string; + base: string; + head: string; + exceptionsPath: string; +} + +function parseCliArgs(argv: readonly string[]): CliArgs { + const args: CliArgs = { + root: ".", + base: "HEAD~1", + head: "HEAD", + exceptionsPath: ".config/python-exceptions.json", + }; + for (let i = 0; i < argv.length; i++) { + const flag = argv[i]; + const next = argv[i + 1]; + if (flag === "--root" && next) { + args.root = next; + i++; + } else if (flag === "--base" && next) { + args.base = next; + i++; + } else if (flag === "--head" && next) { + args.head = next; + i++; + } else if (flag === "--exceptions" && next) { + args.exceptionsPath = next; + i++; + } else { + throw new Error(`unknown or incomplete argument: ${flag}`); + } + } + return args; +} + +function main(argv: readonly string[]): number { + let args: CliArgs; + try { + args = parseCliArgs(argv); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + return 2; + } + const root = resolve(args.root); + const { exceptions, errors } = loadExceptions(root, args.exceptionsPath); + const entries = collectGitDiffEntries(root, args.base, args.head); + const result = evaluateAddedFiles(entries, exceptions, errors); + console.log(JSON.stringify(result, null, 2)); + return result.status === "PASS" ? 0 : 1; +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/scripts/quality/check-new-python.test.mts b/scripts/quality/check-new-python.test.mts new file mode 100644 index 0000000..e21265e --- /dev/null +++ b/scripts/quality/check-new-python.test.mts @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { + collectGitDiffEntries, + evaluateAddedFiles, + loadExceptions, + POLICY_REFERENCE, +} from "./check-new-python.mts"; + +function withTempRepo(fn: (dir: string) => void): void { + const dir = mkdtempSync(join(tmpdir(), "new-python-guard-")); + try { + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); + execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: dir }); + execFileSync("git", ["config", "user.name", "Test User"], { cwd: dir }); + fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function commitFile(dir: string, relPath: string, content: string, message: string): void { + const full = join(dir, relPath); + mkdirSync(join(full, ".."), { recursive: true }); + writeFileSync(full, content, "utf8"); + execFileSync("git", ["add", relPath], { cwd: dir }); + execFileSync("git", ["commit", "-q", "-m", message], { cwd: dir }); +} + +test("negative fixture (pc-setup PR #147 shape): newly added .py files fail with ADR-0001 citation", () => { + const result = evaluateAddedFiles([ + { status: "A", path: "platforms/ubuntu-wsl/worker-runtime.py" }, + { status: "A", path: "scripts/test-worker-runtime.py" }, + ]); + assert.equal(result.status, "FAIL"); + assert.equal(result.violations.length, 2); + assert.deepEqual( + result.violations.map((v) => v.code), + ["NEW_PYTHON_FILE", "NEW_PYTHON_FILE"], + ); + assert.ok(result.violations.every((v) => v.policy === POLICY_REFERENCE)); +}); + +test("negative fixture: extensionless file with python shebang fails", () => { + const result = evaluateAddedFiles([ + { + status: "A", + path: "scripts/bootstrap-helper", + firstLine: "#!/usr/bin/env python3", + }, + ]); + assert.equal(result.status, "FAIL"); + assert.equal(result.violations[0]?.code, "NEW_PYTHON_SHEBANG"); +}); + +test("positive fixture: editing pre-existing .py file and unrelated python-named docs pass", () => { + const result = evaluateAddedFiles([ + { status: "M", path: "legacy/existing-tool.py" }, + { status: "A", path: "docs/python-migration-notes.md", firstLine: "# Python notes" }, + { status: "A", path: "scripts/check.mts", firstLine: "#!/usr/bin/env node" }, + ]); + assert.equal(result.status, "PASS"); + assert.equal(result.violations.length, 0); +}); + +test("positive and fail-closed exception fixtures with real git diff", () => { + withTempRepo((dir) => { + commitFile(dir, "legacy/existing.py", "print('v1')\n", "initial legacy python"); + execFileSync("git", ["checkout", "-q", "-b", "feature"], { cwd: dir }); + // Edit existing .py (allowed) + add approved bootstrap exception + add unapproved shebang script + commitFile(dir, "legacy/existing.py", "print('v2')\n", "edit existing python"); + commitFile( + dir, + "docs/adr/ADR-9001.md", + "# ADR-9001: Bootstrap Python exception\n", + "add local ADR", + ); + commitFile( + dir, + ".config/python-exceptions.json", + JSON.stringify({ + exceptions: [ + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "docs/adr/ADR-9001.md", + reason: "Bun is not installed yet during early OS bootstrap", + alternatives: "POSIX sh lacks JSON parsing in minimal image", + sunsetCondition: "Remove once mise/Bun bootstrap runs first", + }, + ], + }), + "declare approved exception", + ); + commitFile(dir, "bootstrap/pre-bun-init.py", "print('bootstrap')\n", "add approved python"); + + const loaded = loadExceptions(dir, ".config/python-exceptions.json"); + assert.equal(loaded.errors.length, 0); + const entries = collectGitDiffEntries(dir, "main", "HEAD"); + const passResult = evaluateAddedFiles(entries, loaded.exceptions, loaded.errors); + assert.equal(passResult.status, "PASS"); + assert.deepEqual(passResult.exemptedFiles, ["bootstrap/pre-bun-init.py"]); + + // Now add an unapproved extensionless Python script -> must FAIL + commitFile(dir, "scripts/sneaky", "#!/usr/bin/python3\nprint('hi')\n", "add python shebang"); + const failEntries = collectGitDiffEntries(dir, "main", "HEAD"); + const failResult = evaluateAddedFiles(failEntries, loaded.exceptions, loaded.errors); + assert.equal(failResult.status, "FAIL"); + assert.equal(failResult.violations.length, 1); + assert.equal(failResult.violations[0]?.code, "NEW_PYTHON_SHEBANG"); + assert.equal(failResult.violations[0]?.path, "scripts/sneaky"); + + // Missing ADR file in exception manifest must fail closed + commitFile( + dir, + ".config/bad-exceptions.json", + JSON.stringify({ + exceptions: [ + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "docs/adr/ADR-MISSING.md", + reason: "missing adr", + alternatives: "none", + sunsetCondition: "never", + }, + ], + }), + "add broken exception manifest", + ); + const broken = loadExceptions(dir, ".config/bad-exceptions.json"); + assert.equal(broken.errors.length, 1); + assert.equal(broken.errors[0]?.code, "INVALID_EXCEPTION"); + const brokenResult = evaluateAddedFiles(entries, broken.exceptions, broken.errors); + assert.equal(brokenResult.status, "FAIL"); + }); +}); diff --git a/skills/quality-gate/SKILL.md b/skills/quality-gate/SKILL.md index 823f79e..d71b72b 100644 --- a/skills/quality-gate/SKILL.md +++ b/skills/quality-gate/SKILL.md @@ -486,7 +486,7 @@ quality profileに対象check、入力・環境の識別、最大間隔、強制 新規実装・追加時はformatter・lint・型検査とは別に、[code-naming](../code-naming/SKILL.md) と [system-quality](../system-quality/SKILL.md) に基づき、影響範囲の新旧ファイル・兄弟entry・責務の所有者・import・利用側をコードで評価する。今回の変更が生んだ重複・曖昧な命名・階層不整合は、同じticketで解消する。後日のリファクタリングは受入の代わりにならない。 -機械判定可能な違反は低コストのproject-local検査で拒否する。ファイル数や共通prefixだけで意味の良否を決めず、残る意味判断は実コードの差分と周辺構造で確認する。自己申告を独立強制と呼ばず、通常ticketへrelease候補のGUI・full E2Eを追加しない。 +機械判定可能な違反は低コストのproject-local検査で拒否する。新規Pythonスクリプト導入のPR差分検査とADR例外境界は [new-python-guard](references/new-python-guard.md)(ADR-0001 §11)に従う。ファイル数や共通prefixだけで意味の良否を決めず、残る意味判断は実コードの差分と周辺構造で確認する。自己申告を独立強制と呼ばず、通常ticketへrelease候補のGUI・full E2Eを追加しない。 ## 9. Worker gate diff --git a/skills/quality-gate/references/new-python-guard.md b/skills/quality-gate/references/new-python-guard.md new file mode 100644 index 0000000..3ab3f50 --- /dev/null +++ b/skills/quality-gate/references/new-python-guard.md @@ -0,0 +1,28 @@ +# New Python Introduction Guard (ADR-0001 §11) + +`docs/adr/ADR-0001.md` §11(`new Python scripts: prohibited`)の下流 PR での再導入を検出する軽量 PR gate 契約。 + +## 対象と境界 + +- **検出対象**: PR 差分で **新規追加(`A` / `C`)** された `.py` / `.pyw` / `.pyi` ファイル、および Python shebang(`#!/usr/bin/env python*`, `#!/usr/bin/python*`)を持つ新規ファイル。 +- **非対象(誤検知禁止)**: 既存 Python ファイルの単純変更(`M`)、ファイル名に `python` を含む非 Python ファイル(例: Markdown 文書)。既存 Python の全面撤去は本 gate の責務外。 +- **導入先の既存方針優先**: 対象リポジトリに、より厳しい方針またはプロジェクト固有の言語例外がある場合はそちらを優先する。 + +## 例外の承認条件(fail-closed) + +OS 初期化時の循環依存(Bun 未導入等)で例外が不可避な場合のみ、project-local の例外マニフェスト(既定 `.config/python-exceptions.json`)で以下すべてを明示したものだけを許可する。 + +- `paths`: 許可対象の正確な相対パス一覧 +- `adr`: 実在する project-local ADR ファイルへのパス +- `reason`: 例外が不可避な技術的根拠 +- `alternatives`: 検討した代替手段と不採用理由 +- `sunsetCondition`: 例外を解除する条件 + +マニフェストの形式不正・必須項目欠落・参照 ADR 不在はいずれも fail-closed とし、検査を黙って skip しない。 + +## 実行入口 + +```bash +node scripts/quality/check-new-python.mts --base --head +bun run test:new-python +``` From b43f679e20b9d2ed81991f0cab4cc990f2cca41d Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 21:50:35 +0900 Subject: [PATCH 2/5] 142: harden new-python PR diff guard against bypasses and tree mismatch --- scripts/quality/check-new-python.mts | 674 ++++++++++++++++-- scripts/quality/check-new-python.test.mts | 323 +++++++-- skills/quality-gate/SKILL.md | 2 +- .../references/new-python-guard.md | 32 +- 4 files changed, 907 insertions(+), 124 deletions(-) diff --git a/scripts/quality/check-new-python.mts b/scripts/quality/check-new-python.mts index c826f5c..4540525 100644 --- a/scripts/quality/check-new-python.mts +++ b/scripts/quality/check-new-python.mts @@ -1,15 +1,22 @@ #!/usr/bin/env node -import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync, statSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { execFileSync, spawn } from "node:child_process"; +import { existsSync, lstatSync, readFileSync } from "node:fs"; +import { posix, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; export const POLICY_REFERENCE = "docs/adr/ADR-0001.md#11-tooling-conventions"; +const MAX_SHEBANG_BYTES = 4096; +const MAX_DIFF_BUFFER_BYTES = 64 * 1024 * 1024; +const MAX_MANIFEST_BUFFER_BYTES = 10 * 1024 * 1024; +const HEADER_SCAN_LINES = 40; + export interface DiffEntry { readonly status: string; readonly path: string; + readonly previousPath?: string; readonly firstLine?: string; + readonly previousFirstLine?: string; } export interface PythonException { @@ -34,9 +41,21 @@ export interface CheckResult { readonly violations: readonly Violation[]; } +export interface LoadExceptionsOptions { + readonly ref?: string; + readonly policy?: string; +} + const PYTHON_EXTENSION = /\.py[wi]?$/i; -const PYTHON_SHEBANG = - /^#!\s*(?:\/usr\/bin\/env\s+(?:-\S+\s+)*python(?:\d+(?:\.\d+)?)?|\/[^\s]*\/python(?:\d+(?:\.\d+)?)?)(?:\s|$)/; +const PYTHON_EXECUTABLE = /^(?:pythonw?|pypy)(?:\d+(?:\.\d+)*)?t?$/i; +const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/; +const ENV_FLAGS_WITH_ARG = new Set(["-u", "--unset", "-C", "--chdir", "-P", "-a"]); +const ADR_PATH_PATTERN = /(?:^|\/)(?:docs\/)?adrs?\/.+\.md$/i; +const STATUS_KEY_PATTERN = + /^(?:[-*+]\s+)?(?:\*\*)?(?:Status|ステータス|状態)(?:\*\*)?\s*[::]\s*(.+)$/i; +const STATUS_HEADING_PATTERN = /^#{1,3}\s*(?:Status|ステータス|状態)\s*$/i; +const ACCEPTED_STATUS_VALUE = + /^(?:accepted|approved)\b|^(?:承認(?:済み|済)?|採用(?:済み|済)?)(?:\s|$|[;;。、(\(,::])/i; function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); @@ -46,36 +65,304 @@ function nonEmptyString(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0; } +export function normalizeRepoRelativePath(raw: string): string | undefined { + const trimmed = raw.trim(); + if (!trimmed || trimmed.includes("\0")) return undefined; + const slashNormalized = trimmed.replaceAll("\\", "/"); + if (slashNormalized.startsWith("/") || /^[a-zA-Z]:/.test(slashNormalized)) { + return undefined; + } + const rawSegments = slashNormalized.split("/"); + if (rawSegments.some((segment) => segment === "..")) { + return undefined; + } + const normalized = posix.normalize(slashNormalized); + if ( + !normalized || + normalized === "." || + normalized === ".." || + normalized.startsWith("../") || + normalized.startsWith("/") + ) { + return undefined; + } + return normalized; +} + +export function isAdrPath(repoRelativePath: string): boolean { + return ADR_PATH_PATTERN.test(repoRelativePath); +} + +function stripMarkdownWrapper(raw: string): string { + return raw.trim().replace(/^[*_`]+/, "").replace(/[*_`]+$/, "").trim(); +} + +export function isAcceptedAdrContent(content: string): boolean { + const normalized = content.replace(/^\uFEFF/, ""); + const lines = normalized.split(/\r?\n/).slice(0, HEADER_SCAN_LINES); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]?.trim() ?? ""; + const inlineMatch = STATUS_KEY_PATTERN.exec(line); + if (inlineMatch?.[1] !== undefined) { + return ACCEPTED_STATUS_VALUE.test(stripMarkdownWrapper(inlineMatch[1])); + } + if (STATUS_HEADING_PATTERN.test(line)) { + for (let j = i + 1; j < lines.length; j++) { + const nextLine = lines[j]?.trim() ?? ""; + if (!nextLine) continue; + if (nextLine.startsWith("#")) return false; + const cleaned = stripMarkdownWrapper(nextLine.replace(/^[-*+]\s+/, "")); + return ACCEPTED_STATUS_VALUE.test(cleaned); + } + return false; + } + } + return false; +} + export function hasPythonExtension(filePath: string): boolean { return PYTHON_EXTENSION.test(filePath); } +function tokenizeShebangCommand(command: string): string[] { + const tokens: string[] = []; + let current = ""; + let quote: "'" | '"' | null = null; + let escaping = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]!; + if (escaping) { + current += ch; + escaping = false; + continue; + } + if (ch === "\\" && quote !== "'") { + escaping = true; + continue; + } + if (quote !== null) { + if (ch === quote) { + quote = null; + } else { + current += ch; + } + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (/\s/.test(ch)) { + if (current.length > 0) { + tokens.push(current); + current = ""; + } + continue; + } + current += ch; + } + if (escaping) current += "\\"; + if (current.length > 0) tokens.push(current); + return tokens; +} + +function baseCommandName(token: string): string { + const normalized = token.replaceAll("\\", "/"); + const idx = normalized.lastIndexOf("/"); + return idx === -1 ? normalized : normalized.slice(idx + 1); +} + +function isPythonExecutableToken(token: string | undefined): boolean { + if (!token) return false; + return PYTHON_EXECUTABLE.test(baseCommandName(token)); +} + export function hasPythonShebang(firstLine: string | undefined): boolean { if (!firstLine) return false; - return PYTHON_SHEBANG.test(firstLine.trimEnd()); + const cleaned = firstLine.replace(/^\uFEFF/, "").trimEnd(); + if (!cleaned.startsWith("#!")) return false; + const command = cleaned.slice(2).trimStart(); + if (!command) return false; + + const tokens = tokenizeShebangCommand(command); + const interpreter = tokens[0]; + if (!interpreter) return false; + if (isPythonExecutableToken(interpreter)) return true; + + if (baseCommandName(interpreter).toLowerCase() !== "env") { + return false; + } + + for (let i = 1; i < tokens.length; i++) { + const token = tokens[i]!; + if (token === "--") { + return isPythonExecutableToken(tokens[i + 1]); + } + if (token.startsWith("--split-string=")) { + const splitTokens = tokenizeShebangCommand(token.slice("--split-string=".length)); + tokens.splice(i + 1, 0, ...splitTokens); + continue; + } + if (token.startsWith("-S") && token.length > 2) { + const splitTokens = tokenizeShebangCommand(token.slice(2)); + tokens.splice(i + 1, 0, ...splitTokens); + continue; + } + if (token.startsWith("-")) { + if (ENV_FLAGS_WITH_ARG.has(token)) { + i++; + } + continue; + } + if (ENV_ASSIGNMENT.test(token)) { + continue; + } + return isPythonExecutableToken(token); + } + return false; +} + +type TreeFileLookup = + | { readonly status: "missing" } + | { readonly status: "non-regular"; readonly detail: string } + | { readonly status: "found"; readonly content: string }; + +function verifyGitTreeRef(root: string, ref: string): void { + execFileSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{tree}`], { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }); +} + +function readRegularFileFromGitTree( + root: string, + ref: string, + repoRelativePath: string, +): TreeFileLookup { + const lsOut = execFileSync( + "git", + ["-c", "core.quotePath=false", "ls-tree", "-z", ref, "--", repoRelativePath], + { + cwd: root, + encoding: "utf8", + maxBuffer: MAX_MANIFEST_BUFFER_BYTES, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + if (!lsOut) { + return { status: "missing" }; + } + const firstEntry = lsOut.split("\0")[0] ?? ""; + const tabIndex = firstEntry.indexOf("\t"); + if (tabIndex === -1) { + throw new Error(`unexpected git ls-tree output for ${ref}:${repoRelativePath}`); + } + const meta = firstEntry.slice(0, tabIndex).split(" "); + const mode = meta[0] ?? ""; + const objectType = meta[1] ?? ""; + const sha = meta[2] ?? ""; + if (objectType !== "blob" || (mode !== "100644" && mode !== "100755")) { + return { + status: "non-regular", + detail: `expected regular file blob, found mode=${mode} type=${objectType}`, + }; + } + const content = execFileSync("git", ["cat-file", "blob", sha], { + cwd: root, + encoding: "utf8", + maxBuffer: MAX_MANIFEST_BUFFER_BYTES, + stdio: ["ignore", "pipe", "pipe"], + }); + return { status: "found", content }; +} + +function readRegularFileFromWorkdir( + root: string, + repoRelativePath: string, +): TreeFileLookup { + const rootAbs = resolve(root); + const targetAbs = resolve(rootAbs, repoRelativePath); + const rel = relative(rootAbs, targetAbs); + if (!rel || rel.startsWith("..") || rel.includes("\0") || rel.startsWith("/")) { + return { status: "non-regular", detail: "path escapes repository root" }; + } + if (!existsSync(targetAbs)) { + return { status: "missing" }; + } + const stat = lstatSync(targetAbs); + if (!stat.isFile()) { + return { + status: "non-regular", + detail: stat.isSymbolicLink() + ? "symlinks are not permitted" + : "target is not a regular file", + }; + } + return { status: "found", content: readFileSync(targetAbs, "utf8") }; } export function loadExceptions( root: string, exceptionsPath: string, + options: LoadExceptionsOptions = {}, ): { exceptions: PythonException[]; errors: Violation[] } { - const absolute = resolve(root, exceptionsPath); - if (!existsSync(absolute)) { + const policy = options.policy ?? POLICY_REFERENCE; + const normalizedManifestPath = normalizeRepoRelativePath(exceptionsPath); + if (!normalizedManifestPath) { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: exceptionsPath, + detail: "exception manifest path must be a repo-relative path without '..'", + policy, + }, + ], + }; + } + + if (options.ref !== undefined) { + verifyGitTreeRef(root, options.ref); + } + + const readFile = (repoRelativePath: string): TreeFileLookup => + options.ref !== undefined + ? readRegularFileFromGitTree(root, options.ref, repoRelativePath) + : readRegularFileFromWorkdir(root, repoRelativePath); + + const manifestLookup = readFile(normalizedManifestPath); + if (manifestLookup.status === "missing") { return { exceptions: [], errors: [] }; } + if (manifestLookup.status === "non-regular") { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: normalizedManifestPath, + detail: `invalid exception manifest file: ${manifestLookup.detail}`, + policy, + }, + ], + }; + } + const errors: Violation[] = []; let parsed: unknown; try { - parsed = JSON.parse(readFileSync(absolute, "utf8")) as unknown; + parsed = JSON.parse(manifestLookup.content) as unknown; } catch (error) { return { exceptions: [], errors: [ { code: "INVALID_EXCEPTION", - path: exceptionsPath, + path: normalizedManifestPath, detail: `malformed exception manifest: ${error instanceof Error ? error.message : String(error)}`, - policy: POLICY_REFERENCE, + policy, }, ], }; @@ -86,32 +373,45 @@ export function loadExceptions( errors: [ { code: "INVALID_EXCEPTION", - path: exceptionsPath, + path: normalizedManifestPath, detail: 'exception manifest must contain an "exceptions" array', - policy: POLICY_REFERENCE, + policy, }, ], }; } const valid: PythonException[] = []; + const sourceLabel = options.ref !== undefined ? ` at ${options.ref}` : ""; for (const [index, raw] of parsed.exceptions.entries()) { - const label = `${exceptionsPath}#exceptions[${index}]`; + const label = `${normalizedManifestPath}#exceptions[${index}]`; if (!isRecord(raw)) { errors.push({ code: "INVALID_EXCEPTION", path: label, detail: "exception entry must be an object", - policy: POLICY_REFERENCE, + policy, }); continue; } - const paths = Array.isArray(raw.paths) - ? raw.paths.filter((p): p is string => nonEmptyString(p)) - : []; + const rawPaths = Array.isArray(raw.paths) ? raw.paths : []; + const normalizedPaths: string[] = []; + let invalidPathFound = false; + for (const p of rawPaths) { + if (!nonEmptyString(p)) { + invalidPathFound = true; + break; + } + const norm = normalizeRepoRelativePath(p); + if (!norm) { + invalidPathFound = true; + break; + } + normalizedPaths.push(norm); + } if ( - paths.length === 0 || - paths.length !== (Array.isArray(raw.paths) ? raw.paths.length : -1) || + normalizedPaths.length === 0 || + invalidPathFound || !nonEmptyString(raw.adr) || !nonEmptyString(raw.reason) || !nonEmptyString(raw.alternatives) || @@ -121,24 +421,55 @@ export function loadExceptions( code: "INVALID_EXCEPTION", path: label, detail: - "exception requires non-empty paths[], adr, reason, alternatives, and sunsetCondition", - policy: POLICY_REFERENCE, + "exception requires valid repo-relative paths[], adr, reason, alternatives, and sunsetCondition", + policy, + }); + continue; + } + + const normalizedAdr = normalizeRepoRelativePath(raw.adr); + if (!normalizedAdr || !isAdrPath(normalizedAdr)) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: `adr must be a repo-relative Markdown file under an ADR directory (e.g. docs/adr/*.md): ${raw.adr}`, + policy, + }); + continue; + } + + const adrLookup = readFile(normalizedAdr); + if (adrLookup.status === "missing") { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: `approved ADR file not found${sourceLabel}: ${normalizedAdr}`, + policy, }); continue; } - const adrAbs = resolve(root, raw.adr); - if (!existsSync(adrAbs) || !statSync(adrAbs).isFile()) { + if (adrLookup.status === "non-regular") { errors.push({ code: "INVALID_EXCEPTION", path: label, - detail: `approved ADR file not found: ${raw.adr}`, - policy: POLICY_REFERENCE, + detail: `approved ADR file is not a regular file${sourceLabel}: ${normalizedAdr} (${adrLookup.detail})`, + policy, }); continue; } + if (!isAcceptedAdrContent(adrLookup.content)) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: `ADR must declare an Accepted/Approved status (e.g. "Status: Accepted")${sourceLabel}: ${normalizedAdr}`, + policy, + }); + continue; + } + valid.push({ - paths, - adr: raw.adr, + paths: normalizedPaths, + adr: normalizedAdr, reason: raw.reason, alternatives: raw.alternatives, sunsetCondition: raw.sunsetCondition, @@ -147,26 +478,48 @@ export function loadExceptions( return { exceptions: valid, errors }; } +function isExistingPythonRename(entry: DiffEntry, normalizedStatus: string): boolean { + if (!normalizedStatus.startsWith("R")) return false; + if (!entry.previousPath) return false; + return ( + hasPythonExtension(entry.previousPath.replaceAll("\\", "/")) || + hasPythonShebang(entry.previousFirstLine) + ); +} + export function evaluateAddedFiles( entries: readonly DiffEntry[], exceptions: readonly PythonException[] = [], exceptionErrors: readonly Violation[] = [], + policy: string = POLICY_REFERENCE, ): CheckResult { const violations: Violation[] = [...exceptionErrors]; const exemptedFiles: string[] = []; const allowedPaths = new Set(); for (const ex of exceptions) { - for (const p of ex.paths) allowedPaths.add(p.replaceAll("\\", "/")); + for (const p of ex.paths) { + const normalized = normalizeRepoRelativePath(p) ?? p.replaceAll("\\", "/"); + allowedPaths.add(normalized); + } } let checkedAddedFiles = 0; for (const entry of entries) { const normalizedStatus = entry.status.trim().toUpperCase(); - // Only newly added files ('A' or copy 'C*') are inspected; edits ('M') to - // pre-existing Python files are out of scope for ADR-0001 §11. - if (!normalizedStatus.startsWith("A") && !normalizedStatus.startsWith("C")) { + const isAddedOrCopied = + normalizedStatus.startsWith("A") || normalizedStatus.startsWith("C"); + const isRename = normalizedStatus.startsWith("R"); + + // Only newly added ('A'), copied ('C*'), or renamed-into-Python ('R*' from + // non-Python) files are inspected; edits ('M') and Python->Python renames + // of pre-existing Python files are out of scope for ADR-0001 §11. + if (!isAddedOrCopied && !isRename) { + continue; + } + if (isRename && isExistingPythonRename(entry, normalizedStatus)) { continue; } + checkedAddedFiles++; const normalizedPath = entry.path.replaceAll("\\", "/"); const extMatch = hasPythonExtension(normalizedPath); @@ -184,7 +537,7 @@ export function evaluateAddedFiles( detail: extMatch ? "newly added Python file violates ADR-0001 §11 (new Python scripts prohibited unless backed by an approved project-local ADR exception)" : "newly added file with Python shebang violates ADR-0001 §11 (new Python scripts prohibited unless backed by an approved project-local ADR exception)", - policy: POLICY_REFERENCE, + policy, }); } @@ -196,44 +549,222 @@ export function evaluateAddedFiles( }; } -function readFirstLineFromGit(root: string, ref: string, path: string): string | undefined { - try { - const content = execFileSync("git", ["show", `${ref}:${path}`], { +export function readFirstLineFromGitObject( + root: string, + objectSpec: string, +): Promise { + return new Promise((resolvePromise, rejectPromise) => { + const child = spawn("git", ["cat-file", "blob", objectSpec], { cwd: root, - encoding: "utf8", - maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], }); - const idx = content.indexOf("\n"); - return idx === -1 ? content : content.slice(0, idx); - } catch { - return undefined; + const chunks: Buffer[] = []; + let collected = 0; + let stoppedEarly = false; + let settled = false; + let stderr = ""; + + const finish = (err: Error | null, value?: string) => { + if (settled) return; + settled = true; + if (err) rejectPromise(err); + else resolvePromise(value ?? ""); + }; + + const stopChild = () => { + if (stoppedEarly) return; + stoppedEarly = true; + child.stdout.destroy(); + if (child.exitCode === null && child.signalCode === null) { + child.kill(); + } + }; + + child.stdout.on("error", (err) => { + if (!stoppedEarly) { + finish(new Error(`failed reading git blob ${objectSpec}: ${err.message}`)); + } + }); + + child.stderr.on("data", (chunk: Buffer) => { + if (stderr.length < 4096) { + stderr += chunk.toString("utf8"); + } + }); + + child.stdout.on("data", (chunk: Buffer) => { + if (stoppedEarly) return; + const remaining = MAX_SHEBANG_BYTES - collected; + const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk; + const newlineIndex = slice.indexOf(0x0a); + if (newlineIndex !== -1) { + chunks.push(slice.subarray(0, newlineIndex)); + collected += newlineIndex; + stopChild(); + return; + } + chunks.push(slice); + collected += slice.length; + if (collected >= MAX_SHEBANG_BYTES) { + stopChild(); + } + }); + + child.on("error", (err) => { + finish(new Error(`failed to spawn git cat-file for ${objectSpec}: ${err.message}`)); + }); + + child.on("close", (code, signal) => { + if (stoppedEarly) { + const line = Buffer.concat(chunks).toString("utf8").replace(/\r$/, ""); + finish(null, line); + return; + } + if (code !== 0 || signal !== null) { + const detail = + stderr.trim() || `exit code ${String(code)} signal ${String(signal)}`; + finish(new Error(`git cat-file blob ${objectSpec} failed: ${detail}`)); + return; + } + const line = Buffer.concat(chunks).toString("utf8").replace(/\r$/, ""); + finish(null, line); + }); + }); +} + +function isRegularFileMode(mode: string): boolean { + return mode === "100644" || mode === "100755"; +} + +interface RawDiffRecord { + readonly oldMode: string; + readonly newMode: string; + readonly oldSha: string; + readonly newSha: string; + readonly status: string; + readonly path: string; + readonly previousPath?: string; +} + +export function parseRawDiffOutput(rawOutput: string): RawDiffRecord[] { + const tokens = rawOutput.split("\0"); + const records: RawDiffRecord[] = []; + let i = 0; + while (i < tokens.length) { + const header = tokens[i]; + if (!header) { + i++; + continue; + } + if (!header.startsWith(":")) { + throw new Error(`unexpected git diff --raw record header: ${header}`); + } + const fields = header.slice(1).split(" "); + if (fields.length < 5) { + throw new Error(`malformed git diff --raw header: ${header}`); + } + const [oldMode, newMode, oldSha, newSha, status] = fields as [ + string, + string, + string, + string, + string, + ]; + const upperStatus = status.toUpperCase(); + if (upperStatus.startsWith("R") || upperStatus.startsWith("C")) { + const previousPath = tokens[i + 1]; + const nextPath = tokens[i + 2]; + if (previousPath === undefined || nextPath === undefined) { + throw new Error(`incomplete rename/copy record in git diff --raw for ${status}`); + } + records.push({ + oldMode, + newMode, + oldSha, + newSha, + status, + path: nextPath, + previousPath, + }); + i += 3; + } else { + const filePath = tokens[i + 1]; + if (filePath === undefined) { + throw new Error(`incomplete record in git diff --raw for ${status}`); + } + records.push({ + oldMode, + newMode, + oldSha, + newSha, + status, + path: filePath, + }); + i += 2; + } } + return records; } -export function collectGitDiffEntries( +export async function collectGitDiffEntries( root: string, baseRef: string, headRef: string, -): DiffEntry[] { +): Promise { const output = execFileSync( "git", - ["diff", "--name-status", "--no-renames", `${baseRef}...${headRef}`], - { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }, + [ + "-c", + "core.quotePath=false", + "diff", + "-z", + "-M", + "--raw", + "--no-abbrev", + `${baseRef}...${headRef}`, + ], + { + cwd: root, + encoding: "utf8", + maxBuffer: MAX_DIFF_BUFFER_BYTES, + stdio: ["ignore", "pipe", "pipe"], + }, ); + const rawRecords = parseRawDiffOutput(output); const entries: DiffEntry[] = []; - for (const rawLine of output.split(/\r?\n/)) { - if (!rawLine.trim()) continue; - const parts = rawLine.split("\t"); - const status = parts[0] ?? ""; - const filePath = parts[parts.length - 1] ?? ""; - if (!filePath) continue; - const isAdded = status.startsWith("A") || status.startsWith("C"); - const firstLine = - isAdded && !hasPythonExtension(filePath) - ? readFirstLineFromGit(root, headRef, filePath) - : undefined; - entries.push({ status, path: filePath, firstLine }); + + for (const record of rawRecords) { + const upperStatus = record.status.toUpperCase(); + const isAddedOrCopied = upperStatus.startsWith("A") || upperStatus.startsWith("C"); + const isRename = upperStatus.startsWith("R"); + + let firstLine: string | undefined; + if ( + (isAddedOrCopied || isRename) && + !hasPythonExtension(record.path) && + isRegularFileMode(record.newMode) + ) { + firstLine = await readFirstLineFromGitObject(root, record.newSha); + } + + let previousFirstLine: string | undefined; + if ( + isRename && + record.previousPath !== undefined && + !hasPythonExtension(record.previousPath) && + (hasPythonExtension(record.path) || hasPythonShebang(firstLine)) && + isRegularFileMode(record.oldMode) + ) { + previousFirstLine = await readFirstLineFromGitObject(root, record.oldSha); + } + + entries.push({ + status: record.status, + path: record.path, + previousPath: record.previousPath, + firstLine, + previousFirstLine, + }); } return entries; } @@ -243,6 +774,7 @@ interface CliArgs { base: string; head: string; exceptionsPath: string; + policy: string; } function parseCliArgs(argv: readonly string[]): CliArgs { @@ -251,6 +783,7 @@ function parseCliArgs(argv: readonly string[]): CliArgs { base: "HEAD~1", head: "HEAD", exceptionsPath: ".config/python-exceptions.json", + policy: POLICY_REFERENCE, }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; @@ -267,6 +800,9 @@ function parseCliArgs(argv: readonly string[]): CliArgs { } else if (flag === "--exceptions" && next) { args.exceptionsPath = next; i++; + } else if (flag === "--policy" && next) { + args.policy = next; + i++; } else { throw new Error(`unknown or incomplete argument: ${flag}`); } @@ -274,7 +810,7 @@ function parseCliArgs(argv: readonly string[]): CliArgs { return args; } -function main(argv: readonly string[]): number { +async function main(argv: readonly string[]): Promise { let args: CliArgs; try { args = parseCliArgs(argv); @@ -283,16 +819,24 @@ function main(argv: readonly string[]): number { return 2; } const root = resolve(args.root); - const { exceptions, errors } = loadExceptions(root, args.exceptionsPath); - const entries = collectGitDiffEntries(root, args.base, args.head); - const result = evaluateAddedFiles(entries, exceptions, errors); - console.log(JSON.stringify(result, null, 2)); - return result.status === "PASS" ? 0 : 1; + try { + const { exceptions, errors } = loadExceptions(root, args.exceptionsPath, { + ref: args.head, + policy: args.policy, + }); + const entries = await collectGitDiffEntries(root, args.base, args.head); + const result = evaluateAddedFiles(entries, exceptions, errors, args.policy); + console.log(JSON.stringify(result, null, 2)); + return result.status === "PASS" ? 0 : 1; + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + return 2; + } } if ( process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url) ) { - process.exitCode = main(process.argv.slice(2)); + process.exitCode = await main(process.argv.slice(2)); } diff --git a/scripts/quality/check-new-python.test.mts b/scripts/quality/check-new-python.test.mts index e21265e..bae161b 100644 --- a/scripts/quality/check-new-python.test.mts +++ b/scripts/quality/check-new-python.test.mts @@ -1,32 +1,42 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import test from "node:test"; +import { fileURLToPath } from "node:url"; import { collectGitDiffEntries, evaluateAddedFiles, + hasPythonShebang, + isAcceptedAdrContent, loadExceptions, POLICY_REFERENCE, + readFirstLineFromGitObject, } from "./check-new-python.mts"; -function withTempRepo(fn: (dir: string) => void): void { +const SCRIPT_PATH = resolve(fileURLToPath(import.meta.url), "..", "check-new-python.mts"); + +async function withTempRepo(fn: (dir: string) => Promise | void): Promise { const dir = mkdtempSync(join(tmpdir(), "new-python-guard-")); try { execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: dir }); execFileSync("git", ["config", "user.name", "Test User"], { cwd: dir }); - fn(dir); + await fn(dir); } finally { rmSync(dir, { recursive: true, force: true }); } } -function commitFile(dir: string, relPath: string, content: string, message: string): void { +function writeRepoFile(dir: string, relPath: string, content: string): void { const full = join(dir, relPath); mkdirSync(join(full, ".."), { recursive: true }); writeFileSync(full, content, "utf8"); +} + +function commitFile(dir: string, relPath: string, content: string, message: string): void { + writeRepoFile(dir, relPath, content); execFileSync("git", ["add", relPath], { cwd: dir }); execFileSync("git", ["commit", "-q", "-m", message], { cwd: dir }); } @@ -45,16 +55,55 @@ test("negative fixture (pc-setup PR #147 shape): newly added .py files fail with assert.ok(result.violations.every((v) => v.policy === POLICY_REFERENCE)); }); -test("negative fixture: extensionless file with python shebang fails", () => { - const result = evaluateAddedFiles([ - { - status: "A", - path: "scripts/bootstrap-helper", - firstLine: "#!/usr/bin/env python3", - }, - ]); - assert.equal(result.status, "FAIL"); - assert.equal(result.violations[0]?.code, "NEW_PYTHON_SHEBANG"); +test("hardened Python shebang detection handles BOM, case, env flags/assignments, absolute path, free-threaded, and pypy", () => { + const positiveShebangs = [ + "#!/usr/bin/env python3", + "\uFEFF#!/usr/bin/env python3", + "\uFEFF#!/usr/bin/env PYTHONDONTWRITEBYTECODE=1 python3.13t", + "#!/usr/bin/env -S FOO=bar BAR=1 python3.13t -u", + "#!/usr/bin/env /usr/bin/python3", + "#!/usr/bin/env -- pypy3", + "#!/usr/local/bin/PYTHON3", + "#!/opt/venv/bin/pypy3.10", + "#!/usr/bin/pythonw3", + ]; + for (const shebang of positiveShebangs) { + assert.equal(hasPythonShebang(shebang), true, `expected match for: ${shebang}`); + } + + const negativeShebangs = [ + "#!/usr/bin/env node", + "#!/usr/bin/env bash", + "#!/usr/bin/env MY_VAR=python3 bash", + "#!/usr/bin/env -u PYTHONHOME node", + '#!/usr/bin/env -S bash -c "python3 -V"', + "# not a shebang python3", + "", + ]; + for (const shebang of negativeShebangs) { + assert.equal(hasPythonShebang(shebang), false, `expected non-match for: ${shebang}`); + } +}); + +test("ADR status parser accepts only Accepted/Approved/承認 status in header", () => { + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n- Status: Accepted\n"), true); + assert.equal( + isAcceptedAdrContent("# ADR-0001\n\n- Status: Accepted; revised by ADR-0003\n"), + true, + ); + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n**Status**: Approved\n"), true); + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n- ステータス: 承認済み\n"), true); + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n## Status\n\nAccepted\n"), true); + assert.equal(isAcceptedAdrContent("---\nstatus: accepted\n---\n"), true); + + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n- Status: Draft\n"), false); + assert.equal(isAcceptedAdrContent("# ADR-0001\n\n- Status: Proposed\n"), false); + assert.equal( + isAcceptedAdrContent("# ADR-0001\n\n- Status: Draft (not yet Accepted)\n"), + false, + ); + assert.equal(isAcceptedAdrContent("# ADR-0001\n\nNo status header here\n"), false); + assert.equal(isAcceptedAdrContent("# README\n\nAccepted by team.\n"), false); }); test("positive fixture: editing pre-existing .py file and unrelated python-named docs pass", () => { @@ -67,19 +116,97 @@ test("positive fixture: editing pre-existing .py file and unrelated python-named assert.equal(result.violations.length, 0); }); -test("positive and fail-closed exception fixtures with real git diff", () => { - withTempRepo((dir) => { - commitFile(dir, "legacy/existing.py", "print('v1')\n", "initial legacy python"); +test("real git repo: non-ASCII filenames and >1 MiB shebang files cannot bypass detection", async () => { + await withTempRepo(async (dir) => { + commitFile(dir, "README.md", "# demo\n", "initial"); execFileSync("git", ["checkout", "-q", "-b", "feature"], { cwd: dir }); - // Edit existing .py (allowed) + add approved bootstrap exception + add unapproved shebang script - commitFile(dir, "legacy/existing.py", "print('v2')\n", "edit existing python"); + + // Non-ASCII .py filename + non-ASCII extensionless python shebang + commitFile(dir, "scripts/日本語.py", "print('ja')\n", "add non-ascii py"); commitFile( dir, - "docs/adr/ADR-9001.md", - "# ADR-9001: Bootstrap Python exception\n", - "add local ADR", + "scripts/日本語スクリプト", + "\uFEFF#!/usr/bin/env FOO=1 python3.13t\nprint('ja')\n", + "add non-ascii shebang", ); + + // >1.5 MiB file starting with Python shebang (must NOT be silently skipped by maxBuffer) + const hugePythonBody = `#!/usr/bin/env python3\n# ${"x".repeat(1_500_000)}\n`; + commitFile(dir, "scripts/huge-script", hugePythonBody, "add huge python shebang"); + + // >1.5 MiB non-Python single-line file (must NOT crash or false-positive) + const hugeNonPythonBody = "A".repeat(1_500_000); + commitFile(dir, "assets/huge-blob.dat", hugeNonPythonBody, "add huge non-python blob"); + + const entries = await collectGitDiffEntries(dir, "main", "HEAD"); + const result = evaluateAddedFiles(entries); + assert.equal(result.status, "FAIL"); + assert.deepEqual( + result.violations.map((v) => [v.code, v.path]).sort(), + [ + ["NEW_PYTHON_FILE", "scripts/日本語.py"], + ["NEW_PYTHON_SHEBANG", "scripts/huge-script"], + ["NEW_PYTHON_SHEBANG", "scripts/日本語スクリプト"], + ].sort(), + ); + + // Fail-closed check: invalid git blob OID throws instead of silently returning undefined + await assert.rejects( + () => readFirstLineFromGitObject(dir, "0000000000000000000000000000000000000000"), + /git cat-file blob/, + ); + }); +}); + +test("real git repo: rename semantics allow .py->.py while catching .txt->.py", async () => { + await withTempRepo(async (dir) => { + const sharedPyBody = Array.from({ length: 20 }, (_, i) => `x_${i} = ${i}\n`).join(""); + const sharedTxtBody = Array.from({ length: 20 }, (_, i) => `line ${i} plain text\n`).join(""); + commitFile(dir, "legacy/old.py", sharedPyBody, "add legacy py"); + commitFile(dir, "notes/plain.txt", sharedTxtBody, "add plain txt"); commitFile( + dir, + "legacy/old-exec", + `#!/usr/bin/env python3\n${sharedPyBody}`, + "add legacy python shebang", + ); + + execFileSync("git", ["checkout", "-q", "-b", "feature"], { cwd: dir }); + execFileSync("git", ["mv", "legacy/old.py", "legacy/moved.py"], { cwd: dir }); + execFileSync("git", ["mv", "legacy/old-exec", "legacy/moved-exec"], { cwd: dir }); + execFileSync("git", ["commit", "-q", "-m", "rename existing python files"], { cwd: dir }); + + const allowedEntries = await collectGitDiffEntries(dir, "main", "HEAD"); + const allowedResult = evaluateAddedFiles(allowedEntries); + assert.equal(allowedResult.status, "PASS"); + assert.equal(allowedResult.violations.length, 0); + + // Now rename a non-Python .txt file into .py -> MUST FAIL + execFileSync("git", ["mv", "notes/plain.txt", "notes/disguised.py"], { cwd: dir }); + execFileSync("git", ["commit", "-q", "-m", "rename txt to py"], { cwd: dir }); + + const caughtEntries = await collectGitDiffEntries(dir, "main", "HEAD"); + const caughtResult = evaluateAddedFiles(caughtEntries); + assert.equal(caughtResult.status, "FAIL"); + assert.equal(caughtResult.violations.length, 1); + assert.equal(caughtResult.violations[0]?.code, "NEW_PYTHON_FILE"); + assert.equal(caughtResult.violations[0]?.path, "notes/disguised.py"); + }); +}); + +test("real git repo: exceptions and ADR are loaded from --head tree, rejecting traversal, Draft ADRs, and non-ADR files", async () => { + await withTempRepo(async (dir) => { + commitFile(dir, "README.md", "# Project\n\nStatus: Accepted\n", "initial"); + execFileSync("git", ["checkout", "-q", "-b", "feature"], { cwd: dir }); + commitFile(dir, "bootstrap/pre-bun-init.py", "print('bootstrap')\n", "add python file"); + + // 1. Exception manifest + ADR present ONLY in working tree (not committed to head) -> MUST FAIL! + writeRepoFile( + dir, + "docs/adr/ADR-9001.md", + "# ADR-9001: Bootstrap Python\n\n- Status: Accepted\n", + ); + writeRepoFile( dir, ".config/python-exceptions.json", JSON.stringify({ @@ -87,33 +214,55 @@ test("positive and fail-closed exception fixtures with real git diff", () => { { paths: ["bootstrap/pre-bun-init.py"], adr: "docs/adr/ADR-9001.md", - reason: "Bun is not installed yet during early OS bootstrap", - alternatives: "POSIX sh lacks JSON parsing in minimal image", - sunsetCondition: "Remove once mise/Bun bootstrap runs first", + reason: "pre-bun bootstrap", + alternatives: "sh lacks json", + sunsetCondition: "remove after bun bootstrap", }, ], }), - "declare approved exception", ); - commitFile(dir, "bootstrap/pre-bun-init.py", "print('bootstrap')\n", "add approved python"); + const headOnlyLoaded = loadExceptions(dir, ".config/python-exceptions.json", { ref: "HEAD" }); + assert.equal(headOnlyLoaded.exceptions.length, 0); + assert.equal(headOnlyLoaded.errors.length, 0); + const headEntries = await collectGitDiffEntries(dir, "main", "HEAD"); + assert.equal( + evaluateAddedFiles(headEntries, headOnlyLoaded.exceptions, headOnlyLoaded.errors).status, + "FAIL", + ); + + // 2. Commit accepted ADR + manifest on feature, then checkout main so working tree lacks them -> --head feature MUST PASS! + execFileSync("git", ["add", "docs/adr/ADR-9001.md", ".config/python-exceptions.json"], { + cwd: dir, + }); + execFileSync("git", ["commit", "-q", "-m", "commit approved exception"], { cwd: dir }); + const featureSha = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: dir, + encoding: "utf8", + }).trim(); + execFileSync("git", ["checkout", "-q", "main"], { cwd: dir }); - const loaded = loadExceptions(dir, ".config/python-exceptions.json"); - assert.equal(loaded.errors.length, 0); - const entries = collectGitDiffEntries(dir, "main", "HEAD"); - const passResult = evaluateAddedFiles(entries, loaded.exceptions, loaded.errors); + const fromCommittedHead = loadExceptions(dir, ".config/python-exceptions.json", { + ref: featureSha, + }); + assert.equal(fromCommittedHead.errors.length, 0); + assert.equal(fromCommittedHead.exceptions.length, 1); + const committedEntries = await collectGitDiffEntries(dir, "main", featureSha); + const passResult = evaluateAddedFiles( + committedEntries, + fromCommittedHead.exceptions, + fromCommittedHead.errors, + ); assert.equal(passResult.status, "PASS"); assert.deepEqual(passResult.exemptedFiles, ["bootstrap/pre-bun-init.py"]); - // Now add an unapproved extensionless Python script -> must FAIL - commitFile(dir, "scripts/sneaky", "#!/usr/bin/python3\nprint('hi')\n", "add python shebang"); - const failEntries = collectGitDiffEntries(dir, "main", "HEAD"); - const failResult = evaluateAddedFiles(failEntries, loaded.exceptions, loaded.errors); - assert.equal(failResult.status, "FAIL"); - assert.equal(failResult.violations.length, 1); - assert.equal(failResult.violations[0]?.code, "NEW_PYTHON_SHEBANG"); - assert.equal(failResult.violations[0]?.path, "scripts/sneaky"); - - // Missing ADR file in exception manifest must fail closed + // 3. Reject path traversal, README.md, and Status: Draft ADR + execFileSync("git", ["checkout", "-q", "feature"], { cwd: dir }); + commitFile( + dir, + "docs/adr/ADR-9002.md", + "# ADR-9002: Draft exception\n\n- Status: Draft\n", + "add draft adr", + ); commitFile( dir, ".config/bad-exceptions.json", @@ -121,19 +270,93 @@ test("positive and fail-closed exception fixtures with real git diff", () => { exceptions: [ { paths: ["bootstrap/pre-bun-init.py"], - adr: "docs/adr/ADR-MISSING.md", - reason: "missing adr", + adr: "../../etc/hosts", + reason: "traversal", + alternatives: "none", + sunsetCondition: "never", + }, + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "README.md", + reason: "non-adr file", + alternatives: "none", + sunsetCondition: "never", + }, + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "docs/adr/ADR-9002.md", + reason: "draft adr", + alternatives: "none", + sunsetCondition: "never", + }, + { + paths: ["../escape.py"], + adr: "docs/adr/ADR-9001.md", + reason: "bad path", alternatives: "none", sunsetCondition: "never", }, ], }), - "add broken exception manifest", + "add invalid exceptions", + ); + const invalidLoaded = loadExceptions(dir, ".config/bad-exceptions.json", { ref: "HEAD" }); + assert.equal(invalidLoaded.exceptions.length, 0); + assert.equal(invalidLoaded.errors.length, 4); + assert.ok(invalidLoaded.errors.every((e) => e.code === "INVALID_EXCEPTION")); + }); +}); + +test("CLI exit codes (0 PASS, 1 FAIL, 2 error) and --policy override", async () => { + await withTempRepo((dir) => { + commitFile(dir, "README.md", "# demo\n", "initial"); + execFileSync("git", ["checkout", "-q", "-b", "clean"], { cwd: dir }); + commitFile(dir, "scripts/ok.mts", "export const ok = true;\n", "add ts"); + + const passRun = spawnSync( + process.execPath, + [SCRIPT_PATH, "--root", dir, "--base", "main", "--head", "HEAD"], + { encoding: "utf8" }, + ); + assert.equal(passRun.status, 0, passRun.stderr); + const passJson = JSON.parse(passRun.stdout) as { status: string }; + assert.equal(passJson.status, "PASS"); + + commitFile(dir, "scripts/bad.py", "print('no')\n", "add py"); + const customPolicy = "docs/adr/LOCAL-ADR-0002.md"; + const failRun = spawnSync( + process.execPath, + [ + SCRIPT_PATH, + "--root", + dir, + "--base", + "main", + "--head", + "HEAD", + "--policy", + customPolicy, + ], + { encoding: "utf8" }, + ); + assert.equal(failRun.status, 1, failRun.stderr); + const failJson = JSON.parse(failRun.stdout) as { + status: string; + violations: Array<{ policy: string }>; + }; + assert.equal(failJson.status, "FAIL"); + assert.equal(failJson.violations[0]?.policy, customPolicy); + + const badArgRun = spawnSync(process.execPath, [SCRIPT_PATH, "--unknown-flag"], { + encoding: "utf8", + }); + assert.equal(badArgRun.status, 2); + + const badRefRun = spawnSync( + process.execPath, + [SCRIPT_PATH, "--root", dir, "--base", "main", "--head", "refs/heads/does-not-exist"], + { encoding: "utf8" }, ); - const broken = loadExceptions(dir, ".config/bad-exceptions.json"); - assert.equal(broken.errors.length, 1); - assert.equal(broken.errors[0]?.code, "INVALID_EXCEPTION"); - const brokenResult = evaluateAddedFiles(entries, broken.exceptions, broken.errors); - assert.equal(brokenResult.status, "FAIL"); + assert.equal(badRefRun.status, 2); }); }); diff --git a/skills/quality-gate/SKILL.md b/skills/quality-gate/SKILL.md index d71b72b..39136ed 100644 --- a/skills/quality-gate/SKILL.md +++ b/skills/quality-gate/SKILL.md @@ -486,7 +486,7 @@ quality profileに対象check、入力・環境の識別、最大間隔、強制 新規実装・追加時はformatter・lint・型検査とは別に、[code-naming](../code-naming/SKILL.md) と [system-quality](../system-quality/SKILL.md) に基づき、影響範囲の新旧ファイル・兄弟entry・責務の所有者・import・利用側をコードで評価する。今回の変更が生んだ重複・曖昧な命名・階層不整合は、同じticketで解消する。後日のリファクタリングは受入の代わりにならない。 -機械判定可能な違反は低コストのproject-local検査で拒否する。新規Pythonスクリプト導入のPR差分検査とADR例外境界は [new-python-guard](references/new-python-guard.md)(ADR-0001 §11)に従う。ファイル数や共通prefixだけで意味の良否を決めず、残る意味判断は実コードの差分と周辺構造で確認する。自己申告を独立強制と呼ばず、通常ticketへrelease候補のGUI・full E2Eを追加しない。 +機械判定可能な違反は低コストのproject-local検査で拒否する。新規Pythonスクリプト導入のPR差分検査とADR例外境界は [new-python-guard](references/new-python-guard.md)(実装: [check-new-python.mts](../../scripts/quality/check-new-python.mts) / 根拠: [ADR-0001](../../docs/adr/ADR-0001.md) §11)に従う。ファイル数や共通prefixだけで意味の良否を決めず、残る意味判断は実コードの差分と周辺構造で確認する。自己申告を独立強制と呼ばず、通常ticketへrelease候補のGUI・full E2Eを追加しない。 ## 9. Worker gate diff --git a/skills/quality-gate/references/new-python-guard.md b/skills/quality-gate/references/new-python-guard.md index 3ab3f50..16befcb 100644 --- a/skills/quality-gate/references/new-python-guard.md +++ b/skills/quality-gate/references/new-python-guard.md @@ -4,25 +4,41 @@ ## 対象と境界 -- **検出対象**: PR 差分で **新規追加(`A` / `C`)** された `.py` / `.pyw` / `.pyi` ファイル、および Python shebang(`#!/usr/bin/env python*`, `#!/usr/bin/python*`)を持つ新規ファイル。 -- **非対象(誤検知禁止)**: 既存 Python ファイルの単純変更(`M`)、ファイル名に `python` を含む非 Python ファイル(例: Markdown 文書)。既存 Python の全面撤去は本 gate の責務外。 -- **導入先の既存方針優先**: 対象リポジトリに、より厳しい方針またはプロジェクト固有の言語例外がある場合はそちらを優先する。 +- **検出対象**: PR 差分で **新規追加(`A` / `C`)** された `.py` / `.pyw` / `.pyi` ファイル、Python shebang(`#!/usr/bin/env ... python*` / `pypy*` / `python3.13t`、BOM・環境変数代入・`-S` 等の `env` フラグを含む)を持つ新規ファイル、および非 Python ファイルから Python ファイル/Python shebang へリネーム(`R`)されたファイル。 +- **非対象(誤検知禁止)**: 既存 Python ファイルの単純変更(`M`)、既存 Python ファイル同士のリネーム(`R`: `.py -> .py` や既存 Python shebang 間の移動)、ファイル名に `python` を含む非 Python ファイル(例: Markdown 文書)。既存 Python の全面撤去は本 gate の責務外。 +- **Tree 一貫性と fail-closed**: 差分・先頭行(最大 4 KiB ストリーミング読取)・例外マニフェスト・参照 ADR はすべて `--head` で指定された Git tree から直接読み取る(working tree を参照しない)。非 ASCII パスも `-z` + `core.quotePath=false` で扱い、Git エラーは黙って skip せず終了コード 2 で fail-closed する。 +- **導入先の既存方針優先**: 対象リポジトリに、より厳しい方針またはプロジェクト固有の根拠 ADR がある場合は `--policy ` で明示して優先する。 ## 例外の承認条件(fail-closed) -OS 初期化時の循環依存(Bun 未導入等)で例外が不可避な場合のみ、project-local の例外マニフェスト(既定 `.config/python-exceptions.json`)で以下すべてを明示したものだけを許可する。 +OS 初期化時の循環依存(Bun 未導入等)で例外が不可避な場合のみ、`--head` tree 上の project-local 例外マニフェスト(既定 `.config/python-exceptions.json`)で以下すべてを明示したものだけを許可する。 -- `paths`: 許可対象の正確な相対パス一覧 -- `adr`: 実在する project-local ADR ファイルへのパス +- `paths`: 許可対象の正確な repo-relative パス一覧(絶対パス・`..` 禁止) +- `adr`: `docs/adr/*.md`(または `adr/*.md`)配下に実在する通常ファイルであり、ヘッダに承認済みステータス(`Status: Accepted` / `Status: Approved` / `ステータス: 承認済み` 等)を持つ project-local ADR パス(`Draft` / `Proposed` / `README.md` / symlink / traversal は拒否) - `reason`: 例外が不可避な技術的根拠 - `alternatives`: 検討した代替手段と不採用理由 - `sunsetCondition`: 例外を解除する条件 -マニフェストの形式不正・必須項目欠落・参照 ADR 不在はいずれも fail-closed とし、検査を黙って skip しない。 +マニフェストの形式不正・必須項目欠落・未承認または不在の ADR 参照はいずれも fail-closed とし、検査を黙って skip しない。 ## 実行入口 ```bash -node scripts/quality/check-new-python.mts --base --head +node scripts/quality/check-new-python.mts --base --head [--exceptions .config/python-exceptions.json] [--policy docs/adr/ADR-0001.md#11-tooling-conventions] bun run test:new-python ``` + +## 下流リポジトリでの opt-in 導入例 + +既存の Python コードベースを壊さず新規導入だけを制限するため、導入を選択した下流リポジトリの PR workflow に以下を追加する(既存 Python の変更や承認済み `.config/python-exceptions.json` は通過する)。 + +```yaml +- name: Reject newly added Python scripts on PR diff + if: github.event_name == 'pull_request' + run: | + node scripts/quality/check-new-python.mts \ + --base "${{ github.event.pull_request.base.sha }}" \ + --head "${{ github.event.pull_request.head.sha }}" \ + --exceptions ".config/python-exceptions.json" \ + --policy "docs/adr/ADR-0001.md#11-tooling-conventions" +``` From 7a1b0ab33b989c9cc7fd039edae146e8edb6f93d Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 23:38:07 +0900 Subject: [PATCH 3/5] 142: diff against merge-tree HEAD in PR workflow to stay compatible with workflow-honesty --- .github/workflows/eval-controls.yml | 2 +- skills/quality-gate/references/new-python-guard.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/eval-controls.yml b/.github/workflows/eval-controls.yml index 28f2b9f..137c5f1 100644 --- a/.github/workflows/eval-controls.yml +++ b/.github/workflows/eval-controls.yml @@ -26,7 +26,7 @@ jobs: run: bun run quality:structure - name: Reject newly added Python scripts on PR diff if: github.event_name == 'pull_request' - run: node scripts/quality/check-new-python.mts --base "${{ github.event.pull_request.base.sha }}" --head "${{ github.event.pull_request.head.sha }}" + run: node scripts/quality/check-new-python.mts --base "${{ github.event.pull_request.base.sha }}" --head HEAD - name: Test quality checks and challenge executor run: bun run test:system-quality - name: Challenge actual repository checks diff --git a/skills/quality-gate/references/new-python-guard.md b/skills/quality-gate/references/new-python-guard.md index 16befcb..68a5fec 100644 --- a/skills/quality-gate/references/new-python-guard.md +++ b/skills/quality-gate/references/new-python-guard.md @@ -38,7 +38,7 @@ bun run test:new-python run: | node scripts/quality/check-new-python.mts \ --base "${{ github.event.pull_request.base.sha }}" \ - --head "${{ github.event.pull_request.head.sha }}" \ + --head HEAD \ --exceptions ".config/python-exceptions.json" \ --policy "docs/adr/ADR-0001.md#11-tooling-conventions" ``` From 9afd023c04d36d177eebf8b74ba80f477574858d Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 23:55:31 +0900 Subject: [PATCH 4/5] 142: anchor ADR path pattern to root and add fetch-depth to downstream example --- scripts/quality/check-new-python.mts | 2 +- scripts/quality/check-new-python.test.mts | 16 ++++++++++++++++ .../quality-gate/references/new-python-guard.md | 3 +++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/scripts/quality/check-new-python.mts b/scripts/quality/check-new-python.mts index 4540525..8306684 100644 --- a/scripts/quality/check-new-python.mts +++ b/scripts/quality/check-new-python.mts @@ -50,7 +50,7 @@ const PYTHON_EXTENSION = /\.py[wi]?$/i; const PYTHON_EXECUTABLE = /^(?:pythonw?|pypy)(?:\d+(?:\.\d+)*)?t?$/i; const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/; const ENV_FLAGS_WITH_ARG = new Set(["-u", "--unset", "-C", "--chdir", "-P", "-a"]); -const ADR_PATH_PATTERN = /(?:^|\/)(?:docs\/)?adrs?\/.+\.md$/i; +const ADR_PATH_PATTERN = /^(?:docs\/)?adrs?\/[^/]+\.md$/i; const STATUS_KEY_PATTERN = /^(?:[-*+]\s+)?(?:\*\*)?(?:Status|ステータス|状態)(?:\*\*)?\s*[::]\s*(.+)$/i; const STATUS_HEADING_PATTERN = /^#{1,3}\s*(?:Status|ステータス|状態)\s*$/i; diff --git a/scripts/quality/check-new-python.test.mts b/scripts/quality/check-new-python.test.mts index bae161b..0488bbb 100644 --- a/scripts/quality/check-new-python.test.mts +++ b/scripts/quality/check-new-python.test.mts @@ -197,6 +197,8 @@ test("real git repo: rename semantics allow .py->.py while catching .txt->.py", test("real git repo: exceptions and ADR are loaded from --head tree, rejecting traversal, Draft ADRs, and non-ADR files", async () => { await withTempRepo(async (dir) => { commitFile(dir, "README.md", "# Project\n\nStatus: Accepted\n", "initial"); + commitFile(dir, "vendor/pkg/adr/notes.md", "# Fake\n\nStatus: Accepted\n", "add vendor adr"); + commitFile(dir, "docs/adr/sub/dir/x.md", "# Nested\n\nStatus: Accepted\n", "add nested adr"); execFileSync("git", ["checkout", "-q", "-b", "feature"], { cwd: dir }); commitFile(dir, "bootstrap/pre-bun-init.py", "print('bootstrap')\n", "add python file"); @@ -282,6 +284,20 @@ test("real git repo: exceptions and ADR are loaded from --head tree, rejecting t alternatives: "none", sunsetCondition: "never", }, + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "vendor/pkg/adr/notes.md", + reason: "prefixed non-root adr", + alternatives: "none", + sunsetCondition: "never", + }, + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "docs/adr/sub/dir/x.md", + reason: "nested subdir adr", + alternatives: "none", + sunsetCondition: "never", + }, { paths: ["bootstrap/pre-bun-init.py"], adr: "docs/adr/ADR-9002.md", diff --git a/skills/quality-gate/references/new-python-guard.md b/skills/quality-gate/references/new-python-guard.md index 68a5fec..dd42a08 100644 --- a/skills/quality-gate/references/new-python-guard.md +++ b/skills/quality-gate/references/new-python-guard.md @@ -33,6 +33,9 @@ bun run test:new-python 既存の Python コードベースを壊さず新規導入だけを制限するため、導入を選択した下流リポジトリの PR workflow に以下を追加する(既存 Python の変更や承認済み `.config/python-exceptions.json` は通過する)。 ```yaml +- uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Reject newly added Python scripts on PR diff if: github.event_name == 'pull_request' run: | From fd7886b3b8cf5b32ca9e7279bc07585195f60a90 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 23:57:47 +0900 Subject: [PATCH 5/5] 142: update invalid exception count assertion for root-anchored ADR tests --- scripts/quality/check-new-python.test.mts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/quality/check-new-python.test.mts b/scripts/quality/check-new-python.test.mts index 0488bbb..75f68d8 100644 --- a/scripts/quality/check-new-python.test.mts +++ b/scripts/quality/check-new-python.test.mts @@ -318,7 +318,7 @@ test("real git repo: exceptions and ADR are loaded from --head tree, rejecting t ); const invalidLoaded = loadExceptions(dir, ".config/bad-exceptions.json", { ref: "HEAD" }); assert.equal(invalidLoaded.exceptions.length, 0); - assert.equal(invalidLoaded.errors.length, 4); + assert.equal(invalidLoaded.errors.length, 6); assert.ok(invalidLoaded.errors.every((e) => e.code === "INVALID_EXCEPTION")); }); });