Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
120 changes: 120 additions & 0 deletions scripts/check-scope-lease.mjs
Original file line number Diff line number Diff line change
@@ -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: `<git-common-dir>/omk-leases/<session>.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=<session-prefix>[,<prefix>] 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 <path>), run /lease release in that session, or");
console.error("commit as that session: OMK_LEASE_AS=<session-prefix> git commit ...");
process.exit(1);
}
82 changes: 82 additions & 0 deletions scripts/test/check-scope-lease.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading