Skip to content

Commit d655caf

Browse files
feat(objectql)!: refuse a (type, name) held twice inside one namespace (#31717)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Ff4UJdxHJzwSQG7VEko8ou)_ Fixes #31670 ADR-0150 child N (D2, ruled 6724570466): inside one namespace, a `(type, name)` of the twelve bucket 2/3 types phase 1 does not cover has one package holder. Claim 6727391505 (`domain:server#1`, card-thread session_01ADHkmQv69sQL5nfT8xuPWs). Clause-②: no (narrowing) — measured on head `97b94ed7` and, for base, by the ablations that remove the one added call at each door (the predicate module is otherwise unread): the package door (`SchemaRegistry.installPackage`, every install, boot included) refuses a package registration it accepted on base, one whose item of these twelve types bears a name another installed package of its namespace holds (ablated = base: the second co-owner installs; head: `NAMESPACE_CONFLICT` 422); `os validate` / `os build` refuse the artifact that carries it (ablated = base: `os validate --json` exits 0; head: exits 1). Riding along at those two commands, because the walk reads `packages[]` through `@objectstack/core`'s `resolveArtifactPackageOrder` (the boot's own resolver): an artifact declaring one package id twice (`DUPLICATE_ARTIFACT_PACKAGE`, 422) and an artifact whose packages' dependencies form a cycle (`[Kernel] Circular dependency detected`, no code) now exit 1 through the commands' catch-all instead of exiting 0; neither artifact ever booted, so the two doors now agree with the boot on them. 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, which already records it. No governed surface is touched. This is a narrowing, so the review of record runs at CONTRACT_REVIEW_TIER. ## 维护者速读 - 改了什么:同一个命名空间里的几个包(同一制品里的包、或靠依赖共用命名空间的包),它们的共享规则、队列、分配规则、hook、job、应用、页面、仪表盘、报表、文档书、分析立方、工具这 12 类元数据不能重名。安装时拒绝(422 `NAMESPACE_CONFLICT`,点出所有持有包),`os validate` 和 `os build` 用同一句话提前拒绝,`os build` 不产出制品。 - 为什么改:ADR-0150 以后按「命名空间/名字」寻址这些元数据,两个同命名空间的包同名时,地址就指向两个条目、读者只能静默取第一个。ADR-0150 D2 已裁定:同一命名空间内一个名字只有一个包持有,就像对象名早已如此(ADR-0130 D3)。 - 风险与回滚:只收窄接受集,不改已存数据、不迁移。实测第一方 0 处冲突(启动的 showcase 29 个包 60 个名字、4 个示例应用)。已经存在这种冲突的部署升级后会启动失败并点名两个包——这一点作为开放问题交席位裁定(另一选项:像一期规则那样冷启动只告警)。回滚即 revert。 - 先看:`packages/objectql/src/namespace-co-owner-names.ts`(唯一判定)、`registry.ts` 里 `installPackage` 紧跟 D3 对象检查的那一行和 `refuseNamespaceNameConflicts`、`packages/cli/src/utils/namespace-co-owner-names.ts`(按启动安装顺序走制品)。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run src/registry-namespace-co-owner-names.test.ts` —— 预期 56 passed。 - 需要你做的:无,席位落地(收窄,席位按契约档复审)。 ## What changes - **`packages/objectql/src/namespace-co-owner-names.ts`** (new) — the ONE predicate. `NAMESPACE_UNIQUE_TYPES` (the twelve, in ADR-0150's child-N order); `declaredNamespaceUniqueNames` reads the names the engine registers (each collection by `singularToPlural(type)`, nested `plugins[]` one level deep, the manifest-as-app and plugin-as-app rows, `name` else `id`); `namespaceNameConflicts(incoming, sitting)` returns, per `(type, name)` of the incoming package, EVERY other package of its namespace that holds it; `namespaceNameConflictMessage` is the one sentence. Not judged: a package with no namespace, the shareable platform namespaces (`base`, `system`, `sys`, the namespace gate's exemption), the environment catalog, the same package again. - **`packages/objectql/src/registry.ts`** — `installPackage` asks it right after the ADR-0130 D3 object check (`refuseNamespaceNameConflicts`), ahead of every mutation, at every install; the sitting holders are the installed package records of the incoming namespace, so an uninstall takes its names with it and nothing new is stored. New `NamespaceNameConflictError`: `code: 'NAMESPACE_CONFLICT'` (the namespace gate's, as the bare-name rule reuses it; no code minted), `status`/`httpStatus` 422, `conflicts[]`, every holder named. No `collisionPolicy` downgrade. ⛔ Not the #31661 hunks (its `registerItem` comment line and `bare-name-one-holder.ts`) — untouched. - **`packages/objectql/src/index.ts`** — exports the predicate, the sentence and the type list for the CLI (the class stays unexported, as the registry's other refusals). - **`packages/cli/src/utils/namespace-co-owner-names.ts`** (new) — the walk: an artifact's `packages[]` bodies in `resolveArtifactPackageOrder`'s order (the order the boot installs them, the same seam `os validate` already drives for the union stack), each against the bodies before it; every refused body reported, each naming every holder. A stack without `packages[]` is one package and is never refused here. - **`packages/cli/src/commands/validate.ts`** (step 2c-bis) and **`compile.ts`** (step 3a-ter) — the same call right after the parse, beside the view-container refusal and with its faces (`--json` `errors` rows; text bullet list); `os build` writes no artifact. **`test/validate-build-gate-parity.test.ts`** — `findNamespaceNameRefusals` joins the shared-gate roster (forced: the roster is closed, every gate either command calls must be classified). - **`scripts/adr-anchors/packages__objectql__src__namespace-co-owner-names.ts.json`** — anchors the module to ADR-0150 D2 / ADR-0130. - **`.changeset/31670-namespace-co-owner-names.md`** — `@objectstack/objectql` and `@objectstack/cli` `minor`, both declaration lines, BREAKING Why / Before / Now / Who moves / Unchanged with the one-line fix (rename the item in one of the two packages), `adr-0087: not-required (no-migration-prescription)`. Forced test edits: two rows, no existing assertion changed. The parity roster row above, and one row in `packages/objectql/src/federated-injected-column-readers.test.ts`'s closed ledger: `namespace-co-owner-names.ts#<module> :: queue` as `not-a-read` (its scanner matches the `'queue'` literal of the twelve-type list as the ADR-0142 injected `queue` column; it names a metadata type and reads no row, the same disposition as `assignment-rules.ts#<module> :: queue`). ## Why (measured, Step 0 on `5d1382a5`) - **ADR-0130 D3's object check lives at ONE door, not two.** `SchemaRegistry.installPackage` → `refuseCoOwnedObjectNameCollision` (registry.ts). `os validate` (`packages/cli/src/commands/validate.ts`) has no D3 check: `git grep` for `DUPLICATE_ARTIFACT_OBJECT_NAME` / `ArtifactObjectNameConflictError` / `ADR-0130 D3` under `packages/cli/src` and `packages/lint/src` is 0 hits. So this card builds the validate door for its own rule; it does not sit on an existing one there. - **How D3 decides "same namespace": it does not compare namespaces.** It reads `coOwnersOf` — `artifact` (every other package of the same release artifact, whatever its namespace), `dependency` and `sibling` (ADR-0141 D5, only for a non-shareable namespace) — and leaves a stranger to the namespace gate. Objects are global names, so that is enough for D3. For these twelve types two packages of one artifact in two namespaces hold two addresses, so this rule compares `manifest.namespace` itself (and so also covers two strangers the `warn` collision policy lets share a namespace). - **The twelve types' collection keys** (`PLURAL_TO_SINGULAR`, the engine's `METADATA_ARRAY_KEYS`): `sharingRules`, `queues`, `assignmentRules`, `hooks`, `jobs`, `apps` (top level only; plus manifest-as-app and plugin-as-app), `pages`, `dashboards`, `reports`, `books`, `analyticsCubes`, `tools`. The namespace field is the package's `manifest.namespace` for every one of them: no item of these types carries its own. - **First-party census.** Booted showcase (`examples/app-showcase`, `pnpm dev --fresh`, `GET /api/v1/packages`): 29 packages (22 in `sys`, 4 with none), 60 declared names of the twelve types, **0** `(namespace, type, name)` held by two packages — `sys` included, though it is not judged. Example stacks (each `objectstack.config.ts`, `packages[]` resolved as the boot does): app-crm 4 names, app-todo 8, app-multi-package 2 packages in `crm`, 1 name, app-showcase 50 — **0** held twice. `os validate --json` on all four: exit 0, 0 errors. HotCRM is not in this container: **NOT MEASURED** (the card's 0 of 297 is its claim). ## ADR-0150's four readings - **(a) phase-1 one-holder tests stay green**: `registry-bare-name-one-holder*.test.ts` run inside the objectql suite below — green in the suite, and run alone: 4 files (`registry-bare-name-one-holder.test.ts` and its ai/flow/request family files) / **154 passed**. - **(b) bare-name behaviour unchanged for one-holder names**: the CONTROL "co-owners with distinct names both install, and the bare name keeps serving its one holder" (real load path, `getItem('page', NAME)` answers each package's own page), and every per-type CONTROL (two namespaces, two types, the same package again) installs; first-party census 0, so no shipped name changes answer. For an uncovered type's name with two holders inside one namespace, this card's declared narrowing stands in its place. - **(c) no migration**: nothing stored changes shape and nothing is rewritten; the refusal reads the installed package records at install time and keeps no state of its own. - **(d)** `Clause-②: no (narrowing)` above and in the changeset; `Metadata-protocol: narrowed`; the changeset carries `adr-0087: not-required (no-migration-prescription)`. ## How the two checks compose at `installPackage` (with #31661) Order in `installPackage`: namespace gate → ADR-0130 D3 object check → **this rule** → security catalog → default record page → phase 1's bare-name rule. So: - A `tool` held twice **inside one namespace** is refused by this rule at every install; after the cold boot's seal the bare-name rule would refuse it too, but this one runs first, so the refusal is `NamespaceNameConflictError` (both carry `NAMESPACE_CONFLICT` / 422). Pinned: "after the cold boot's seal, a same-namespace tool is refused by THIS rule". - A `tool` held by two packages of **different namespaces** is not this rule's: after #31661 the bare-name rule refuses it after the seal. - One difference at the **cold boot**: a deployment already holding a same-namespace tool clash is refused at boot by this rule, where the bare-name rule alone would only warn. See open question 1. - Measured: #31661's head `30b6c84f` merged onto this branch in a scratch worktree (clean, `registry.ts` auto-merged): this file plus `registry-bare-name-one-holder-ai-family.test.ts` **2 files / 94 passed**. If #31661 lands first, this branch merges it (no overlapping hunk). ## Verification Head `97b94ed7` (merged `origin/main` at `a2d0f737` once, no conflict). Every heavy run under `os-verify-lock`: - New: `packages/objectql/src/registry-namespace-co-owner-names.test.ts` **56 passed**; `packages/cli/src/utils/namespace-co-owner-names.test.ts` + parity **2 files / 63 passed**; `packages/cli/test/validate-namespace-name.test.ts` (spawns `os validate` / `os build`; asserts the row's message EQUAL to the package door's thrown message) **4 passed**. - Suites on the final head: `@objectstack/objectql` **573 files / 11672 passed**; `@objectstack/cli` unit project **406 / 5754 passed** (+ the two new/edited integration files **2 / 38 passed**); `@objectstack/metadata-protocol` **328 passed, 4 skipped / 22595 passed, 26 skipped**; `@objectstack/rest` **395 / 7627 passed, 332 skipped**; `@objectstack/runtime` **563 / 9033 passed, 19 skipped**. Typecheck objectql and cli exit 0. - Dogfood battery (narrowing arm): `97b94ed7` · `os-verify-lock: VERDICT command-exit 0` · Test Files 440 passed, 3 skipped (443) · Tests 3652 passed, 41 skipped (3693) · no failure. - Lint: `eslint packages/objectql --no-inline-config` exit 0; `eslint packages/cli --no-inline-config` exit 0. - Gates: `dispatch-gates --ran` on `97b94ed7`: **84 derived, 84 run, 0 NOT-MEASURED, 0 UNRUN**, every one exit 0. Two first ran exit 3 for a missing prerequisite and were re-run green: `check-plugin-teardown-shape --self-test` (its pinned fixture commit fetched first), `check:dual-build-cjs-loads` (after building the five packages without a `dist/`). <details><summary>Ablations (each committed first, `ablation-replace.mjs`, restored, `git diff HEAD` empty)</summary> 1. Package door — `this.refuseNamespaceNameConflicts(manifest);` replaced by a comment (`ABLATION-31670`) in `registry.ts` → `registry-namespace-co-owner-names.test.ts` **17 of 56 red**: the 12 per-type refusals ("expected undefined to be an instance of NamespaceNameConflictError"), the real-load-path per-family refusal, the multi-name refusal, the dependency co-owner, the `warn`-policy refusal, the after-seal tool. The 39 green are the vocabulary cells and every CONTROL. Restored: blob `3b698a04` == HEAD, `git diff HEAD` 0 bytes. (objectql's tests import `src`, so no dist leg.) 2. `os validate` door — `if (namespaceNameRefusals.length > 0) {` → `< 0` in `validate.ts` → `validate-namespace-name.test.ts` **1 of 4 red**: "os validate --json exits 1 …" (`expected +0 to be 1`): with the branch gone `os validate` exits 0, so no other gate catches the clash. The `os build` cell stayed green (its own call). Restored: blob `f997cced` == HEAD, diff 0 bytes. (`run-dev.js` runs the CLI from `src`.) 3. The walk — `if (conflicts.length > 0) {` → `< 0` in the CLI util → `namespace-co-owner-names.test.ts` **14 of 29 red** (12 per-type rows, the three-holder walk, the dependency-order walk); the 15 CONTROLs green. Restored: blob `fc052169` == HEAD, diff 0 bytes. </details> ## Acceptance notes - **Open question 1 (seat's call): the cold boot.** This rule refuses at every install, the boot included, as ADR-0130 D3's object check does. A deployment whose installed packages of one namespace already share one of these names (measured first-party: 0; HotCRM per the card: 0 of 297) no longer boots after upgrading, and the refusal names both packages. The alternative is phase 1's posture: judge only after `kernel:bootstrapped` seals the registry and warn at the cold boot. Recommendation: keep install-time, because D2 is ruled as an install refusal "on the ADR-0130 D3 object check", and the measured population that would stop booting is 0. - **Open question 2 (seat's call): `sys`.** ADR-0150 D2 names `sys/NAME` as an address too, but this rule does not judge the shareable namespaces (`base`, `system`, `sys`), mirroring the namespace gate's exemption and D3's co-owner map. Measured first-party: the 22 `sys` packages of a booted showcase hold 0 duplicate names, so judging `sys` would refuse nothing here today; cloud's `sys` packages are NOT MEASURED. Recommendation: leave `sys` out in this child; a later child can widen it once cloud's `sys` packages are measured. - **Name** (seat's call, house conventions): `NamespaceNameConflictError`; module `namespace-co-owner-names.ts`; exported `NAMESPACE_UNIQUE_TYPES`, `namespacePackageOf`, `namespaceNameConflicts`, `namespaceNameConflictMessage`. No new error code. - Not judged at either door: the residual (top-level items of a `packages[]` stack no body declares), which the boot registers without an install. `os validate` cannot see packages already installed in a deployment; that half is the package door's alone. - Bounds, stated (contract review N1, N2): the sitting holders are read from the stored package record and the incoming one from the live manifest, so a nested `plugins[]` entry that is a plugin class instance counts on the incoming side only; and on a running registry, an upgraded artifact that moves a covered name from co-owner A to co-owner B is refused when B re-registers before A (A's stale record still holds it), the same disposition ADR-0130 D3's object check has; the cold boot starts empty and is unaffected, and `os validate` accepts that artifact. - Integration tier: `test/validate-namespace-name.test.ts` spawns the CLI, so it falls in the cli `integration` project (declared to CI); it was also run locally above. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmQv69sQL5nfT8xuPWs <!-- signed: domain:server#1 · os-steve · session_01ADHkmPF1skfu2kx89BEXZi --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d7a7193 commit d655caf

13 files changed

Lines changed: 1235 additions & 0 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/objectql': minor
3+
'@objectstack/cli': minor
4+
---
5+
6+
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.
7+
8+
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.
9+
Metadata-protocol: narrowed
10+
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.
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) the refusal removes no key, export or field and changes the shape of no stored body; what an author does about a refused name is pick a different one for one of the two items, which no conversion can choose for them -->
13+
14+
**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.
15+
16+
- **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.
17+
- **Before.** Two packages of one namespace could each ship, say, a page `home`; every bare read served the first-registered one, silently.
18+
- **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.
19+
- **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.
20+
- **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.

