Skip to content
Merged
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
26 changes: 26 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@
// the subcommand owns fetch concurrency now),
// OPENCHAMBER_LIB_DIR (ONLY the OpenDesign keeper's credential
// store accessors resolve from here; no quota reading does),
// OPENCHAMBER_LIB_INSTALL_CMD (override for the lib checkout's
// dependency install step, shell-split like QUOTA_SUBCOMMAND;
// default is bun install at the checkout root, #8759),
// TURSO_QUOTA_SINK=0 (or the legacy SUPABASE_QUOTA_SINK=0)
// disables the Turso sink (default on; token resolved by name
// via the resolveBwsSecret plumbing:
Expand All @@ -121,6 +124,7 @@ import {
import { SnapshotStore, isSnapshotRecord, snapshotKey } from "../src/snapshots.ts";
import { safeProviderReason } from "../src/credential-lifecycle.ts";
import { renewOpenDesignSession, type OpenDesignCredentialLike } from "../src/opendesign-renewal.ts";
import { ensureLibDependencies } from "../src/lib-deps.ts";
import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts";
import { renewMetaSession } from "../src/meta-renewal.ts";

Expand Down Expand Up @@ -283,6 +287,28 @@ interface OpenDesignProviderModule {
async function runOpenDesignRenewal(tickAt: string): Promise<void> {
if (process.env.OPENDESIGN_RENEWAL_DISABLED === "1") return;
try {
// #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
// for the process, so install BEFORE the first import
// (src/lib-deps.ts preflight), never as an import retry.
const installCmd = process.env.OPENCHAMBER_LIB_INSTALL_CMD?.split(/\s+/).filter(Boolean) ?? [];
const install =
installCmd.length > 0
? async (root: string): Promise<void> => {
await new Promise<void>((resolve, reject) => {
execFile(installCmd[0], installCmd.slice(1), { cwd: root, timeout: 240_000, maxBuffer: 16 * 1024 * 1024 }, (err) => {
if (err) reject(new Error("OPENCHAMBER_LIB_INSTALL_CMD failed in the OpenChamber lib checkout"));
else resolve();
});
});
}
: undefined;
await ensureLibDependencies({
libDir,
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 state = await renewOpenDesignSession({
Expand Down
130 changes: 130 additions & 0 deletions pm-stack/aggregator/src/lib-deps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { checkLibDependencies, ensureLibDependencies, findLibCheckoutRoot } from "./lib-deps.ts";

async function fakeCheckout(opts: { installed?: boolean } = {}): Promise<{ root: string; libDir: string }> {
const root = await mkdtemp(join(tmpdir(), "lib-deps-checkout-"));
const libDir = join(root, "packages/web/server/lib");
await mkdir(libDir, { recursive: true });
await writeFile(join(root, "package.json"), JSON.stringify({ dependencies: { yaml: "^2.8.1", "@scope/pkg": "1.0.0" } }), "utf8");
await writeFile(join(root, "bun.lock"), "", "utf8");
if (opts.installed) {
await mkdir(join(root, "node_modules/yaml"), { recursive: true });
await mkdir(join(root, "node_modules/@scope/pkg"), { recursive: true });
}
return { root, libDir };
}

test("findLibCheckoutRoot walks up to the manifest+lockfile ancestor", async () => {
const { root, libDir } = await fakeCheckout();
try {
expect(findLibCheckoutRoot(libDir)).toBe(root);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("checkLibDependencies reports declared-but-uninstalled packages, scoped included", async () => {
const { root, libDir } = await fakeCheckout();
try {
const check = checkLibDependencies(libDir);
expect(check.root).toBe(root);
expect(check.missing.sort()).toEqual(["@scope/pkg", "yaml"]);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("checkLibDependencies is clean when node_modules carries the declared packages", async () => {
const { root, libDir } = await fakeCheckout({ installed: true });
try {
expect(checkLibDependencies(libDir).missing).toEqual([]);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("optional and peer dependencies are not mandatory (Codex P2, PR #8764)", async () => {
const root = await mkdtemp(join(tmpdir(), "lib-deps-optional-"));
const libDir = join(root, "packages/web/server/lib");
await mkdir(libDir, { recursive: true });
try {
await writeFile(
join(root, "package.json"),
JSON.stringify({
dependencies: { yaml: "^2.8.1" },
optionalDependencies: { "node-llama-cpp": "^3.0.0" },
peerDependencies: { react: "^19.0.0" },
}),
"utf8",
);
await writeFile(join(root, "bun.lock"), "", "utf8");
await mkdir(join(root, "node_modules/yaml"), { recursive: true });
// yaml (mandatory) resolves; node-llama-cpp and react are absent
// but optional/peer, so nothing is missing and no install runs.
expect(checkLibDependencies(libDir).missing).toEqual([]);
let installs = 0;
await ensureLibDependencies({ libDir, install: async () => { installs++; } });
expect(installs).toBe(0);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("ensure installs exactly once when packages are missing and re-checks clean", async () => {
const { root, libDir } = await fakeCheckout();
try {
const installs: string[] = [];
const logs: string[] = [];
const result = await ensureLibDependencies({
libDir,
log: (line) => logs.push(line),
install: async (r) => {
installs.push(r);
await mkdir(join(r, "node_modules/yaml"), { recursive: true });
await mkdir(join(r, "node_modules/@scope/pkg"), { recursive: true });
},
});
expect(installs).toEqual([root]);
expect(result.missing).toEqual([]);
expect(logs.join(" ")).toContain("yaml");
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("ensure does not install when everything already resolves", async () => {
const { root, libDir } = await fakeCheckout({ installed: true });
try {
let installs = 0;
const result = await ensureLibDependencies({ libDir, install: async () => { installs++; } });
expect(installs).toBe(0);
expect(result.missing).toEqual([]);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("ensure throws an explicit error naming packages still missing after install", async () => {
const { root, libDir } = await fakeCheckout();
try {
await expect(ensureLibDependencies({ libDir, install: async () => {} })).rejects.toThrow("still missing after install");
await expect(ensureLibDependencies({ libDir, install: async () => {} })).rejects.toThrow("yaml");
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("ensure is a no-op outside an installable checkout", async () => {
const dir = await mkdtemp(join(tmpdir(), "lib-deps-nocheckout-"));
try {
let installs = 0;
const result = await ensureLibDependencies({ libDir: dir, install: async () => { installs++; } });
expect(result.root).toBeNull();
expect(installs).toBe(0);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
154 changes: 154 additions & 0 deletions pm-stack/aggregator/src/lib-deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/**
* OpenChamber lib dependency preflight (#8759).
*
* The quota gatherer's OpenDesign keeper dynamically imports modules
* from the OpenChamber lib checkout named by OPENCHAMBER_LIB_DIR.
* That checkout is a plain git clone: when it is (re)created or
* refreshed without an install step, its declared dependencies are
* absent (no node_modules) and every import fails with
* "Cannot find package '<name>'" — the keeper then failed-soft on
* every tick while the tick itself reported healthy, so the
* OpenDesign renewal door was silently dead from 2026-11-09 until
* #8759 was filed.
*
* Why a preflight, not import-retry: Bun caches a failed package
* resolution for the life of the process (verified on bun 1.4.4 —
* a retry import after installing still throws the cached
* ResolveMessage), so install-then-retry inside one tick cannot
* work. Instead, BEFORE the first import: walk the manifests from
* the lib dir up to the checkout root, check every declared package
* resolves from the lib dir, and if any are missing install the
* checkout's declared dependencies once (bun install at the root)
* and re-check. A dependency absence is then a logged recovery on
* the tick that fixes it — or, when the install cannot fix it, an
* explicit error naming the still-missing packages, never a silent
* failed-soft behind a healthy tick.
*/
import { execFile } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";

const LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"];
// Mandatory fields only: an optionalDependency may be intentionally
// absent (platform-specific, e.g. packages/web's node-llama-cpp) and a
// peerDependency is supplied by the consumer — neither is an install
// postcondition, so neither may block the keeper (Codex P2, PR #8764).
const DEPENDENCY_FIELDS = ["dependencies", "devDependencies"];

/** Walk up from libDir to the checkout root: the first ancestor that
* carries both a package.json and a lockfile. Null when no ancestor
* qualifies (libDir is not inside an installable checkout). */
export function findLibCheckoutRoot(libDir: string, exists: (path: string) => boolean = existsSync): string | null {
let dir = libDir;
for (let depth = 0; depth < 10; depth++) {
if (exists(join(dir, "package.json")) && LOCKFILES.some((lock) => exists(join(dir, lock)))) return dir;
const parent = dirname(dir);
if (parent === dir) return null;
dir = parent;
}
return null;
}

/** Directory chain from libDir up to and including root. */
function chainToRoot(libDir: string, root: string): string[] {
const chain: string[] = [];
let dir = libDir;
for (let depth = 0; depth < 12; depth++) {
chain.push(dir);
if (dir === root) break;
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
return chain;
}

function declaredInManifest(path: string, readFile: (path: string) => string): string[] {
try {
const manifest = JSON.parse(readFile(path)) as Record<string, unknown>;
const names: string[] = [];
for (const field of DEPENDENCY_FIELDS) {
const deps = manifest[field];
if (deps && typeof deps === "object") names.push(...Object.keys(deps as Record<string, unknown>));
}
return names;
} catch {
return [];
}
}

export interface LibDependencyCheck {
root: string | null;
/** Declared packages (root + workspace manifests on the lib path)
* that do not resolve from libDir. Empty when the root is unknown:
* the preflight does not apply and imports proceed as before. */
missing: string[];
}

/** Which declared packages are unresolvable from libDir right now.
* Oracle: a package resolves iff node_modules/<name> exists in some
* directory on the libDir-to-root chain (the same walk Node/Bun
* resolution performs for these checkouts). */
export function checkLibDependencies(
libDir: string,
io: { exists?: (path: string) => boolean; readFile?: (path: string) => string } = {},
): LibDependencyCheck {
const exists = io.exists ?? existsSync;
const readFile = io.readFile ?? ((path: string) => readFileSync(path, "utf8"));
const root = findLibCheckoutRoot(libDir, exists);
if (!root) return { root: null, missing: [] };
const chain = chainToRoot(libDir, root);
const declared = new Set<string>();
for (const dir of chain) {
for (const name of declaredInManifest(join(dir, "package.json"), readFile)) declared.add(name);
}
const missing = [...declared].filter((name) => !chain.some((dir) => exists(join(dir, "node_modules", name))));
return { root, missing };
}

export interface EnsureLibDependenciesOptions {
libDir: string;
/** Install the checkout root's declared dependencies. Default:
* at the root (the gatherer runs under bun). */
install?: (root: string) => Promise<void>;
log?: (line: string) => void;
exists?: (path: string) => boolean;
readFile?: (path: string) => string;
}

const INSTALL_TIMEOUT_MS = 240_000;

async function defaultInstall(root: string): Promise<void> {
if (!basename(process.execPath).includes("bun")) {
throw new Error("lib dependency preflight needs bun on the exec path to install");
}
await new Promise<void>((resolve, reject) => {
execFile(process.execPath, ["install"], { cwd: root, timeout: INSTALL_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (err) => {
if (err) reject(new Error("bun install failed in the OpenChamber lib checkout"));
else resolve();
});
});
}

/**
* Make the lib checkout's declared dependencies resolvable, or throw
* an explicit error naming what is still missing. Installs at most
* once, and only when something declared is actually missing.
*/
export async function ensureLibDependencies(options: EnsureLibDependenciesOptions): Promise<LibDependencyCheck> {
const io = { exists: options.exists, readFile: options.readFile };
const before = checkLibDependencies(options.libDir, io);
if (!before.root || before.missing.length === 0) return before;
options.log?.(
"opendesign-renewal: lib dependencies missing in " + before.root + " (" + before.missing.join(", ") +
"); installing declared dependencies and re-checking",
);
await (options.install ?? defaultInstall)(before.root);
const after = checkLibDependencies(options.libDir, io);
if (after.missing.length > 0) {
throw new Error(
"OpenChamber lib dependencies still missing after install in " + before.root + ": " + after.missing.join(", "),
);
}
return after;
}
Loading
Loading