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
45 changes: 20 additions & 25 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@
// token + project ref resolved by name via the resolveBwsSecret
// plumbing: supabase.muse-dev2.access-token-muse-cli /
// supabase.muse-dev2.project-ref).
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";
Expand All @@ -120,27 +119,22 @@ 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 { renewMetaSession } from "../src/meta-renewal.ts";
import { resolveLibDir as resolveOpenChamberLib, type ResolvedOpenChamberLib } from "../src/openchamber-lib.ts";

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. All are validated before use; quota readings still come only
* from the opencode subcommand. */
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");
Expand Down Expand Up @@ -259,15 +253,6 @@ async function resolveBwsSecret(key: string): Promise<string | null> {
}
}

/** 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<unknown>;
}

/**
* The OpenDesign session keeper run. Runs before the subcommand so a
* credential renewed this tick is the one the tick's OpenDesign read
Expand All @@ -277,11 +262,10 @@ interface OpenDesignProviderModule {
* reaches any output). Fail-soft: any error is logged and the tick
* proceeds with the stored credential as-is.
*/
async function runOpenDesignRenewal(tickAt: string): Promise<void> {
async function runOpenDesignRenewal(tickAt: string, lib: ResolvedOpenChamberLib): Promise<void> {
if (process.env.OPENDESIGN_RENEWAL_DISABLED === "1") return;
try {
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 } = lib;
const state = await renewOpenDesignSession({
readCredential: () => credentials.readManagedCredential("opendesign"),
writeCredential: (value) => {
Expand Down Expand Up @@ -646,9 +630,20 @@ async function main(): Promise<number> {
const started = Date.now();
const tickAt = new Date(started).toISOString();

let openChamberLib: ResolvedOpenChamberLib;
try {
openChamberLib = await resolveOpenChamberLib(openChamberLibCandidates());
} catch (err) {
return failTick(
Comment on lines +635 to +637

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep OpenChamber resolution failures local to the keeper

When no candidate OpenChamber checkout passes validation—for example, both laptop checkouts are dirty or on feature branches—this return aborts the entire quota tick before the independent opencode quota subcommand runs. This also happens with OPENDESIGN_RENEWAL_DISABLED=1, since its guard is reached only afterward. Previously, these imports were inside the OpenDesign keeper's fail-soft handler, so unavailable credential plumbing did not stop other providers' readings. Keep rejecting unsafe imports, but resolve the library inside the optional keeper's fail-soft boundary so quota-current, snapshots, and Supabase readings continue updating.

Useful? React with 👍 / 👎.

tickAt,
started,
`OpenChamber lib resolution failed: ${err instanceof Error ? err.message : String(err)}`,
);
}

// The OpenDesign keeper runs first: a session renewed this tick is
// the one the subcommand's OpenDesign read uses.
await runOpenDesignRenewal(tickAt);
await runOpenDesignRenewal(tickAt, openChamberLib);
await runMetaRenewal(tickAt);

// The single source: every reading this tick comes from the
Expand Down
135 changes: 135 additions & 0 deletions pm-stack/aggregator/src/openchamber-lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
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<string>;

export interface OpenChamberCredentialsModule {
readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null;
writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown;
}

export interface OpenChamberProviderModule {
fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise<unknown>;
}

export interface ResolvedOpenChamberLib {
dir: string;
root: string;
revision: string;
credentials: OpenChamberCredentialsModule;
provider: OpenChamberProviderModule;
}

export interface ResolveLibOptions {
gitRun?: GitRun;
log?: (message: string) => void;
}

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 importRequiredModule(dir: string, path: string): Promise<Record<string, unknown>> {
try {
return (await import(pathToFileURL(resolve(dir, path)).href)) as Record<string, unknown>;
} 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}`);
}
}

async function validateExports(dir: string): Promise<{
credentials: OpenChamberCredentialsModule;
provider: OpenChamberProviderModule;
}> {
const [credentials, provider] = await Promise.all(
REQUIRED_MODULE_EXPORTS.map(({ path }) => importRequiredModule(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,
};
}

async function inspectCandidate(dir: string, gitRun: GitRun): Promise<ResolvedOpenChamberLib> {
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)}`);
}

const modules = await validateExports(dir);
return { dir, root, revision, ...modules };
}

/** Pick the first clean main checkout with the credential APIs this gatherer uses. */
export async function resolveLibDir(
candidates: string[],
{ gitRun = defaultGitRun, log = console.warn }: ResolveLibOptions = {},
): Promise<ResolvedOpenChamberLib> {
const rejected: string[] = [];
const seen = new Set<string>();

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})`);
}
115 changes: 115 additions & 0 deletions pm-stack/aggregator/test/openchamber-lib.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
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 { 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", () => {
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("names a missing required export instead of exposing a bare import failure", async () => {
const incomplete = await makeLib({ missingExport: "readManagedCredential" });
const messages: string[] = [];

await expect(
resolveLibDir([incomplete.dir], {
gitRun: fakeGit([incomplete]),
log: (message) => messages.push(message),
}),
).rejects.toThrow('missing required export "readManagedCredential"');

expect(messages.some((message) => message.includes('missing required export "readManagedCredential"'))).toBe(true);
});

test("names a missing export imported by the required module", async () => {
const incomplete = await makeLib({ brokenDependencyExport: "openCodeLocalCredentialSource" });

await expect(
resolveLibDir([incomplete.dir], {
gitRun: fakeGit([incomplete]),
log: () => {},
}),
).rejects.toThrow('missing required export "openCodeLocalCredentialSource"');
});
});