From 1270f90e4b1cb968c6fee071b555bf8d32169c31 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:53:10 +0000 Subject: [PATCH 1/5] fix(core): refuse an artifact package cycle as 422 CYCLIC_ARTIFACT_PACKAGES; install-local answers resolver refusals at step 1c resolvePluginOrder throws its cycle as PluginOrderCycleError (message unchanged, carries `cycle`); resolveArtifactPackageEntries answers it in the ADR-0112 envelope its sibling refusals carry, with details.cycle. The code is registered in ERROR_CODE_LEDGER under @objectstack/core. install-local's step 1c (the runtime binder's judgements, the first reader of the packages on a real runtime) answers a resolver refusal with that refusal instead of letting it reach the transport as a 500, and declaredRefusalAnswer forwards the refusal's details. Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude --- .changeset/34574-artifact-cycle-refusal.md | 14 ++ .../src/marketplace-install-local-plugin.ts | 48 +++-- ...stall-local-resolver-refusal-34432.test.ts | 26 +-- ...ocal-resolver-refusal-real-runtime.test.ts | 198 ++++++++++++++++++ packages/core/src/artifact-packages.test.ts | 37 ++++ packages/core/src/artifact-packages.ts | 45 +++- packages/core/src/plugin-order.test.ts | 34 +++ packages/core/src/plugin-order.ts | 34 ++- .../src/dev-i18n-packages-reader.test.ts | 19 +- packages/plugins/plugin-dev/src/dev-i18n.ts | 12 +- packages/runtime/src/artifact-collections.ts | 18 +- .../spec/src/api/error-code-ledger.zod.ts | 10 + 12 files changed, 428 insertions(+), 67 deletions(-) create mode 100644 .changeset/34574-artifact-cycle-refusal.md create mode 100644 packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts diff --git a/.changeset/34574-artifact-cycle-refusal.md b/.changeset/34574-artifact-cycle-refusal.md new file mode 100644 index 00000000000..a3dad7a6943 --- /dev/null +++ b/.changeset/34574-artifact-cycle-refusal.md @@ -0,0 +1,14 @@ +--- +'@objectstack/core': patch +'@objectstack/spec': patch +'@objectstack/cloud-connection': patch +--- + +fix(core): a composed artifact whose packages depend on each other in a cycle is refused as `422 CYCLIC_ARTIFACT_PACKAGES` naming the cycle, and install-local answers every artifact-resolver refusal instead of a 500 + +Clause-②: yes (widening) +Metadata-protocol: none + +- `@objectstack/core`: `resolveArtifactPackageEntries` / `resolveArtifactPackageOrder` refuse packages that depend on each other in a cycle with the ADR-0112 envelope their other refusals carry: `code: 'CYCLIC_ARTIFACT_PACKAGES'`, `status: 422`, and `details.cycle` listing the package ids along the cycle (each depends on the next, the first repeated last). Before, the cycle was a bare `Error` with no `code` or `status`. A caller that matched on the old message still finds `Circular dependency detected` in it. `resolvePluginOrder` now throws its cycle as `PluginOrderCycleError`, a new exported `Error` subclass that carries `cycle`. Its message is unchanged and it carries no `code`, so a kernel boot that hits a plugin cycle reads exactly as before. +- `@objectstack/spec`: `CYCLIC_ARTIFACT_PACKAGES` is registered in `ERROR_CODE_LEDGER` under `@objectstack/core`, so `ErrorCode` accepts it. +- `@objectstack/cloud-connection`: `POST /api/v1/marketplace/install-local` answered `500 INTERNAL_ERROR` with no reason for a composed artifact the resolver refuses: a `packages` that is not a list, a malformed entry, a duplicate package id, or a dependency cycle. On a real runtime, the step that judges the package's jobs and hooks reads the packages first and let the refusal escape. That step now answers the refusal itself, with its own status, code and `details`, and nothing is written. Every other step that reads the packages already did. diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index c81043840d2..2dcb06e89af 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -475,26 +475,32 @@ function isDeclaredRegisterRefusal(err: unknown): boolean { } /** - * [#34407, #34432] The answer to a package body the artifact resolver refuses - * before any write (`resolveStackCollection` → `resolveArtifactPackageEntries`: + * [#34407, #34432, #34574] The answer to a package body the artifact resolver + * refuses before any write (`resolveArtifactPackageEntries`, reached through + * `resolveStackCollection` or the runtime binder's judgements: * `INVALID_ARTIFACT_PACKAGES`, `INVALID_ARTIFACT_PACKAGE_ENTRY`, - * `DUPLICATE_ARTIFACT_PACKAGE`, each an ADR-0112 envelope with its declared - * `status: 422`): that refusal's own declared status and code, the resolver's - * sentence, and that nothing was written. The one reader of such a refusal on - * this door's pre-write steps — the D5e gate (2b) and the declared renames - * (2c″) both read the bodies through the resolver, so the same bytes are - * answered the same way whichever step reads them first. + * `DUPLICATE_ARTIFACT_PACKAGE`, `CYCLIC_ARTIFACT_PACKAGES`, each an ADR-0112 + * envelope with its declared `status: 422`): that refusal's own declared + * status and code, the resolver's sentence, its `details` when it states any + * (a cycle's `details.cycle`), and that nothing was written. The one reader of + * such a refusal on this door's pre-write steps — the unrunnable-code + * judgements (1c), the datasource holder (2a), the D5e gate (2b) and the + * declared renames (2c″) all read the bodies through the resolver, so the same + * bytes are answered the same way whichever step reads them first. * * `undefined` for a throw that declares no status below 500 — an undeclared - * throw (the resolver's own dependency-cycle error among them) or a declared - * 5xx: the caller rethrows it, never relabels it. + * throw or a declared 5xx: the caller rethrows it, never relabels it. */ function declaredRefusalAnswer( manifestId: string, err: unknown, -): { status: number; body: { success: false; error: { code: string; message: string } } } | undefined { +): { status: number; body: { success: false; error: { code: string; message: string; details?: Record } } } | undefined { const refusal = resolveThrownHttpError(err); if (refusal.declaredStatus === undefined || refusal.status >= 500) return undefined; + const stated = (err as { details?: unknown } | null | undefined)?.details; + const details = stated !== null && typeof stated === 'object' && !Array.isArray(stated) + ? stated as Record + : undefined; return { status: refusal.status, body: { @@ -502,6 +508,7 @@ function declaredRefusalAnswer( error: { code: refusal.code, message: `Package '${manifestId}' cannot be installed: ${String((err as any)?.message ?? err)} Nothing was installed or written.`, + ...(details !== undefined ? { details } : {}), }, }, }; @@ -2956,7 +2963,24 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // unbindable `pull` is warned by the binder and NOT scheduled), and // its hook with no `body` is warned and NOT bound // ({@link bindArtifactHandlers}). - const unrunnable = await this.unrunnableCode(ctx, manifest, manifestId); + // [#34574] The binder's judgements read every package body of a + // composed bundle through the artifact resolver, so over a runtime + // that carries them THIS is the first step to resolve the + // packages. A `packages` the resolver refuses — not a list, a + // malformed entry, a duplicate id, packages that depend on each + // other in a cycle — is answered here with that refusal + // ({@link declaredRefusalAnswer}), as 2a, 2b and 2c″ answer it. + // Before, the refusal left the door as a throw, and the transport, + // which renders no `422`, answered `500 INTERNAL_ERROR`. An + // undeclared throw stays a throw. + let unrunnable: UnrunnableCode; + try { + unrunnable = await this.unrunnableCode(ctx, manifest, manifestId); + } catch (err: unknown) { + const refused = declaredRefusalAnswer(manifestId, err); + if (!refused) throw err; + return c.json(refused.body, refused.status); + } if (unrunnable.jobs.length > 0 || unrunnable.sharedJobNames.length > 0 || unrunnable.hooks.length > 0) { return c.json({ success: false, diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts index f5759aba534..19c2fb027b5 100644 --- a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts @@ -17,10 +17,13 @@ * `marketplace-install-local-composed-top-level-reads.test.ts`), so 2c″ is the * first step to resolve the packages. (A runtime that carries those * judgements resolves the packages at step 1c first, and the resolver's - * refusal leaves the door as a throw.) The controls pin the rest of the - * contract: a table that really could not be read still answers 503, and an - * undeclared throw out of the resolver (its own dependency-cycle error) is - * rethrown, never relabelled. + * refusal is answered there, at step 1c — pinned over the real runtime in + * `marketplace-install-local-resolver-refusal-real-runtime.test.ts`.) The + * controls pin the rest of the contract: a table that really could not be read + * still answers 503, and a dependency cycle between two packages — an + * undeclared throw out of the resolver until #34574 — is now the resolver's + * declared `422 CYCLIC_ARTIFACT_PACKAGES`, answered like its siblings, never + * the 503. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -188,7 +191,7 @@ describe('#34432 — step 2c″ answers a body the artifact resolver refuses wit }); }); -describe('#34432 — controls: the 503 stays the unread table\'s, and an undeclared throw stays a throw', () => { +describe('#34432 — controls: the 503 stays the unread table\'s, and a cycle is the resolver\'s declared refusal', () => { it('CONTROL: a well-formed composed artifact whose renamed field\'s table cannot be read still answers 503 SERVICE_UNAVAILABLE', async () => { const driver = fakeDriver({ planThrows: true }); const rt = await boot(dir, driver); @@ -212,7 +215,7 @@ describe('#34432 — controls: the 503 stays the unread table\'s, and an undecla expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1); }); - it('an undeclared throw out of the resolver (a dependency cycle between two packages) is rethrown, never answered 503', async () => { + it('a dependency cycle between two packages answers 422 CYCLIC_ARTIFACT_PACKAGES naming the cycle, never 503, and nothing is written', async () => { const driver = fakeDriver(); const rt = await boot(dir, driver); const cyclic = [ @@ -220,13 +223,12 @@ describe('#34432 — controls: the 503 stays the unread table\'s, and an undecla entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' }), ]; - const outcome = await rt.install({ manifest: composed(cyclic) }).then( - (res: any) => ({ answered: res }), - (err: unknown) => ({ thrown: err as Error }), - ); + const res = await rt.install({ manifest: composed(cyclic) }); - expect('answered' in outcome ? JSON.stringify(outcome.answered.payload) : 'thrown').toBe('thrown'); - expect((outcome as { thrown: Error }).thrown.message).toContain('Circular dependency'); + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('CYCLIC_ARTIFACT_PACKAGES'); + expect(res.payload.error.details).toEqual({ cycle: [`${SUITE}.core`, `${SUITE}.leads`, `${SUITE}.core`] }); expectNothingWritten(rt, driver); }); }); diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts new file mode 100644 index 00000000000..2bd1e81b3fb --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts @@ -0,0 +1,198 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34574] Over the REAL `@objectstack/runtime` — no module mock — the first + * step of `POST /api/v1/marketplace/install-local` to resolve a composed + * bundle's packages is 1c, the runtime binder's unrunnable-code judgements + * (`collectJobsWithoutBody` and its siblings read every package body through + * the artifact resolver). That step answers a refusal of the resolver with + * that refusal, as 2a / 2b / 2c″ do: its own declared `422`, its code, its + * `details`, and nothing written. + * + * Before, the resolver's refusal left the door there as a throw, and the + * transport (which renders no `422`) answered `500 INTERNAL_ERROR` with no + * reason — for all four refusals, and a dependency cycle was a bare `Error` + * on top of that. `marketplace-install-local-resolver-refusal-34432.test.ts` + * pins the later steps under a runtime that predates the judgements; this + * file pins the door a real deployment runs. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; + +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { declareInstallerPlatformOwner, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; +import { LocalManifestSource } from './local-manifest-source.js'; + +type Handler = (c: any) => Promise; +type Row = Record; + +const ROUTE = '/api/v1/marketplace/install-local'; +const SUITE = 'com.example.suite'; + +const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }; +const LEAD = { name: 'crm_lead', label: 'Lead', fields: { company: { type: 'text', label: 'Company' } } }; + +const entry = (id: string, objects: Row[], dependencies?: Record): Row => ({ + manifest: { id, name: id, version: '1.0.0', type: 'module', ...(dependencies ? { dependencies } : {}), objects }, +}); + +/** A composed artifact: `packages[]` and no top-level `objects`, so every reader goes through the resolver. */ +const composed = (packages: unknown): Row => ({ id: SUITE, name: 'Suite', version: '1.0.0', type: 'app', packages }); + +function makeRawApp() { + const routes = new Map(); + return { + routes, + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; +} + +function makeC(reqBody: any) { + return { + req: { + url: `http://localhost:3000${ROUTE}`, + raw: new Request(`http://localhost:3000${ROUTE}`), + json: async () => reqBody, + param: () => undefined, + header: () => undefined, + query: () => undefined, + }, + json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })), + }; +} + +/** A driver with the declared-rename members the door asks; it reads no table. */ +function fakeDriver() { + return { + planDeclaredRenames: vi.fn(async () => ({ carries: [], refusals: [] })), + carryDeclaredRenames: vi.fn(async () => []), + reverseDeclaredRenames: vi.fn(async () => undefined), + }; +} + +async function boot(dir: string, driver: ReturnType) { + const rawApp = makeRawApp(); + const hooks = new Map(); + const register = vi.fn(); + const services: Record = { + manifest: { register }, + auth: installerAuthService(), + objectql: withInstallerGrants({ + syncSchemas: async () => undefined, + getDriverForObject: () => driver, + registry: { getObject: () => undefined }, + }), + metadata: {}, + }; + const ctx = { + hook: (e: string, h: any) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + const svc = services[name]; + if (svc === undefined) throw new Error(`no ${name}`); + return svc; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + await plugin.start(ctx as any); + await hooks.get('kernel:ready')?.(); + // The door registers its own plugin manifest at boot; only the install's registrations count. + register.mockClear(); + return { + // A throw here is the defect: the door must ANSWER, never let a refusal reach the transport. + install: (reqBody: Row) => rawApp.routes.get(`POST ${ROUTE}`)!(makeC(reqBody)), + register, + warn: ctx.logger.warn, + }; +} + +let dir: string; +let posture: string | undefined; +let restoreOwner: () => void; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'mil-resolver-refusal-real-runtime-')); + posture = process.env.OS_TENANCY_POSTURE; + process.env.OS_TENANCY_POSTURE = 'single'; + restoreOwner = declareInstallerPlatformOwner('admin'); +}); +afterEach(() => { + restoreOwner(); + rmSync(dir, { recursive: true, force: true }); + if (posture === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = posture; + vi.restoreAllMocks(); +}); + +/** Nothing registered, no ledger entry, and the table never read. */ +function expectNothingWritten(rt: Awaited>, driver: ReturnType) { + expect(rt.register).not.toHaveBeenCalled(); + expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull(); + expect(driver.planDeclaredRenames).not.toHaveBeenCalled(); +} + +describe('#34574 — over the real runtime, step 1c answers a refusal of the artifact resolver with that refusal', () => { + it('the runtime under test carries the judgements, so step 1c is the first reader of the packages', async () => { + const runtime = await import('@objectstack/runtime'); + expect(typeof runtime.collectJobsWithoutBody).toBe('function'); + }); + + it('two packages that depend on each other answer 422 CYCLIC_ARTIFACT_PACKAGES naming the cycle, and nothing is written', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + const cyclic = [ + entry(`${SUITE}.core`, [ACCOUNT], { [`${SUITE}.leads`]: '*' }), + entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' }), + ]; + + const res = await rt.install({ manifest: composed(cyclic) }); + + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('CYCLIC_ARTIFACT_PACKAGES'); + expect(res.payload.error.details).toEqual({ cycle: [`${SUITE}.core`, `${SUITE}.leads`, `${SUITE}.core`] }); + expect(res.payload.error.message).toContain(`"${SUITE}.core" -> "${SUITE}.leads" -> "${SUITE}.core"`); + expectNothingWritten(rt, driver); + }); + + it('a `packages` that is not a list answers 422 INVALID_ARTIFACT_PACKAGES, and nothing is written', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + + const res = await rt.install({ manifest: composed('not-a-list') }); + + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGES'); + expectNothingWritten(rt, driver); + }); + + it('a package id declared twice answers 422 DUPLICATE_ARTIFACT_PACKAGE, and nothing is written', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + + const res = await rt.install({ manifest: composed([entry(`${SUITE}.core`, [ACCOUNT]), entry(`${SUITE}.core`, [LEAD])]) }); + + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.error.code).toBe('DUPLICATE_ARTIFACT_PACKAGE'); + expectNothingWritten(rt, driver); + }); + + it('CONTROL: the same packages without the closing dependency install', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + + const res = await rt.install({ + manifest: composed([entry(`${SUITE}.core`, [ACCOUNT]), entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' })]), + }); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(res.payload.success).toBe(true); + expect(rt.register).toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/artifact-packages.test.ts b/packages/core/src/artifact-packages.test.ts index fe5bfa9db07..0c10117a1a9 100644 --- a/packages/core/src/artifact-packages.test.ts +++ b/packages/core/src/artifact-packages.test.ts @@ -132,3 +132,40 @@ describe('an entry refusal ends on what is wrong with the entry', () => { expect(message).not.toContain(GLOBS); }); }); + +describe('packages that depend on each other in a cycle are refused with CYCLIC_ARTIFACT_PACKAGES', () => { + const pkg = (id: string, dependencies?: Record) => ({ + manifest: { id, name: id, version: '1.0.0', type: 'module', ...(dependencies ? { dependencies } : {}) }, + }); + + it('a two-package cycle answers 422 CYCLIC_ARTIFACT_PACKAGES, naming the cycle in the message and in `details.cycle`', () => { + const refused = refusalOf({ + packages: [pkg('com.example.a', { 'com.example.b': '^1.0.0' }), pkg('com.example.b', { 'com.example.a': '^1.0.0' })], + }); + expect(refused).toBeInstanceOf(Error); + expect(refused?.code).toBe('CYCLIC_ARTIFACT_PACKAGES'); + expect(refused?.status).toBe(422); + expect(refused?.details).toEqual({ cycle: ['com.example.a', 'com.example.b', 'com.example.a'] }); + expect(refused?.message).toContain('"com.example.a" -> "com.example.b" -> "com.example.a"'); + }); + + it('the cycle path skips packages outside it, and ignores a dependency on a package the artifact does not carry', () => { + const refused = refusalOf({ + packages: [ + pkg('com.example.base', { '@external/auth': '^2.0.0' }), + pkg('com.example.a', { 'com.example.base': '*', 'com.example.c': '*' }), + pkg('com.example.b', { 'com.example.a': '*' }), + pkg('com.example.c', { 'com.example.b': '*' }), + ], + }); + expect(refused?.code).toBe('CYCLIC_ARTIFACT_PACKAGES'); + expect(refused?.details).toEqual({ cycle: ['com.example.a', 'com.example.c', 'com.example.b', 'com.example.a'] }); + }); + + it('control: the same packages without the closing edge resolve in dependency order', () => { + const resolved = resolveArtifactPackageOrder({ + packages: [pkg('com.example.a', { 'com.example.b': '^1.0.0' }), pkg('com.example.b')], + }) as Array<{ id: string }>; + expect(resolved.map((body) => body.id)).toEqual(['com.example.b', 'com.example.a']); + }); +}); diff --git a/packages/core/src/artifact-packages.ts b/packages/core/src/artifact-packages.ts index f1c2cd7e8e8..5e389a0c832 100644 --- a/packages/core/src/artifact-packages.ts +++ b/packages/core/src/artifact-packages.ts @@ -129,13 +129,17 @@ * the closure and simply stops walking (`protocol.ts`, * `resolveWritePackageScope`) rather than treating it as a fault. * - * Cycles keep the sorter's behaviour untouched: two packages in one artifact - * that depend on each other throw, because an optional dependency is a real - * edge whenever both sides are composed. ⛔ Neither the cycle throw nor the - * missing-dependency semantics are re-adjudicated here. + * Cycles keep the sorter's verdict untouched: two packages in one artifact + * that depend on each other are refused, because an optional dependency is a + * real edge whenever both sides are composed. ⛔ Neither that verdict nor the + * missing-dependency semantics are re-adjudicated here. What this module adds + * is the envelope: the sorter throws its typed `PluginOrderCycleError`, and + * the refusal leaves here as `CYCLIC_ARTIFACT_PACKAGES` (`status: 422`) with + * `details.cycle`, like every other refusal of this resolver — the cycle path + * is read off the sorter's own error, never off a second walk of the graph. */ -import { resolvePluginOrder, type OrderablePlugin } from './plugin-order.js'; +import { PluginOrderCycleError, resolvePluginOrder, type OrderablePlugin } from './plugin-order.js'; import { ArtifactPackageSchema, type ArtifactPackageSource } from '@objectstack/spec'; /** @@ -143,7 +147,7 @@ import { ArtifactPackageSchema, type ArtifactPackageSource } from '@objectstack/ * (`code` + `status`) — the shape this repository's rejection tests assert * against, never a bare throw. */ -export type ArtifactPackageError = Error & { code: string; status: number }; +export type ArtifactPackageError = Error & { code: string; status: number; details?: Record }; /** * How many Zod issues one refusal quotes before it starts counting instead. @@ -155,10 +159,11 @@ export type ArtifactPackageError = Error & { code: string; status: number }; */ const MAX_REPORTED_ENTRY_ISSUES = 5; -function refuse(code: string, message: string): ArtifactPackageError { +function refuse(code: string, message: string, details?: Record): ArtifactPackageError { const err = new Error(message) as ArtifactPackageError; err.code = code; err.status = 422; + if (details !== undefined) err.details = details; return err; } @@ -302,8 +307,10 @@ export function resolveArtifactPackageOrder(artifact: unknown): unknown[] { * @throws An ADR-0112 envelope (`code` + `status: 422`): * `INVALID_ARTIFACT_PACKAGES` for a `packages` that is present but is not an * array (`null` included), `INVALID_ARTIFACT_PACKAGE_ENTRY` for a malformed entry, and - * `DUPLICATE_ARTIFACT_PACKAGE` for a duplicate package id. Also - * `resolvePluginOrder`'s own error for a cycle. + * `DUPLICATE_ARTIFACT_PACKAGE` for a duplicate package id, and + * `CYCLIC_ARTIFACT_PACKAGES` for packages that depend on each other in a + * cycle, with `details.cycle` naming the package ids along it (each depends + * on the next, the first repeated last). */ export function resolveArtifactPackageEntries(artifact: unknown): ArtifactPackageRegistration[] { const declared = (artifact as { packages?: unknown } | null | undefined)?.packages; @@ -419,5 +426,23 @@ export function resolveArtifactPackageEntries(artifact: unknown): ArtifactPackag }); }); - return resolvePluginOrder(nodes).map(({ manifest, source }) => (source !== undefined ? { manifest, source } : { manifest })); + let ordered: ArtifactPackageNode[]; + try { + ordered = resolvePluginOrder(nodes); + } catch (err) { + // The sorter's verdict, answered in this resolver's envelope (ADR-0112): + // a bare Error here reached the install door as an opaque 500. The path + // is the sorter's own reading; nothing else it throws is relabelled. + if (!(err instanceof PluginOrderCycleError)) throw err; + const cycle = [...err.cycle]; + throw refuse( + 'CYCLIC_ARTIFACT_PACKAGES', + `Release artifact packages depend on each other in a cycle: ${cycle.map((id) => `"${id}"`).join(' -> ')} ` + + '(Circular dependency detected). Packages inside one artifact register in dependency order (ADR-0130 D5), ' + + 'and a cycle has none: remove one `manifest.dependencies` entry along the cycle, or merge the packages ' + + 'that need each other into one.', + { cycle }, + ); + } + return ordered.map(({ manifest, source }) => (source !== undefined ? { manifest, source } : { manifest })); } diff --git a/packages/core/src/plugin-order.test.ts b/packages/core/src/plugin-order.test.ts index a7f573aea27..73f97003027 100644 --- a/packages/core/src/plugin-order.test.ts +++ b/packages/core/src/plugin-order.test.ts @@ -13,6 +13,7 @@ import { describe, it, expect } from 'vitest'; import { resolvePluginOrder, + PluginOrderCycleError, validateInitServiceContract, assertInitServiceRequirements, type OrderablePlugin, @@ -68,6 +69,39 @@ describe('resolvePluginOrder', () => { ])), ).toThrow('Circular dependency detected'); }); + + it('throws a cycle as a PluginOrderCycleError naming the path, the message and the envelope unchanged', () => { + let caught: unknown; + try { + resolvePluginOrder(toMap([ + { name: 'x' }, + { name: 'a', dependencies: ['b'] }, + { name: 'b', optionalDependencies: ['c'] }, + { name: 'c', dependencies: ['a'] }, + ])); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PluginOrderCycleError); + expect(caught).toBeInstanceOf(Error); + const cycleError = caught as PluginOrderCycleError & { code?: unknown; status?: unknown }; + // Each name depends on the next; the first is repeated last. + expect(cycleError.cycle).toEqual(['a', 'b', 'c', 'a']); + // What a kernel boot reads is what it read before the class existed. + expect(cycleError.message).toBe('[Kernel] Circular dependency detected: a'); + expect(cycleError.code).toBeUndefined(); + expect(cycleError.status).toBeUndefined(); + }); + + it('names a plugin that depends on itself as a one-name cycle', () => { + let caught: unknown; + try { + resolvePluginOrder(toMap([{ name: 'a', optionalDependencies: ['a'] }])); + } catch (err) { + caught = err; + } + expect((caught as PluginOrderCycleError).cycle).toEqual(['a', 'a']); + }); }); describe('validateInitServiceContract', () => { diff --git a/packages/core/src/plugin-order.ts b/packages/core/src/plugin-order.ts index 0abe3013dc1..1b37279dace 100644 --- a/packages/core/src/plugin-order.ts +++ b/packages/core/src/plugin-order.ts @@ -56,23 +56,51 @@ export interface OrderablePlugin { providesServices?: string[]; } +/** + * The cycle {@link resolvePluginOrder} refuses, as a typed error. + * + * Non-breaking on purpose: it IS an `Error`, its `message` is the sorter's + * unchanged `[Kernel] Circular dependency detected: `, and it carries no + * `code` / `status`, so a kernel boot that throws it reads exactly as it did + * before this class existed. What it adds is {@link cycle}, for a caller that + * answers the cycle to an author (the artifact resolver's ADR-0112 refusal, + * `artifact-packages.ts`) instead of re-parsing a message or walking the graph + * a second time. + */ +export class PluginOrderCycleError extends Error { + /** + * The names along the cycle, in edge order (each depends on the next), + * the first repeated last: `['a', 'b', 'a']` for two plugins that depend + * on each other, `['a', 'a']` for a plugin that depends on itself. + */ + readonly cycle: readonly string[]; + + constructor(cycle: readonly string[]) { + super(`[Kernel] Circular dependency detected: ${cycle[cycle.length - 1]}`); + this.name = 'PluginOrderCycleError'; + this.cycle = Object.freeze([...cycle]); + } +} + /** * Topologically order plugins: every plugin's `dependencies` (throw when * missing) and `optionalDependencies` (skip when missing) init before it. * Insertion order is preserved for plugins with no edges between them. * Cycles through either edge kind throw — an optional dependency is a real - * edge whenever both sides are composed. + * edge whenever both sides are composed — as a {@link PluginOrderCycleError}. */ export function resolvePluginOrder

(plugins: Map): P[] { const resolved: P[] = []; const visited = new Set(); const visiting = new Set(); + // The names being visited, in visit order: the path a cycle is read off. + const path: string[] = []; const visit = (pluginName: string) => { if (visited.has(pluginName)) return; if (visiting.has(pluginName)) { - throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`); + throw new PluginOrderCycleError([...path.slice(path.indexOf(pluginName)), pluginName]); } const plugin = plugins.get(pluginName); @@ -81,6 +109,7 @@ export function resolvePluginOrder

(plugins: Map(plugins: Map { - // Documented under @throws because it is the one refusal here that does not - // carry the ADR-0112 envelope: it comes from `resolvePluginOrder`, the - // platform's one topological sorter, not from the artifact gate. A caller - // matching on `code` alone would miss it — `DevPlugin`'s catch does not. + it('a dependency CYCLE between two packages is refused with the envelope: 422 CYCLIC_ARTIFACT_PACKAGES naming the cycle', () => { + // The sorter's verdict, answered by the artifact gate in the ADR-0112 + // envelope its sibling refusals carry, so a caller matching on `code` sees + // it like the rest. const cyclic = { manifest: { id: 'com.example.a', name: 'A', version: '1.0.0', type: 'app' }, packages: [ @@ -297,16 +296,16 @@ describe('#15232 — DevPlugin i18n auto-detect over a multi-package stack', () { manifest: { id: 'com.example.b', name: 'B', version: '1.0.0', type: 'module', dependencies: { 'com.example.a': '^1.0.0' } } }, ], }; - let caught: (Error & { code?: unknown; status?: unknown }) | undefined; + let caught: (Error & { code?: unknown; status?: unknown; details?: unknown }) | undefined; try { devI18nPluginOptions(cyclic); } catch (err) { - caught = err as Error & { code?: unknown; status?: unknown }; + caught = err as Error & { code?: unknown; status?: unknown; details?: unknown }; } expect(caught).toBeInstanceOf(Error); - expect(caught?.message).toContain('Circular dependency detected'); - expect(caught?.code).toBeUndefined(); - expect(caught?.status).toBeUndefined(); + expect(caught?.code).toBe('CYCLIC_ARTIFACT_PACKAGES'); + expect(caught?.status).toBe(422); + expect(caught?.details).toEqual({ cycle: ['com.example.a', 'com.example.b', 'com.example.a'] }); }); it('an EMPTY top-level `translations` is not an answer — `packages[]` supplies it', () => { diff --git a/packages/plugins/plugin-dev/src/dev-i18n.ts b/packages/plugins/plugin-dev/src/dev-i18n.ts index 6703956bca9..2a37af23b79 100644 --- a/packages/plugins/plugin-dev/src/dev-i18n.ts +++ b/packages/plugins/plugin-dev/src/dev-i18n.ts @@ -167,14 +167,10 @@ const declaresTranslationArray = (body: unknown): boolean => { * `resolveArtifactPackageOrder` when `packages` is present but not loadable: * `INVALID_ARTIFACT_PACKAGES` (not an array, `null` included), `INVALID_ARTIFACT_PACKAGE_ENTRY` * (an entry that is not `{ manifest: … }`, a body carrying authoring-time - * globs where definitions belong, or a manifest with no usable id) or - * `DUPLICATE_ARTIFACT_PACKAGE`. - * @throws A **bare** `Error` — no `code`, no `status` — from `resolvePluginOrder` - * when two packages in `packages[]` depend on each other - * (`[Kernel] Circular dependency detected: …`). Documented because it is the - * one failure here that does NOT carry the envelope every other refusal in - * this repo does, so a caller matching on `code` alone will miss it. Measured, - * not inferred from the sorter's prose. + * globs where definitions belong, or a manifest with no usable id), + * `DUPLICATE_ARTIFACT_PACKAGE`, or `CYCLIC_ARTIFACT_PACKAGES` when packages + * in `packages[]` depend on each other in a cycle (`details.cycle` names the + * package ids along it). */ export function stackDeclaresTranslations(stack: unknown): boolean { // The caller's ORIGINAL expression, first and unchanged. diff --git a/packages/runtime/src/artifact-collections.ts b/packages/runtime/src/artifact-collections.ts index cdbb210a698..fdf491cf56d 100644 --- a/packages/runtime/src/artifact-collections.ts +++ b/packages/runtime/src/artifact-collections.ts @@ -461,24 +461,16 @@ function mergeCollection(key: string, top: unknown, fromBodies: readonly Contrib * * @throws The ADR-0112 refusal `resolveArtifactPackageOrder` raises for a * `packages` that is not an array, `null` included (`INVALID_ARTIFACT_PACKAGES`), a malformed - * `packages[]` entry, a package with no usable id, or a duplicate package. - * It is the same refusal `ObjectQLPlugin`'s `manifest` service already - * raises on the same artifact during boot. Resolving collections out of an + * `packages[]` entry, a package with no usable id, a duplicate package, or + * packages inside one artifact that depend on each other in a cycle + * (`CYCLIC_ARTIFACT_PACKAGES`, with `details.cycle`). It is the same + * refusal `ObjectQLPlugin`'s `manifest` service already raises on the same + * artifact during boot. Resolving collections out of an * artifact the loader would refuse is not a quieter outcome, it is a * different answer to what the artifact contains. * @throws `MIXED_ARTIFACT_COLLECTION_SHAPE` (ADR-0112, 422) — this module's own * refusal — when one collection key is declared in the array form by one * source and in the record form by another. - * @throws ⚠️ `resolvePluginOrder`'s dependency-CYCLE error, propagated through - * `resolveArtifactPackageOrder` when two packages inside one artifact depend - * on each other. Unlike the three refusals above it is a BARE `Error`: it - * carries no `code` and no `status`, so a caller matching on `err.code` / - * `err.status` does not match it and falls through to its generic branch. - * That is `resolveArtifactPackageOrder`'s own contract — reached identically - * by `ObjectQLPlugin`'s manifest service today — and enveloping it would - * change that function's behaviour for every caller, which is not this - * module's call to make. Recorded here so a caller writing a `catch` knows - * the third shape exists. */ export function resolveArtifactCollections(artifact: T): T { if (artifact === null || typeof artifact !== 'object') return artifact; diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index f13a930ec60..adf3e8b2798 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1196,6 +1196,16 @@ export const ERROR_CODE_LEDGER = { 'INVALID_ARTIFACT_PACKAGES', 'INVALID_ARTIFACT_PACKAGE_ENTRY', 'DUPLICATE_ARTIFACT_PACKAGE', + // ADR-0130 D5 — `resolveArtifactPackageEntries` refuses an artifact two or + // more of whose packages depend on each other through + // `manifest.dependencies`, a cycle `resolvePluginOrder` cannot order (the + // sorter's typed `PluginOrderCycleError`, answered in this envelope). + // `refuse()` stamps `code` + `status: 422` like its siblings, and + // `details.cycle` lists the package ids along the cycle, each depending on + // the next, the first repeated last. Door reading as the siblings: + // `POST /api/v1/marketplace/install-local` answers it through + // `declaredRefusalAnswer`, `details` included. + 'CYCLIC_ARTIFACT_PACKAGES', // ADR-0119 D2 — the migration-journal runner's four refusals // (`MigrationJournalRefusal`, `utils/migration-journal.ts`: a // `(code, message)` constructor, `code` only, no `status`). Raised by From f118d4c6b9ae22da93ed5d25d2c67c62e2d47997 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:57:34 +0000 Subject: [PATCH 2/5] docs(spec): regenerate the API references for CYCLIC_ARTIFACT_PACKAGES Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude --- content/docs/references/api/automation-api.mdx | 3 ++- content/docs/references/api/contract.mdx | 3 ++- content/docs/references/api/error-code-ledger.mdx | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 5ebe0b2f4d8..a75820fc6bd 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -417,7 +417,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +368 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -523,6 +523,7 @@ const result = AutomationApiErrorCode.parse(data); * `CREATE_FAILED` * `CREDENTIALS_NAME_DIFFERENT_ACCOUNTS` * `CUBE_NOT_FOUND` +* `CYCLIC_ARTIFACT_PACKAGES` * `DATASET_INVALID` * `DATASOURCE_ADMIN_ERROR` * `DEFAULT_RECORD_PAGE_CONFLICT` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 68a28e06f04..61383d13513 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +368 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -141,6 +141,7 @@ const result = ApiErrorSchema.parse(data); * `CREATE_FAILED` * `CREDENTIALS_NAME_DIFFERENT_ACCOUNTS` * `CUBE_NOT_FOUND` +* `CYCLIC_ARTIFACT_PACKAGES` * `DATASET_INVALID` * `DATASOURCE_ADMIN_ERROR` * `DEFAULT_RECORD_PAGE_CONFLICT` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index 9e80dc13d16..60681acb4c1 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -308,6 +308,7 @@ const result = ErrorCode.parse(data); * `CREATE_FAILED` * `CREDENTIALS_NAME_DIFFERENT_ACCOUNTS` * `CUBE_NOT_FOUND` +* `CYCLIC_ARTIFACT_PACKAGES` * `DATASET_INVALID` * `DATASOURCE_ADMIN_ERROR` * `DEFAULT_RECORD_PAGE_CONFLICT` From bf013a8ebfb5c2f4c4f6861d7e326a354330d214 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:12:21 +0000 Subject: [PATCH 3/5] test(cloud-connection): an artifact member's refused namespace is answered 422, no longer thrown out of the door Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude --- ...e-install-local-namespace-gate-33922.test.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/cloud-connection/src/marketplace-install-local-namespace-gate-33922.test.ts b/packages/cloud-connection/src/marketplace-install-local-namespace-gate-33922.test.ts index 15ca26fb897..67aacf5dd84 100644 --- a/packages/cloud-connection/src/marketplace-install-local-namespace-gate-33922.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-namespace-gate-33922.test.ts @@ -193,9 +193,12 @@ describe('install-local parses the inline manifest\'s `namespace` through its de it('UNMOVED — an artifact MEMBER\'s refused namespace keeps the artifact-entry parse\'s refusal, nothing written', async () => { // Each `packages[]` entry is parsed whole through `ArtifactPackageSchema` - // before any write; this door adds no second judge of it. + // before any write; this door adds no second judge of it. [#34574] The + // refusal is ANSWERED with its own 422 and code (step 1c reads the + // packages first over this real runtime), where it used to leave the + // door as a throw the transport answered `500`. const h = await mount(dir); - const thrown = await h.install({ + const res = await h.install({ manifest: { id: 'com.qa.suite', version: '1.0.0', @@ -204,10 +207,12 @@ describe('install-local parses the inline manifest\'s `namespace` through its de { manifest: { id: 'com.qa.two', name: 'qa_two', version: '1.0.0', type: 'module', namespace: 'QA_N', objects: [] } }, ], }, - }).then(() => undefined, (e: unknown) => e as { code?: string; status?: number; message?: string }); - expect(thrown?.code).toBe('INVALID_ARTIFACT_PACKAGE_ENTRY'); - expect(thrown?.status).toBe(422); - expect(thrown?.message).toContain(declaredSentence('QA_N')); + }); + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(envelopeViolations(res.payload)).toEqual([]); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGE_ENTRY'); + expect(res.payload.error.message).toContain(declaredSentence('QA_N')); expectNothingWritten(h); }); From e7c60d6817ffc98af8de027a359e8420e5d51907 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:47:55 +0000 Subject: [PATCH 4/5] test: pay the lazy runtime and memory-driver loads at module top in the new pins Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude --- ...etplace-install-local-resolver-refusal-real-runtime.test.ts | 3 +++ .../plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts index 2bd1e81b3fb..870deb06d90 100644 --- a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-real-runtime.test.ts @@ -21,6 +21,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; +// The door reaches the runtime through a lazy `import()`; its first load is +// paid here, during collection, never inside a clocked test body. +import '@objectstack/runtime'; import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; import { declareInstallerPlatformOwner, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; diff --git a/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts b/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts index dd725a2d455..cf249105dcf 100644 --- a/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts +++ b/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts @@ -47,6 +47,9 @@ import { composeStacks, defineStack, type ObjectStackDefinition } from '@objects import { resolveArtifactPackageOrder } from '@objectstack/core'; import { devI18nPluginOptions, stackDeclaresTranslations } from './dev-i18n'; import { DevPlugin } from './dev-plugin'; +// `DevPlugin` reaches the memory driver through a lazy `import()`; its first +// load is paid here, during collection, never inside a clocked test body. +import '@objectstack/driver-memory'; const absent = (name: string): Error => Object.assign(new Error(`Cannot find package '${name}'`), { code: 'ERR_MODULE_NOT_FOUND' }); From b1dc2a69c8159c01c2fc60b71e4b6fb6296d8b8d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:47:02 +0000 Subject: [PATCH 5/5] test(plugin-dev): replace the memory driver with a not-found mock in the packages-reader suite, ledgered as mock-replacement Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude --- .../src/dev-i18n-packages-reader.test.ts | 23 ++++++++----------- scripts/driver-memory-census.ledger.json | 6 +++++ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts b/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts index cf249105dcf..f9f5f1ba925 100644 --- a/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts +++ b/packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts @@ -47,9 +47,6 @@ import { composeStacks, defineStack, type ObjectStackDefinition } from '@objects import { resolveArtifactPackageOrder } from '@objectstack/core'; import { devI18nPluginOptions, stackDeclaresTranslations } from './dev-i18n'; import { DevPlugin } from './dev-plugin'; -// `DevPlugin` reaches the memory driver through a lazy `import()`; its first -// load is paid here, during collection, never inside a clocked test body. -import '@objectstack/driver-memory'; const absent = (name: string): Error => Object.assign(new Error(`Cannot find package '${name}'`), { code: 'ERR_MODULE_NOT_FOUND' }); @@ -68,17 +65,17 @@ vi.mock('@objectstack/service-i18n', () => ({ vi.mock('@objectstack/objectql', () => { throw absent('@objectstack/objectql'); }); vi.mock('@objectstack/runtime', () => { throw absent('@objectstack/runtime'); }); -// ⛔ NO `@objectstack/driver-memory` mock here, deliberately — do not copy one in -// from the sibling harnesses. `vi.mock` counts as a DECLARATION to -// `scripts/check-driver-memory-census.mjs`, and that package's consumer set is -// locked by maintainer ruling (#5499 froze investment, #5704 / #6664 ruled each -// remaining consumer). A third test consumer is the #6664 defect itself, not a -// bookkeeping chore. Nothing here needs it: every boot below passes -// `services: { driver: false }`, and `dev-plugin.ts`'s ONE +// The memory driver is REPLACED, never loaded: every boot below passes +// `services: { driver: false }`, and `dev-plugin.ts`'s one // `import('@objectstack/driver-memory')` sits inside `if (enabled('driver'))`, -// so the specifier is never reached. Measured, not assumed: with the line gone -// this suite is unchanged at 68 passed, both BOOT cases below green in 5ms and -// 1ms — timings a real `import()` of that package would not fit in. +// so nothing here needs the real driver. The mock exists because the file +// reaches that lazy import, and `pnpm check:test-source-alias` asks an edited +// test to pay such a load during collection or to mock it — paying it would +// make this file a real consumer of a driver whose consumer set is ruled +// (#5499, #5704, #6664). A not-found-throwing replacement is not a consumer: +// it is ledgered as `mock-replacement` in +// `scripts/driver-memory-census.ledger.json`, like the sibling harnesses. +vi.mock('@objectstack/driver-memory', () => { throw absent('@objectstack/driver-memory'); }); vi.mock('@objectstack/service-storage', () => { throw absent('@objectstack/service-storage'); }); vi.mock('@objectstack/service-realtime', () => { throw absent('@objectstack/service-realtime'); }); vi.mock('@objectstack/plugin-auth', () => { throw absent('@objectstack/plugin-auth'); }); diff --git a/scripts/driver-memory-census.ledger.json b/scripts/driver-memory-census.ledger.json index 02d8b267531..04fa56df4d1 100644 --- a/scripts/driver-memory-census.ledger.json +++ b/scripts/driver-memory-census.ledger.json @@ -113,6 +113,12 @@ "axis": "mock-replacement", "why": "same absent-module mock as dev-plugin.test.ts — the optional stack is forced unavailable so the tenancy posture is the only thing under test." }, + { + "file": "packages/plugins/plugin-dev/src/dev-i18n-packages-reader.test.ts", + "kind": "mock", + "axis": "mock-replacement", + "why": "an absent-module mock like dev-plugin.test.ts's — every DevPlugin boot in the file passes `driver: false`, so the real driver is never loaded; the mock stands in for the collection-time load check:test-source-alias asks of a test that reaches dev-plugin.ts's lazy driver import." + }, { "file": "packages/services/service-datasource/src/__tests__/datasource-update-kept-pool-stores-nothing.test.ts", "kind": "mock",