From c86d3d19482f4b566761ea7108cd9fafe106a139 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 21:34:36 +0000 Subject: [PATCH 1/5] feat(objectql)!: refuse a (type, name) held twice inside one namespace Inside one namespace, an item of the twelve bucket 2/3 types phase 1's one-holder rule does not cover (sharing rule, queue, assignment rule, hook, job, app, page, dashboard, report, book, analytics cube, tool) has one package holder (ADR-0150 D2). The package door refuses the install beside the ADR-0130 D3 object check, and os validate / os build refuse the artifact, through one predicate and one sentence. Claude-Session: https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs Co-authored-by: Claude --- packages/cli/src/commands/compile.ts | 25 ++ packages/cli/src/commands/validate.ts | 38 +++ .../cli/src/utils/namespace-co-owner-names.ts | 88 ++++++ .../test/validate-build-gate-parity.test.ts | 8 + packages/objectql/src/index.ts | 16 + .../objectql/src/namespace-co-owner-names.ts | 293 ++++++++++++++++++ packages/objectql/src/registry.ts | 99 ++++++ 7 files changed, 567 insertions(+) create mode 100644 packages/cli/src/utils/namespace-co-owner-names.ts create mode 100644 packages/objectql/src/namespace-co-owner-names.ts diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index b65a74f758f..bfa2f51aed8 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -73,6 +73,9 @@ import type { PermissionSetNameCollisionDiagnostic } from '@objectstack/plugin-s // [#20393] The boot registrar's divergent view-container `name` refusal — the // walk `os validate` step 2c runs, over `@objectstack/objectql`'s one judge. import { findViewContainerNameRefusals } from '../utils/view-container-names.js'; +// [ADR-0150 D2, child N] The package door's namespace name refusal — the same +// call `os validate` makes at its step 2c-bis. +import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js'; // A field `picklist` that names no picklist the stack declares — the walk // `os validate` step 2d runs, over the same judge. import { judgePicklistReferences, picklistRefusalHeading, printPicklistReferenceNotices } from '../utils/picklist-references.js'; @@ -513,6 +516,28 @@ export default class Compile extends Command { this.exit(1); } + // 3a-ter. [ADR-0150 D2, child N] A package of this artifact holding a + // name of the twelve uncovered bucket 2/3 types that another package + // of its namespace holds is REFUSED, naming every holder — the SAME + // call `os validate` makes at its step 2c-bis, so the artifact this + // door writes is one the package door installs. Right after the + // parse and ahead of every artifact write, like 3a, with 3a's faces. + const namespaceNameRefusals = findNamespaceNameRefusals(result.data as Record); + if (namespaceNameRefusals.length > 0) { + if (flags.json) { + await emitJson({ success: false, errors: namespaceNameRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true }); + this.exit(1); + } + const n = namespaceNameRefusals.length; + console.log(''); + printError(`The server would refuse this stack at boot (${n} package${n > 1 ? 's' : ''} holding a name another package of its namespace holds)`); + printBulletList( + namespaceNameRefusals.map((r) => r.message), + { noun: 'namespace name refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3a-bis. A field `picklist`, or a `picklistExtensions` entry's `extend`, // that names no picklist the stack declares is REFUSED — the SAME call // `os validate` makes at its step 2d, so the two doors cannot disagree diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 24e3a9a8cbc..f997cced842 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -74,6 +74,10 @@ import type { PermissionSetNameCollisionDiagnostic } from '@objectstack/plugin-s // over the parsed stack the way the load path registers it. The verdict is // `@objectstack/objectql`'s; see the module header. import { findViewContainerNameRefusals } from '../utils/view-container-names.js'; +// [ADR-0150 D2, child N] Inside one namespace, an item of the twelve uncovered +// bucket 2/3 types has one package holder: the package door's predicate and +// sentence, walked over the artifact's packages in boot order. +import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js'; // [ADR-0146 D2, #28410] The override write gate's author-time half: the publish // door's own judge, walked over the artifact's packages. import { findOverrideDeclarationRefusals } from '../utils/override-declarations.js'; @@ -505,6 +509,40 @@ export default class Validate extends Command { this.exit(1); } + // 2c-bis. [ADR-0150 D2, child N] A package of this artifact declaring a + // sharing rule, queue, assignment rule, hook, job, app, page, + // dashboard, report, book, analytics cube or tool under a name + // another package of its namespace already declares is REFUSED, + // naming every holder — the package door + // (`SchemaRegistry.installPackage`) refuses that install at boot. + // + // One judge: the predicate and the sentence are + // `@objectstack/objectql`'s; the helper owns only the walk (the + // artifact's packages, in the order the boot installs them). Right + // after the parse, beside 2c and for its reason: the runtime's own + // accept set. `os build` makes the same call. + const namespaceNameRefusals = findNamespaceNameRefusals(result.data as Record); + if (namespaceNameRefusals.length > 0) { + if (flags.json) { + await emitJson({ + valid: false, + errors: namespaceNameRefusals, + warnings: warningsSoFar(), + conversions: conversionNotices, + duration: timer.elapsed(), + }); + this.exit(1); + } + const n = namespaceNameRefusals.length; + console.log(''); + printError(`The server would refuse this stack at boot (${n} package${n > 1 ? 's' : ''} holding a name another package of its namespace holds)`); + printBulletList( + namespaceNameRefusals.map((r) => r.message), + { noun: 'namespace name refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 2d. A field `picklist`, or a `picklistExtensions` entry's `extend`, that // names no picklist the stack declares is REFUSED, naming the field // (or the extension) and the list. `FieldSchema` and diff --git a/packages/cli/src/utils/namespace-co-owner-names.ts b/packages/cli/src/utils/namespace-co-owner-names.ts new file mode 100644 index 00000000000..fc052169839 --- /dev/null +++ b/packages/cli/src/utils/namespace-co-owner-names.ts @@ -0,0 +1,88 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D2, child N] `os validate`'s and `os build`'s half of the package + * door's namespace name refusal: inside one namespace, an item of the twelve + * uncovered bucket 2/3 types (sharing rule, queue, assignment rule, hook, job, + * app, page, dashboard, report, book, analytics cube, tool) has one package + * holder. + * + * ## One judge, not a second rule + * + * The predicate and its sentence are `@objectstack/objectql`'s + * (`namespaceNameConflicts`, `namespaceNameConflictMessage`) — the SAME pair + * `SchemaRegistry.installPackage` throws the answer of. ⛔ Not an + * `@objectstack/lint` rule and not a re-spelling of the check: what this module + * owns is the WALK — which packages the boot installs, in which order. + * + * ## The walk is the boot path's + * + * The boot installs an artifact's `packages[]` bodies one after another, in + * `resolveArtifactPackageOrder`'s dependency order (`@objectstack/core`, the + * one reader of `packages[]`), and asks the predicate about each against the + * packages installed before it. This walk does the same: each body, in that + * order, against the bodies before it. A stack with no `packages[]` is one + * package, which never holds a name beside itself, so it is never refused + * here. + * + * Unlike the boot, which stops at the first refusal, every refused body is + * reported, and a refused body still counts as a holder for the bodies after + * it: the artifact declares it, and the author has to hear about every holder + * (red line 2: ambiguity is reported, never guessed). + * + * ⚠️ Bounds, stated rather than hidden: the packages a deployment already has + * installed are not visible here (that half is the package door's alone), and + * the residual — top-level items no body declares, registered under the + * stack's own id without an install — is not judged at either door. + */ + +import { resolveArtifactPackageOrder } from '@objectstack/core'; +import { + NAMESPACE_CONFLICT_CODE, + namespaceNameConflictMessage, + namespaceNameConflicts, + namespacePackageOf, + type NamespaceNameConflict, + type NamespacePackage, +} from '@objectstack/objectql'; + +/** One refused package, located. `message` is the package door's, verbatim. */ +export interface NamespaceNameRefusalRow { + /** The refused package's id, as the registry installs it. */ + packageId: string; + /** The ADR-0112 code the package door throws with. */ + code: string; + /** The HTTP status the package door throws with. */ + httpStatus: number; + /** The refusal, in the package door's own words. */ + message: string; + /** Every `(type, name)` refused, each naming every holder. */ + conflicts: NamespaceNameConflict[]; +} + +/** + * Every package of this stack's artifact that the package door would refuse + * for a name another package of its namespace holds, in the order the boot + * installs them. `[]` for a stack the door accepts on this axis. + */ +export function findNamespaceNameRefusals(parsed: Record): NamespaceNameRefusalRow[] { + if (parsed.packages === undefined) return []; + const installed: NamespacePackage[] = []; + const rows: NamespaceNameRefusalRow[] = []; + for (const body of resolveArtifactPackageOrder(parsed)) { + const incoming = namespacePackageOf(body); + if (incoming === undefined) continue; + const conflicts = namespaceNameConflicts(incoming, installed); + if (conflicts.length > 0) { + rows.push({ + packageId: incoming.packageId, + code: NAMESPACE_CONFLICT_CODE, + httpStatus: 422, + message: namespaceNameConflictMessage(conflicts), + conflicts, + }); + } + installed.push(incoming); + } + return rows; +} diff --git a/packages/cli/test/validate-build-gate-parity.test.ts b/packages/cli/test/validate-build-gate-parity.test.ts index 9f8859a5578..5db26704918 100644 --- a/packages/cli/test/validate-build-gate-parity.test.ts +++ b/packages/cli/test/validate-build-gate-parity.test.ts @@ -221,6 +221,14 @@ const SHARED_NON_REGISTRY_GATES: readonly string[] = [ // a new package edge, and a copy of the walk is what the ruling forbids. So // `os lint` does not give this verdict; validate and build do. 'findFlowCycleRefusals', + // [ADR-0150 D2, child N] A package of the artifact holding a name of the + // twelve uncovered bucket 2/3 types another package of its namespace holds — + // the package door's predicate and sentence (`@objectstack/objectql`). Not a + // registry rule: cross-package by construction, and the verdict depends on + // the order the boot installs the packages, which the per-package walk a + // registry rule gets cannot see. Both doors make the call, right after the + // parse. + 'findNamespaceNameRefusals', ]; /** diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 66ee64ac40a..e0781c34592 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -133,6 +133,22 @@ export type { // words. A consumer calls this; it does not re-derive the check. export { viewContainerNameRefusal } from './view-container-name-refusal.js'; export type { ViewContainerNameRefusal } from './view-container-name-refusal.js'; +// [ADR-0150 D2, child N] Inside one namespace, a `(type, name)` of the twelve +// uncovered bucket 2/3 types has one package holder. Exported because +// `os validate` is the second door that asks it — of an artifact's packages, in +// the order the boot installs them — and it must answer with the package door's +// predicate and sentence. A consumer calls these; it does not re-derive the rule. +export { + NAMESPACE_UNIQUE_TYPES, + namespacePackageOf, + namespaceNameConflicts, + namespaceNameConflictMessage, +} from './namespace-co-owner-names.js'; +export type { + NamespaceNameConflict, + NamespacePackage, + NamespaceUniqueType, +} from './namespace-co-owner-names.js'; // [ADR-0130 D4] The residual-picklist refusal the `manifest` service throws: a // composed stack's top-level picklist that no package body declares and no diff --git a/packages/objectql/src/namespace-co-owner-names.ts b/packages/objectql/src/namespace-co-owner-names.ts new file mode 100644 index 00000000000..650aa7646cf --- /dev/null +++ b/packages/objectql/src/namespace-co-owner-names.ts @@ -0,0 +1,293 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D2, child N] Inside one namespace, a `(type, name)` has one + * package holder — for the bucket 2/3 types phase 1's one-holder rule does + * not cover. The ONE predicate both doors ask: the package door + * ({@link SchemaRegistry.installPackage}, beside the ADR-0130 D3 object check) + * and `os validate` (`packages/cli/src/utils/namespace-co-owner-names.ts`, + * which walks an artifact's packages in the order the boot installs them and + * asks this module the same question about each). + * + * ## Why + * + * ADR-0150 addresses behavioural metadata by `(namespace, name)` — the URL + * segment, the AI face's derived flat name — while its identity is + * `(package id, name)`. ADR-0130 and ADR-0141 let several packages share one + * namespace (an artifact's packages, a parent and its modules), so the + * address `crm/home` names one item only if no two co-owners of `crm` both + * hold a page `home`. D2 (ruled, record 6724570466) extends ADR-0130 D3's + * object rule to these types: within a namespace, at most one package holder. + * + * ## The types + * + * {@link NAMESPACE_UNIQUE_TYPES}: the twelve bucket 2/3 types phase 1's + * `BARE_NAME_ONE_HOLDER_TYPES` does not list in ADR-0150's execution plan — + * sharing rule, queue, assignment rule, hook, job, app, page, dashboard, + * report, book, analytics cube and tool. ⛔ No other type: a narrowing beyond + * these twelve is the maintainer's to rule. (`tool` is in both lists once + * phase 1 takes it: that rule refuses a second holder anywhere in the + * deployment after the cold boot; this one refuses a second holder inside one + * namespace at every install. The two never disagree about a refusal, only + * about when it applies.) + * + * ## The holders + * + * A package, by the id the registry installs it under (`artifactPackageId`), + * and by its `manifest.namespace`. Two packages are in one namespace when they + * declare the same one. ⛔ Never: + * + * - a package with no namespace — it has no address to share; + * - a shareable platform namespace ({@link isNamespaceJudged}): `base`, + * `system` and `sys`, the namespaces the install-time namespace gate lets + * any number of packages share, and which ADR-0130 D3's co-owner map never + * reads either; + * - the environment catalog — an environment item belongs to the implicit + * environment package, which has no namespace (ADR-0150 D2), and an item + * authored under a package's name is that package's ADR-0005 overlay; + * - the same package again — a reload, a re-install or an upgrade holds its + * own names, and a package declaring one name twice (two `page/home` in + * one manifest) is one holder: that duplicate is the intra-package + * duplicate rule's, not this one. + * + * ## The names + * + * Read from the SAME sources the engine's registration seams read + * ({@link declaredNamespaceUniqueNames}): the manifest's own collections and + * each nested `plugins[]` entry's, named the way the seams name an item + * (`name`, else `id`); for `app`, also the manifest-as-app and plugin-as-app + * rows the engine registers under the manifest's (or plugin's) `name`. + * + * ⛔ No package-scoped resolution here (that is ADR-0150 child R), and phase + * 1's one-holder rule is not touched. + */ + +import { artifactPackageId } from '@objectstack/core'; +import { singularToPlural } from '@objectstack/spec/shared'; + +/** A type the rule covers, spelt as the registry keys it. */ +export type NamespaceUniqueType = + | 'sharing_rule' | 'queue' | 'assignment_rule' + | 'hook' | 'job' + | 'app' | 'page' | 'dashboard' | 'report' | 'book' | 'analytics_cube' + | 'tool'; + +/** + * The covered types, in the order a refusal lists them — ADR-0150's + * execution-plan order (child N's row). + */ +export const NAMESPACE_UNIQUE_TYPES: readonly NamespaceUniqueType[] = Object.freeze([ + 'sharing_rule', + 'queue', + 'assignment_rule', + 'hook', + 'job', + 'app', + 'page', + 'dashboard', + 'report', + 'book', + 'analytics_cube', + 'tool', +]); + +/** Is `type` one of the covered types? */ +export function isNamespaceUniqueType(type: unknown): type is NamespaceUniqueType { + return typeof type === 'string' && (NAMESPACE_UNIQUE_TYPES as readonly string[]).includes(type); +} + +/** + * The namespaces any number of packages may share by design — the install + * gate's exemption (`isShareableNamespace` in `registry.ts`, ADR-0048 Phase 1): + * the FQN-exempt reserved namespaces plus `sys`. Spelt here because this + * module may not import the registry; `namespace-co-owner-names.test.ts` holds + * the two equal. + */ +const SHAREABLE_NAMESPACES: ReadonlySet = new Set(['base', 'system', 'sys']); + +/** + * Does the rule judge names inside `namespace`? A non-empty namespace that is + * not a shareable platform one. + */ +export function isNamespaceJudged(namespace: unknown): namespace is string { + return typeof namespace === 'string' && namespace !== '' && !SHAREABLE_NAMESPACES.has(namespace); +} + +/** One covered `(type, name)` a manifest declares. */ +export interface NamespaceUniqueName { + readonly type: NamespaceUniqueType; + readonly name: string; +} + +/** The name the engine's collection seam registers an item under (`name`, else `id`). */ +function itemName(item: unknown): string | undefined { + if (!item || typeof item !== 'object') return undefined; + const { name, id } = item as { name?: unknown; id?: unknown }; + if (typeof name === 'string' && name !== '') return name; + if (typeof id === 'string' && id !== '') return id; + return undefined; +} + +const asRecord = (value: unknown): Record | undefined => + value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : undefined; + +/** + * Every covered `(type, name)` a manifest declares, in declaration order, read + * the way the engine registers them: + * + * - the manifest: each covered collection (`singularToPlural(type)`; `apps` + * included), and the manifest itself as an app when it registers as one + * (a `name` and a `navigation`, and no `apps`: `registersManifestAsApp`); + * - each nested `plugins[]` entry, one level deep: its covered collections + * except `apps` (the nested seam does not register that key), and the + * plugin itself as an app when it carries a `name` and a `navigation`. + * + * A name declared twice is returned twice; the predicate counts holders, not + * declarations. + */ +export function declaredNamespaceUniqueNames(manifest: unknown): NamespaceUniqueName[] { + const out: NamespaceUniqueName[] = []; + const read = (source: Record, nested: boolean) => { + for (const type of NAMESPACE_UNIQUE_TYPES) { + if (type === 'app' && nested) continue; + const items = source[singularToPlural(type)]; + if (!Array.isArray(items)) continue; + for (const item of items) { + const name = itemName(item); + if (name !== undefined) out.push({ type, name }); + } + } + }; + const root = asRecord(manifest); + if (!root) return out; + read(root, false); + const apps = root.apps; + if (typeof root.name === 'string' && root.name !== '' && root.navigation && !(Array.isArray(apps) && apps.length > 0)) { + out.push({ type: 'app', name: root.name }); + } + if (Array.isArray(root.plugins)) { + for (const entry of root.plugins) { + const plugin = asRecord(entry); + if (!plugin) continue; + if (typeof plugin.name === 'string' && plugin.name !== '' && plugin.navigation) { + out.push({ type: 'app', name: plugin.name }); + } + read(plugin, true); + } + } + return out; +} + +/** One package as the predicate sees it. */ +export interface NamespacePackage { + /** The id the registry installs it under (`artifactPackageId`). */ + readonly packageId: string; + /** Its `manifest.namespace`, if any. */ + readonly namespace: string | undefined; + /** Its covered names ({@link declaredNamespaceUniqueNames}). */ + readonly names: readonly NamespaceUniqueName[]; +} + +/** Read one manifest as the predicate sees it, or `undefined` when it has no id. */ +export function namespacePackageOf(manifest: unknown): NamespacePackage | undefined { + const packageId = artifactPackageId(manifest); + if (packageId === undefined) return undefined; + const namespace = asRecord(manifest)?.namespace; + return { + packageId, + namespace: typeof namespace === 'string' ? namespace : undefined, + names: declaredNamespaceUniqueNames(manifest), + }; +} + +/** One `(type, name)` an incoming package would hold beside another package of its namespace. */ +export interface NamespaceNameConflict { + /** The namespace both hold it in. */ + readonly namespace: string; + /** The covered type, as the registry keys it. */ + readonly type: NamespaceUniqueType; + /** The name. */ + readonly name: string; + /** The package whose registration this refuses. */ + readonly incomingPackageId: string; + /** Every OTHER package of the namespace that already holds it, in the order given. Never empty. */ + readonly existingPackageIds: readonly string[]; +} + +/** + * THE predicate: every covered `(type, name)` `incoming` declares that a + * DIFFERENT package of its namespace among `sitting` already declares — one + * entry per `(type, name)`, in `incoming`'s declaration order, each naming + * every other holder. `[]` when `incoming`'s namespace is not judged + * ({@link isNamespaceJudged}), and for a `sitting` entry with `incoming`'s own + * id (the same package again, never a second holder). + */ +export function namespaceNameConflicts( + incoming: NamespacePackage, + sitting: Iterable, +): NamespaceNameConflict[] { + const namespace = incoming.namespace; + if (!isNamespaceJudged(namespace) || incoming.names.length === 0) return []; + const holders = new Map(); + const keyOf = (n: NamespaceUniqueName) => `${n.type}\u0000${n.name}`; + for (const other of sitting) { + if (other.packageId === incoming.packageId || other.namespace !== namespace) continue; + for (const n of other.names) { + const key = keyOf(n); + const ids = holders.get(key) ?? []; + if (!ids.includes(other.packageId)) ids.push(other.packageId); + holders.set(key, ids); + } + } + const out: NamespaceNameConflict[] = []; + const seen = new Set(); + for (const n of incoming.names) { + const key = keyOf(n); + if (seen.has(key)) continue; + seen.add(key); + const existing = holders.get(key); + if (!existing || existing.length === 0) continue; + out.push({ namespace, type: n.type, name: n.name, incomingPackageId: incoming.packageId, existingPackageIds: existing }); + } + return out; +} + +/** How a refusal names a covered type. */ +export function namespaceUniqueTypeLabel(type: NamespaceUniqueType): string { + switch (type) { + case 'sharing_rule': return 'sharing rule'; + case 'assignment_rule': return 'assignment rule'; + case 'analytics_cube': return 'analytics cube'; + default: return type; + } +} + +const quoteAll = (ids: readonly string[]): string => { + const quoted = ids.map((id) => `package "${id}"`); + return quoted.length <= 1 ? (quoted[0] ?? '') : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`; +}; + +/** One conflict's line, the same at both doors: every holder named. */ +export function namespaceNameConflictLine(c: NamespaceNameConflict): string { + return ( + `package "${c.incomingPackageId}" declares the ${namespaceUniqueTypeLabel(c.type)} "${c.name}" in namespace ` + + `"${c.namespace}", already held there by ${quoteAll(c.existingPackageIds)}` + ); +} + +/** + * The refusal's sentence for `conflicts` (non-empty, one incoming package), + * the same at both doors. + */ +export function namespaceNameConflictMessage(conflicts: readonly NamespaceNameConflict[]): string { + const [first] = conflicts; + const others = [...new Set(conflicts.flatMap((c) => c.existingPackageIds))]; + return ( + `Namespace name conflict: package "${first.incomingPackageId}" cannot register ` + + `${conflicts.length === 1 ? 'a name' : `${conflicts.length} names`} another package of its namespace already ` + + `holds — ${conflicts.map(namespaceNameConflictLine).join('; ')}. Packages may share a namespace (an ` + + `artifact's packages, a package and the packages that declare it), but inside one namespace an item of these ` + + `types has one package holder, so that the address NAMESPACE/NAME names exactly one item (ADR-0150 D2). ` + + `Rename the item in "${first.incomingPackageId}" or in ${quoteAll(others)}, or leave one of the packages out.` + ); +} diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 9d12f869c52..3b698a044fc 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -96,6 +96,18 @@ import { type BareNameHolder, type BareNameOneHolderType, } from './bare-name-one-holder.js'; +// [ADR-0150 D2, child N] Inside one namespace, a `(type, name)` of the twelve +// uncovered bucket 2/3 types has one package holder — the one predicate the +// package door and `os validate` both ask (module doc). +import { + isNamespaceJudged, + namespaceNameConflictMessage, + namespaceNameConflicts, + namespacePackageOf, + type NamespaceNameConflict, + type NamespacePackage, + type NamespaceUniqueType, +} from './namespace-co-owner-names.js'; // One default record page per object per deployment — the holders and the one // place a manifest's default record pages are read from (module doc). import { @@ -3239,6 +3251,57 @@ export class ArtifactObjectNameConflictError extends Error { } } +/** + * [ADR-0150 D2, child N] Raised when a package declares an item of one of the + * twelve uncovered bucket 2/3 types — sharing rule, queue, assignment rule, + * hook, job, app, page, dashboard, report, book, analytics cube, tool — under a + * name another package of its namespace already holds, at the package door + * (`namespace-co-owner-names.ts` states the rule, the holders and what it does + * not judge). `os validate` prints the same sentence for the same predicate. + * + * {@link ArtifactObjectNameConflictError}'s sibling in placement — it sits + * right after the ADR-0130 D3 object check, ahead of every mutation — and + * {@link BareNameConflictError}'s in its envelope and code: `code: + * 'NAMESPACE_CONFLICT'`, `status: 422`, because the condition is the one the + * namespace gate registers that code for, "a name in a namespace is already + * taken", and so is the remedy: rename, or leave one package out. No code is + * minted. + * + * Every conflict the install carries is listed — `conflicts` — and each names + * EVERY package of the namespace that already holds the name (red line 2: + * ambiguity is reported, never guessed). The top-level fields repeat the first. + */ +export class NamespaceNameConflictError extends Error { + readonly code = NAMESPACE_CONFLICT_CODE; + readonly status = 422; + /** The same number under ADR-0112 D5's spelling — what a consumer holding the THROWN error reads. */ + readonly httpStatus = 422; + /** Every `(type, name)` this install would have held twice inside its namespace, in declaration order. */ + readonly conflicts: readonly NamespaceNameConflict[]; + /** The namespace. */ + readonly namespace: string; + /** The first conflict's type. */ + readonly itemType: NamespaceUniqueType; + /** The first conflict's name. */ + readonly itemName: string; + /** The package whose install this refusal stopped. */ + readonly incomingPackageId: string; + /** The first conflict's existing holders, every one of them. */ + readonly existingPackageIds: readonly string[]; + + constructor(conflicts: readonly NamespaceNameConflict[]) { + const [first] = conflicts; + super(namespaceNameConflictMessage(conflicts)); + this.name = 'NamespaceNameConflictError'; + this.conflicts = conflicts; + this.namespace = first.namespace; + this.itemType = first.type; + this.itemName = first.name; + this.incomingPackageId = first.incomingPackageId; + this.existingPackageIds = first.existingPackageIds; + } +} + /** * [ADR-0029 D3] The cross-package ownership refusal: a package claims `own` * on an object name that a DIFFERENT package already owns. Raised by @@ -8691,6 +8754,14 @@ export class SchemaRegistry { // behind — the same disposition the namespace gate above has. this.refuseCoOwnedObjectNameCollision(manifest, selfId, coOwners); + // [ADR-0150 D2, child N] The object rule above, extended to the twelve + // bucket 2/3 types phase 1 does not cover: inside one namespace, a + // `(type, name)` has one package holder, so that NAMESPACE/NAME names one + // item (`namespace-co-owner-names.ts`). Ahead of every mutation, like the + // check above; at every install, boot included, like it; with no + // `collisionPolicy` downgrade, like the bare-name rule below. + this.refuseNamespaceNameConflicts(manifest); + // The security catalog's one-name-one-holder rule (ADR-0048 §3.4 narrowed // for positions, permission sets and capabilities; maintainer ruling Q4 = A // on #15196) — also ahead of every mutation, for the same reason. No @@ -8924,6 +8995,34 @@ export class SchemaRegistry { } } + /** + * [ADR-0150 D2, child N] Refuse an install whose package declares an item of + * a covered type under a name another installed package of its namespace + * already holds (`namespace-co-owner-names.ts`). + * + * The sitting holders are the installed package records — their manifests, + * as {@link installPackage} recorded them — of the incoming package's + * namespace: the record is the one place every door's install lands, so an + * uninstall takes its names with it and nothing else is kept. The same + * package's own record is never a second holder (a reload, a re-install or + * an upgrade). + * + * @throws {NamespaceNameConflictError} ADR-0112 envelope, naming every holder. + */ + private refuseNamespaceNameConflicts(manifest: ObjectStackManifest): void { + const incoming = namespacePackageOf(manifest); + if (incoming === undefined || !isNamespaceJudged(incoming.namespace) || incoming.names.length === 0) return; + const sitting: NamespacePackage[] = []; + for (const record of this.metadata.get('package')?.values() ?? []) { + const recorded = (record as InstalledPackage | undefined)?.manifest; + if (recorded?.namespace !== incoming.namespace) continue; + const holder = namespacePackageOf(recorded); + if (holder !== undefined) sitting.push(holder); + } + const conflicts = namespaceNameConflicts(incoming, sitting); + if (conflicts.length > 0) throw new NamespaceNameConflictError(conflicts); + } + /** * Withdraw an installed package: its objects, namespace, items, catalog * claims and record (each step's reason is on it below). From 104b9ea1030e4c27f9acdd3f8bca9213fdc25b6c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 21:42:45 +0000 Subject: [PATCH 2/5] test: pin the namespace name refusal at the package door, os validate and os build Claude-Session: https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs Co-authored-by: Claude --- .../utils/namespace-co-owner-names.test.ts | 151 ++++++++ .../cli/test/validate-namespace-name.test.ts | 152 ++++++++ .../registry-namespace-co-owner-names.test.ts | 333 ++++++++++++++++++ 3 files changed, 636 insertions(+) create mode 100644 packages/cli/src/utils/namespace-co-owner-names.test.ts create mode 100644 packages/cli/test/validate-namespace-name.test.ts create mode 100644 packages/objectql/src/registry-namespace-co-owner-names.test.ts diff --git a/packages/cli/src/utils/namespace-co-owner-names.test.ts b/packages/cli/src/utils/namespace-co-owner-names.test.ts new file mode 100644 index 00000000000..8f11b23b4ab --- /dev/null +++ b/packages/cli/src/utils/namespace-co-owner-names.test.ts @@ -0,0 +1,151 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D2, child N] `findNamespaceNameRefusals` — the WALK `os validate` + * and `os build` run the package door's namespace name predicate over. + * + * The predicate and its sentence are `@objectstack/objectql`'s + * (`namespaceNameConflicts`, `namespaceNameConflictMessage`), the pair the + * package door throws the answer of; its own file pins them. What this module + * owns, and what is pinned here, is which packages it hands that predicate and + * in which order — the boot's: an artifact's `packages[]` bodies, in + * dependency order, each against the bodies before it. + * + * Every row's message is asserted EQUAL to the predicate's sentence for the + * same conflicts — never re-spelled. + */ + +import { describe, expect, it } from 'vitest'; +import { + NAMESPACE_CONFLICT_CODE, + NAMESPACE_UNIQUE_TYPES, + namespaceNameConflictMessage, + type NamespaceUniqueType, +} from '@objectstack/objectql'; +import { findNamespaceNameRefusals } from './namespace-co-owner-names.js'; + +const COLLECTION: Record = { + sharing_rule: 'sharingRules', + queue: 'queues', + assignment_rule: 'assignmentRules', + hook: 'hooks', + job: 'jobs', + app: 'apps', + page: 'pages', + dashboard: 'dashboards', + report: 'reports', + book: 'books', + analytics_cube: 'analyticsCubes', + tool: 'tools', +}; + +/** + * A spec-valid item of each type: the walk reads packages through + * `resolveArtifactPackageOrder`, which parses every entry as the boot does. + */ +const item = (type: NamespaceUniqueType, name: string): Record => { + switch (type) { + case 'sharing_rule': + return { name, label: name, type: 'criteria', object: 'crm_account', sharedWith: { type: 'team', value: 'sales' }, condition: 'true', accessLevel: 'read' }; + case 'assignment_rule': + return { name, label: name, object: 'crm_account', entries: [{ name: 'e1', assignTo: { type: 'queue', value: 'triage' } }] }; + case 'hook': + return { name, label: name, object: 'crm_account', events: ['beforeInsert'], body: { language: 'js', source: 'return;' } }; + case 'job': + return { name, label: name, schedule: { type: 'cron', expression: '0 * * * *' }, handler: 'noop' }; + case 'page': + return { name, label: name, type: 'app', regions: [] }; + case 'dashboard': + return { name, label: name, widgets: [] }; + case 'report': + return { name, label: name, dataset: 'ds', values: ['total'] }; + case 'book': + return { name, label: name, groups: [] }; + case 'analytics_cube': + return { name, title: name, sql: 'select 1', measures: {}, dimensions: {} }; + case 'tool': + return { name, label: name, description: 'A tool', parameters: {} }; + default: + return { name, label: name }; + } +}; + +const body = (id: string, ns: string | undefined, decl: Partial> = {}, extra: Record = {}) => { + const out: Record = { id, name: id.split('.').pop(), version: '1.0.0', type: 'app', ...(ns ? { namespace: ns } : {}), ...extra }; + for (const [type, names] of Object.entries(decl) as Array<[NamespaceUniqueType, string[]]>) { + out[COLLECTION[type]] = names.map((name) => item(type, name)); + } + return out; +}; + +const artifact = (...bodies: Array>) => ({ packages: bodies.map((manifest) => ({ manifest })) }); + +describe.each(NAMESPACE_UNIQUE_TYPES)('%s — os validate refuses an artifact whose packages share a name inside one namespace', (type) => { + it('one row for the second package, naming both holders, in the package door\'s words', () => { + const rows = findNamespaceNameRefusals(artifact( + body('com.acme.alpha', 'crm', { [type]: ['shared_item'] }), + body('com.acme.beta', 'crm', { [type]: ['shared_item', 'beta_only'] }), + )); + expect(rows).toHaveLength(1); + const [row] = rows; + expect([row.packageId, row.code, row.httpStatus]).toEqual(['com.acme.beta', NAMESPACE_CONFLICT_CODE, 422]); + expect(row.conflicts).toEqual([ + { namespace: 'crm', type, name: 'shared_item', incomingPackageId: 'com.acme.beta', existingPackageIds: ['com.acme.alpha'] }, + ]); + expect(row.message).toBe(namespaceNameConflictMessage(row.conflicts)); + expect(row.message).toContain('"com.acme.alpha"'); + expect(row.message).toContain('"com.acme.beta"'); + }); + + it('CONTROL — the same name in two different namespaces is not refused', () => { + expect(findNamespaceNameRefusals(artifact( + body('com.acme.alpha', 'crm', { [type]: ['shared_item'] }), + body('com.other.hr', 'hr', { [type]: ['shared_item'] }), + ))).toEqual([]); + }); +}); + +describe('the walk', () => { + it('a stack with no `packages[]` is one package: never refused here', () => { + expect(findNamespaceNameRefusals({ + manifest: { id: 'com.acme.alpha', name: 'alpha', version: '1.0.0', type: 'app', namespace: 'crm' }, + pages: [item('page', 'home'), item('page', 'home')], + })).toEqual([]); + }); + + it('CONTROL — the same name across two types, and one package declaring a name twice, are not refused', () => { + expect(findNamespaceNameRefusals(artifact( + body('com.acme.alpha', 'crm', { page: ['home', 'home'] }), + body('com.acme.beta', 'crm', { dashboard: ['home'] }), + ))).toEqual([]); + }); + + it('CONTROL — a shareable platform namespace is not judged', () => { + expect(findNamespaceNameRefusals(artifact( + body('com.platform.one', 'sys', { page: ['home'] }), + body('com.platform.two', 'sys', { page: ['home'] }), + ))).toEqual([]); + }); + + it('every refused package is reported, and a refused one still counts as a holder for the packages after it', () => { + const rows = findNamespaceNameRefusals(artifact( + body('com.acme.alpha', 'crm', { report: ['pipeline'] }), + body('com.acme.beta', 'crm', { report: ['pipeline'] }), + body('com.acme.gamma', 'crm', { report: ['pipeline'] }), + )); + expect(rows.map((r) => [r.packageId, r.conflicts[0].existingPackageIds])).toEqual([ + ['com.acme.beta', ['com.acme.alpha']], + ['com.acme.gamma', ['com.acme.alpha', 'com.acme.beta']], + ]); + }); + + it('walks in the boot\'s dependency order, not the array\'s: the dependent is the one refused', () => { + const rows = findNamespaceNameRefusals(artifact( + body('com.acme.billing', 'crm', { queue: ['triage'] }, { dependencies: { 'com.acme.core': '^1.0.0' } }), + body('com.acme.core', 'crm', { queue: ['triage'] }), + )); + expect(rows.map((r) => [r.packageId, r.conflicts[0].existingPackageIds])).toEqual([ + ['com.acme.billing', ['com.acme.core']], + ]); + }); +}); diff --git a/packages/cli/test/validate-namespace-name.test.ts b/packages/cli/test/validate-namespace-name.test.ts new file mode 100644 index 00000000000..29ebf3364dc --- /dev/null +++ b/packages/cli/test/validate-namespace-name.test.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D2, child N] `os validate` and `os build` refuse an artifact two of + * whose packages hold one `(type, name)` inside one namespace — for the twelve + * uncovered bucket 2/3 types — in the package door's words, and `os build` + * writes nothing. + * + * The row's message is asserted EQUAL to the refusal the real package door + * throws for the same artifact (`manifest.register()` on a booted kernel), so + * the two doors cannot drift into two sentences. + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { childEnv } from './helpers/serve-process.js'; +import { defineStackSource, linkSpec } from './helpers/define-stack-fixture.js'; + +const HERE = resolve(fileURLToPath(import.meta.url), '..'); +const CLI = resolve(HERE, '../bin/run-dev.js'); +/** A cold spawn of the CLI source entry runs well past vitest's 5 s default. */ +const SPAWN_TIMEOUT_MS = 120_000; +/** `os build`'s default `--output`, relative to the working directory. */ +const ARTIFACT = join('dist', 'objectstack.json'); + +interface Run { + code: number; + stdout: string; + stderr: string; +} + +function runCli(args: string[], cwd: string): Promise { + return new Promise((resolvePromise) => { + execFile( + process.execPath, + [CLI, ...args], + { cwd, maxBuffer: 16 * 1024 * 1024, env: childEnv({ NO_COLOR: '1' }) }, + (err, stdout, stderr) => { + resolvePromise({ + code: err ? (typeof (err as { code?: unknown }).code === 'number' ? (err as unknown as { code: number }).code : 1) : 0, + stdout: String(stdout), + stderr: String(stderr), + }); + }, + ); + }); +} + +function payloadOf(run: Run, label: string): Record { + try { + return JSON.parse(run.stdout) as Record; + } catch { + throw new Error(`${label}: stdout was not one JSON document (exit ${run.code})\n${run.stdout}\n${run.stderr}`); + } +} + +const ALPHA = 'com.example.nsn-alpha'; +const BETA = 'com.example.nsn-beta'; + +/** A two-package artifact; `betaNs` is the second package's namespace. */ +function packagesStack(betaNs: string): Record { + const pkg = (id: string, ns: string, tag: string) => ({ + id, + name: tag, + version: '1.0.0', + type: 'app', + namespace: ns, + pages: [{ name: 'nsn_home', label: `${tag} home`, type: 'app', regions: [] }], + tools: [{ name: 'nsn_lookup', label: `${tag} lookup`, description: 'Looks a record up', parameters: {} }], + }); + return { packages: [{ manifest: pkg(ALPHA, 'nsn', 'nsn_alpha') }, { manifest: pkg(BETA, betaNs, 'nsn_beta') }] }; +} + +/** What the package door throws for the same artifact, driven the way the load path drives it. */ +async function doorRefusal(artifact: Record): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + try { + await (kernel.getService('manifest') as { register(m: unknown): void | Promise }).register(artifact); + return undefined; + } catch (e) { + return e; + } finally { + await kernel.shutdown(); + } +} + +const dirs: Record = {}; +let root = ''; + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'os-validate-namespace-name-')); + const make = (label: string, s: Record) => { + const dir = join(root, label); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'objectstack.config.ts'), defineStackSource(s)); + linkSpec(dir); + dirs[label] = dir; + }; + make('shared-validate', packagesStack('nsn')); + make('shared-build', packagesStack('nsn')); + make('two-namespaces', packagesStack('nsn_other')); +}); + +afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe('ADR-0150 child N — os validate and os build refuse what the package door refuses, in its words', () => { + it('premise: the package door refuses the shared artifact and installs the two-namespace one', async () => { + const refusal = await doorRefusal(packagesStack('nsn')); + expect([refusal?.code, refusal?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + expect(await doorRefusal(packagesStack('nsn_other'))).toBeUndefined(); + }); + + it('os validate --json exits 1 with one row for the second package, naming both holders, in the door\'s words', async () => { + const run = await runCli(['validate', '--json'], dirs['shared-validate']); + const payload = payloadOf(run, 'validate --json'); + expect(run.code).toBe(1); + expect(payload.valid).toBe(false); + expect(payload.errors).toHaveLength(1); + const [row] = payload.errors; + expect([row.packageId, row.code, row.httpStatus]).toEqual([BETA, 'NAMESPACE_CONFLICT', 422]); + expect(row.conflicts.map((c: any) => `${c.type}/${c.name}:${c.existingPackageIds.join(',')}`)) + .toEqual([`page/nsn_home:${ALPHA}`, `tool/nsn_lookup:${ALPHA}`]); + expect(row.message).toBe((await doorRefusal(packagesStack('nsn'))).message); + }, SPAWN_TIMEOUT_MS); + + it('os build --json exits 1 with the same row and writes no artifact', async () => { + const dir = dirs['shared-build']; + const run = await runCli(['build', '--json'], dir); + const payload = payloadOf(run, 'build --json'); + expect(run.code).toBe(1); + expect(payload.success).toBe(false); + expect(payload.errors.map((r: any) => [r.packageId, r.code])).toEqual([[BETA, 'NAMESPACE_CONFLICT']]); + expect(existsSync(join(dir, ARTIFACT)), 'os build wrote an artifact the package door refuses').toBe(false); + }, SPAWN_TIMEOUT_MS); + + it('CONTROL — the same names in two namespaces validate', async () => { + const run = await runCli(['validate', '--json'], dirs['two-namespaces']); + const payload = payloadOf(run, 'two-namespaces --json'); + expect(payload.valid, JSON.stringify(payload.errors)).toBe(true); + expect(run.code).toBe(0); + }, SPAWN_TIMEOUT_MS); +}); diff --git a/packages/objectql/src/registry-namespace-co-owner-names.test.ts b/packages/objectql/src/registry-namespace-co-owner-names.test.ts new file mode 100644 index 00000000000..f294dad51ee --- /dev/null +++ b/packages/objectql/src/registry-namespace-co-owner-names.test.ts @@ -0,0 +1,333 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D2, child N] Inside one namespace, a `(type, name)` of the twelve + * uncovered bucket 2/3 types has one package holder — refused at the package + * door (`SchemaRegistry.installPackage`, beside the ADR-0130 D3 object check), + * naming every holder (`namespace-co-owner-names.ts`). + * + * Every refusal is asserted by its ADR-0112 envelope (`code` + `status`), the + * holders it names and the structured `conflicts[]` — never a bare throw. + * + * The CONTROLs pin what the rule leaves alone: the same name in two + * namespaces, the same name across two types, the same package again, a + * shareable platform namespace, the environment catalog, and every type + * outside the twelve. + */ + +import { describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from './plugin.js'; +import { NamespaceNameConflictError, RESERVED_NAMESPACES, SchemaRegistry } from './registry.js'; +import { BARE_NAME_ONE_HOLDER_TYPES } from './bare-name-one-holder.js'; +import { + NAMESPACE_UNIQUE_TYPES, + declaredNamespaceUniqueNames, + isNamespaceJudged, + namespaceNameConflictMessage, + namespaceNameConflicts, + namespacePackageOf, + type NamespaceUniqueType, +} from './namespace-co-owner-names.js'; +import type { ObjectQL } from './engine.js'; + +type Refusal = Error & { + code?: string; + status?: number; + httpStatus?: number; + conflicts?: Array<{ namespace: string; type: string; name: string; incomingPackageId: string; existingPackageIds: string[] }>; +}; + +const COLLECTION: Record = { + sharing_rule: 'sharingRules', + queue: 'queues', + assignment_rule: 'assignmentRules', + hook: 'hooks', + job: 'jobs', + app: 'apps', + page: 'pages', + dashboard: 'dashboards', + report: 'reports', + book: 'books', + analytics_cube: 'analyticsCubes', + tool: 'tools', +}; + +/** A package of namespace `ns` declaring `decl`'s items, each labelled with the package's last id segment. */ +const pkg = (id: string, ns: string | undefined, decl: Partial> = {}, extra: Record = {}) => { + const tag = id.split('.').pop()!; + const out: Record = { id, name: tag, version: '1.0.0', type: 'app', ...(ns ? { namespace: ns } : {}), ...extra }; + for (const [type, names] of Object.entries(decl) as Array<[NamespaceUniqueType, string[]]>) { + out[COLLECTION[type]] = names.map((name) => ({ name, label: `${tag} ${type}` })); + } + return out; +}; + +const scopeOf = (...ids: string[]) => ({ packageIds: ids }); + +const install = (registry: SchemaRegistry, manifest: unknown, scope?: { packageIds: string[] }): Refusal | undefined => { + try { + registry.installPackage(manifest as never, 'code', undefined, scope); + return undefined; + } catch (e) { + return e as Refusal; + } +}; + +const fresh = (collisionPolicy: 'error' | 'warn' = 'error') => new SchemaRegistry({ multiTenant: false, collisionPolicy }); + +describe('the vocabulary', () => { + it('the twelve types, in ADR-0150 child N\'s order', () => { + expect(NAMESPACE_UNIQUE_TYPES).toEqual([ + 'sharing_rule', 'queue', 'assignment_rule', 'hook', 'job', + 'app', 'page', 'dashboard', 'report', 'book', 'analytics_cube', 'tool', + ]); + }); + + it('phase 1\'s one-holder list is not touched: the two lists share at most `tool`', () => { + const shared = NAMESPACE_UNIQUE_TYPES.filter((t) => (BARE_NAME_ONE_HOLDER_TYPES as readonly string[]).includes(t)); + expect(shared.filter((t) => t !== 'tool')).toEqual([]); + }); + + it('judges every named namespace but the install gate\'s shareable ones (`RESERVED_NAMESPACES` and `sys`)', () => { + for (const ns of [...RESERVED_NAMESPACES, 'sys']) expect(isNamespaceJudged(ns), ns).toBe(false); + expect(isNamespaceJudged('')).toBe(false); + expect(isNamespaceJudged(undefined)).toBe(false); + expect(isNamespaceJudged('crm')).toBe(true); + }); + + it('reads each collection by its manifest key, nested plugins one level deep, and the app rows the engine registers', () => { + const declared = declaredNamespaceUniqueNames({ + id: 'com.acme.alpha', + name: 'alpha', + ...Object.fromEntries(NAMESPACE_UNIQUE_TYPES.map((t) => [COLLECTION[t], [{ name: `${t}_one` }]])), + // an item named by `id` alone, as the engine's seam names it + pages: [{ id: 'by_id' }, { label: 'nameless' }], + plugins: [ + // a nested plugin's `apps` is NOT registered by the nested seam; its own app row is + { name: 'inner', navigation: [], apps: [{ name: 'nested_apps_entry' }], tools: [{ name: 'inner_tool' }] }, + ], + }); + const spelt = declared.map((d) => `${d.type}/${d.name}`); + expect(spelt).toEqual([ + 'sharing_rule/sharing_rule_one', 'queue/queue_one', 'assignment_rule/assignment_rule_one', + 'hook/hook_one', 'job/job_one', 'app/app_one', 'page/by_id', 'dashboard/dashboard_one', + 'report/report_one', 'book/book_one', 'analytics_cube/analytics_cube_one', 'tool/tool_one', + 'app/inner', 'tool/inner_tool', + ]); + expect(spelt).not.toContain('app/nested_apps_entry'); + }); + + it('the manifest itself is an app only when it registers as one (a name, a navigation, no `apps`)', () => { + expect(declaredNamespaceUniqueNames({ id: 'x', name: 'shell', navigation: [] })).toEqual([{ type: 'app', name: 'shell' }]); + expect(declaredNamespaceUniqueNames({ id: 'x', name: 'shell', navigation: [], apps: [{ name: 'a' }] })) + .toEqual([{ type: 'app', name: 'a' }]); + expect(declaredNamespaceUniqueNames({ id: 'x', name: 'shell' })).toEqual([]); + }); + + it('the predicate names EVERY other holder of the namespace, once per (type, name)', () => { + const incoming = namespacePackageOf(pkg('com.acme.gamma', 'crm', { page: ['home', 'home'] }))!; + const conflicts = namespaceNameConflicts(incoming, [ + namespacePackageOf(pkg('com.acme.alpha', 'crm', { page: ['home'] }))!, + namespacePackageOf(pkg('com.acme.beta', 'crm', { page: ['home'] }))!, + namespacePackageOf(pkg('com.other.delta', 'hr', { page: ['home'] }))!, + ]); + expect(conflicts).toEqual([ + { namespace: 'crm', type: 'page', name: 'home', incomingPackageId: 'com.acme.gamma', existingPackageIds: ['com.acme.alpha', 'com.acme.beta'] }, + ]); + const message = namespaceNameConflictMessage(conflicts); + for (const id of ['com.acme.gamma', 'com.acme.alpha', 'com.acme.beta']) expect(message).toContain(`"${id}"`); + expect(message).not.toContain('com.other.delta'); + expect(message).toContain('the page "home" in namespace "crm"'); + }); +}); + +describe.each(NAMESPACE_UNIQUE_TYPES)('%s — a second package of one namespace declaring a held name is refused at install', (type) => { + it('refuses the second co-owner, naming both holders, ahead of every mutation', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { [type]: ['shared_item', 'alpha_only'] }), scope)).toBeUndefined(); + + const err = install(registry, pkg('com.acme.beta', 'crm', { [type]: ['beta_only', 'shared_item'] }), scope); + expect(err).toBeInstanceOf(NamespaceNameConflictError); + expect([err?.code, err?.status, err?.httpStatus]).toEqual(['NAMESPACE_CONFLICT', 422, 422]); + expect(err?.conflicts).toEqual([ + { namespace: 'crm', type, name: 'shared_item', incomingPackageId: 'com.acme.beta', existingPackageIds: ['com.acme.alpha'] }, + ]); + expect(err?.message).toContain('package "com.acme.beta"'); + expect(err?.message).toContain('package "com.acme.alpha"'); + expect(err?.message).toContain('"shared_item"'); + // Ahead of every mutation: no record, no namespace ownership. + expect(registry.getPackage('com.acme.beta')).toBeUndefined(); + expect(registry.getNamespaceOwners('crm')).toEqual(['com.acme.alpha']); + }); + + it('CONTROL — the same name in two DIFFERENT namespaces installs (phase 1\'s business, unchanged)', () => { + const registry = fresh(); + expect(install(registry, pkg('com.acme.alpha', 'crm', { [type]: ['shared_item'] }))).toBeUndefined(); + expect(install(registry, pkg('com.other.hr', 'hr', { [type]: ['shared_item'] }))).toBeUndefined(); + expect(registry.getPackage('com.other.hr')).toBeDefined(); + }); + + it('CONTROL — the same package re-registering its own item installs', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { [type]: ['shared_item'] }), scope)).toBeUndefined(); + expect(install(registry, pkg('com.acme.alpha', 'crm', { [type]: ['shared_item'] }), scope)).toBeUndefined(); + expect(install(registry, pkg('com.acme.alpha', 'crm', { [type]: ['shared_item'] }))).toBeUndefined(); + }); +}); + +describe('what the rule leaves alone', () => { + it('CONTROL — the same name across two different types in one namespace installs', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home'], tool: ['lookup'] }), scope)).toBeUndefined(); + expect(install(registry, pkg('com.acme.beta', 'crm', { dashboard: ['home'], report: ['lookup'] }), scope)).toBeUndefined(); + }); + + it('CONTROL — co-owners with distinct names both install, and the bare name keeps serving its one holder (reading (b))', async () => { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + try { + const svc = kernel.getService('manifest') as { register(m: unknown): void | Promise }; + await svc.register({ + packages: [ + { manifest: pkg('com.acme.alpha', 'crm', { page: ['alpha_home'] }) }, + { manifest: pkg('com.acme.beta', 'crm', { page: ['beta_home'] }) }, + ], + }); + const ql = kernel.getService('objectql'); + expect((ql.registry.getItem('page', 'alpha_home') as { label?: string } | undefined)?.label).toBe('alpha page'); + expect((ql.registry.getItem('page', 'beta_home') as { label?: string } | undefined)?.label).toBe('beta page'); + } finally { + await kernel.shutdown(); + } + }); + + it('CONTROL — a package declaring one name twice in itself is one holder, never refused here', () => { + const registry = fresh(); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home', 'home'] }))).toBeUndefined(); + }); + + it('CONTROL — a shareable platform namespace is not judged (the install gate lets packages share it)', () => { + const registry = fresh(); + for (const ns of ['sys', ...RESERVED_NAMESPACES]) { + expect(install(registry, pkg(`com.platform.${ns}.one`, ns, { page: ['home'] }))).toBeUndefined(); + expect(install(registry, pkg(`com.platform.${ns}.two`, ns, { page: ['home'] }))).toBeUndefined(); + } + }); + + it('CONTROL — a package with no namespace holds nothing to share', () => { + const registry = fresh(); + expect(install(registry, pkg('com.acme.alpha', undefined, { page: ['home'] }))).toBeUndefined(); + expect(install(registry, pkg('com.acme.beta', undefined, { page: ['home'] }))).toBeUndefined(); + }); + + it('CONTROL — the environment catalog is never a holder', () => { + const registry = fresh(); + registry.registerItem('page', { name: 'home', label: 'environment page' }, 'name'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home'] }))).toBeUndefined(); + }); + + it('CONTROL — a type outside the twelve is not judged here (a view, a flow, a permission set)', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + const extra = (tag: string) => ({ views: [{ name: 'shared_view', label: tag }], flows: [{ name: 'shared_flow', label: tag }] }); + expect(install(registry, pkg('com.acme.alpha', 'crm', {}, extra('alpha')), scope)).toBeUndefined(); + expect(install(registry, pkg('com.acme.beta', 'crm', {}, extra('beta')), scope)).toBeUndefined(); + }); + + it('an uninstall takes its names with it: the next package of the namespace may hold them', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home'] }), scope)).toBeUndefined(); + registry.uninstallPackage('com.acme.alpha'); + expect(install(registry, pkg('com.acme.beta', 'crm', { page: ['home'] }), scope)).toBeUndefined(); + }); +}); + +describe('the refusal', () => { + it('lists every conflicting name in one refusal, in declaration order', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home'], queue: ['triage'], hook: ['on_save'] }), scope)).toBeUndefined(); + const err = install(registry, pkg('com.acme.beta', 'crm', { queue: ['triage'], hook: ['on_save'], page: ['home'] }), scope); + expect(err?.code).toBe('NAMESPACE_CONFLICT'); + expect(err?.conflicts?.map((c) => `${c.type}/${c.name}`)).toEqual(['queue/triage', 'hook/on_save', 'page/home']); + expect(err?.message).toContain('3 names'); + }); + + it('a co-owner by a declared dependency is judged as an artifact co-owner is (ADR-0141 D5)', () => { + const registry = fresh(); + expect(install(registry, pkg('com.acme.crm', 'crm', { app: ['crm_home'] }))).toBeUndefined(); + const err = install(registry, pkg('com.acme.crm.billing', 'crm', { app: ['crm_home'] }, { dependencies: { 'com.acme.crm': '^1.0.0' } })); + expect([err?.code, err?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + expect(err?.conflicts?.[0]?.existingPackageIds).toEqual(['com.acme.crm']); + }); + + it('`OS_METADATA_COLLISION=warn` does not downgrade it: two strangers the namespace gate let share `crm` are refused', () => { + const registry = fresh('warn'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { report: ['pipeline'] }))).toBeUndefined(); + const err = install(registry, pkg('com.other.beta', 'crm', { report: ['pipeline'] })); + expect(err).toBeInstanceOf(NamespaceNameConflictError); + expect(registry.getPackage('com.other.beta')).toBeUndefined(); + }); + + it('runs after the ADR-0130 D3 object check: an install refused by both answers the object refusal', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + const object = { name: 'crm_account', label: 'Account', fields: { name: { name: 'name', label: 'Name', type: 'text' } } }; + registry.registerObject({ ...object } as never, 'com.acme.alpha', 'crm', 'own'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { page: ['home'] }, { objects: [object] }), scope)).toBeUndefined(); + const err = install(registry, pkg('com.acme.beta', 'crm', { page: ['home'] }, { objects: [object] }), scope); + expect(err?.code).toBe('DUPLICATE_ARTIFACT_OBJECT_NAME'); + }); + + it('after the cold boot\'s seal, a same-namespace tool is refused by THIS rule (it runs ahead of the bare-name rule)', () => { + const registry = fresh(); + const scope = scopeOf('com.acme.alpha', 'com.acme.beta'); + expect(install(registry, pkg('com.acme.alpha', 'crm', { tool: ['lookup'] }), scope)).toBeUndefined(); + registry.sealBareNameHolders(); + const err = install(registry, pkg('com.acme.beta', 'crm', { tool: ['lookup'] }), scope); + expect(err).toBeInstanceOf(NamespaceNameConflictError); + expect(err?.conflicts?.[0]).toMatchObject({ type: 'tool', name: 'lookup', existingPackageIds: ['com.acme.alpha'] }); + }); + + it('on the real load path, an artifact whose co-owners share a name is refused at install, per family', async () => { + // One spec-valid body per family (the load path parses each package entry). + const account = { name: 'crm_account', label: 'Account', fields: { name: { name: 'name', label: 'Name', type: 'text' } } }; + const bodies = { + sharing_rule: { sharingRules: [{ name: 'shared_item', label: 'x', type: 'criteria', object: 'crm_account', sharedWith: { type: 'team', value: 'sales' }, condition: 'true', accessLevel: 'read' }] }, + hook: { hooks: [{ name: 'shared_item', label: 'x', object: 'crm_account', events: ['beforeInsert'], body: { language: 'js', source: 'return;' } }] }, + page: { pages: [{ name: 'shared_item', label: 'x', type: 'app', regions: [] }] }, + tool: { tools: [{ name: 'shared_item', label: 'x', description: 'A tool', parameters: {} }] }, + } as const; + for (const type of ['sharing_rule', 'hook', 'page', 'tool'] as const) { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + try { + const svc = kernel.getService('manifest') as { register(m: unknown): void | Promise }; + let err: Refusal | undefined; + try { + await svc.register({ + packages: [ + { manifest: pkg('com.acme.alpha', 'crm', {}, { objects: [account], ...bodies[type] }) }, + { manifest: pkg('com.acme.beta', 'crm', {}, { ...bodies[type] }) }, + ], + }); + } catch (e) { + err = e as Refusal; + } + expect([err?.code, err?.status], `${type}: ${err?.message}`).toEqual(['NAMESPACE_CONFLICT', 422]); + expect(err?.message).toContain('com.acme.alpha'); + expect(err?.message).toContain('com.acme.beta'); + expect(kernel.getService('objectql').registry.getPackage('com.acme.beta'), type).toBeUndefined(); + } finally { + await kernel.shutdown(); + } + } + }); +}); From 156068259aff25648802f394c9ba9a585256acc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 21:43:21 +0000 Subject: [PATCH 3/5] chore: changeset for the namespace name refusal Claude-Session: https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs Co-authored-by: Claude --- .changeset/31670-namespace-co-owner-names.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/31670-namespace-co-owner-names.md diff --git a/.changeset/31670-namespace-co-owner-names.md b/.changeset/31670-namespace-co-owner-names.md new file mode 100644 index 00000000000..8b1b21fab14 --- /dev/null +++ b/.changeset/31670-namespace-co-owner-names.md @@ -0,0 +1,20 @@ +--- +'@objectstack/objectql': minor +'@objectstack/cli': minor +--- + +feat(objectql)!: inside one namespace, a sharing rule, queue, assignment rule, hook, job, app, page, dashboard, report, book, analytics cube or tool has one package holder — a package declaring one under a name another package of its namespace already holds is refused at install, `os validate` and `os build`, naming every holder. + +Clause-②: no (narrowing) — the package door (`SchemaRegistry.installPackage`, every install, boot included) refuses a package registration it accepted before: one whose item of these twelve types bears a name another installed package of the same namespace holds; `os validate` and `os build` refuse the artifact that would carry it. Nothing is widened. +Metadata-protocol: narrowed +Skills-docs: none — `skills/**` does not teach that two packages of one namespace may share one of these names; the rule ships in the refusal text and in ADR-0150 D2 (child N), which already records it. + + + +**BREAKING** accept-set narrowing at the package registration door, for twelve types: sharing rule, queue, assignment rule, hook, job, app, page, dashboard, report, book, analytics cube and tool — ADR-0150 D2, ruled (record 6724570466), child N of its execution plan. Measured first-party: 0 such names on a booted showcase (29 packages, 60 declared names) and in the four example apps. + +- **Why.** ADR-0150 addresses behavioural metadata by namespace and name (a URL segment, the AI face's flat name), and several packages may share one namespace (one artifact's packages, a package and the packages that declare it). The address `crm/home` names one item only if no two packages of `crm` both hold a page `home`. ADR-0130 D3 already refuses that for objects; this extends it to the twelve bucket 2/3 types phase 1's one-holder rule does not cover. +- **Before.** Two packages of one namespace could each ship, say, a page `home`; every bare read served the first-registered one, silently. +- **Now.** The second package's install is refused ahead of every mutation, so it leaves no record behind. The envelope is the namespace gate's: `code: 'NAMESPACE_CONFLICT'`, `status: 422`, every conflicting name in one refusal, every holder named, `conflicts[]` structured. `os validate` and `os build` give the same sentence for an artifact that carries the clash, and `os build` writes no artifact. A deployment whose installed packages of one namespace already share such a name no longer boots: the boot names both holders. +- **Who moves.** An author whose artifact ships two packages of one namespace holding one such name, or whose package declares a name another installed package of its namespace already holds. **The one-line fix: rename the item in one of the two packages.** A reference that named the old name must name the new one; nothing rewrites stored references. +- **Unchanged.** The same name in two different namespaces. The same name across two different types. The same package registering its own item again, or declaring one name twice in itself. A package with no namespace, and the shareable platform namespaces (`base`, `system`, `sys`) the namespace gate lets packages share. An environment item under a package's name (the ADR-0005 overlay). Every type outside the twelve, and phase 1's one-holder rule. `OS_METADATA_COLLISION=warn` does not downgrade the refusal. From cfcaab58d1b6855b3ac6a7a1e216bcdb3bf58a90 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 21:54:45 +0000 Subject: [PATCH 4/5] chore(adr-anchors): anchor the namespace name predicate to ADR-0150 D2 Claude-Session: https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs Co-authored-by: Claude --- ...kages__objectql__src__namespace-co-owner-names.ts.json | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 scripts/adr-anchors/packages__objectql__src__namespace-co-owner-names.ts.json diff --git a/scripts/adr-anchors/packages__objectql__src__namespace-co-owner-names.ts.json b/scripts/adr-anchors/packages__objectql__src__namespace-co-owner-names.ts.json new file mode 100644 index 00000000000..c5b0eff6530 --- /dev/null +++ b/scripts/adr-anchors/packages__objectql__src__namespace-co-owner-names.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/objectql/src/namespace-co-owner-names.ts", + "adrs": [ + "ADR-0150", + "ADR-0130" + ], + "invariant": "ADR-0150 D2 (ruled): behavioural metadata is addressed by (namespace, name) while its identity is (package id, name), and several packages may share one namespace (ADR-0130 D1 artifact co-owners, ADR-0141 D5 dependency co-owners), so the address NAMESPACE/NAME names one item only if no two packages of the namespace hold it. This module is the ONE predicate for the twelve bucket 2/3 types phase 1's one-holder list does not cover (sharing_rule, queue, assignment_rule, hook, job, app, page, dashboard, report, book, analytics_cube, tool): SchemaRegistry.installPackage asks it right after the ADR-0130 D3 object check, ahead of every mutation and at every install, and os validate / os build ask it over an artifact's packages in the boot's install order, printing the same sentence. Every holder is named. ⛔ Never judge a package with no namespace, a shareable platform namespace (base, system, sys: the namespace gate's exemption), the environment catalog, or the same package again; never a type outside the twelve (a wider narrowing is the maintainer's); never package-scoped resolution (ADR-0150 child R); never let OS_METADATA_COLLISION=warn downgrade it; never a second copy of the predicate at either door." +} From 97b94ed710055aa56eb2b6db2b1feaa02f381383 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 22:15:06 +0000 Subject: [PATCH 5/5] test(objectql): name the namespace rule's queue type literal in the injected-column ledger Claude-Session: https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs Co-authored-by: Claude --- .../objectql/src/federated-injected-column-readers.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 684e8a11dfa..34a51415648 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -439,6 +439,10 @@ const READERS: Record = { why: 'the name the injection writes the ADR-0142 D3 ownership-queue column under', }, 'assignment-rules.ts# :: owner_id': { disposition: 'not-a-read', why: VOCABULARY }, + 'namespace-co-owner-names.ts# :: queue': { + disposition: 'not-a-read', + why: 'names the `queue` metadata TYPE in the namespace name rule\'s type list (ADR-0150 D2); it reads no row and no column', + }, 'assignment-rules.ts# :: queue': { disposition: 'not-a-read', why: VOCABULARY }, 'assignment-rules.ts#carriesQueueColumn :: resolveInjectedColumnProvenance()': { disposition: 'excludes',