diff --git a/.github/workflows/eval-controls.yml b/.github/workflows/eval-controls.yml index 2c6a950..a1be871 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 HEAD - name: Check workflow gate honesty run: bun run quality:workflow-honesty - name: Test gate honesty and verify real execution count diff --git a/package.json b/package.json index 221383c..4981d1f 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,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", "quality:workflow-honesty": "node scripts/gate-honesty/cli.mts workflow --workflows-dir .github/workflows", "test:gate-honesty": "node scripts/gate-honesty/cli.mts run-and-verify --partition gate-honesty --floor 1 -- node --test --test-reporter=tap scripts/gate-honesty/gate-honesty.test.mts scripts/quality/check-gate-honesty.test.mts", "test:system-quality": "node --test evals/system-quality/*.test.mts evals/code-structure/*.test.mts scripts/quality/*.test.mts", diff --git a/scripts/quality/check-new-python.mts b/scripts/quality/check-new-python.mts new file mode 100644 index 0000000..8306684 --- /dev/null +++ b/scripts/quality/check-new-python.mts @@ -0,0 +1,842 @@ +#!/usr/bin/env node +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 { + 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[]; +} + +export interface LoadExceptionsOptions { + readonly ref?: string; + readonly policy?: string; +} + +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 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); +} + +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; + 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 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(manifestLookup.content) as unknown; + } catch (error) { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: normalizedManifestPath, + detail: `malformed exception manifest: ${error instanceof Error ? error.message : String(error)}`, + policy, + }, + ], + }; + } + if (!isRecord(parsed) || !Array.isArray(parsed.exceptions)) { + return { + exceptions: [], + errors: [ + { + code: "INVALID_EXCEPTION", + path: normalizedManifestPath, + detail: 'exception manifest must contain an "exceptions" array', + policy, + }, + ], + }; + } + + const valid: PythonException[] = []; + const sourceLabel = options.ref !== undefined ? ` at ${options.ref}` : ""; + for (const [index, raw] of parsed.exceptions.entries()) { + const label = `${normalizedManifestPath}#exceptions[${index}]`; + if (!isRecord(raw)) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: "exception entry must be an object", + policy, + }); + continue; + } + 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 ( + normalizedPaths.length === 0 || + invalidPathFound || + !nonEmptyString(raw.adr) || + !nonEmptyString(raw.reason) || + !nonEmptyString(raw.alternatives) || + !nonEmptyString(raw.sunsetCondition) + ) { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + detail: + "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; + } + if (adrLookup.status === "non-regular") { + errors.push({ + code: "INVALID_EXCEPTION", + path: label, + 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: normalizedPaths, + adr: normalizedAdr, + reason: raw.reason, + alternatives: raw.alternatives, + sunsetCondition: raw.sunsetCondition, + }); + } + 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) { + const normalized = normalizeRepoRelativePath(p) ?? p.replaceAll("\\", "/"); + allowedPaths.add(normalized); + } + } + + let checkedAddedFiles = 0; + for (const entry of entries) { + const normalizedStatus = entry.status.trim().toUpperCase(); + 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); + 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, + }); + } + + return { + status: violations.length > 0 ? "FAIL" : "PASS", + checkedAddedFiles, + exemptedFiles, + violations, + }; +} + +export function readFirstLineFromGitObject( + root: string, + objectSpec: string, +): Promise { + return new Promise((resolvePromise, rejectPromise) => { + const child = spawn("git", ["cat-file", "blob", objectSpec], { + cwd: root, + stdio: ["ignore", "pipe", "pipe"], + }); + 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 async function collectGitDiffEntries( + root: string, + baseRef: string, + headRef: string, +): Promise { + const output = execFileSync( + "git", + [ + "-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 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; +} + +interface CliArgs { + root: string; + base: string; + head: string; + exceptionsPath: string; + policy: string; +} + +function parseCliArgs(argv: readonly string[]): CliArgs { + const args: CliArgs = { + root: ".", + 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]; + 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 if (flag === "--policy" && next) { + args.policy = next; + i++; + } else { + throw new Error(`unknown or incomplete argument: ${flag}`); + } + } + return args; +} + +async function main(argv: readonly string[]): Promise { + 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); + 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 = await 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..75f68d8 --- /dev/null +++ b/scripts/quality/check-new-python.test.mts @@ -0,0 +1,378 @@ +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +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"; + +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 }); + await fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +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 }); +} + +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("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", () => { + 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("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 }); + + // Non-ASCII .py filename + non-ASCII extensionless python shebang + commitFile(dir, "scripts/日本語.py", "print('ja')\n", "add non-ascii py"); + commitFile( + dir, + "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"); + 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"); + + // 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({ + exceptions: [ + { + paths: ["bootstrap/pre-bun-init.py"], + adr: "docs/adr/ADR-9001.md", + reason: "pre-bun bootstrap", + alternatives: "sh lacks json", + sunsetCondition: "remove after bun bootstrap", + }, + ], + }), + ); + 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 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"]); + + // 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", + JSON.stringify({ + exceptions: [ + { + paths: ["bootstrap/pre-bun-init.py"], + 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: "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", + reason: "draft adr", + alternatives: "none", + sunsetCondition: "never", + }, + { + paths: ["../escape.py"], + adr: "docs/adr/ADR-9001.md", + reason: "bad path", + alternatives: "none", + sunsetCondition: "never", + }, + ], + }), + "add invalid exceptions", + ); + const invalidLoaded = loadExceptions(dir, ".config/bad-exceptions.json", { ref: "HEAD" }); + assert.equal(invalidLoaded.exceptions.length, 0); + assert.equal(invalidLoaded.errors.length, 6); + 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" }, + ); + assert.equal(badRefRun.status, 2); + }); +}); diff --git a/skills/quality-gate/SKILL.md b/skills/quality-gate/SKILL.md index 49abcde..b032da6 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)(実装: [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 new file mode 100644 index 0000000..dd42a08 --- /dev/null +++ b/skills/quality-gate/references/new-python-guard.md @@ -0,0 +1,47 @@ +# 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*` / `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 未導入等)で例外が不可避な場合のみ、`--head` tree 上の project-local 例外マニフェスト(既定 `.config/python-exceptions.json`)で以下すべてを明示したものだけを許可する。 + +- `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 しない。 + +## 実行入口 + +```bash +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 +- uses: actions/checkout@v4 + with: + fetch-depth: 0 +- 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 HEAD \ + --exceptions ".config/python-exceptions.json" \ + --policy "docs/adr/ADR-0001.md#11-tooling-conventions" +```