Skip to content

Commit 5b2ec82

Browse files
feat(spec)!: strict defineStack judges a packages[] stack's namespace prefixes per body and its top level by the residual rule (#33122)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoWK5rFW1SUGSkDw9iatZE4f)_ Fixes #33069 Clause-②: yes (narrowing) — one face widens and one narrows. Widened: a stack carrying `packages[]` whose top level repeats objects that package bodies of different namespaces declare (an additive artifact, such as `resolveArtifactCollections` output) is accepted by strict `defineStack`, where it was refused. Narrowed: a `packages[]` body whose object its own body's namespace does not prefix is refused, where it was accepted when the stack's top level held no copy of it or a copy the manifest's namespace prefixes. Metadata-protocol: narrowed Skills-docs: none — the taught rule (every `object.name` carries its own package's `namespace` prefix) is unchanged, and no skill or docs page teaches handing a `packages[]` stack to `defineStack`; what moves is which namespace strict `defineStack` judges each object of such a stack against. ## 维护者速读 - 改了什么:严格模式 `defineStack` 判带 `packages[]` 的栈的命名空间前缀时,按加载路径的登记方式判:每个包体的对象对照该包体自己的命名空间;没有包体声明的顶层对象(残余)才对照栈 manifest 的命名空间。判残余用的是 #33074 已有的同一份 `isResidualTopLevelItem`,没有第二份实现。 - 为什么改:原来把顶层合并后的所有对象都拿去比 manifest 的一个命名空间,多包、多命名空间的组合制品(`resolveArtifactCollections` 的输出)交回 `defineStack` 会被 `STACK_NAMESPACE_PREFIX_INVALID` 误拒;而包体里前缀写错的对象反而没人判。 - 风险与回滚:一放一收(`Clause-②: yes (narrowing)`)。收的一面只影响手搭的或 `strict: false` 构建的包体(经严格 `defineStack` 产出的包体早已按自己的命名空间判过)。实测本仓与 HotCRM 没有产品代码把带 `packages[]` 的栈交给严格 `defineStack`。不带 `packages[]` 的栈判法与报错原文逐字不变。回滚即 revert。 - 先看:`packages/spec/src/stack.zod.ts` 的 `namespacePrefixErrors`(新函数,`validateNamespacePrefix` 改为调用它);`packages/spec/src/stack.test.ts` 新 describe;`packages/runtime/src/artifact-collections.public-reader.test.ts` 新 describe。 - 两分钟验证:`pnpm --filter @objectstack/spec exec vitest run src/stack.test.ts -t "namespace prefixes are judged per body"`,预期 4 条全绿,其中一条是「两个命名空间的组合制品被接受」,一条是「残余对象前缀不对被拒(422 `STACK_NAMESPACE_PREFIX_INVALID`)」。 - 需要你做的:无,席位落地。 ## What changes **`validateNamespacePrefix`** (the strict `defineStack` pass, `packages/spec/src/stack.zod.ts`) now reads its prefix findings from a new `namespacePrefixErrors`, which judges each object against the namespace of the package the load path registers it under: - **No `packages[]`:** unchanged. Every top-level object is judged against `manifest.namespace`, and the finding is `validateObjectNamespacePrefix`'s own sentence, byte for byte. - **`packages[]`** (ADR-0130 D4): each body's objects are judged against that body's own `namespace`, the finding prefixed `Package 'ID' (packages[J].manifest.objects[I]): `. A top-level object that no body declares is the residual, registered under `manifest.id` by the boot's residual rule (`unclaimedTopLevel`, `@objectstack/metadata`), and is judged against `manifest.namespace`, prefixed `Top-level objects[I], which no package body declares, is registered under package 'ID': `. A top-level object a body declares is a copy of that body's object and is judged with the body only. - **Shared reading, not a second one:** which top-level object is residual is `isResidualTopLevelItem(bodies)`, the mirror of `unclaimedTopLevel` that the owner-stamp gate and the single-app judge (#33074) already read. `packages/metadata` is read, not changed. - A package with no `namespace` is not judged (the rule's legacy skip); the namespace/object-name clash half of `validateNamespacePrefix` (ADR-0150 D6) is untouched. Example finding (the residual pin): "Top-level objects[2], which no package body declares, is registered under package 'com.example.svc': Object 'zzz_orphan' is missing the package namespace prefix. Rename it to 'svc_zzz_orphan' (namespace = 'svc')." **ADR-0087.** New semantic entry `define-stack-packages-body-namespace-prefix-refused` (`packages/spec/src/migrations/entries/semantic/18.define-stack-packages-body-namespace-prefix-refused.ts`), no D2 conversion (an object's name is its table and API name, only the author renames it). The changeset registers it. **Changeset.** `.changeset/33069-define-stack-packages-namespace.md`, `@objectstack/spec` minor, both declaration lines, BREAKING banner with Before / Now / Unchanged / Fix. **No error code added**: the refusal is the existing `STACK_NAMESPACE_PREFIX_INVALID` (422). ## Tests New top-level describe in `packages/spec/src/stack.test.ts` ("defineStack — a packages[] stack's namespace prefixes are judged per body, and its top level by the residual rule"), two packages of namespaces `crm` and `svc` composed under `manifest: 'preserve'`: 1. accepts the additive artifact (the reader's shape: both bodies' objects on the top level) under the `svc` manifest, with anti-vacuity (`crm_account` at the top level); 2. refuses a residual top-level object no body's namespace and not the manifest's prefixes: `code` `STACK_NAMESPACE_PREFIX_INVALID`, `status` 422, `issues` exactly the located finding; a residual the manifest's namespace prefixes is accepted; 3. refuses a body object its own body's namespace does not prefix (though another body's and the manifest's would), located at the body; 4. CONTROL: a stack without `packages[]` gives the exact finding and the exact message (header, line, hint) it gave on `main`. New top-level describe in `packages/runtime/src/artifact-collections.public-reader.test.ts`: `defineStack(resolveArtifactCollections(composeStacks([crm app, svc module], { manifest: 'preserve' })))` passes, with anti-vacuity (both objects at the top level, manifest namespace `svc`). Measured on `origin/main` `2c98485d` (which carries #33074; the order's `64551047` is its parent and lacks the shared residual reading) before the fix, with a probe through the real reader: the round trip was refused `STACK_NAMESPACE_PREFIX_INVALID` (`Object 'crm_account' is missing the package namespace prefix … (namespace = 'svc')`); `unclaimedTopLevel` of the same artifact answered an empty residual (every top-level object is claimed by a body, so none is registered from the top level); a body object `crm_stray` in the `svc` body with no top-level copy was accepted. <details><summary>Ablations (fix committed first at `1dbbe63d`, mutated through `scripts/ablation-replace.mjs`, restored to the HEAD blob)</summary> Each mutation landed (anchor 1 → 0, blob `bf975a2fe1a7` → a new blob) and each restore read `blob == HEAD (bf975a2) and git diff HEAD is empty`. | # | Mutation in `stack.zod.ts` | Expected | Observed | |:--|:--|:--|:--| | 1 | the residual filter dropped (every top-level object judged against the manifest, the old reading) | additive pin red, runtime round-trip pin red | spec: 2 failed (additive, and residual, which now also reports `crm_account`); runtime: 1 failed (round trip) | | 2 | body objects not judged | body pin red | 1 failed (body) | | 3 | residual judged never | residual pin red | 1 failed (residual) | | main | `stack.zod.ts` restored to `origin/main` `2c98485d` (blob `f5dc7819`, checked against `git rev-parse origin/main:…`), tests unchanged | additive, residual, body pins red; CONTROL green | spec: 3 failed, control passed (the no-`packages[]` finding and message are byte-identical to `main`); runtime: round trip failed | Both suites resolve `@objectstack/spec` to `src/` (`stack.test.ts` imports `./stack.zod`; `packages/runtime/vitest.config.ts` aliases the package to `src`), so no dist rebuild was owed per leg. </details> ## Acceptance notes - Delta, measured (order step 1). Newly accepted: a `packages[]` stack whose top-level objects are copies of body objects prefixed by their own bodies' namespaces but not by the manifest's (the reader round trip of a multi-namespace suite). Newly refused: a `packages[]` body object its own body's namespace does not prefix, when the stack's top level holds no copy of it, holds a copy the manifest's namespace prefixes, or the manifest declares no namespace. Unchanged: every stack without `packages[]`; a residual top-level object is judged against the manifest's namespace exactly as before, now with a locator in front of the same sentence. A copy of a body object that the manifest's namespace does NOT prefix but its own body's does now passes; a mis-prefixed body object that used to be caught through its top-level copy is still refused, located at the body instead of the top level. - Producers: no first-party production code hands a `packages[]` stack to strict `defineStack`. HotCRM (`4f0ffd8`, read-only) builds each package with strict `defineStack` (all five declare `namespace: 'crm'`) and reads the composed suite through `resolveArtifactCollections` in `test/helpers/composed-stack.ts` without re-judging it. The consumer suites below are the empirical half. - The `defineStack` hint after the findings still reads "Every object.name must be `${manifest.namespace}_${shortName}`"; on a `packages[]` stack the namespace is the body's, which each located finding names. Left as is so the no-`packages[]` message stays byte-identical. - Ruling-surface grep (`ruling|Ruling-ref|maintainer|⛔`): `stack.zod.ts` 68 hits file-wide, none inside the edited region (`validateNamespacePrefix` and the new `namespacePrefixErrors`, ~:2540–2670); `stack.test.ts` 2 hits (~:1846, :1855, the retired `type: page` block), untouched; `artifact-collections.public-reader.test.ts` none. No ruling sits on the edited lines. - ADR-0019 (governed, not edited). Its Status line's "Landed in spec" list is its enforcement log; after this lands it could name that strict `defineStack` judges a `packages[]` suite's namespace prefixes per package body (D4: an app owns a set of namespaces), so a suite whose packages declare different namespaces round-trips through `resolveArtifactCollections`, with this PR and its merge sha. That is the landing seat's card to file, not this PR's. - Serial: no open PR edits `stack.zod.ts` (search of open PRs naming it: 0; the two open spec-touching PRs, #32895 and #33110, list no `stack.zod.ts` in their files). - Contract-review nits (record 6858193093, PASS at `da607a7f`), noted and not pushed for: - N1 · the declaration line lists two before-states of the newly refused body object; a third is missing (the stack manifest declares no namespace). The changeset's Before bullet and the delta note above cover it. - N2 · "its own body's namespace does not prefix" names one arm: `validateObjectNamespacePrefix` also refuses the legacy `__` form, so a body object such as `crm_a__b` is newly refused too. Same rule, code and status. - N3 · pin gaps: N1's third state, N2's arm, a namespace-less body's copy, `packages: []`, and a multi-namespace suite with apps through the reader are not pinned. Pin 2's "refuses" half does not discriminate by verdict (the old rule refuses that stack too). - N4 · `namespacePrefixErrors` re-spells the two-line `entry.manifest` walk the clash half repeats, and labels packages through `singleAppPackageLabel`, a helper named for the other rule. - N5 · on a body finding the hint still reads "Every object.name must be `${manifest.namespace}_${shortName}`" while the body's namespace is the one judged; left so the no-`packages[]` message stays byte-identical (the hint note above). ## Verification Readings at head `da607a7f` (after merging `origin/main` `e997113c`: #33110, #33080, #33078, none on this diff's files) unless named, after `pnpm install --frozen-lockfile` and `pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' --filter @objectstack/cli build`, every heavy command under `scripts/pm/os-verify-lock.sh` (VERDICT command-exit 0 on each unless named), exit codes captured before any pipe: - `pnpm --filter @objectstack/spec check:generated`: all 14 generated artefacts up to date. (At `1dbbe63d` it named one `test-typecheck-debt.json` arrival, a TS2488 on the new body pin's spread; fixed in `6112dbb9`, not ledgered.) - `pnpm --filter @objectstack/spec test`: Test Files 840 passed (840), Tests 26832 passed, 1 todo. `typecheck` (at `6112dbb9`): exit 0. - Consumers of the changed schema door (run by hand; `dispatch-gates` does not derive them), at `6112dbb9`, the merge touching none of their sources: - `@objectstack/metadata` test (the `unclaimedTopLevel` load path): Test Files 76 passed (76), Tests 2204 passed. - `@objectstack/metadata-protocol` test: Test Files 337 passed, 7 skipped (344); Tests 22799 passed, 36 skipped. - `@objectstack/core` test: Test Files 146 passed (146), Tests 3369 passed. - `@objectstack/cli` unit (`vitest run --project unit`): Test Files 414 passed of 416; the other two (`published-subpath-console.pin`, `published-subpath-hook-body.pin`) refused for an unbuilt `packages/cli/dist` (PREREQUISITE, the pins' own guard), and after building the cli they passed at `da607a7f` (2 files, 29 tests). The integration layer is CI's (no spawn entry or integration file in the diff). - `@objectstack/runtime` `artifact-collections.test.ts` + `artifact-collections.public-reader.test.ts`: Test Files 2 passed (2), Tests 26 passed; runtime `typecheck`: exit 0. - Full dogfood battery (`Clause-②` carries a `(narrowing)` arm): `pnpm --filter @objectstack/dogfood test` at `da607a7f`, lock VERDICT command-exit 0, Test Files 460 passed, 3 skipped (463); Tests 3874 passed, 42 skipped (3916); no failure (finished after this PR opened; also in the os-dev report, comment 6857790505). - Derived gates: `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` → 91 families (same list at `6112dbb9` and `da607a7f`), each run with stdin from /dev/null. 85 exited 0 on the first pass; six read built output while a closure build was rewriting it (`check:api-surface`, `check:dual-source-exports`, `check:entry-nameability`, `check:exported-any` exit 3 PREREQUISITE; `check:dts-closure` exit 1 naming two packages mid-build; `check:dual-build-cjs-loads` exit 3) and all six exited 0 when rerun after the build settled. `node scripts/check-plugin-teardown-shape.mjs --self-test` exit 0 after `git fetch origin 621a487 --depth=1`. Reconciliation `--ran` with exit codes: `91 derived famil(ies) accounted for — 91 run, 0 NOT-MEASURED (a DERIVED zero — all 91 recorded an exit code and none of them is 3)`. - CI: not yet run at opening; the contract review (6858193093) read 52 success, 11 skipped, 3 Test Core shards in progress, no failure at 15:59Z. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibxbMr8S6rSezDVowtd)_ <!-- signed: domain:spec#2 · os-tesla · session_01L9qibxbMr8S6rSezDVowtd --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5c005e0 commit 5b2ec82

5 files changed

Lines changed: 224 additions & 10 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': minor
3+
---
4+
5+
feat(spec)!: strict `defineStack` judges a `packages[]` stack's namespace prefixes per package body, and its top level by the residual rule, the way the load path registers its objects (ADR-0028, ADR-0130 D4)
6+
7+
Clause-②: yes (narrowing) — one face widens and one narrows. Widened: a stack carrying `packages[]` whose top level repeats objects that package bodies of different namespaces declare (an additive artifact, such as `resolveArtifactCollections` output) is accepted, where it was refused. Narrowed: a `packages[]` body whose object its own body's namespace does not prefix is refused, where it was accepted when the stack's top level held no copy of it or a copy the manifest's namespace prefixes.
8+
Metadata-protocol: narrowed
9+
10+
<!-- adr-0087: registered define-stack-packages-body-namespace-prefix-refused -->
11+
12+
**BREAKING** accept-set narrowing in strict `defineStack` (`@objectstack/spec`, the root export), for a stack that carries `packages[]`.
13+
14+
- **Before.** Strict `defineStack` judged every top-level object of such a stack against the stack manifest's one `namespace`, and no package body's objects at all. The load path registers each body's objects under that body's own package and namespace, and only the top-level objects no body declares under the manifest id (the residual rule, `unclaimedTopLevel` in `@objectstack/metadata`). So the reader round trip of a suite whose packages declare different namespaces, `defineStack(resolveArtifactCollections(composeStacks(stacks, { manifest: 'preserve' })))`, was refused with `STACK_NAMESPACE_PREFIX_INVALID`, and a body object its own namespace does not prefix passed.
15+
- **Now.** Each body's objects are judged against that body's own `namespace`, the finding located as `Package 'ID' (packages[J].manifest.objects[I]): ` before the rule's sentence. A top-level object that no body declares is judged against `manifest.namespace` (`Top-level objects[I], which no package body declares, is registered under package 'ID': `). A top-level object a body declares is that body's object and is judged with the body only, so the two-namespace round trip is accepted.
16+
- **Unchanged.** A stack without `packages[]` (every authored package): every object is judged against its own `manifest.namespace`, with the same sentence. A package with no `namespace` is not judged, and `defineStack(…, { strict: false })` judges nothing. Every body that came out of its own strict `defineStack` call was already judged this way.
17+
- **Fix.** Rename the object to its own package's prefix (`NAMESPACE_shortName`; the finding names the body and the exact rename), or move it into the package body whose namespace it carries.

‎packages/runtime/src/artifact-collections.public-reader.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,31 @@ describe('resolveArtifactCollections — its output handed back to strict define
145145
expect(() => defineStack(read as never)).not.toThrow();
146146
});
147147
});
148+
149+
describe('resolveArtifactCollections — its output handed back to strict defineStack passes the namespace-prefix rule when the packages declare different namespaces (ADR-0028, ADR-0130 D4)', () => {
150+
// The reader merges every body's objects onto the top level beside
151+
// `packages[]`. Each of those objects is declared by a body, so the load
152+
// path registers it under that body's own namespace, and strict
153+
// `defineStack` judges it there too, not against the artifact's manifest.
154+
const strictPackage = (id: string, type: 'app' | 'module', namespace: string, slug: string) =>
155+
defineStack({
156+
manifest: { id, name: slug, version: '1.0.0', type, namespace },
157+
objects: [{ name: `${namespace}_${slug}`, label: slug, fields: { title: { type: 'text', label: 'Title' } } }],
158+
} as never);
159+
160+
it('accepts the reader\'s output of a preserve composition of two namespaces', () => {
161+
const preserved = composeStacks(
162+
[strictPackage('com.example.crm', 'app', 'crm', 'account'), strictPackage('com.example.svc', 'module', 'svc', 'case')],
163+
{ manifest: 'preserve' },
164+
);
165+
const read = resolveArtifactCollections(preserved) as Raw & { manifest?: { namespace?: string } };
166+
167+
// Anti-vacuity: both bodies' objects at the top level, one of them not
168+
// prefixed by the manifest's namespace.
169+
expect(((read.objects as Array<{ name: string }>) ?? []).map((o) => o.name)).toEqual(['crm_account', 'svc_case']);
170+
expect(read.manifest?.namespace).toBe('svc');
171+
expect(Array.isArray(read.packages)).toBe(true);
172+
173+
expect(() => defineStack(read as never)).not.toThrow();
174+
});
175+
});
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import type { SemanticMigration } from '../../types.js';
4+
5+
// An accept-set narrowing of strict defineStack on a stack that carries
6+
// packages[]: its namespace prefixes are judged the way the load path
7+
// registers its objects, each package body's objects against that body's own
8+
// namespace (ADR-0028 prefix rule, ADR-0130 D4). No D2 conversion: which
9+
// package an object belongs to, and so its name, is the author's call.
10+
export const entry: SemanticMigration = {
11+
id: 'define-stack-packages-body-namespace-prefix-refused',
12+
surface:
13+
'defineStack(stack) (strict, the default) on a stack that carries packages[] whose package body declares '
14+
+ 'a namespace and an object that namespace does not prefix, e.g. a hand-assembled packages[] body, or one '
15+
+ 'built with defineStack(…, { strict: false }), whose object carries another package\'s prefix',
16+
replacement:
17+
'Rename the object to its own package\'s prefix (NAMESPACE_shortName; the finding names the package body '
18+
+ 'and the exact rename), or move it into the package body whose namespace it carries. A top-level object a '
19+
+ 'package body declares (an additive artifact\'s merged copy, such as the output of '
20+
+ 'resolveArtifactCollections from @objectstack/runtime) is judged with that body only and is now accepted '
21+
+ 'when the packages declare different namespaces. A stack without packages[] is judged as before.',
22+
reason:
23+
'The load path registers each packages[] body\'s objects under that body\'s own package and namespace, and '
24+
+ 'a top-level object that no body declares under the stack\'s manifest id (the residual rule, '
25+
+ 'unclaimedTopLevel in @objectstack/metadata). Strict defineStack judged every top-level object against the '
26+
+ 'manifest\'s one namespace instead and never judged a body\'s objects, so it refused the reader round trip '
27+
+ 'of a suite whose packages declare different namespaces, and it accepted a body object its own namespace '
28+
+ 'does not prefix. defineStack now judges each body against its own namespace and the residual against the '
29+
+ 'manifest\'s, and refuses the second shape with STACK_NAMESPACE_PREFIX_INVALID (422). Not convertible: an '
30+
+ 'object\'s name is its table name and its API name, which only the author can rename.',
31+
acceptanceCriteria:
32+
'os validate and os build, and every config or test helper that calls defineStack on a packages[] stack, run '
33+
+ 'without a STACK_NAMESPACE_PREFIX_INVALID finding. Then boot the artifact and confirm each object answers on '
34+
+ '/api/v1/data under its own package.',
35+
};

