From 086e38f0a4e6e031b3a078ea5af179e80b938317 Mon Sep 17 00:00:00 2001 From: dmae97 <146327957+dmae97@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:48:39 +0900 Subject: [PATCH] =?UTF-8?q?chore(husky):=20=EB=8B=A4=EB=A5=B8=20=EC=84=B8?= =?UTF-8?q?=EC=85=98=EC=9D=B4=20=EC=A0=90=EC=9C=A0=ED=95=9C=20=EA=B2=BD?= =?UTF-8?q?=EB=A1=9C=EC=9D=98=20=EC=BB=A4=EB=B0=8B=EC=9D=84=20pre-commit?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EA=B1=B0=EB=B6=80=ED=95=98=EB=9D=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .husky/pre-commit | 2 + scripts/check-scope-lease.mjs | 120 ++++++++++++++++++++++++ scripts/test/check-scope-lease.test.mjs | 82 ++++++++++++++++ 3 files changed, 204 insertions(+) create mode 100644 scripts/check-scope-lease.mjs create mode 100644 scripts/test/check-scope-lease.test.mjs diff --git a/.husky/pre-commit b/.husky/pre-commit index a7f4acf54f..c6d3a887f4 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -3,6 +3,8 @@ # Preserve the exact selection, including partially staged files. STAGED_TREE=$(git write-tree) || exit 1 +node scripts/check-scope-lease.mjs || exit 1 + node scripts/check-lockfile-commit.mjs if [ $? -ne 0 ]; then exit 1 diff --git a/scripts/check-scope-lease.mjs b/scripts/check-scope-lease.mjs new file mode 100644 index 0000000000..fa3270caa2 --- /dev/null +++ b/scripts/check-scope-lease.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * Pre-commit half of the OMK scope-lease extension: refuse a commit whose index + * holds a path that another live OMK session has leased, so a commit made from + * a plain terminal obeys the same leases as one made inside a session. + * + * Lease files: `/omk-leases/.json` with + * `{ session, pid, host, worktree, branch, patterns, heartbeat }`. Patterns are + * repo-relative paths or globs. Liveness matches the extension: same host means + * the PID runs and the lease is under 24 h old; another host means a heartbeat + * under 2 h old. + * + * A lease whose OMK process is an ancestor of this hook is the committer's own. + * To commit a live session's files from another terminal, name that session: + * OMK_LEASE_AS=[,] git commit ... + */ +import { execFileSync } from "node:child_process"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { hostname } from "node:os"; +import { join, matchesGlob, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const REMOTE_TTL_MS = 2 * 60 * 60 * 1000; +const LOCAL_MAX_MS = 24 * 60 * 60 * 1000; + +export function pidAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error?.code === "EPERM"; + } +} + +export function leaseLive(lease, now, host, alive = pidAlive) { + const age = now - lease.heartbeat; + if (lease.host === host) return age < LOCAL_MAX_MS && alive(lease.pid); + return age < REMOTE_TTL_MS; +} + +export function patternMatches(pattern, path) { + return pattern === path || (/[*?[{]/.test(pattern) && matchesGlob(path, pattern)); +} + +function parentPid(pid) { + try { + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]); + } catch { + try { + return Number(execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim()); + } catch { + return 0; + } + } +} + +export function ancestorPids(pid = process.pid) { + const seen = new Set(); + for (let p = pid; p > 1 && !seen.has(p); p = parentPid(p)) seen.add(p); + return seen; +} + +/** Conflicts as `{ path, lease }` for staged paths held by a live lease that is not the committer's. */ +export function findConflicts({ leases, staged, now, host, ancestors, as = [], alive = pidAlive }) { + const conflicts = []; + for (const lease of leases) { + if (!leaseLive(lease, now, host, alive)) continue; + if (lease.host === host && ancestors.has(lease.pid)) continue; + if (as.some((prefix) => prefix && lease.session.startsWith(prefix))) continue; + for (const path of staged) { + if (lease.patterns.some((p) => patternMatches(p, path))) conflicts.push({ path, lease }); + } + } + return conflicts; +} + +export function readLeases(dir) { + if (!existsSync(dir)) return []; + const leases = []; + for (const name of readdirSync(dir)) { + if (!name.endsWith(".json")) continue; + try { + const lease = JSON.parse(readFileSync(join(dir, name), "utf8")); + if (typeof lease?.session === "string" && Array.isArray(lease.patterns)) leases.push(lease); + } catch { + // A lease being rewritten is skipped; the session's own tool gate still applies. + } + } + return leases; +} + +function git(args) { + return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const common = git(["rev-parse", "--path-format=absolute", "--git-common-dir"]).trim(); + const leases = readLeases(join(common, "omk-leases")); + if (leases.length === 0) process.exit(0); + const staged = git(["diff", "--cached", "--name-only", "-z"]).split("\0").filter(Boolean); + const conflicts = findConflicts({ + leases, + staged, + now: Date.now(), + host: hostname(), + ancestors: ancestorPids(), + as: (process.env.OMK_LEASE_AS ?? "").split(",").map((s) => s.trim()), + }); + if (conflicts.length === 0) process.exit(0); + console.error("❌ Staged paths are leased by another live OMK session:"); + for (const { path, lease } of conflicts) { + console.error( + ` - ${path}: session ${lease.session.slice(0, 8)} (branch ${lease.branch}, worktree ${lease.worktree}, pid ${lease.pid}@${lease.host})`, + ); + } + console.error("Unstage them (git restore --staged ), run /lease release in that session, or"); + console.error("commit as that session: OMK_LEASE_AS= git commit ..."); + process.exit(1); +} diff --git a/scripts/test/check-scope-lease.test.mjs b/scripts/test/check-scope-lease.test.mjs new file mode 100644 index 0000000000..58cb600367 --- /dev/null +++ b/scripts/test/check-scope-lease.test.mjs @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import { execFileSync, spawn, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { hostname, tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { after, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { ancestorPids, findConflicts, leaseLive } from "../check-scope-lease.mjs"; + +const script = join(dirname(fileURLToPath(import.meta.url)), "..", "check-scope-lease.mjs"); +const lease = (over) => ({ + session: "aaaaaaaa-1", + pid: 10, + host: "h", + worktree: "/w", + branch: "main", + patterns: ["web/**"], + heartbeat: 0, + ...over, +}); + +describe("findConflicts", () => { + const base = { now: 1000, host: "h", ancestors: new Set([1, 2]), alive: () => true }; + it("reports staged paths held by another live session", () => { + const out = findConflicts({ ...base, leases: [lease()], staged: ["web/a.ts", "api/b.ts"] }); + assert.deepEqual( + out.map((c) => c.path), + ["web/a.ts"], + ); + }); + it("skips the committer's own session, OMK_LEASE_AS prefixes and dead leases", () => { + const staged = ["web/a.ts"]; + assert.equal(findConflicts({ ...base, leases: [lease({ pid: 2 })], staged }).length, 0); + assert.equal(findConflicts({ ...base, leases: [lease()], staged, as: ["aaaa"] }).length, 0); + assert.equal(findConflicts({ ...base, leases: [lease()], staged, alive: () => false }).length, 0); + assert.equal(findConflicts({ ...base, leases: [lease()], staged, as: [""] }).length, 1); + }); + it("follows heartbeat for other hosts", () => { + assert.ok(leaseLive(lease({ host: "x" }), 1000, "h")); + assert.ok(!leaseLive(lease({ host: "x" }), 3 * 3600e3, "h")); + }); + it("walks up to the test runner's parent", () => { + assert.ok(ancestorPids().has(process.ppid)); + }); +}); + +describe("pre-commit run in a real repository", () => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "check-scope-lease-"))); + const holder = spawn("sleep", ["60"]); + after(() => { + holder.kill(); + rmSync(dir, { recursive: true, force: true }); + }); + // The pre-commit hook exports GIT_DIR/GIT_INDEX_FILE; inheriting them would write to the outer repository. + const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))); + const git = (...args) => execFileSync("git", ["-C", dir, ...args], { encoding: "utf8", env: cleanEnv }); + git("init", "-q", "-b", "main"); + mkdirSync(join(dir, "web")); + writeFileSync(join(dir, "web", "a.ts"), "x"); + writeFileSync(join(dir, "b.ts"), "y"); + const leases = join(git("rev-parse", "--path-format=absolute", "--git-common-dir").trim(), "omk-leases"); + mkdirSync(leases); + const run = (env = {}) => spawnSync(process.execPath, [script], { cwd: dir, encoding: "utf8", env: { ...cleanEnv, ...env } }); + const write = (over) => writeFileSync(join(leases, "a.json"), JSON.stringify(lease({ host: hostname(), heartbeat: Date.now(), ...over }))); + + it("blocks a terminal commit of a path another live session holds", () => { + write({ pid: holder.pid }); + git("add", "web/a.ts", "b.ts"); + const out = run(); + assert.equal(out.status, 1); + assert.match(out.stderr, /web\/a\.ts: session aaaaaaaa/); + assert.doesNotMatch(out.stderr, /b\.ts: session/); + }); + it("passes for unleased paths, the holder named in OMK_LEASE_AS, and the committer's own session", () => { + git("rm", "-q", "--cached", "web/a.ts"); + assert.equal(run().status, 0); + git("add", "web/a.ts"); + assert.equal(run({ OMK_LEASE_AS: "aaaaaaaa" }).status, 0); + write({ pid: process.pid }); + assert.equal(run().status, 0); + }); +});