‎packages/cli/src/commands/compile.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,9 @@ import type { PermissionSetNameCollisionDiagnostic } from '@objectstack/plugin-s
7373
// [#20393] The boot registrar's divergent view-container `name` refusal — the
7474
// walk `os validate` step 2c runs, over `@objectstack/objectql`'s one judge.
7575
import { findViewContainerNameRefusals } from '../utils/view-container-names.js';
76+
// [ADR-0150 D2, child N] The package door's namespace name refusal — the same
77+
// call `os validate` makes at its step 2c-bis.
78+
import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js';
7679
// A field `picklist` that names no picklist the stack declares — the walk
7780
// `os validate` step 2d runs, over the same judge.
7881
import { judgePicklistReferences, picklistRefusalHeading, printPicklistReferenceNotices } from '../utils/picklist-references.js';
@@ -513,6 +516,28 @@ export default class Compile extends Command {
513516
this.exit(1);
514517
}
515518

519+
// 3a-ter. [ADR-0150 D2, child N] A package of this artifact holding a
520+
// name of the twelve uncovered bucket 2/3 types that another package
521+
// of its namespace holds is REFUSED, naming every holder — the SAME
522+
// call `os validate` makes at its step 2c-bis, so the artifact this
523+
// door writes is one the package door installs. Right after the
524+
// parse and ahead of every artifact write, like 3a, with 3a's faces.
525+
const namespaceNameRefusals = findNamespaceNameRefusals(result.data as Record<string, unknown>);
526+
if (namespaceNameRefusals.length > 0) {
527+
if (flags.json) {
528+
await emitJson({ success: false, errors: namespaceNameRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
529+
this.exit(1);
530+
}
531+
const n = namespaceNameRefusals.length;
532+
console.log('');
533+
printError(`The server would refuse this stack at boot (${n} package${n > 1 ? 's' : ''} holding a name another package of its namespace holds)`);
534+
printBulletList(
535+
namespaceNameRefusals.map((r) => r.message),
536+
{ noun: 'namespace name refusal(s)', remedy: JSON_FULL_LIST_REMEDY },
537+
);
538+
this.exit(1);
539+
}
540+
516541
// 3a-bis. A field `picklist`, or a `picklistExtensions` entry's `extend`,
517542
// that names no picklist the stack declares is REFUSED — the SAME call
518543
// `os validate` makes at its step 2d, so the two doors cannot disagree

‎packages/cli/src/commands/validate.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ import type { PermissionSetNameCollisionDiagnostic } from '@objectstack/plugin-s
7474
// over the parsed stack the way the load path registers it. The verdict is
7575
// `@objectstack/objectql`'s; see the module header.
7676
import { findViewContainerNameRefusals } from '../utils/view-container-names.js';
77+
// [ADR-0150 D2, child N] Inside one namespace, an item of the twelve uncovered
78+
// bucket 2/3 types has one package holder: the package door's predicate and
79+
// sentence, walked over the artifact's packages in boot order.
80+
import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js';
7781
// [ADR-0146 D2, #28410] The override write gate's author-time half: the publish
7882
// door's own judge, walked over the artifact's packages.
7983
import { findOverrideDeclarationRefusals } from '../utils/override-declarations.js';
@@ -505,6 +509,40 @@ export default class Validate extends Command {
505509
this.exit(1);
506510
}
507511

512+
// 2c-bis. [ADR-0150 D2, child N] A package of this artifact declaring a
513+
// sharing rule, queue, assignment rule, hook, job, app, page,
514+
// dashboard, report, book, analytics cube or tool under a name
515+
// another package of its namespace already declares is REFUSED,
516+
// naming every holder — the package door
517+
// (`SchemaRegistry.installPackage`) refuses that install at boot.
518+
//
519+
// One judge: the predicate and the sentence are
520+
// `@objectstack/objectql`'s; the helper owns only the walk (the
521+
// artifact's packages, in the order the boot installs them). Right
522+
// after the parse, beside 2c and for its reason: the runtime's own
523+
// accept set. `os build` makes the same call.
524+
const namespaceNameRefusals = findNamespaceNameRefusals(result.data as Record<string, unknown>);
525+
if (namespaceNameRefusals.length > 0) {
526+
if (flags.json) {
527+
await emitJson({
528+
valid: false,
529+
errors: namespaceNameRefusals,
530+
warnings: warningsSoFar(),
531+
conversions: conversionNotices,
532+
duration: timer.elapsed(),
533+
});
534+
this.exit(1);
535+
}
536+
const n = namespaceNameRefusals.length;
537+
console.log('');
538+
printError(`The server would refuse this stack at boot (${n} package${n > 1 ? 's' : ''} holding a name another package of its namespace holds)`);
539+
printBulletList(
540+
namespaceNameRefusals.map((r) => r.message),
541+
{ noun: 'namespace name refusal(s)', remedy: JSON_FULL_LIST_REMEDY },
542+
);
543+
this.exit(1);
544+
}
545+
508546
// 2d. A field `picklist`, or a `picklistExtensions` entry's `extend`, that
509547
// names no picklist the stack declares is REFUSED, naming the field
510548
// (or the extension) and the list. `FieldSchema` and
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0150 D2, child N] `findNamespaceNameRefusals` — the WALK `os validate`
5+
* and `os build` run the package door's namespace name predicate over.
6+
*
7+
* The predicate and its sentence are `@objectstack/objectql`'s
8+
* (`namespaceNameConflicts`, `namespaceNameConflictMessage`), the pair the
9+
* package door throws the answer of; its own file pins them. What this module
10+
* owns, and what is pinned here, is which packages it hands that predicate and
11+
* in which order — the boot's: an artifact's `packages[]` bodies, in
12+
* dependency order, each against the bodies before it.
13+
*
14+
* Every row's message is asserted EQUAL to the predicate's sentence for the
15+
* same conflicts — never re-spelled.
16+
*/
17+
18+
import { describe, expect, it } from 'vitest';
19+
import {
20+
NAMESPACE_CONFLICT_CODE,
21+
NAMESPACE_UNIQUE_TYPES,
22+
namespaceNameConflictMessage,
23+
type NamespaceUniqueType,
24+
} from '@objectstack/objectql';
25+
import { findNamespaceNameRefusals } from './namespace-co-owner-names.js';
26+
27+
const COLLECTION: Record<NamespaceUniqueType, string> = {
28+
sharing_rule: 'sharingRules',
29+
queue: 'queues',
30+
assignment_rule: 'assignmentRules',
31+
hook: 'hooks',
32+
job: 'jobs',
33+
app: 'apps',
34+
page: 'pages',
35+
dashboard: 'dashboards',
36+
report: 'reports',
37+
book: 'books',
38+
analytics_cube: 'analyticsCubes',
39+
tool: 'tools',
40+
};
41+
42+
/**
43+
* A spec-valid item of each type: the walk reads packages through
44+
* `resolveArtifactPackageOrder`, which parses every entry as the boot does.
45+
*/
46+
const item = (type: NamespaceUniqueType, name: string): Record<string, unknown> => {
47+
switch (type) {
48+
case 'sharing_rule':
49+
return { name, label: name, type: 'criteria', object: 'crm_account', sharedWith: { type: 'team', value: 'sales' }, condition: 'true', accessLevel: 'read' };
50+
case 'assignment_rule':
51+
return { name, label: name, object: 'crm_account', entries: [{ name: 'e1', assignTo: { type: 'queue', value: 'triage' } }] };
52+
case 'hook':
53+
return { name, label: name, object: 'crm_account', events: ['beforeInsert'], body: { language: 'js', source: 'return;' } };
54+
case 'job':
55+
return { name, label: name, schedule: { type: 'cron', expression: '0 * * * *' }, handler: 'noop' };
56+
case 'page':
57+
return { name, label: name, type: 'app', regions: [] };
58+
case 'dashboard':
59+
return { name, label: name, widgets: [] };
60+
case 'report':
61+
return { name, label: name, dataset: 'ds', values: ['total'] };
62+
case 'book':
63+
return { name, label: name, groups: [] };
64+
case 'analytics_cube':
65+
return { name, title: name, sql: 'select 1', measures: {}, dimensions: {} };
66+
case 'tool':
67+
return { name, label: name, description: 'A tool', parameters: {} };
68+
default:
69+
return { name, label: name };
70+
}
71+
};
72+
73+
const body = (id: string, ns: string | undefined, decl: Partial<Record<NamespaceUniqueType, string[]>> = {}, extra: Record<string, unknown> = {}) => {
74+
const out: Record<string, unknown> = { id, name: id.split('.').pop(), version: '1.0.0', type: 'app', ...(ns ? { namespace: ns } : {}), ...extra };
75+
for (const [type, names] of Object.entries(decl) as Array<[NamespaceUniqueType, string[]]>) {
76+
out[COLLECTION[type]] = names.map((name) => item(type, name));
77+
}
78+
return out;
79+
};
80+
81+
const artifact = (...bodies: Array<Record<string, unknown>>) => ({ packages: bodies.map((manifest) => ({ manifest })) });
82+
83+
describe.each(NAMESPACE_UNIQUE_TYPES)('%s — os validate refuses an artifact whose packages share a name inside one namespace', (type) => {
84+
it('one row for the second package, naming both holders, in the package door\'s words', () => {
85+
const rows = findNamespaceNameRefusals(artifact(
86+
body('com.acme.alpha', 'crm', { [type]: ['shared_item'] }),
87+
body('com.acme.beta', 'crm', { [type]: ['shared_item', 'beta_only'] }),
88+
));
89+
expect(rows).toHaveLength(1);
90+
const [row] = rows;
91+
expect([row.packageId, row.code, row.httpStatus]).toEqual(['com.acme.beta', NAMESPACE_CONFLICT_CODE, 422]);
92+
expect(row.conflicts).toEqual([
93+
{ namespace: 'crm', type, name: 'shared_item', incomingPackageId: 'com.acme.beta', existingPackageIds: ['com.acme.alpha'] },
94+
]);
95+
expect(row.message).toBe(namespaceNameConflictMessage(row.conflicts));
96+
expect(row.message).toContain('"com.acme.alpha"');
97+
expect(row.message).toContain('"com.acme.beta"');
98+
});
99+
100+
it('CONTROL — the same name in two different namespaces is not refused', () => {
101+
expect(findNamespaceNameRefusals(artifact(
102+
body('com.acme.alpha', 'crm', { [type]: ['shared_item'] }),
103+
body('com.other.hr', 'hr', { [type]: ['shared_item'] }),
104+
))).toEqual([]);
105+
});
106+
});
107+
108+
describe('the walk', () => {
109+
it('a stack with no `packages[]` is one package: never refused here', () => {
110+
expect(findNamespaceNameRefusals({
111+
manifest: { id: 'com.acme.alpha', name: 'alpha', version: '1.0.0', type: 'app', namespace: 'crm' },
112+
pages: [item('page', 'home'), item('page', 'home')],
113+
})).toEqual([]);
114+
});
115+
116+
it('CONTROL — the same name across two types, and one package declaring a name twice, are not refused', () => {
117+
expect(findNamespaceNameRefusals(artifact(
118+
body('com.acme.alpha', 'crm', { page: ['home', 'home'] }),
119+
body('com.acme.beta', 'crm', { dashboard: ['home'] }),
120+
))).toEqual([]);
121+
});
122+
123+
it('CONTROL — a shareable platform namespace is not judged', () => {
124+
expect(findNamespaceNameRefusals(artifact(
125+
body('com.platform.one', 'sys', { page: ['home'] }),
126+
body('com.platform.two', 'sys', { page: ['home'] }),
127+
))).toEqual([]);
128+
});
129+
130+
it('every refused package is reported, and a refused one still counts as a holder for the packages after it', () => {
131+
const rows = findNamespaceNameRefusals(artifact(
132+
body('com.acme.alpha', 'crm', { report: ['pipeline'] }),
133+
body('com.acme.beta', 'crm', { report: ['pipeline'] }),
134+
body('com.acme.gamma', 'crm', { report: ['pipeline'] }),
135+
));
136+
expect(rows.map((r) => [r.packageId, r.conflicts[0].existingPackageIds])).toEqual([
137+
['com.acme.beta', ['com.acme.alpha']],
138+
['com.acme.gamma', ['com.acme.alpha', 'com.acme.beta']],
139+
]);
140+
});
141+
142+
it('walks in the boot\'s dependency order, not the array\'s: the dependent is the one refused', () => {
143+
const rows = findNamespaceNameRefusals(artifact(
144+
body('com.acme.billing', 'crm', { queue: ['triage'] }, { dependencies: { 'com.acme.core': '^1.0.0' } }),
145+
body('com.acme.core', 'crm', { queue: ['triage'] }),
146+
));
147+
expect(rows.map((r) => [r.packageId, r.conflicts[0].existingPackageIds])).toEqual([
148+
['com.acme.billing', ['com.acme.core']],
149+
]);
150+
});
151+
});
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0150 D2, child N] `os validate`'s and `os build`'s half of the package
5+
* door's namespace name refusal: inside one namespace, an item of the twelve
6+
* uncovered bucket 2/3 types (sharing rule, queue, assignment rule, hook, job,
7+
* app, page, dashboard, report, book, analytics cube, tool) has one package
8+
* holder.
9+
*
10+
* ## One judge, not a second rule
11+
*
12+
* The predicate and its sentence are `@objectstack/objectql`'s
13+
* (`namespaceNameConflicts`, `namespaceNameConflictMessage`) — the SAME pair
14+
* `SchemaRegistry.installPackage` throws the answer of. ⛔ Not an
15+
* `@objectstack/lint` rule and not a re-spelling of the check: what this module
16+
* owns is the WALK — which packages the boot installs, in which order.
17+
*
18+
* ## The walk is the boot path's
19+
*
20+
* The boot installs an artifact's `packages[]` bodies one after another, in
21+
* `resolveArtifactPackageOrder`'s dependency order (`@objectstack/core`, the
22+
* one reader of `packages[]`), and asks the predicate about each against the
23+
* packages installed before it. This walk does the same: each body, in that
24+
* order, against the bodies before it. A stack with no `packages[]` is one
25+
* package, which never holds a name beside itself, so it is never refused
26+
* here.
27+
*
28+
* Unlike the boot, which stops at the first refusal, every refused body is
29+
* reported, and a refused body still counts as a holder for the bodies after
30+
* it: the artifact declares it, and the author has to hear about every holder
31+
* (red line 2: ambiguity is reported, never guessed).
32+
*
33+
* ⚠️ Bounds, stated rather than hidden: the packages a deployment already has
34+
* installed are not visible here (that half is the package door's alone), and
35+
* the residual — top-level items no body declares, registered under the
36+
* stack's own id without an install — is not judged at either door.
37+
*/
38+
39+
import { resolveArtifactPackageOrder } from '@objectstack/core';
40+
import {
41+
NAMESPACE_CONFLICT_CODE,
42+
namespaceNameConflictMessage,
43+
namespaceNameConflicts,
44+
namespacePackageOf,
45+
type NamespaceNameConflict,
46+
type NamespacePackage,
47+
} from '@objectstack/objectql';
48+
49+
/** One refused package, located. `message` is the package door's, verbatim. */
50+
export interface NamespaceNameRefusalRow {
51+
/** The refused package's id, as the registry installs it. */
52+
packageId: string;
53+
/** The ADR-0112 code the package door throws with. */
54+
code: string;
55+
/** The HTTP status the package door throws with. */
56+
httpStatus: number;
57+
/** The refusal, in the package door's own words. */
58+
message: string;
59+
/** Every `(type, name)` refused, each naming every holder. */
60+
conflicts: NamespaceNameConflict[];
61+
}
62+
63+
/**
64+
* Every package of this stack's artifact that the package door would refuse
65+
* for a name another package of its namespace holds, in the order the boot
66+
* installs them. `[]` for a stack the door accepts on this axis.
67+
*/
68+
export function findNamespaceNameRefusals(parsed: Record<string, unknown>): NamespaceNameRefusalRow[] {
69+
if (parsed.packages === undefined) return [];
70+
const installed: NamespacePackage[] = [];
71+
const rows: NamespaceNameRefusalRow[] = [];
72+
for (const body of resolveArtifactPackageOrder(parsed)) {
73+
const incoming = namespacePackageOf(body);
74+
if (incoming === undefined) continue;
75+
const conflicts = namespaceNameConflicts(incoming, installed);
76+
if (conflicts.length > 0) {
77+
rows.push({
78+
packageId: incoming.packageId,
79+
code: NAMESPACE_CONFLICT_CODE,
80+
httpStatus: 422,
81+
message: namespaceNameConflictMessage(conflicts),
82+
conflicts,
83+
});
84+
}
85+
installed.push(incoming);
86+
}
87+
return rows;
88+
}

0 commit comments

Comments
 (0)