Skip to content
Closed
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
11 changes: 5 additions & 6 deletions packages/loopover-miner/lib/deny-hook-synthesis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
// this module is now a thin wrapper that re-exports those pure helpers and keeps the local SQLite store for
// refresh + maintainer review before any synthesized rule takes effect. Approved rules merge with
// {@link DEFAULT_DENY_RULES}; unapproved proposals never block tool calls. No behavior change.
import { chmodSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import {
aggregateBlockerHistory,
Expand All @@ -23,6 +22,7 @@ import {
} from "@loopover/engine";
import type { DenyRuleProposal, SynthesisConfig } from "@loopover/engine";
import { DEFAULT_FORGE_CONFIG } from "./forge-config.js";
import { openLocalStoreDb } from "./local-store.js";
import type { DenyRule } from "./deny-hooks.js";
import { DENY_HOOK_SYNTHESIS_PURGE_SPEC, purgeStoreByRepo } from "./store-maintenance.js";

Expand Down Expand Up @@ -162,10 +162,9 @@ function ensureDenyRuleProposalsForgeScope(db: DatabaseSync): void {
*/
export function initDenyHookSynthesisStore(dbPath: string = resolveDenyHookSynthesisDbPath()): DenyHookSynthesisStore {
const resolvedPath = normalizeDbPath(dbPath);
mkdirSync(dirname(resolvedPath), { recursive: true, mode: 0o700 });
const db = new DatabaseSync(resolvedPath);
chmodSync(resolvedPath, 0o600);
db.exec("PRAGMA busy_timeout = 5000");
// Delegate the crash-safe open (mkdir 0700 + chmod 0600 + busy_timeout + cleanup registration) to the shared
// helper (#8319) instead of hand-rolling it, matching plan-store.ts/attempt-log.ts.
const db = openLocalStoreDb(resolvedPath);
db.exec(`
CREATE TABLE IF NOT EXISTS deny_rule_proposals (
repo_full_name TEXT NOT NULL,
Expand Down
9 changes: 5 additions & 4 deletions packages/loopover-miner/lib/laptop-init.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { accessSync, chmodSync, constants, existsSync, mkdirSync } from "node:fs";
import { accessSync, constants, existsSync } from "node:fs";
import { homedir } from "node:os";
import { delimiter, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { applySchemaMigrations } from "./schema-version.js";
import { openLocalStoreDb } from "./local-store.js";
import { reportCliFailure } from "./cli-error.js";
import { resolveGitHubToken } from "./github-token-resolution.js";

Expand Down Expand Up @@ -52,9 +53,10 @@ export function resolveLaptopStateDbPath(env: Record<string, string | undefined>
export function initLaptopState(env: Record<string, string | undefined> = process.env): LaptopInitResult {
const stateDir = resolveMinerStateDir(env);
const dbPath = resolveLaptopStateDbPath(env);
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
// Sample created before openLocalStoreDb opens (and thus creates) the file. The shared helper (#8319) does the
// mkdir 0700 (on the parent = stateDir), chmod 0600, busy_timeout, and crash-safe cleanup registration.
const created = !existsSync(dbPath);
const db = new DatabaseSync(dbPath);
const db = openLocalStoreDb(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS laptop_meta (
key TEXT PRIMARY KEY,
Expand All @@ -67,7 +69,6 @@ export function initLaptopState(env: Record<string, string | undefined> = proces
db.prepare("INSERT INTO laptop_meta (key, value) VALUES ('initialized_at', ?)")
.run(new Date().toISOString());
}
chmodSync(dbPath, 0o600);
db.close();
return { stateDir, dbPath, created };
}
Expand Down
12 changes: 5 additions & 7 deletions packages/loopover-miner/lib/orb-export.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { chmodSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { join } from "node:path";
import { createHash, createHmac } from "node:crypto";
import { openLocalStoreDb } from "./local-store.js";
import { generateAnonSecret, hmacAnonymize as engineHmacAnonymize } from "@loopover/engine";
import { readPrOutcomes } from "./pr-outcome.js";
import type { NormalizedPrOutcomePayload, PrOutcomeLedgerReader } from "./pr-outcome.js";
Expand Down Expand Up @@ -125,10 +124,9 @@ export function buildAnonymizedOrbBatch(
*/
export function openOrbExportStore(dbPath: string = resolveOrbExportDbPath()): OrbExportStore {
const resolvedPath = normalizeDbPath(dbPath);
mkdirSync(dirname(resolvedPath), { recursive: true, mode: 0o700 });
const db = new DatabaseSync(resolvedPath);
chmodSync(resolvedPath, 0o600);
db.exec("PRAGMA busy_timeout = 5000");
// Delegate the crash-safe open (mkdir 0700 + chmod 0600 + busy_timeout + cleanup registration) to the shared
// helper (#8319) instead of hand-rolling it, matching plan-store.ts/attempt-log.ts.
const db = openLocalStoreDb(resolvedPath);
db.exec(`CREATE TABLE IF NOT EXISTS orb_export_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`);

const getStatement = db.prepare("SELECT value FROM orb_export_meta WHERE key = ?");
Expand Down
16 changes: 16 additions & 0 deletions test/unit/miner-deny-hook-synthesis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import type { DenyRuleProposal } from "../../packages/loopover-engine/src/miner/
// #7525: normalizeRepoFullName is defined in the engine and re-exported unchanged by the miner-lib module
// above; import it from the engine source directly so the guard's src branches are the ones exercised.
import { normalizeRepoFullName } from "../../packages/loopover-engine/src/miner/deny-hook-synthesis";
import {
cleanupResourceCount,
resetProcessLifecycleForTesting,
} from "../../packages/loopover-miner/lib/process-lifecycle.js";

const tempDirs: string[] = [];
const stores: Array<{ close(): void }> = [];
Expand Down Expand Up @@ -163,6 +167,18 @@ describe("initDenyHookSynthesisStore() (#4522)", () => {
expect(() => initDenyHookSynthesisStore(" ")).toThrow("invalid_deny_hook_synthesis_db_path");
});

it("registers the store for crash-safe cleanup and unregisters it on close (#8319)", () => {
const dir = mkdtempSync(join(tmpdir(), "miner-deny-hook-synthesis-cleanup-"));
tempDirs.push(dir);
resetProcessLifecycleForTesting();
expect(cleanupResourceCount()).toBe(0);
const store = initDenyHookSynthesisStore(join(dir, "deny-hook-synthesis.sqlite3"));
// openLocalStoreDb registered the handle for crash-safe close on SIGINT/SIGTERM; close() unregisters it.
expect(cleanupResourceCount()).toBe(1);
store.close();
expect(cleanupResourceCount()).toBe(0);
});

it("skips the forge-scope migration on a second open of an already-migrated file", () => {
const dir = mkdtempSync(join(tmpdir(), "miner-deny-hook-synthesis-remigrate-"));
tempDirs.push(dir);
Expand Down
15 changes: 15 additions & 0 deletions test/unit/miner-laptop-init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import {
resolveLaptopStateDbPath,
runInit,
} from "../../packages/loopover-miner/lib/laptop-init.js";
import {
cleanupResourceCount,
resetProcessLifecycleForTesting,
} from "../../packages/loopover-miner/lib/process-lifecycle.js";

const roots: string[] = [];

Expand Down Expand Up @@ -73,6 +77,17 @@ describe("loopover-miner laptop init (#2329)", () => {
expect(checkLaptopStateSqlite(env).ok).toBe(true);
});

it("routes through the crash-safe openLocalStoreDb helper without leaking a cleanup registration (#8319)", () => {
const root = tempRoot();
const env = { LOOPOVER_MINER_CONFIG_DIR: join(root, "state") };
resetProcessLifecycleForTesting();
expect(cleanupResourceCount()).toBe(0);
initLaptopState(env);
// openLocalStoreDb registered the bootstrap handle for crash-safe cleanup and initLaptopState closed it,
// which unregisters -- so a completed init leaves no leaked/half-written handle behind.
expect(cleanupResourceCount()).toBe(0);
});

it("re-running init is idempotent and does not clobber existing metadata", () => {
const root = tempRoot();
const env = { LOOPOVER_MINER_CONFIG_DIR: join(root, "state") };
Expand Down
15 changes: 15 additions & 0 deletions test/unit/miner-orb-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import {
sendAmsExportBatch,
} from "../../packages/loopover-miner/lib/orb-export.js";
import type { OrbExportOutcome, OrbExportRow } from "../../packages/loopover-miner/lib/orb-export.js";
import {
cleanupResourceCount,
resetProcessLifecycleForTesting,
} from "../../packages/loopover-miner/lib/process-lifecycle.js";

let dir: string;
function storePath() {
Expand Down Expand Up @@ -68,6 +72,17 @@ describe("orb-export store (#4277)", () => {
expect(store.getCursor()).toBe("2026-01-02T00:00:00Z");
store.close();
});

it("registers the store for crash-safe cleanup and unregisters it on close (#8319)", () => {
resetProcessLifecycleForTesting();
expect(cleanupResourceCount()).toBe(0);
const store = openOrbExportStore(storePath());
// openLocalStoreDb registered the handle so a SIGINT/SIGTERM mid-write closes it instead of leaving the file
// half-written; the normal close() path unregisters, so the happy path never leaks or double-closes at exit.
expect(cleanupResourceCount()).toBe(1);
store.close();
expect(cleanupResourceCount()).toBe(0);
});
});

describe("hmacAnonymize", () => {
Expand Down