‎packages/spec/src/stack.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,6 +1813,83 @@ describe('defineStack — a packages[] stack is judged per body, and its top lev
18131813
});
18141814
});
18151815

1816+
describe('defineStack — a packages[] stack\'s namespace prefixes are judged per body, and its top level by the residual rule (ADR-0028, ADR-0130 D4)', () => {
1817+
// The load path registers each body under its own id, its objects under that
1818+
// body's own namespace, and a top-level object that no body declares under
1819+
// the stack's manifest id (`unclaimedTopLevel`, `@objectstack/metadata`).
1820+
// Strict `defineStack` judges a `packages[]` stack's prefixes the same way, so
1821+
// the two packages here declare DIFFERENT namespaces.
1822+
const objectOf = (name: string) => ({ name, label: name, fields: { title: { type: 'text' as const } } });
1823+
const pkg = (id: string, type: 'app' | 'module', namespace: string) =>
1824+
({ id, version: '1.0.0', type, name: id, namespace });
1825+
const sales = () => defineStack({ manifest: pkg('com.example.crm', 'app', 'crm'), objects: [objectOf('crm_account')] });
1826+
const service = () => defineStack({ manifest: pkg('com.example.svc', 'module', 'svc'), objects: [objectOf('svc_case')] });
1827+
/** A suite artifact: two bodies of two namespaces, under the service package's manifest. */
1828+
const suite = () => composeStacks([sales(), service()], { manifest: 'preserve' });
1829+
/** The shape `resolveArtifactCollections` (`@objectstack/runtime`) returns: every body's objects merged onto the top level. */
1830+
const additive = () => ({ ...suite(), objects: [objectOf('crm_account'), objectOf('svc_case')] });
1831+
1832+
type Refusal = { code?: string; status?: number; issues?: readonly string[]; message: string };
1833+
const refusalOf = (stack: unknown): Refusal | null => {
1834+
try {
1835+
defineStack(stack as never);
1836+
return null;
1837+
} catch (e) {
1838+
return e as Refusal;
1839+
}
1840+
};
1841+
1842+
it('accepts an additive artifact whose top level repeats the objects of two bodies of different namespaces: each is judged with its own body', () => {
1843+
const artifact = additive();
1844+
// Anti-vacuity: a top-level object the manifest's namespace does not prefix.
1845+
expect(artifact.manifest?.namespace).toBe('svc');
1846+
expect(artifact.objects.map((o) => o.name)).toContain('crm_account');
1847+
expect(refusalOf(artifact)).toBeNull();
1848+
});
1849+
1850+
it('refuses a top-level object that no body declares when the manifest\'s namespace does not prefix it: the load path registers it under the manifest id', () => {
1851+
const artifact = additive();
1852+
const r = refusalOf({ ...artifact, objects: [...artifact.objects, objectOf('zzz_orphan')] });
1853+
expect(r, 'refused').not.toBeNull();
1854+
expect(r!.code).toBe('STACK_NAMESPACE_PREFIX_INVALID');
1855+
expect(r!.status).toBe(422);
1856+
expect(r!.issues).toEqual([
1857+
"Top-level objects[2], which no package body declares, is registered under package 'com.example.svc': " +
1858+
"Object 'zzz_orphan' is missing the package namespace prefix. Rename it to 'svc_zzz_orphan' (namespace = 'svc').",
1859+
]);
1860+
// …and one the manifest's namespace prefixes is accepted.
1861+
expect(refusalOf({ ...artifact, objects: [...artifact.objects, objectOf('svc_orphan')] })).toBeNull();
1862+
});
1863+
1864+
it('refuses a body object its own body\'s namespace does not prefix, located at the body, though another body\'s namespace or the manifest\'s would', () => {
1865+
const artifact = suite();
1866+
const packages = artifact.packages!.map((entry, j) =>
1867+
(j === 0 ? { ...entry, manifest: { ...entry.manifest, objects: [...((entry.manifest.objects ?? []) as unknown[]), objectOf('svc_stray')] } } : entry));
1868+
const r = refusalOf({ ...artifact, packages });
1869+
expect(r?.code).toBe('STACK_NAMESPACE_PREFIX_INVALID');
1870+
expect(r?.status).toBe(422);
1871+
expect(r?.issues).toEqual([
1872+
"Package 'com.example.crm' (packages[0].manifest.objects[1]): " +
1873+
"Object 'svc_stray' is missing the package namespace prefix. Rename it to 'crm_svc_stray' (namespace = 'crm').",
1874+
]);
1875+
});
1876+
1877+
it('control: a stack without packages[] judges every object against its own namespace, with the rule\'s own sentence unchanged', () => {
1878+
const r = refusalOf({ manifest: pkg('com.example.svc', 'module', 'svc'), objects: [objectOf('svc_case'), objectOf('crm_account')] });
1879+
expect(r?.code).toBe('STACK_NAMESPACE_PREFIX_INVALID');
1880+
expect(r?.status).toBe(422);
1881+
expect(r?.issues).toEqual([
1882+
"Object 'crm_account' is missing the package namespace prefix. Rename it to 'svc_crm_account' (namespace = 'svc').",
1883+
]);
1884+
expect(r?.message).toBe(
1885+
'defineStack namespace-prefix validation failed (1 issue):\n\n' +
1886+
" ✗ Object 'crm_account' is missing the package namespace prefix. Rename it to 'svc_crm_account' (namespace = 'svc')." +
1887+
'\n\nEvery object.name must be `${manifest.namespace}_${shortName}`. This is the only supported writing style — ' +
1888+
'the platform does not provide ns() helpers or factory wrappers.',
1889+
);
1890+
});
1891+
});
1892+
18161893
// ── ADR-0087 D2 conversion notices reach the author ─────────────────────────
18171894
//
18181895
// Moved to `stack-conversion-notices.test.ts` with #23543 F5-http: the block

