diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 1b941036d3..dc14c34165 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -107,7 +107,6 @@ // disables the Turso sink (default on; token resolved by name // via the resolveBwsSecret plumbing: // turso.fleet-platform-rw-token). -import { existsSync } from "node:fs"; import { execFile } from "node:child_process"; import { access, appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; @@ -135,6 +134,7 @@ import { SnapshotStore, isSnapshotRecord, snapshotKey } from "../src/snapshots.t import { safeProviderReason } from "../src/credential-lifecycle.ts"; import { renewOpenDesignSession, type OpenDesignCredentialLike } from "../src/opendesign-renewal.ts"; import { ensureLibDependencies } from "../src/lib-deps.ts"; +import { loadOpenChamberLib, resolveLibDir as resolveOpenChamberLib } from "../src/openchamber-lib.ts"; import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts"; import { renewMetaSession } from "../src/meta-renewal.ts"; import { classEnabled, getAlertsStore } from "../src/alerts.ts"; @@ -144,22 +144,19 @@ const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); const HOME = homedir(); const HIDDEN = join(HOME, "workspace/goals/keep-the-four-repos-healthy/hidden_files"); -/** The OpenDesign keeper's credential-store accessors live in the - * OpenChamber lib (the managed store's home). Store plumbing for ONE - * credential the keeper maintains — never a quota reading path: all - * readings come from the subcommand (see the header). */ -function resolveLibDir(): string { - const candidates = [ +/** Candidate checkouts for the OpenDesign keeper's managed credential + * store (the OpenChamber lib). Store plumbing for ONE credential the + * keeper maintains, never a quota reading path: all readings come from + * the subcommand (see the header). Each candidate must be a clean main + * checkout (src/openchamber-lib.ts), so a parked or stale checkout is + * rejected rather than imported. */ +function openChamberLibCandidates(): string[] { + return [ process.env.OPENCHAMBER_LIB_DIR, join(HOME, "git/devtoday-openchamber/packages/web/server/lib"), join(HOME, "git/openchamber-fork/packages/web/server/lib"), ].filter((d): d is string => typeof d === "string" && d !== ""); - for (const dir of candidates) { - if (existsSync(join(dir, "quota/index.js"))) return dir; - } - return candidates[0]; } -const libDir = resolveLibDir(); const currentPath = process.env.QUOTA_CURRENT_PATH ?? join(PKG, "quota-current.json"); const heartbeatPath = process.env.QUOTA_HEARTBEAT_PATH ?? join(PKG, "quota-gatherer-heartbeat.json"); const statePath = process.env.QUOTA_GATHERER_STATE_PATH ?? join(PKG, "quota-gatherer-state.json"); @@ -294,15 +291,6 @@ async function resolveBwsSecret(key: string): Promise { } } -/** Managed-credential accessors for the OpenDesign keeper (libDir). */ -interface OpenDesignCredentialsModule { - readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null; - writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown; -} -interface OpenDesignProviderModule { - fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise; -} - /** * The OpenDesign session keeper run. Runs before the subcommand so a * credential renewed this tick is the one the tick's OpenDesign read @@ -315,6 +303,10 @@ interface OpenDesignProviderModule { async function runOpenDesignRenewal(tickAt: string): Promise { if (process.env.OPENDESIGN_RENEWAL_DISABLED === "1") return; try { + // Resolve first: a parked, dirty or non-main checkout is rejected + // here, before anything from it is installed or imported. The keeper + // then fails soft and the subcommand readings still run. + const lib = await resolveOpenChamberLib(openChamberLibCandidates()); // #8759: the lib checkout is a plain clone; if its declared // dependencies were never installed, every import below fails // with "Cannot find package ..." and Bun caches that failure @@ -338,16 +330,11 @@ async function runOpenDesignRenewal(tickAt: string): Promise { } : undefined; await ensureLibDependencies({ - libDir, + libDir: lib.dir, log: (line) => console.log("quota-gatherer: " + line), ...(install ? { install } : {}), }); - const credentials = (await import( - join(libDir, "quota/credentials/providers.js") - )) as unknown as OpenDesignCredentialsModule; - const provider = (await import( - join(libDir, "quota/providers/opendesign.js") - )) as unknown as OpenDesignProviderModule; + const { credentials, provider } = await loadOpenChamberLib(lib); const state = await renewOpenDesignSession({ readCredential: () => credentials.readManagedCredential("opendesign"), writeCredential: (value) => { diff --git a/pm-stack/aggregator/src/openchamber-lib.ts b/pm-stack/aggregator/src/openchamber-lib.ts new file mode 100644 index 0000000000..947adde532 --- /dev/null +++ b/pm-stack/aggregator/src/openchamber-lib.ts @@ -0,0 +1,136 @@ +import { execFile } from "node:child_process"; +import { existsSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import type { OpenDesignCredentialLike } from "./opendesign-renewal.ts"; + +export type GitRun = (cwd: string, args: string[]) => Promise; + +export interface OpenChamberCredentialsModule { + readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null; + writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown; +} + +export interface OpenChamberProviderModule { + fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise; +} + +export interface ResolvedOpenChamberLib { + dir: string; + root: string; + revision: string; +} + +export interface ResolveLibOptions { + gitRun?: GitRun; + log?: (message: string) => void; +} + +export interface OpenChamberLibModules { + credentials: OpenChamberCredentialsModule; + provider: OpenChamberProviderModule; +} + +const REQUIRED_MODULE_EXPORTS = [ + { + path: "quota/credentials/providers.js", + names: ["readManagedCredential", "writeManagedCredential"], + }, + { path: "quota/providers/opendesign.js", names: ["fetchOpenDesignQuota"] }, +] as const; + +const defaultGitRun: GitRun = (cwd, args) => + new Promise((resolveOutput, reject) => { + execFile("git", args, { cwd, timeout: 10_000, maxBuffer: 1 << 20 }, (err, stdout) => { + if (err) reject(err); + else resolveOutput(stdout.trim()); + }); + }); + +async function inspectCandidate(dir: string, gitRun: GitRun): Promise { + if (!existsSync(resolve(dir, "quota/index.js"))) { + throw new Error("quota/index.js is missing"); + } + + const root = (await gitRun(dir, ["rev-parse", "--show-toplevel"])).trim(); + if (!root) throw new Error("Git returned an empty checkout root"); + + const branch = (await gitRun(root, ["branch", "--show-current"])).trim(); + if (branch !== "main") { + throw new Error(`checkout is on ${branch ? `branch ${branch}` : "a detached HEAD"}, not main`); + } + + const changes = (await gitRun(root, ["status", "--porcelain", "--untracked-files=normal"])).trim(); + if (changes) throw new Error("checkout has a dirty working tree"); + + const revision = (await gitRun(root, ["rev-parse", "--verify", "HEAD^{commit}"])).trim(); + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(revision)) { + throw new Error(`Git returned an invalid HEAD revision ${JSON.stringify(revision)}`); + } + + return { dir, root, revision }; +} + +/** Pick the first clean main checkout. Imports nothing: the caller installs + * the checkout's dependencies (src/lib-deps.ts) before loading its modules. */ +export async function resolveLibDir( + candidates: string[], + { gitRun = defaultGitRun, log = console.warn }: ResolveLibOptions = {}, +): Promise { + const rejected: string[] = []; + const seen = new Set(); + + for (const candidate of candidates) { + const dir = resolve(candidate); + if (seen.has(dir)) continue; + seen.add(dir); + try { + const lib = await inspectCandidate(dir, gitRun); + log(`quota-gatherer: OpenChamber lib dir=${lib.dir} branch=main rev=${lib.revision}`); + return lib; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + rejected.push(`${dir}: ${reason}`); + log(`quota-gatherer: rejected OpenChamber lib ${dir}: ${reason}`); + } + } + + const detail = rejected.length ? rejected.join("; ") : "no candidates were configured"; + throw new Error(`no usable clean main OpenChamber lib checkout found (${detail})`); +} + +async function importRequiredModule(dir: string, path: string): Promise> { + try { + return (await import(pathToFileURL(resolve(dir, path)).href)) as Record; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + const missing = + message.match(/does not provide an export named ['"]([^'"]+)['"]/i) ?? + message.match(/export named ['"]([^'"]+)['"] not found/i); + if (missing) { + throw new Error(`missing required export "${missing[1]}" while importing ${path}`); + } + throw new Error(`could not import ${path}: ${message}`); + } +} + +/** Import the credential APIs from a resolved checkout and name any missing export. */ +export async function loadOpenChamberLib(lib: ResolvedOpenChamberLib): Promise { + const [credentials, provider] = await Promise.all( + REQUIRED_MODULE_EXPORTS.map(({ path }) => importRequiredModule(lib.dir, path)), + ); + const modules = [credentials, provider]; + for (let index = 0; index < REQUIRED_MODULE_EXPORTS.length; index += 1) { + const required = REQUIRED_MODULE_EXPORTS[index]; + const module = modules[index]; + for (const name of required.names) { + if (typeof module[name] !== "function") { + throw new Error(`missing required export "${name}" in ${required.path}`); + } + } + } + return { + credentials: credentials as unknown as OpenChamberCredentialsModule, + provider: provider as unknown as OpenChamberProviderModule, + }; +} diff --git a/pm-stack/aggregator/test/gather-quota.test.ts b/pm-stack/aggregator/test/gather-quota.test.ts index 829fb07d35..23567a7609 100644 --- a/pm-stack/aggregator/test/gather-quota.test.ts +++ b/pm-stack/aggregator/test/gather-quota.test.ts @@ -535,8 +535,8 @@ test("an uninstalled lib checkout dependency is installed and the OpenDesign kee usage: { windows: { weekly: { usedPercent: null } } }, }; - // A plain-clone lib checkout: manifest + lockfile declare fake-dep, - // but node_modules was never installed — the #8759 defect shape. + // A clean main lib checkout (#5721 gate): manifest + lockfile declare + // fake-dep, but node_modules was never installed — the #8759 defect shape. await mkdir(join(libDir, "quota/credentials"), { recursive: true }); await mkdir(join(libDir, "quota/providers"), { recursive: true }); await writeFile( @@ -560,6 +560,14 @@ test("an uninstalled lib checkout dependency is installed and the OpenDesign kee "export async function fetchOpenDesignQuota() { return {}; }\n", "utf8", ); + await writeFile(join(checkoutRoot, ".gitignore"), "node_modules/\n", "utf8"); + const git = (...args: string[]) => { + const r = spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd: checkoutRoot, encoding: "utf8" }); + if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`); + }; + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-q", "-m", "lib checkout"); // The install step (OPENCHAMBER_LIB_INSTALL_CMD seam; production // default is bun install at the checkout root): materialize the // declared package under the cwd the gatherer gives it — the root. diff --git a/pm-stack/aggregator/test/openchamber-lib.test.ts b/pm-stack/aggregator/test/openchamber-lib.test.ts new file mode 100644 index 0000000000..9bdef1b255 --- /dev/null +++ b/pm-stack/aggregator/test/openchamber-lib.test.ts @@ -0,0 +1,148 @@ +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "bun:test"; +import { loadOpenChamberLib, resolveLibDir, type GitRun } from "../src/openchamber-lib.ts"; + +const roots: string[] = []; +const REVISION = "a".repeat(40); + +interface FixtureOptions { + missingExport?: string; + brokenDependencyExport?: string; +} + +async function makeLib({ missingExport, brokenDependencyExport }: FixtureOptions = {}) { + const root = await mkdtemp(join(tmpdir(), "openchamber-lib-test-")); + roots.push(root); + const dir = join(root, "packages/web/server/lib"); + await mkdir(join(dir, "quota/credentials"), { recursive: true }); + await mkdir(join(dir, "quota/providers"), { recursive: true }); + await writeFile(join(dir, "quota/index.js"), "export {};\n"); + + const credentialExports = ["readManagedCredential", "writeManagedCredential"].filter((name) => name !== missingExport); + const imports = brokenDependencyExport ? `import { ${brokenDependencyExport} } from "./auth.js";\nvoid ${brokenDependencyExport};\n` : ""; + await writeFile( + join(dir, "quota/credentials/providers.js"), + `${imports}${credentialExports.map((name) => `export function ${name}() { return null; }`).join("\n")}\n`, + ); + await writeFile(join(dir, "quota/providers/opendesign.js"), "export async function fetchOpenDesignQuota() {}\n"); + await writeFile(join(dir, "quota/credentials/auth.js"), "export {};\n"); + return { root, dir }; +} + +function fakeGit(states: Array<{ root: string; dir: string; branch?: string; changes?: string }>): GitRun { + return async (cwd, args) => { + const state = states.find((candidate) => cwd === candidate.root || cwd === candidate.dir); + if (!state) throw new Error(`unexpected git cwd: ${cwd}`); + switch (args.join(" ")) { + case "rev-parse --show-toplevel": + return state.root; + case "branch --show-current": + return state.branch ?? "main"; + case "status --porcelain --untracked-files=normal": + return state.changes ?? ""; + case "rev-parse --verify HEAD^{commit}": + return REVISION; + default: + throw new Error(`unexpected git call: ${args.join(" ")}`); + } + }; +} + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("resolveLibDir (candidate gate: git state, no imports)", () => { + test("skips a dirty candidate and logs the selected path and revision", async () => { + const dirty = await makeLib(); + const clean = await makeLib(); + const messages: string[] = []; + + const resolved = await resolveLibDir([dirty.dir, clean.dir], { + gitRun: fakeGit([ + { ...dirty, changes: "?? untracked.txt" }, + clean, + ]), + log: (message) => messages.push(message), + }); + + expect(resolved.dir).toBe(clean.dir); + expect(resolved.revision).toBe(REVISION); + expect(messages.some((message) => message.includes(`${dirty.dir}: checkout has a dirty working tree`))).toBe(true); + expect(messages).toContain(`quota-gatherer: OpenChamber lib dir=${clean.dir} branch=main rev=${REVISION}`); + }); + + test("skips a candidate checked out on a non-main branch", async () => { + const offMain = await makeLib(); + const clean = await makeLib(); + const messages: string[] = []; + + const resolved = await resolveLibDir([offMain.dir, clean.dir], { + gitRun: fakeGit([{ ...offMain, branch: "queue/8357-224" }, clean]), + log: (message) => messages.push(message), + }); + + expect(resolved.dir).toBe(clean.dir); + expect(messages.some((message) => message.includes(`${offMain.dir}: checkout is on branch queue/8357-224, not main`))).toBe(true); + }); + + test("rejects a detached HEAD", async () => { + const detached = await makeLib(); + await expect( + resolveLibDir([detached.dir], { + gitRun: fakeGit([{ ...detached, branch: "" }]), + log: () => {}, + }), + ).rejects.toThrow("checkout is on a detached HEAD, not main"); + }); + + test("never falls through to an unvalidated candidate when every checkout is rejected", async () => { + const parked = await makeLib(); + await expect( + resolveLibDir([parked.dir, join(parked.root, "absent/lib")], { + gitRun: fakeGit([{ ...parked, branch: "queue/8357-224" }]), + log: () => {}, + }), + ).rejects.toThrow("no usable clean main OpenChamber lib checkout found"); + }); + + test("rejects a candidate without quota/index.js before touching git", async () => { + const empty = await mkdtemp(join(tmpdir(), "openchamber-lib-test-")); + roots.push(empty); + let gitCalls = 0; + await expect( + resolveLibDir([empty], { + gitRun: async () => { + gitCalls += 1; + return ""; + }, + log: () => {}, + }), + ).rejects.toThrow("quota/index.js is missing"); + expect(gitCalls).toBe(0); + }); +}); + +describe("loadOpenChamberLib (export check, after dependency install)", () => { + test("loads the credential APIs from a validated checkout", async () => { + const lib = await makeLib(); + const resolved = await resolveLibDir([lib.dir], { gitRun: fakeGit([lib]), log: () => {} }); + const modules = await loadOpenChamberLib(resolved); + expect(typeof modules.credentials.readManagedCredential).toBe("function"); + expect(typeof modules.provider.fetchOpenDesignQuota).toBe("function"); + }); + + test("names a missing required export instead of exposing a bare import failure", async () => { + const incomplete = await makeLib({ missingExport: "readManagedCredential" }); + const resolved = await resolveLibDir([incomplete.dir], { gitRun: fakeGit([incomplete]), log: () => {} }); + await expect(loadOpenChamberLib(resolved)).rejects.toThrow('missing required export "readManagedCredential"'); + }); + + test("names a missing export imported by the required module", async () => { + const incomplete = await makeLib({ brokenDependencyExport: "openCodeLocalCredentialSource" }); + const resolved = await resolveLibDir([incomplete.dir], { gitRun: fakeGit([incomplete]), log: () => {} }); + await expect(loadOpenChamberLib(resolved)).rejects.toThrow('missing required export "openCodeLocalCredentialSource"'); + }); +});