From c3786276d58f9d47a76d5b27c996a49dd560156f Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 13:37:54 -0600 Subject: [PATCH 1/2] fix(quota-gatherer): install the OpenChamber lib checkout's declared dependencies before importing it (#8759) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The OpenDesign keeper imports from a plain-clone OpenChamber lib checkout; when the checkout was refreshed without an install step it had no node_modules, so every tick failed-soft with Cannot find package yaml while reporting healthy. A new lib-deps preflight (src/lib-deps.ts) checks every package declared in the manifests on the lib path resolves from the lib dir, installs the checkout's declared dependencies once at the root when any are missing, and re-checks — throwing an explicit error naming still-missing packages instead of a silent failed-soft. Preflight, not import-retry: Bun caches failed package resolution for the process (verified on bun 1.4.4). OPENCHAMBER_LIB_INSTALL_CMD overrides the install step (default bun install at the checkout root). Live remediation done with this fix: bun install --frozen-lockfile in ~/git/openchamber-quota-lib (1525 packages); the 19:37Z tick logged opendesign-renewal status=valid horizonHours=150.8 with no yaml error, 16/16 providers ok. --- pm-stack/aggregator/scripts/gather-quota.ts | 26 +++ pm-stack/aggregator/src/lib-deps.test.ts | 103 ++++++++++++ pm-stack/aggregator/src/lib-deps.ts | 150 ++++++++++++++++++ pm-stack/aggregator/test/gather-quota.test.ts | 96 +++++++++++ 4 files changed, 375 insertions(+) create mode 100644 pm-stack/aggregator/src/lib-deps.test.ts create mode 100644 pm-stack/aggregator/src/lib-deps.ts diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 91694e5176..0be7fa93b2 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -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: @@ -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"; @@ -283,6 +287,28 @@ interface OpenDesignProviderModule { async function runOpenDesignRenewal(tickAt: string): Promise { 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 => { + await new Promise((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({ diff --git a/pm-stack/aggregator/src/lib-deps.test.ts b/pm-stack/aggregator/src/lib-deps.test.ts new file mode 100644 index 0000000000..6ee4323a27 --- /dev/null +++ b/pm-stack/aggregator/src/lib-deps.test.ts @@ -0,0 +1,103 @@ +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("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 }); + } +}); diff --git a/pm-stack/aggregator/src/lib-deps.ts b/pm-stack/aggregator/src/lib-deps.ts new file mode 100644 index 0000000000..46795af5b9 --- /dev/null +++ b/pm-stack/aggregator/src/lib-deps.ts @@ -0,0 +1,150 @@ +/** + * 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 ''" — 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"]; +const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + +/** 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; + 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)); + } + 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/ 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(); + 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; + log?: (line: string) => void; + exists?: (path: string) => boolean; + readFile?: (path: string) => string; +} + +const INSTALL_TIMEOUT_MS = 240_000; + +async function defaultInstall(root: string): Promise { + if (!basename(process.execPath).includes("bun")) { + throw new Error("lib dependency preflight needs bun on the exec path to install"); + } + await new Promise((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 { + 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; +} diff --git a/pm-stack/aggregator/test/gather-quota.test.ts b/pm-stack/aggregator/test/gather-quota.test.ts index 1f137602ce..66ea2094e0 100644 --- a/pm-stack/aggregator/test/gather-quota.test.ts +++ b/pm-stack/aggregator/test/gather-quota.test.ts @@ -512,3 +512,99 @@ test("a lapsed Go workspace survives retention when a sibling workspace fails", await rm(dir, { recursive: true, force: true }); } }); + +test("an uninstalled lib checkout dependency is installed and the OpenDesign keeper runs (#8759)", async () => { + const dir = await mkdtemp(join(tmpdir(), "gather-quota-libdeps-")); + try { + const currentPath = join(dir, "quota-current.json"); + const heartbeatPath = join(dir, "quota-gatherer-heartbeat.json"); + const statePath = join(dir, "quota-gatherer-state.json"); + const snapshotsDir = join(dir, "snapshots"); + const outboxPath = join(dir, "snapshots.outbox.jsonl"); + const subcommandPath = join(dir, "quota-subcommand.mjs"); + const installerPath = join(dir, "install-fake-dep.mjs"); + const checkoutRoot = join(dir, "checkout"); + const libDir = join(checkoutRoot, "packages/web/server/lib"); + const renewalStatePath = join(dir, "opendesign-renewal.json"); + const providerResult = { + providerId: "meta", + providerName: "Meta", + ok: true, + configured: true, + fetchedAt: Date.parse("2026-11-06T04:30:00.000Z"), + failureClass: "no-data", + lastSuccessAt: Date.parse("2026-11-06T04:00:00.000Z"), + 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. + await mkdir(join(libDir, "quota/credentials"), { recursive: true }); + await mkdir(join(libDir, "quota/providers"), { recursive: true }); + await writeFile(join(checkoutRoot, "package.json"), JSON.stringify({ dependencies: { "fake-dep": "1.0.0" } }), "utf8"); + await writeFile(join(checkoutRoot, "bun.lock"), "", "utf8"); + await writeFile(join(libDir, "quota/index.js"), "export async function listConfiguredQuotaProviders() { return []; }\n", "utf8"); + await writeFile( + join(libDir, "quota/credentials/providers.js"), + "import 'fake-dep';\nexport function readManagedCredential() { return null; }\nexport function writeManagedCredential() {}\n", + "utf8", + ); + await writeFile( + join(libDir, "quota/providers/opendesign.js"), + "export async function fetchOpenDesignQuota() { return {}; }\n", + "utf8", + ); + // 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. + const installerSource = [ + "import { mkdir, writeFile } from 'node:fs/promises';", + "import { join } from 'node:path';", + "const pkgDir = join(process.cwd(), 'node_modules/fake-dep');", + "await mkdir(pkgDir, { recursive: true });", + "await writeFile(join(pkgDir, 'package.json'), JSON.stringify({ name: 'fake-dep', version: '1.0.0', main: 'index.js', type: 'module' }));", + "await writeFile(join(pkgDir, 'index.js'), 'export {};');", + "", + ].join("\n"); + await writeFile(installerPath, installerSource, "utf8"); + await writeFile(subcommandPath, "console.log(" + JSON.stringify(JSON.stringify([providerResult])) + ");\n", "utf8"); + + const result = spawnSync(process.execPath, [GATHERER_SCRIPT], { + cwd: dir, + encoding: "utf8", + timeout: 30_000, + env: { + PATH: process.env.PATH ?? "", + HOME: dir, + QUOTA_CURRENT_PATH: currentPath, + QUOTA_HEARTBEAT_PATH: heartbeatPath, + QUOTA_GATHERER_STATE_PATH: statePath, + QUOTA_SNAPSHOTS_DIR: snapshotsDir, + USAGE_SNAPSHOT_OUTBOX_PATH: outboxPath, + QUOTA_SUBCOMMAND: process.execPath + " " + subcommandPath, + QUOTA_SUBCOMMAND_TIMEOUT_MS: "5000", + META_RENEWAL_DISABLED: "1", + SUPABASE_QUOTA_SINK: "0", + OPENCHAMBER_LIB_DIR: libDir, + OPENCHAMBER_LIB_INSTALL_CMD: process.execPath + " " + installerPath, + OPENDESIGN_RENEWAL_STATE_PATH: renewalStatePath, + }, + }); + + if (result.error || result.status !== 0) { + throw new Error("gatherer failed: " + (result.error?.message ?? result.stderr) + "\n" + result.stdout); + } + // Oracle: the missing dependency was recovered explicitly, the + // keeper ran to a real outcome (no stored credential in the + // fixture), and no failed-soft line was emitted. + expect(result.stdout).toContain("installing declared dependencies"); + expect(result.stdout).toContain("opendesign-renewal: status=not-configured"); + expect(result.stdout).not.toContain("failed-soft"); + const renewalState = JSON.parse(await readFile(renewalStatePath, "utf8")); + expect(renewalState.status).toBe("not-configured"); + const installed = JSON.parse(await readFile(join(checkoutRoot, "node_modules/fake-dep/package.json"), "utf8")); + expect(installed.name).toBe("fake-dep"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); From 27818b5c83ba20b9d1128dd11e320271349cd669 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 13:45:25 -0600 Subject: [PATCH 2/2] fix(quota-gatherer): optional/peer lib deps are not mandatory install postconditions (#8759) Codex P2 on PR #8764: an optionalDependency that is intentionally absent (platform-specific, e.g. packages/web node-llama-cpp) would have blocked the OpenDesign keeper every tick. Mandatory checks now cover dependencies + devDependencies only, with a regression test. --- pm-stack/aggregator/src/lib-deps.test.ts | 27 ++++++++++++++++++++++++ pm-stack/aggregator/src/lib-deps.ts | 6 +++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/pm-stack/aggregator/src/lib-deps.test.ts b/pm-stack/aggregator/src/lib-deps.test.ts index 6ee4323a27..177a6f2ef1 100644 --- a/pm-stack/aggregator/src/lib-deps.test.ts +++ b/pm-stack/aggregator/src/lib-deps.test.ts @@ -46,6 +46,33 @@ test("checkLibDependencies is clean when node_modules carries the declared packa } }); +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 { diff --git a/pm-stack/aggregator/src/lib-deps.ts b/pm-stack/aggregator/src/lib-deps.ts index 46795af5b9..6d5cc9d8fc 100644 --- a/pm-stack/aggregator/src/lib-deps.ts +++ b/pm-stack/aggregator/src/lib-deps.ts @@ -29,7 +29,11 @@ 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"]; -const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; +// 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