‎packages/spec/src/stack.zod.ts‎

Lines changed: 67 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2541,6 +2541,12 @@ export interface DefineStackOptions {
25412541
* Rules:
25422542
* - When `manifest.namespace` is set, every `object.name` MUST start with
25432543
* `${namespace}_` (single underscore). Returns one error per offender.
2544+
* - What is judged against which namespace is what the load path registers
2545+
* under each package ({@link namespacePrefixErrors}): a stack without
2546+
* `packages[]` is its one package, so every top-level object is judged
2547+
* against `manifest.namespace`; a stack with `packages[]` (ADR-0130 D4) is
2548+
* judged per body, each body's objects against that body's own namespace,
2549+
* and its top level by the residual rule.
25442550
* - Names starting with `sys_` are platform-reserved and always allowed.
25452551
* - Names containing `__` (legacy FQN double-underscore form) are flagged
25462552
* so authors migrate to the canonical single-prefix form.
@@ -2556,16 +2562,7 @@ export interface DefineStackOptions {
25562562
* prefixed references will surface there once the objects are correct.
25572563
*/
25582564
function validateNamespacePrefix(config: ObjectStackDefinition): string[] {
2559-
const errors: string[] = [];
2560-
const ns = config.manifest?.namespace;
2561-
if (ns && config.objects) {
2562-
// Single source of the per-object prefix rule — shared verbatim with the
2563-
// runtime publish enforcement in MetadataManager.publishPackage.
2564-
for (const obj of config.objects) {
2565-
const err = validateObjectNamespacePrefix(obj.name, ns);
2566-
if (err) errors.push(err);
2567-
}
2568-
}
2565+
const errors = namespacePrefixErrors(config as unknown as Record<string, unknown>);
25692566

25702567
// [ADR-0150 D6, child K] …and a namespace never equals an object name, in
25712568
// either direction, and no object is short-named `custom` (`NS_custom`, the
@@ -2599,6 +2596,66 @@ function validateNamespacePrefix(config: ObjectStackDefinition): string[] {
25992596
return errors;
26002597
}
26012598

2599+
/**
2600+
* The namespace-prefix rule ({@link validateObjectNamespacePrefix}, the single
2601+
* source shared verbatim with the runtime publish enforcement in
2602+
* `MetadataManager.publishPackage`) applied to each object under the namespace
2603+
* of the package the load path registers it under:
2604+
*
2605+
* - **A stack with no `packages[]`** is its one package, so every top-level
2606+
* object is judged against `manifest.namespace`, and the finding is the
2607+
* rule's own sentence.
2608+
* - **A stack with `packages[]`** (ADR-0130 D4) registers each body under its
2609+
* own id, so each body's objects are judged against that body's own
2610+
* `namespace`. A top-level object that no body declares is the stack's
2611+
* residual, registered under `manifest.id` by the boot's residual rule
2612+
* (`unclaimedTopLevel`, `@objectstack/metadata`, mirrored by
2613+
* {@link isResidualTopLevelItem}), and is judged against
2614+
* `manifest.namespace`. A top-level object a body declares is a copy of that
2615+
* body's object (an additive artifact's merged collections, as
2616+
* `resolveArtifactCollections` gives them) and is judged with that body
2617+
* only, so a suite whose packages declare different namespaces is not
2618+
* judged against one of them.
2619+
*
2620+
* A package with no `namespace` is a legacy package: its objects are not
2621+
* judged, the rule's own skip.
2622+
*/
2623+
function namespacePrefixErrors(config: Record<string, unknown>): string[] {
2624+
const manifest = isRecord(config.manifest) ? config.manifest : undefined;
2625+
const namespaceOf = (body: Record<string, unknown> | undefined): string | undefined =>
2626+
typeof body?.namespace === 'string' ? body.namespace : undefined;
2627+
const judge = (
2628+
objects: unknown,
2629+
namespace: string | undefined,
2630+
where: (i: number) => string,
2631+
judged?: (item: unknown) => boolean,
2632+
): string[] => {
2633+
if (!namespace || !Array.isArray(objects)) return [];
2634+
return objects.flatMap((obj: unknown, i: number) => {
2635+
if (judged && !judged(obj)) return [];
2636+
const name = isRecord(obj) && typeof obj.name === 'string' ? obj.name : undefined;
2637+
const err = validateObjectNamespacePrefix(name, namespace);
2638+
return err ? [`${where(i)}${err}`] : [];
2639+
});
2640+
};
2641+
if (!Array.isArray(config.packages)) return judge(config.objects, namespaceOf(manifest), () => '');
2642+
const bodies: Record<string, unknown>[] = [];
2643+
const errors: string[] = [];
2644+
config.packages.forEach((entry: unknown, j: number) => {
2645+
const body = isRecord(entry) && isRecord(entry.manifest) ? entry.manifest : undefined;
2646+
if (body === undefined) return;
2647+
bodies.push(body);
2648+
errors.push(...judge(body.objects, namespaceOf(body),
2649+
(i) => `Package '${singleAppPackageLabel(body)}' (packages[${j}].manifest.objects[${i}]): `));
2650+
});
2651+
const isResidual = isResidualTopLevelItem(bodies);
2652+
errors.push(...judge(config.objects, namespaceOf(manifest),
2653+
(i) => `Top-level objects[${i}], which no package body declares, is registered under package ` +
2654+
`'${singleAppPackageLabel(manifest)}': `,
2655+
(obj) => isResidual('objects', obj)));
2656+
return errors;
2657+
}
2658+
26022659
/**
26032660
* The package types a suite is made of, each held to at most one app —
26042661
* ADR-0019 (app-as-consumer-unit) D3 as amended: a suite (one install of an

0 commit comments

Comments
 (0)