diff --git a/.changeset/32967-dataset-reader-closure-authoring.md b/.changeset/32967-dataset-reader-closure-authoring.md new file mode 100644 index 00000000000..8238a6e9709 --- /dev/null +++ b/.changeset/32967-dataset-reader-closure-authoring.md @@ -0,0 +1,36 @@ +--- +'@objectstack/lint': minor +'@objectstack/core': patch +'@objectstack/cli': patch +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +Clause-②: no (narrowing) — `os validate`, `os build` and `os lint` refuse (`widget-dataset-unknown`, error) a dashboard widget in a package of a multi-package artifact whose `dataset` only a package outside that package's declared dependency closure holds, or two packages inside it hold, where they accepted it. The runtime already refused both reads (`409 RESOURCE_CONFLICT`) since 18.4.0; no runtime answer changes. +Metadata-protocol: narrowed +Skills-docs: none — `skills/**` teaches neither cross-package dataset resolution nor `widget-dataset-unknown`. + + + +fix(lint)!: `os validate` and `os build` resolve a dashboard's dataset through the reading package's declared dependency closure, as the runtime does + +**BREAKING** accept-set narrowing in the authoring doors (`os validate`, `os build`, `os lint`; `@objectstack/lint`'s `widget-dataset-unknown`), for a package of a multi-package artifact (`packages[]`, the `composeStacks(stacks, { manifest: 'preserve' })` shape). + +- **Before.** The per-package pass resolved a dashboard widget's `dataset` against every package of the artifact, so a widget bound to a dataset another package holds was accepted whether or not the reading package declares it. +- **Now.** The name resolves in the reading package, then to the one holder in its declared dependency closure (`manifest.dependencies`, transitively, plus `sys`). A name held only outside that closure, or by two packages inside it, is refused with `widget-dataset-unknown` (error), naming the dataset, the holders and the open fix. When the reading package declares a dependency the artifact does not carry, an outside-closure name is reported (`widget-dataset-unknown`, warning, suppressible with `suppressWarnings`) instead, since that package may hold it once installed; two holders inside the closure are refused even then. +- **Unchanged.** A stack without `packages[]`, the union run over the whole artifact, a package's own dataset, a dataset of a declared dependency, and a name no package holds (refused as before). Every runtime answer. +- **Fix.** Declare the holding package in the reading package's `dependencies`; where the holder already depends on the reader (a module of the app), move the dashboard into the holder, or move the dataset into the reader. Upgrade-guide entry `dashboard-dataset-outside-reader-closure-refused`. + +Since 18.2.0 (#25514) the per-package authoring pass resolved a widget's `dataset` against every package of the artifact. The runtime does not: since 18.4.0 a package's dashboard resolves a dataset name in its own package, then in the packages its manifest declares in `dependencies` (transitively) plus `sys`, and refuses the rest (ADR-0150 D3, the maintainer's ruling on #32929). So `os validate` passed a dashboard that answered `409 RESOURCE_CONFLICT` once installed. HotCRM is the first-party app built this way: its app package's CRM Overview read `product_metrics`, which its revenue module holds. Repository examples affected: 0. Other first-party apps outside this repository: not measured. + +The authoring pass now asks the same question. Who moves: an app whose package dashboard binds a dataset that another package of the same artifact holds, without declaring that package. The finding names the dataset, the holders and the open fix, read off the artifact: + +- the holder does not depend on the reading package: declare it in the reader's `dependencies`, or move the dataset into the reader; +- the holder already depends on the reading package (a module of the app): declaring it back is a dependency cycle the kernel refuses at boot, so move the dashboard into the holder, or move the dataset into the reader; +- two holders inside the closure: nothing picks one; keep one, or depend on one. + +A report's (or a joined block's) `runtimeFilter` reads the same index: on the per-package pass its keys are no longer judged against a dataset the report cannot resolve. No verdict is lost: `chart-dataset-unknown` already refuses that report there, and the union run still judges the filter. + +The refusal sentences that name a fix for `outside-closure` now name the open one too: the core sentence (`409` at every package-scoped by-name door) says "move the TYPE into P" alone when only the environment holds the item, and asks for a dependency on ONE package when two or more hold it; `os migrate stored-references` (the report and `bind`), the CLI's picklist-reference hint and the publish probe's `widget_not_probed` fix name the move beside the dependency. Which item a read answers, its status, code and `details.candidates` do not change. + +The remedy (correcting the 18.4.0 note of #32310, which named only the dependency and the `?package=` qualifier): declare the holder in the reading package's `dependencies`; where the holder already depends on the reader, move the reading item into the holder, or move the read item into the reader. diff --git a/packages/cli/src/commands/migrate/stored-references/index.ts b/packages/cli/src/commands/migrate/stored-references/index.ts index 3b24e271630..b64c3797446 100644 --- a/packages/cli/src/commands/migrate/stored-references/index.ts +++ b/packages/cli/src/commands/migrate/stored-references/index.ts @@ -27,7 +27,7 @@ export function describeCandidate(c: ReferenceCandidate): string { const REASONS = { ambiguous: 'more than one holder, none picked — bind one after review', 'environment-only': 'only an environment-authored item holds it, which a package never reaches (ADR-0150 D3 (a)) — not bindable', - 'outside-closure': 'only packages outside the writer\'s declared dependencies hold it (ADR-0150 D3 (c)) — declare the dependency; not bindable', + 'outside-closure': 'only packages outside the writer\'s declared dependencies hold it (ADR-0150 D3 (c)) — declare the dependency, or move the item where that dependency would be a cycle; not bindable', } as const; /** diff --git a/packages/cli/src/utils/picklist-references.test.ts b/packages/cli/src/utils/picklist-references.test.ts index e9fd40702cb..ed19e5936aa 100644 --- a/packages/cli/src/utils/picklist-references.test.ts +++ b/packages/cli/src/utils/picklist-references.test.ts @@ -226,6 +226,16 @@ describe('judgePicklistReferences — a field naming a sibling package\'s list ( expect(refusals[0].hint).toContain('`dependencies` of package \'com.example.orders\''); }); + it('[#32967] a holder that already depends on the declaring package: the hint names the move, never the cycle', () => { + const { refusals } = judgePicklistReferences({ + packages: [core({ dependencies: { 'com.example.orders': '^1.0.0' } }), orders()], + }); + expect(refusals).toHaveLength(1); + expect(refusals[0].hint).toContain('dependency cycle'); + expect(refusals[0].hint).toContain('declare the list in \'com.example.orders\' itself'); + expect(refusals[0].hint).not.toContain('Declare the dependency'); + }); + it('names every holder when two siblings hold the list and the declaring package depends on neither', () => { const { refusals } = judgePicklistReferences({ packages: [core(), { manifest: { ...manifest('com.example.crm'), picklists: [industry] } }, orders()], diff --git a/packages/cli/src/utils/picklist-references.ts b/packages/cli/src/utils/picklist-references.ts index 0e54d2bc707..a485eeab42f 100644 --- a/packages/cli/src/utils/picklist-references.ts +++ b/packages/cli/src/utils/picklist-references.ts @@ -390,9 +390,20 @@ function refusedReferenceHint(refusal: PackageScopedRefusal, bodies: readonly Ju const holders = refusal.candidates.flatMap((c) => (c.kind === 'package' ? [c.packageId] : [])); const caller = refusal.callerPackageId; if (refusal.reason === 'outside-closure' && caller !== null) { - const declare = holders.length === 1 - ? `add \`'${holders[0]}': '${rangeOf(holders[0], bodies)}'\` to the \`dependencies\` of package '${caller}'` - : `add the one package whose list the field means (${holders.map((id) => `'${id}'`).join(' or ')}) ` + + // [#32967] A holder that already depends on the caller (a module of the + // app whose field names it) cannot be declared back: the kernel refuses + // the cycle at boot. Read off the artifact, so the hint names the open fix. + const registry = artifactRegistry(bodies); + const declarable = holders.filter((id) => !packageResolutionClosure(registry, id).has(caller)); + if (holders.length > 0 && declarable.length === 0) { + return `${holders.length === 1 ? `'${holders[0]}' already depends` : `${holders.map((id) => `'${id}'`).join(' and ')} already depend`} ` + + `on '${caller}', so declaring a holder back would be a dependency cycle: declare the list in '${caller}' itself, ` + + `or move the field into the package that holds the list. ` + + 'Until then the installed field serves no options and its values are refused.'; + } + const declare = declarable.length === 1 + ? `add \`'${declarable[0]}': '${rangeOf(declarable[0], bodies)}'\` to the \`dependencies\` of package '${caller}'` + : `add the one package whose list the field means (${declarable.map((id) => `'${id}'`).join(' or ')}) ` + `to the \`dependencies\` of package '${caller}'`; return `Declare the dependency: ${declare}. Or declare the list in '${caller}' itself. ` + 'Until then the installed field serves no options and its values are refused.'; diff --git a/packages/cli/src/utils/stored-package-references.ts b/packages/cli/src/utils/stored-package-references.ts index a39dc81dd0a..6e56e981857 100644 --- a/packages/cli/src/utils/stored-package-references.ts +++ b/packages/cli/src/utils/stored-package-references.ts @@ -666,7 +666,8 @@ export async function bindStoredPackageReference( } if (reason === 'outside-closure') { return refuse('outside-closure', `${answer.message} Binding it would resolve past the package's declared dependencies, ` - + 'which the rule never does (ADR-0150 D3 (c)): declare the dependency instead. Nothing written.', candidates); + + 'which the rule never does (ADR-0150 D3 (c)): declare the dependency instead, or, where the holder already depends ' + + 'on the package (a cycle), make the move the sentence names. Nothing written.', candidates); } const chosen = candidates.find((c) => c.holder === 'package' && c.packageId === request.packageId); if (!chosen) { diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts index 088baf01f4d..08798c20757 100644 --- a/packages/core/src/package-scoped-resolution.test.ts +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -88,6 +88,23 @@ describe('[#32929] the outside-closure sentence names both fixes', () => { ); }); + it('[#32967] an environment-only holder: no package to depend on, so the sentence names only the move into the caller', () => { + const answer = resolvePackageScopedHolders({ type: 'dataset', name: 'n', callerPackageId: P }, packageScopedHolderSource([[null, 'env']]), closure([])); + expect(answer).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'environment' }] }); + const message = (answer as { message: string }).message; + expect(message).toContain(`move the dataset into "${P}"`); + expect(message).not.toContain('Declare a dependency'); + expect(message).not.toContain('that package'); + }); + + it('[#32967] two package holders: the dependency asked for is ONE of them, never every one', () => { + const answer = resolvePackageScopedHolders({ type: 'dataset', name: 'n', callerPackageId: P }, packageScopedHolderSource([[A, 'a'], [B, 'b']]), closure([])); + expect(answer).toMatchObject({ status: 'refused', reason: 'outside-closure' }); + const message = (answer as { message: string }).message; + expect(message).toContain('the one package whose dataset is meant'); + expect(message).not.toContain('the package that holds it'); + }); + it('names the type in its own words', () => { const answer = resolvePackageScopedHolders({ type: 'email_template', name: 'n', callerPackageId: P }, packageScopedHolderSource([[A, 'a']]), closure([])); expect((answer as { message: string }).message).toContain(`or move the email template into "${P}"`); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index 2d1fc30899f..535cc91c77f 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -565,15 +565,29 @@ export function packageScopedRefusalMessage(refusal: Omit c.kind === 'package').length; + const head = `${subject} is held outside the declared dependency closure of package "${caller}": ${named}.`; + // [#32967] Only the environment holds it (step 3's environment + // candidate): no package holds it, so there is nothing to depend on. + if (packages === 0) { + return `${head} No package holds it, so no dependency reaches it: ${moveIn} (ADR-0150 D3).`; + } + // [#32967] Two or more package holders: depending on every one would + // only turn this refusal into `ambiguous-in-closure`. + const declare = packages === 1 + ? 'Declare a dependency on the package that holds it (ADR-0141).' + : `Declare a dependency on the one package whose ${typeLabel(refusal.type)} is meant; depending on more than one ` + + 'leaves the name ambiguous (ADR-0141).'; + return `${head} ${declare} If that package already depends on "${caller}", the dependency would be a cycle: ` + + `move what reads it into that package, or ${moveIn} (ADR-0150 D3).`; + } case 'not-held-by-qualifier': return `${subject} is not held by ${refusal.callerPackageId === null ? 'the environment' : `package "${refusal.callerPackageId}"`}, ` + `which the address names exactly (ADR-0150 D5): it is held by ${named}. Address it by its holder.`; diff --git a/packages/lint/src/validate-widget-bindings.artifact-datasets.test.ts b/packages/lint/src/validate-widget-bindings.artifact-datasets.test.ts index 9ea32bbcf9d..9a69ff332b5 100644 --- a/packages/lint/src/validate-widget-bindings.artifact-datasets.test.ts +++ b/packages/lint/src/validate-widget-bindings.artifact-datasets.test.ts @@ -1,27 +1,40 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * #25514 — `widget-dataset-unknown` resolves a widget's `dataset` against the - * ARTIFACT's `packages[]`, not the one package body it judges. + * #25514, #32929 — `widget-dataset-unknown` resolves a widget's `dataset` + * against the artifact's `packages[]` the way the runtime resolves it: the + * judged package's own datasets, then the packages its manifest DECLARES in + * `dependencies` (transitively), ADR-0150 D3. * * The CLI's per-package pass (`runPerPackageAuthoringRules`) hands each rule * one package body re-read as a stack, with the artifact's `packages[]` as - * resolution context (`packageBodyAsStack`). An app-package dashboard binding a - * dataset a module package owns was refused there — measured on HotCRM's - * module split as `dataset "product_metrics" does not resolve to a declared - * dataset.` while the composed artifact carried the dataset. + * resolution context (`packageBodyAsStack`). #25514 made every body of the + * artifact context, so HotCRM's app-package dashboard bound to the revenue + * module's `product_metrics` passed `os validate` — and, once installed, + * answered `409 RESOURCE_CONFLICT` (outside-closure) on the dataset door + * (#32929). The maintainer ruled option two on #32929: the rule stays the + * declared closure (N1, 6729820123; ADR-0150 D3 (c): the artifact is the + * co-ownership boundary, not a resolution scope), and authoring refuses what + * the runtime refuses. Where the holder already depends on the reader, the fix + * the refusal names is the move, never the dependency (a cycle). * - * Both directions are pinned: a sibling-provided dataset is accepted (and its - * dimensions / measures are then judged like a local one), and a name no - * package provides is refused exactly as before. + * BASE (main 2c98485d, before this change): the HotCRM-shaped binding below + * produced no finding. */ import { describe, it, expect } from 'vitest'; +import { composeStacks, defineStack } from '@objectstack/spec'; import { runAuthoringRules } from './authoring-rules.js'; +import { buildRuntimeWriteSnapshots, runRuntimeAuthoringRules } from './runtime-gate.js'; import { validateWidgetBindings, WIDGET_DATASET_UNKNOWN, WIDGET_MEASURE_UNKNOWN } from './validate-widget-bindings.js'; -const revenueBody = { - id: 'app.objectstack.hotcrm.revenue', +const APP = 'app.objectstack.hotcrm'; +const REVENUE = 'app.objectstack.hotcrm.revenue'; + +/** HotCRM's module: it depends on the app package, as every module of a suite does. */ +const revenueBody: Record & { datasets: Array> } = { + id: REVENUE, name: 'revenue', + dependencies: { [APP]: '^1.0.0' }, objects: [{ name: 'crm_product', fields: { name: { type: 'text' }, price: { type: 'currency' } } }], datasets: [{ name: 'product_metrics', @@ -32,9 +45,10 @@ const revenueBody = { }], }; -const appBody = (dataset: string, values: string[] = ['product_count']) => ({ - id: 'app.objectstack.hotcrm', +const appBody = (dataset: string, values: string[] = ['product_count'], extra: Record = {}) => ({ + id: APP, name: 'hotcrm', + ...extra, dashboards: [{ name: 'crm_overview_dashboard', label: 'CRM Overview', @@ -59,48 +73,207 @@ const asPackageStack = (body: Record, siblings: Record) => validateWidgetBindings(stack).filter((f) => f.rule === WIDGET_DATASET_UNKNOWN); -describe('widget-dataset-unknown — the artifact resolves a sibling package’s dataset', () => { - it('ACCEPTS an app widget bound to a dataset the module package owns', () => { - expect(datasetUnknown(asPackageStack(appBody('product_metrics'), [revenueBody]))).toEqual([]); - }); +/** A package the app declares, holding a dataset of its own: the closure's control. */ +const libraryBody = { + id: 'com.example.library', + name: 'library', + objects: [{ name: 'lib_book', fields: { name: { type: 'text' } } }], + datasets: [{ + name: 'book_metrics', + label: 'Book metrics', + object: 'lib_book', + measures: [{ name: 'book_count', label: 'Books', aggregate: 'count' }], + dimensions: [{ name: 'name', field: 'name' }], + }], +}; +const appOnLibrary = (dataset: string, values: string[]) => + appBody(dataset, values, { dependencies: { 'com.example.library': '^1.0.0' } }); - it('still REFUSES a dataset NO package of the artifact declares', () => { - const findings = datasetUnknown(asPackageStack(appBody('product_nowhere'), [revenueBody])); +describe('widget-dataset-unknown — a sibling package’s dataset resolves through the declared closure (#32929)', () => { + it('REFUSES the app widget bound to the dataset its module holds, naming the move (the module depends on the app)', () => { + const findings = datasetUnknown(asPackageStack(appBody('product_metrics'), [revenueBody])); expect(findings).toHaveLength(1); expect(findings[0]).toMatchObject({ severity: 'error', where: 'dashboard "crm_overview_dashboard" › widget "top_products"', }); + expect(findings[0].message).toContain('outside the declared dependency closure'); + expect(findings[0].message).toContain(`"${REVENUE}"`); + expect(findings[0].message).toContain(`"${APP}"`); + // The arm: the holder already depends on the reader, so the fix is a move, never the dependency. + expect(findings[0].hint).toContain('dependency cycle'); + expect(findings[0].hint).not.toContain('Declare'); + }); + + it('names the dependency when the holder does not depend on the reader', () => { + const unrelated = { ...revenueBody, dependencies: undefined }; + const [finding] = datasetUnknown(asPackageStack(appBody('product_metrics'), [unrelated])); + expect(finding.message).toContain('outside the declared dependency closure'); + expect(finding.hint).toContain(`add "${REVENUE}" to the \`dependencies\` of package "${APP}"`); + expect(finding.hint).not.toContain('cycle'); + }); + + it('two holders outside the closure: both named, and the dependency asked for is ONE of them', () => { + const second = { ...libraryBody, id: 'com.example.second', datasets: [{ ...revenueBody.datasets[0] }] }; + const unrelated = { ...revenueBody, dependencies: undefined }; + const [finding] = datasetUnknown(asPackageStack(appBody('product_metrics'), [unrelated, second])); + expect(finding.message).toContain(`"${REVENUE}", "com.example.second"`); + expect(finding.hint).toContain('the one package'); + expect(finding.hint).toContain('more than one leaves the name ambiguous'); + }); + + it('REFUSES a name two packages of the closure hold, naming both: nothing picks one (red line 2)', () => { + const second = { ...libraryBody, id: 'com.example.second', datasets: [{ ...libraryBody.datasets[0] }] }; + const app = appBody('book_metrics', ['book_count'], { + dependencies: { 'com.example.library': '^1.0.0', 'com.example.second': '^1.0.0' }, + }); + const findings = datasetUnknown(asPackageStack(app, [libraryBody, second])); + expect(findings).toHaveLength(1); + expect(findings[0].severity).toBe('error'); + expect(findings[0].message).toContain('in the declared dependency closure'); + expect(findings[0].message).toContain('"com.example.library", "com.example.second"'); + }); + + it('the judged package’s own dataset wins a name a package of its closure also holds (ADR-0150 D3 step 1)', () => { + const app = { ...appOnLibrary('book_metrics', ['book_count']), objects: libraryBody.objects, datasets: libraryBody.datasets }; + expect(datasetUnknown(asPackageStack(app, [libraryBody]))).toEqual([]); + }); + + it('CONTROL: the same dashboard in the module resolves the module’s own dataset', () => { + const moduleDashboard = { ...revenueBody, dashboards: appBody('product_metrics').dashboards }; + const app = { id: APP, name: 'hotcrm' }; + expect(datasetUnknown(asPackageStack(moduleDashboard, [app]))).toEqual([]); + }); + + it('CONTROL: a module widget resolves the app’s dataset, which it depends on', () => { + const app = { ...appBody('product_metrics'), dashboards: undefined, objects: revenueBody.objects, datasets: revenueBody.datasets }; + const module = { id: REVENUE, name: 'revenue', dependencies: { [APP]: '^1.0.0' }, dashboards: appBody('product_metrics').dashboards }; + expect(datasetUnknown(asPackageStack(module, [app]))).toEqual([]); + }); + + it('ACCEPTS an app widget bound to a dataset of a package the app declares', () => { + expect(datasetUnknown(asPackageStack(appOnLibrary('book_metrics', ['book_count']), [libraryBody]))).toEqual([]); + }); + + it('REPORTS, not refuses, when the reader declares a dependency the artifact does not carry (S1)', () => { + const app = appBody('product_metrics', ['product_count'], { dependencies: { 'com.example.elsewhere': '^1.0.0' } }); + const findings = datasetUnknown(asPackageStack(app, [revenueBody])); + expect(findings).toHaveLength(1); + expect(findings[0].severity).toBe('warning'); + expect(findings[0].message).toContain('not judged: it may come from "com.example.elsewhere", a dependency this artifact does not carry'); + // Nothing is said about what the installed read answers: the outside package may serve it. + expect(findings[0].message).not.toContain('409'); + expect(findings[0].hint).toContain('If that package holds "product_metrics", nothing is wrong. Otherwise:'); + expect(findings[0].hint).toContain('dependency cycle'); + // The suppression a warning takes is open to the author once the outside package is confirmed. + const suppressed = appBody('product_metrics', ['product_count'], { dependencies: { 'com.example.elsewhere': '^1.0.0' } }); + (suppressed.dashboards[0].widgets[0] as Record).suppressWarnings = [WIDGET_DATASET_UNKNOWN]; + expect(datasetUnknown(asPackageStack(suppressed, [revenueBody]))).toEqual([]); + }); + + it('an outside dependency never softens an ambiguity: two holders inside the closure stay refused (S1)', () => { + const second = { ...libraryBody, id: 'com.example.second', datasets: [{ ...libraryBody.datasets[0] }] }; + const app = appBody('book_metrics', ['book_count'], { + dependencies: { 'com.example.library': '^1.0.0', 'com.example.second': '^1.0.0', 'com.example.elsewhere': '^1.0.0' }, + }); + const findings = datasetUnknown(asPackageStack(app, [libraryBody, second])); + expect(findings).toHaveLength(1); + expect(findings[0].severity).toBe('error'); + expect(findings[0].message).toContain('in the declared dependency closure'); + }); + + it('neither arm reaches the publish door: its write snapshot carries no `packages[]` (S1, review 6860238813)', () => { + // The door resolves `datasets` from the live context, never narrowed (runtime-gate.ts); the + // package's own read is judged at the dataset door (409), not here. + const item = appBody('product_metrics', ['product_count'], { dependencies: { 'com.example.elsewhere': '^1.0.0' } }).dashboards[0]; + const context = { objects: revenueBody.objects as unknown[], datasets: revenueBody.datasets }; + const snapshot = buildRuntimeWriteSnapshots({ type: 'dashboard', item, context, packageScope: { packageId: APP, dependencies: [] } }); + expect(snapshot && Object.keys(snapshot.candidate).filter((k) => k === 'packages' || k === 'manifest')).toEqual([]); + const gate = runRuntimeAuthoringRules({ type: 'dashboard', item, context, packageScope: { packageId: APP, dependencies: [] } }); + expect([...gate.errors, ...gate.advisories].filter((f) => f.rule === WIDGET_DATASET_UNKNOWN)).toEqual([]); + }); + + it('still REFUSES a dataset NO package of the artifact declares, as before', () => { + const findings = datasetUnknown(asPackageStack(appBody('product_nowhere'), [revenueBody])); + expect(findings).toHaveLength(1); + expect(findings[0].message).toBe('dataset "product_nowhere" does not resolve to a declared dataset.'); }); it('REFUSES the sibling dataset when judged WITHOUT the artifact — the unchanged single-package answer', () => { expect(datasetUnknown(appBody('product_metrics'))).toHaveLength(1); }); - it('judges the resolved sibling dataset’s measures like a local one', () => { - const findings = validateWidgetBindings(asPackageStack(appBody('product_metrics', ['revenue_sum']), [revenueBody])); + it('judges a resolved dependency’s dataset measures like a local one', () => { + const findings = validateWidgetBindings(asPackageStack(appOnLibrary('book_metrics', ['book_sum']), [libraryBody])); expect(findings.map((f) => f.rule)).toContain(WIDGET_MEASURE_UNKNOWN); }); - it('does not judge a sibling’s dataset-level conditions on this package’s pass', () => { + it('does not judge a dependency’s dataset-level conditions on this package’s pass', () => { const incoherent = { - ...revenueBody, + ...libraryBody, + objects: [{ name: 'lib_book', fields: { name: { type: 'text' }, rate: { type: 'percent' } } }], datasets: [{ - ...revenueBody.datasets[0], - measures: [{ name: 'price_total', label: 'Total', aggregate: 'sum', field: 'price' }], + ...libraryBody.datasets[0], + measures: [{ name: 'rate_total', label: 'Total', aggregate: 'sum', field: 'rate' }], }], }; - const findings = validateWidgetBindings(asPackageStack(appBody('product_metrics', ['price_total']), [incoherent])); + const findings = validateWidgetBindings(asPackageStack(appOnLibrary('book_metrics', ['rate_total']), [incoherent])); expect(findings.filter((f) => f.path.startsWith('datasets['))).toEqual([]); }); + it('the union run of a `manifest: \'preserve\'` composition with a residual top-level dataset reads every body, as before (M2)', () => { + // The shape the doors hand the rule (review 6857932402 M2): the composition + // keeps the LAST input's manifest, whose id names the app's body, and a + // top-level `datasets` (the residual ADR-0130 D4 registers under that id) + // stops the union fold from folding the bodies' datasets. The module's + // dashboard on the module's OWN dataset, the module depending on the app, + // must stay accepted: the runtime serves it. + const module = defineStack({ + manifest: { id: REVENUE, namespace: 'crm', name: 'revenue', version: '1.0.0', type: 'module', dependencies: { [APP]: '^1.0.0' } }, + objects: revenueBody.objects, + datasets: revenueBody.datasets, + dashboards: appBody('product_metrics').dashboards, + } as never); + const app = defineStack({ + manifest: { id: APP, namespace: 'crm', name: 'hotcrm', version: '1.0.0', type: 'app' }, + objects: [{ name: 'crm_account', fields: { name: { type: 'text' } } }], + } as never); + const composed = composeStacks([module, app], { manifest: 'preserve' }) as unknown as Record & { + manifest: { id: string }; + packages: Array<{ manifest: Record }>; + }; + expect(composed.manifest.id).toBe(APP); + const residual = { + name: 'account_metrics', object: 'crm_account', + measures: [{ name: 'account_count', label: 'Accounts', aggregate: 'count' }], + dimensions: [{ name: 'name', field: 'name' }], + }; + // `authoringRuleUnionStack` (cli): a top-level key already present is kept, an absent one is folded from the bodies. + const union = { + ...composed, + datasets: [residual], + dashboards: composed.packages.flatMap((p) => (p.manifest.dashboards as unknown[] | undefined) ?? []), + }; + expect(union.dashboards).toHaveLength(1); + expect(datasetUnknown(union)).toEqual([]); + // CONTROL: the per-package pass of the same composition still refuses the app reading the module's dataset. + // The app's body carries the module's dashboard and is handed as its own manifest, as `packageBodyAsStack` does. + const appEntry = composed.packages.find((p) => p.manifest.id === APP)!.manifest; + const appReads = { ...appEntry, dashboards: union.dashboards }; + const entries = composed.packages.map((p) => (p.manifest.id === APP ? { manifest: appReads } : p)); + const refused = datasetUnknown({ ...appReads, manifest: appReads, packages: entries }); + expect(refused).toHaveLength(1); + expect(refused[0]).toMatchObject({ severity: 'error' }); + expect(refused[0].hint).toContain('dependency cycle'); + }); + it('reaches the rule table the per-package pass runs', () => { const stack = asPackageStack(appBody('product_metrics'), [revenueBody]); const findings = runAuthoringRules('validate', { normalized: stack, parsed: stack }); - expect(findings.filter((f) => f.rule === WIDGET_DATASET_UNKNOWN)).toEqual([]); - const dangling = asPackageStack(appBody('product_nowhere'), [revenueBody]); + expect(findings.filter((f) => f.rule === WIDGET_DATASET_UNKNOWN)).toHaveLength(1); + const declared = asPackageStack(appOnLibrary('book_metrics', ['book_count']), [libraryBody]); expect( - runAuthoringRules('validate', { normalized: dangling, parsed: dangling }).filter((f) => f.rule === WIDGET_DATASET_UNKNOWN), - ).toHaveLength(1); + runAuthoringRules('validate', { normalized: declared, parsed: declared }).filter((f) => f.rule === WIDGET_DATASET_UNKNOWN), + ).toEqual([]); }); }); diff --git a/packages/lint/src/validate-widget-bindings.ts b/packages/lint/src/validate-widget-bindings.ts index 603cdc59376..1254a2305c2 100644 --- a/packages/lint/src/validate-widget-bindings.ts +++ b/packages/lint/src/validate-widget-bindings.ts @@ -1,5 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { packageResolutionClosure, type PackageClosureRegistry } from '@objectstack/metadata-core'; import { isIncoherentAggregate } from '@objectstack/spec/data'; import { ChartTypeSchema } from '@objectstack/spec/ui'; @@ -713,35 +714,241 @@ function effectiveFilterField( /** * [#29900] The datasets a presentation's `dataset` binding resolves against: - * `stack.datasets`, then every `packages[]` body's datasets as resolution - * context. One index for every presentation that binds a dataset by name (a - * dashboard widget, a report and its joined blocks), so the two cannot disagree - * about which dataset a name reaches. + * `stack.datasets`, then the datasets of the `packages[]` bodies this stack's + * package may reach, as resolution context. One index for every presentation + * that binds a dataset by name (a dashboard widget, a report and its joined + * blocks), so the two cannot disagree about which dataset a name reaches. + * {@link indexArtifactDatasetResolution} carries the rule. */ export function indexResolvableDatasets(stack: AnyRec): Map { - const datasets = new Map(); + return indexArtifactDatasetResolution(stack).resolvable; +} + +/** + * [#32929, ADR-0150 D3] Why a name the artifact declares does not resolve for + * the judged package: every holder is outside its declared dependency closure + * (`outside-closure`), or two or more holders are inside it + * (`ambiguous-in-closure`). The runtime's two refusals of a package reader's + * bare dataset name, `409 RESOURCE_CONFLICT` at the dataset doors. + */ +export interface DatasetResolutionRefusal { + reason: 'outside-closure' | 'ambiguous-in-closure'; + /** The artifact packages holding the name, in `packages[]` order. */ + holders: string[]; +} + +/** + * [#32929, ADR-0150 D3] Which datasets a stack's presentations resolve, and + * which names the artifact declares that the judged package's readers are + * refused. + */ +export interface ArtifactDatasetResolution { + /** Name → dataset, for every name this stack's presentations resolve. */ + resolvable: Map; + /** + * Name → why it is refused, for a name the artifact's packages declare that + * does not resolve for the judged package. Empty outside the per-package pass. + */ + refused: Map; + /** The judged package (the per-package pass), or `undefined` for any other stack. */ + callerPackageId?: string; + /** Does `holder`'s own declared closure reach the judged package, so declaring `holder` back is a cycle? */ + dependsOnCaller(holder: string): boolean; + /** + * [#32967 S1] The judged package's declared dependencies this artifact does + * not carry, in declaration order. Any one of them may hold a name the + * artifact holds only outside the closure, and the installed read then + * resolves there, so an `outside-closure` name is reported, not refused, + * while this is non-empty (the reading `picklist-references.ts` takes). + * Empty outside the per-package pass. + */ + outsideDependencies: string[]; +} + +/** + * [#25514, #32929] The resolution {@link indexResolvableDatasets} answers. + * + * `stack.datasets` resolves first: on the per-package pass that body IS this + * package, and the stack's own declaration wins a name it shares with a body + * (ADR-0150 D3 step 1). The datasets the `packages[]` bodies declare then join + * as RESOLUTION CONTEXT, the way `validate-object-references.ts` widens rung ① + * with the artifact's objects. ⛔ It changes what a binding can RESOLVE, never + * what is JUDGED: the dataset-level checks of `validateWidgetBindings` still + * walk `stack.datasets` alone, and a name no package declares still resolves + * nowhere. + * + * [#32929] Which bodies join is the runtime's rule (ADR-0150 D3 (c), ruling + * N1 6729820123; the maintainer's ruling on #32929, option two, 6840360115): a + * package's reader resolves a bare dataset name in its own package, then to the + * ONE holder in its DECLARED dependency closure (ADR-0141) plus `sys` — + * `packageResolutionClosure`, the walk the dataset doors resolve + * `?callerPackage=` by, read over the artifact's bodies as + * `picklist-references.ts` reads them. The release artifact is the + * co-ownership boundary, not a resolution scope. So on the per-package pass + * (`stack.manifest` IS one of the bodies, as `packageBodyAsStack` hands it) a name held only outside that + * closure, or by two packages inside it, is {@link ArtifactDatasetResolution.refused} + * and resolves to nothing, where #25514 accepted every body and the installed + * dashboard answered `409 RESOURCE_CONFLICT`. + * + * Any other stack reads every body, first declaration winning, as before: + * the union run, whose folded collections carry no package provenance even + * when its manifest's id names a body (a `manifest: 'preserve'` composition + * keeps the last input's manifest beside that input's assembled body, a + * different object), and a stack without `packages[]`. The per-package pass + * is the one that knows the reader's package. + * + * [#32967 S1] A name held only outside the closure is refused only when the + * judged package declares no dependency the artifact does not carry. When it + * declares one, that package may hold the name once installed, and the read + * resolves there: {@link ArtifactDatasetResolution.outsideDependencies} names + * them, and the binding is reported, never refused. Two holders inside the + * closure stay refused whatever is installed: an outside package can add a + * holder, never remove one. + */ +export function indexArtifactDatasetResolution(stack: AnyRec): ArtifactDatasetResolution { + const resolvable = new Map(); + const refused = new Map(); for (const ds of recordsOf(stack.datasets)) { - if (typeof ds.name === 'string') datasets.set(ds.name, ds); + if (typeof ds.name === 'string') resolvable.set(ds.name, ds); } - // [#25514] A widget's `dataset` resolves against the ARTIFACT: the datasets - // every `packages[]` body declares join the map as RESOLUTION CONTEXT, the way - // `validate-object-references.ts` widens rung ① with the artifact's objects. - // A cross-domain dashboard in the app package reads a module's dataset (the - // ADR-0130 plan rule "multi-module dashboards move to the app package"), and - // the runtime serves every package's datasets from one analytics service. - // ⛔ It changes what a widget can RESOLVE, never what is JUDGED: the - // dataset-level checks of `validateWidgetBindings` still walk `stack.datasets` - // alone, and a name no package declares still resolves nowhere. The stack's - // own declaration wins a name it shares with a body — on the per-package - // pass that body IS this one. + const bodies: Array<{ id: string | undefined; body: AnyRec }> = []; for (const entry of packagesOf(stack)) { const body = entry.manifest; if (!body || typeof body !== 'object' || Array.isArray(body)) continue; - for (const ds of recordsOf((body as AnyRec).datasets)) { - if (typeof ds.name === 'string' && !datasets.has(ds.name)) datasets.set(ds.name, ds); + const id = (body as AnyRec).id; + bodies.push({ id: typeof id === 'string' && id !== '' ? id : undefined, body: body as AnyRec }); + } + // [#32967 M2] The per-package pass hands the body ITSELF as `manifest` + // (`packageBodyAsStack`). An id match is not enough: the union run of a + // `composeStacks(…, { manifest: 'preserve' })` artifact carries the last + // input's manifest, whose id names a body, and its folded dashboards belong + // to every package, not to that one. + const own = bodies.find((b) => b.body === stack.manifest); + const callerPackageId = own?.id; + const byId = new Map(); + for (const b of bodies) if (b.id !== undefined && !byId.has(b.id)) byId.set(b.id, { manifest: b.body }); + const registry: PackageClosureRegistry = { + getPackage: (id) => byId.get(id), + getAllPackages: () => [...byId.values()], + }; + const dependsOnCaller = (holder: string): boolean => + callerPackageId !== undefined && packageResolutionClosure(registry, holder).has(callerPackageId); + + if (callerPackageId === undefined) { + for (const { body } of bodies) { + for (const ds of recordsOf(body.datasets)) { + if (typeof ds.name === 'string' && !resolvable.has(ds.name)) resolvable.set(ds.name, ds); + } + } + return { resolvable, refused, dependsOnCaller, outsideDependencies: [] }; + } + const declared = own?.body.dependencies; + const outsideDependencies = declared && typeof declared === 'object' && !Array.isArray(declared) + ? Object.keys(declared).filter((id) => id !== callerPackageId && !byId.has(id)) + : []; + + // Every other package's holdings, by name: who holds it inside the + // caller's reach, who outside. The caller's own body is `stack.datasets`. + const reach = packageResolutionClosure(registry, callerPackageId); + const holdings = new Map; outside: string[] }>(); + for (const { id, body } of bodies) { + if (id === undefined || id === callerPackageId || byId.get(id)?.manifest !== body) continue; + for (const ds of recordsOf(body.datasets)) { + if (typeof ds.name !== 'string' || resolvable.has(ds.name)) continue; + const held = holdings.get(ds.name) ?? { inside: [], outside: [] }; + if (reach.has(id)) { + if (!held.inside.some((h) => h.id === id)) held.inside.push({ id, ds }); + } else if (!held.outside.includes(id)) { + held.outside.push(id); + } + holdings.set(ds.name, held); } } - return datasets; + for (const [name, { inside, outside }] of holdings) { + // ⛔ Never a pick among two: the runtime refuses the name naming both. + if (inside.length === 1) resolvable.set(name, inside[0].ds); + else if (inside.length > 1) refused.set(name, { reason: 'ambiguous-in-closure', holders: inside.map((h) => h.id) }); + else refused.set(name, { reason: 'outside-closure', holders: outside }); + } + return { resolvable, refused, callerPackageId, dependsOnCaller, outsideDependencies }; +} + +/** + * [#32929] The finding's two sentences for a binding the runtime refuses for + * the judged package ({@link DatasetResolutionRefusal}). Unlike the runtime's + * sentence, which cannot see the holders' manifests, the artifact here says + * which fix is open: a holder that already depends on the judged package + * cannot be declared back (the kernel refuses the cycle at boot), so the fix + * for it is a move; and with two or more candidates, declaring every one + * would only turn the refusal into an ambiguity. + */ +export function datasetRefusalWording( + resolution: ArtifactDatasetResolution, + dsName: string, + reader: string, +): { message: string; hint: string } { + const refusal = resolution.refused.get(dsName); + const holders = refusal?.holders ?? []; + const caller = resolution.callerPackageId ?? 'this package'; + const named = holders.map((id) => `"${id}"`).join(', '); + const moveIn = `move the dataset into "${caller}"`; + if (refusal?.reason === 'ambiguous-in-closure') { + return { + message: + `dataset "${dsName}" is held by ${holders.length} packages in the declared dependency closure of package ` + + `"${caller}" (${named}), so the installed ${reader}'s read of it is refused 409: nothing picks one (ADR-0150 D3).`, + hint: `Make "${dsName}" mean one dataset for "${caller}": ${moveIn}, or depend on only one of the packages that hold it.`, + }; + } + const message = + `dataset "${dsName}" is held by ${holders.length === 1 ? 'package' : 'packages'} ${named}, outside the declared ` + + `dependency closure of package "${caller}", so the installed ${reader}'s read of it is refused 409 (ADR-0150 D3).`; + const declarable = holders.filter((id) => !resolution.dependsOnCaller(id)); + if (declarable.length === 0) { + return { + message, + hint: + `${holders.length === 1 ? `Package ${named} already depends` : `Packages ${named} already depend`} on ` + + `"${caller}", so declaring ${holders.length === 1 ? 'it' : 'one'} back would be a dependency cycle: move this ` + + `${reader} into ${holders.length === 1 ? 'that package' : 'the package whose dataset it means'}, or ${moveIn}.`, + }; + } + return { + message, + hint: + (declarable.length === 1 + ? `Declare the dependency: add "${declarable[0]}" to the \`dependencies\` of package "${caller}" (ADR-0141)` + : `Declare a dependency on the one package whose dataset this ${reader} means (` + + `${declarable.map((id) => `"${id}"`).join(', ')}); depending on more than one leaves the name ambiguous (ADR-0141)`) + + `, or ${moveIn}.`, + }; +} + +/** + * [#32967 S1] The report for an `outside-closure` name when the judged + * package declares dependencies this artifact does not carry + * ({@link ArtifactDatasetResolution.outsideDependencies}): one of them may + * hold the name, so nothing here says what the installed read answers. The + * hint is the refusal's own fix, conditional on none of them holding it. + */ +export function datasetUnverifiedWording( + resolution: ArtifactDatasetResolution, + dsName: string, + reader: string, +): { message: string; hint: string } { + const refusal = resolution.refused.get(dsName); + const holders = refusal?.holders ?? []; + const caller = resolution.callerPackageId ?? 'this package'; + const outside = resolution.outsideDependencies.map((id) => `"${id}"`).join(', '); + const one = resolution.outsideDependencies.length === 1; + const fix = datasetRefusalWording(resolution, dsName, reader).hint; + return { + message: + `dataset "${dsName}" is held in this artifact only by ${holders.length === 1 ? 'package' : 'packages'} ` + + `${holders.map((id) => `"${id}"`).join(', ')}, outside the declared dependency closure of package "${caller}" — ` + + `not judged: it may come from ${outside}, ${one ? 'a dependency' : 'dependencies'} this artifact does not carry.`, + hint: `If ${one ? 'that package holds' : 'one of those packages holds'} "${dsName}", nothing is wrong. Otherwise: ${fix}`, + }; } /** One filter key of a dataset-bound filter that the dataset query cannot satisfy. */ @@ -896,7 +1103,8 @@ function measureColumn(measure: AnyRec): string | undefined { export function validateWidgetBindings(stack: AnyRec): WidgetBindingFinding[] { const findings: WidgetBindingFinding[] = []; - const datasets = indexResolvableDatasets(stack); + const resolution = indexArtifactDatasetResolution(stack); + const datasets = resolution.resolvable; // ── (0) dataset measures aggregate their field coherently ── // A measure that SUMs a percentage/rate field produces a meaningless total @@ -1067,7 +1275,20 @@ export function validateWidgetBindings(stack: AnyRec): WidgetBindingFinding[] { // ── (a) dataset reference resolves ── const dsName = typeof w.dataset === 'string' ? w.dataset : undefined; const dataset = dsName ? datasets.get(dsName) : undefined; - if (dsName && !dataset) { + const refusal = dsName && !dataset ? resolution.refused.get(dsName) : undefined; + if (dsName && refusal?.reason === 'outside-closure' && resolution.outsideDependencies.length > 0) { + // [#32967 S1] A dependency this artifact does not carry may hold the + // name, and the installed read then resolves there: reported, never + // refused, as `picklist-references.ts` reports its twin. No user + // sentence (`validate-widget-bindings.user-text.ts`): the publish + // door's write snapshot carries no `packages[]`, so this arm runs + // only at `os validate` / `os build` / `os lint`. + push({ severity: 'warning', rule: WIDGET_DATASET_UNKNOWN, ...datasetUnverifiedWording(resolution, dsName, 'dashboard') }); + } else if (dsName && refusal) { + // [#32929] Declared in the artifact, but the runtime refuses this + // package's read of it (ADR-0150 D3), so it is refused here. + push({ severity: 'error', rule: WIDGET_DATASET_UNKNOWN, ...datasetRefusalWording(resolution, dsName, 'dashboard') }); + } else if (dsName && !dataset) { push({ severity: 'error', rule: WIDGET_DATASET_UNKNOWN, diff --git a/packages/metadata-protocol/src/build-probes-dataset-holders.test.ts b/packages/metadata-protocol/src/build-probes-dataset-holders.test.ts index f6ccd8af89c..b8f778f0edb 100644 --- a/packages/metadata-protocol/src/build-probes-dataset-holders.test.ts +++ b/packages/metadata-protocol/src/build-probes-dataset-holders.test.ts @@ -182,5 +182,7 @@ describe('[#31700] the probes read a widget\'s dataset from the publishing packa const [issue] = report.issues; expect(issue!.message).toContain('is held only outside the declared dependencies of package "com.qa.app"'); expect(issue!.fix).toContain('Declare package "com.qa.app"\'s dependency'); + // [#32967] …and the move, for a holder that already depends on the publishing package. + expect(issue!.fix).toContain('would be a cycle, so move the dashboard into that package'); }); }); diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 7eb33170f20..043dbc667e0 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -264,8 +264,11 @@ function datasetNotProbed(refused: PackageScopedRefusal, dsName: string): { why: return { why: `dataset "${dsName}" is held only outside the declared dependencies of package "${caller}" ` + `(${holders.join(', ')}), so the dashboard's read of it is refused`, + // [#32967] The runtime sentence's second fix too: a holder that + // already depends on the caller cannot be declared back (a cycle). fix: `Declare package "${caller}"'s dependency on the package whose dataset "${dsName}" the widget means, ` - + `or hold the dataset in "${caller}" itself, then republish.`, + + `or hold the dataset in "${caller}" itself; if that package already depends on "${caller}", the ` + + 'dependency would be a cycle, so move the dashboard into that package or hold the dataset here. Then republish.', }; } if (caller !== null) { diff --git a/packages/qa/dogfood/test/dataset-app-reads-module.dogfood.test.ts b/packages/qa/dogfood/test/dataset-app-reads-module.dogfood.test.ts new file mode 100644 index 00000000000..eaa3a74ee35 --- /dev/null +++ b/packages/qa/dogfood/test/dataset-app-reads-module.dogfood.test.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#32929, #32967, ADR-0150 D3 (c)] An app package's dashboard on a dataset +// its own module holds — HotCRM's shape — on the two doors an author meets: +// `os validate` on the composed config, and the dataset door of the booted +// build-shaped artifact. One app package (`com.qa.sib.app`) and one module +// package (`com.qa.sib.rev`) that declares it, sharing a namespace. The module +// holds the object and the dataset. +// +// The maintainer ruled option two on #32929 (6840360115): the resolution rule +// stays the declared closure (N1, 6729820123), and authoring refuses what the +// runtime refuses. The three cells: +// +// 1. HotCRM's shape (the app's dashboard binds the module's dataset): +// `os validate` exits 1 naming the move (BASE main 2c98485d: exit 0), and +// the app's reader is refused `409 RESOURCE_CONFLICT` (outside-closure). +// 2. Moved into the module (the dashboard is the module's): `os validate` +// exits 0, and the module's reader is served 200. +// 3. The dependency the old sentence asked for (the app declaring its own +// module) is a cycle the kernel refuses at boot. +// +// Plus two fences of review 6857932402: a residual top-level `datasets` beside +// the composition leaves the union run as it was (M2), and an app declaring a +// dependency the artifact does not carry is reported, not refused (S1). + +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { composeStacks, defineStack } from '@objectstack/spec'; +import { writeBuildShapedArtifact } from './build-shaped-artifact.js'; + +const APP = 'com.qa.sib.app'; +const REV = 'com.qa.sib.rev'; +const DATASET = 'sib_product_metrics'; + +const widget = (id: string) => ({ id, type: 'bar', title: id, dataset: DATASET, dimensions: ['category'], values: ['list_price_sum'], layout: { x: 0, y: 0, w: 6, h: 4 } }); + +/** A dependency no input of the artifact carries: an installed package may hold the dataset (#32967 S1). */ +const ELSEWHERE = 'com.qa.sib.elsewhere'; + +/** The two input stacks, as plain configs: `appReads` puts the dashboard in the app package (HotCRM's shape). */ +function inputsFor(appDependsOnModule: boolean, appReads = true, appDependsElsewhere = false) { + const dependencies = { + ...(appDependsOnModule ? { [REV]: '^1.0.0' } : {}), + ...(appDependsElsewhere ? { [ELSEWHERE]: '^1.0.0' } : {}), + }; + const app = { + manifest: { + id: APP, namespace: 'sib', name: 'qa_sib_app', version: '1.0.0', type: 'app', + ...(Object.keys(dependencies).length > 0 ? { dependencies } : {}), + }, + objects: [{ name: 'sib_account', label: 'Account', sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' } } }], + ...(appReads ? { dashboards: [{ name: 'sib_overview', label: 'Overview', columns: 12, widgets: [widget('top_products')] }] } : {}), + }; + const module = { + manifest: { id: REV, namespace: 'sib', name: 'qa_sib_rev', version: '1.0.0', type: 'module', dependencies: { [APP]: '^1.0.0' } }, + objects: [{ name: 'sib_product', label: 'Product', sharingModel: 'public_read_write', fields: { + name: { type: 'text', label: 'Name' }, category: { type: 'text', label: 'Category' }, list_price: { type: 'number', label: 'List price' }, + } }], + datasets: [{ + name: DATASET, label: 'Product metrics', object: 'sib_product', + dimensions: [{ name: 'category', label: 'Category', field: 'category', type: 'string' }], + measures: [{ name: 'list_price_sum', label: 'List price', aggregate: 'sum', field: 'list_price' }], + }], + dashboards: [{ name: 'sib_rev_dashboard', label: 'Revenue', columns: 12, widgets: [widget('top_products')] }], + }; + return { module, app }; +} + +function artifactFor(appDependsOnModule: boolean) { + const { module, app } = inputsFor(appDependsOnModule); + return composeStacks([defineStack(module as never), defineStack(app as never)], { manifest: 'preserve' }) as any; +} + +const CLI_BIN = join(dirname(createRequire(import.meta.url).resolve('@objectstack/cli/package.json')), 'bin', 'run.js'); +const SPEC_ROOT = dirname(createRequire(import.meta.url).resolve('@objectstack/spec/package.json')); + +/** A top-level dataset no package body declares: the residual ADR-0130 D4 registers under the manifest's id. */ +const RESIDUAL = { + name: 'sib_account_metrics', label: 'Account metrics', object: 'sib_account', + dimensions: [{ name: 'name', label: 'Name', field: 'name', type: 'string' }], + measures: [{ name: 'account_count', label: 'Accounts', aggregate: 'count' }], +}; + +/** + * `os validate` on the composed config an author writes (the `app-multi-package` shape), in a scratch directory. + * `residual` adds a top-level `datasets` beside the composition's `packages[]` (#32967 M2); `elsewhere` has the + * app declare a dependency the artifact does not carry (#32967 S1). + */ +function validate(appReads: boolean, opts: { residual?: boolean; elsewhere?: boolean } = {}): { exitCode: number; output: string } { + const dir = mkdtempSync(join(tmpdir(), 'dogfood-app-reads-module-validate-')); + try { + const { module, app } = inputsFor(false, appReads, opts.elsewhere); + const composed = `composeStacks([defineStack(${JSON.stringify(module)}), defineStack(${JSON.stringify(app)})], { manifest: 'preserve' })`; + writeFileSync( + join(dir, 'objectstack.config.mjs'), + "import { composeStacks, defineStack } from '@objectstack/spec';\n\n" + + (opts.residual + ? `export default defineStack({ ...${composed}, datasets: [${JSON.stringify(RESIDUAL)}] });\n` + : `export default ${composed};\n`), + ); + mkdirSync(join(dir, 'node_modules', '@objectstack'), { recursive: true }); + symlinkSync(SPEC_ROOT, join(dir, 'node_modules', '@objectstack', 'spec'), 'dir'); + const res = spawnSync(process.execPath, [CLI_BIN, 'validate'], { + cwd: dir, encoding: 'utf8', timeout: 120_000, env: { ...process.env, NO_COLOR: '1' }, + }); + return { exitCode: res.status ?? 1, output: `${res.stdout ?? ''}${res.stderr ?? ''}` }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +describe('[#32967] os validate refuses what the runtime refuses: the app\'s dashboard on its module\'s dataset', () => { + it('cell 1: HotCRM\'s shape exits 1, naming the dataset, both packages and the move (BASE: exit 0)', () => { + const run = validate(true); + expect(run.exitCode, run.output).toBe(1); + expect(run.output).toContain('widget-dataset-unknown'); + expect(run.output).toContain(DATASET); + expect(run.output).toContain(REV); + expect(run.output).toContain('dependency cycle'); + }, 180_000); + + it('cell 2: the dashboard moved into the module exits 0', () => { + const run = validate(false); + expect(run.exitCode, run.output).toBe(0); + }, 180_000); + + it('M2: a residual top-level dataset leaves the union run unchanged: the module\'s dashboard on its own dataset exits 0', () => { + // The union run carries the app's manifest (the last input's) and, the top level + // holding `datasets`, folds only the bodies' dashboards: judged as the app's, the + // module's own dataset would be outside the app's closure. + const run = validate(false, { residual: true }); + expect(run.exitCode, run.output).toBe(0); + expect(run.output).not.toContain('widget-dataset-unknown'); + }, 180_000); + + it('S1: HotCRM\'s shape with a dependency the artifact does not carry is reported, not refused (exit 0)', () => { + const run = validate(true, { elsewhere: true }); + expect(run.exitCode, run.output).toBe(0); + expect(run.output).toContain('widget-dataset-unknown'); + expect(run.output).toContain(`not judged: it may come from "${ELSEWHERE}"`); + expect(run.output).not.toContain('refused 409'); + }, 180_000); +}); + +async function boot(artifact: unknown, dir: string): Promise { + const artifactPath = join(dir, 'objectstack.json'); + writeBuildShapedArtifact(artifact as Record, artifactPath); + return bootStack(artifact, { + extraPlugins: [new MetadataPlugin({ rootDir: dir, watch: false, artifactWatch: false, registerSystemObjects: false, artifactSource: { mode: 'local-file', path: artifactPath } })], + }); +} + +const codeOf = (b: any) => (b?.error && typeof b.error === 'object' ? b.error.code : undefined) ?? b?.code ?? null; +const messageOf = (b: any) => String((b?.error && typeof b.error === 'object' ? b.error.message : b?.error) ?? b?.message ?? ''); +/** The runtime's refusal names the move beside the dependency (#32929 PR 1). */ +const CYCLE_MOVE = 'the dependency would be a cycle: move what reads it into that package'; + +describe('[#32929] an app package\'s dashboard on its own module\'s dataset (ADR-0150 D3 (c))', () => { + let stack: VerifyStack; + let admin: string; + let dir: string; + const selection = { dimensions: ['category'], measures: ['list_price_sum'] }; + + const query = async (qs: string) => { + const res = await stack.apiAs(admin, 'POST', `/analytics/dataset/query${qs}`, { datasetName: DATASET, selection }); + const text = await res.text(); + let body: any; + try { body = JSON.parse(text); } catch { body = undefined; } + return { status: res.status, text, body }; + }; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'dogfood-app-reads-module-')); + stack = await boot(artifactFor(false), dir); + admin = await stack.signIn(); + for (const [category, list_price] of [['hw', 10], ['sw', 20], ['hw', 5]] as const) { + const res = await stack.apiAs(admin, 'POST', '/data/sib_product', { name: `${category}${list_price}`, category, list_price }); + expect(res.status).toBeLessThan(300); + } + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it('each dashboard is served under its own package, the reader package the console sends', async () => { + for (const [name, pkg] of [['sib_overview', APP], ['sib_rev_dashboard', REV]] as const) { + const res = await stack.apiAs(admin, 'GET', `/meta/dashboard/${name}`); + expect(res.status).toBe(200); + expect(((await res.json()) as any).item._packageId).toBe(pkg); + } + }); + + it('cell 1: the app\'s reader is refused 409 outside-closure, naming the move beside the dependency', async () => { + const door = await query(`?callerPackage=${APP}`); + expect([door.status, codeOf(door.body)], door.text).toEqual([409, 'RESOURCE_CONFLICT']); + expect(messageOf(door.body)).toContain(`The dataset "${DATASET}" is held outside the declared dependency closure of package "${APP}"`); + expect(messageOf(door.body)).toContain(CYCLE_MOVE); + }); + + it('the batch door refuses the same entry in the same words, one entry per query', async () => { + const res = await stack.apiAs(admin, 'POST', `/analytics/dataset/query/batch?callerPackage=${APP}`, { queries: [{ datasetName: DATASET, selection }] }); + expect(res.status).toBe(200); + const [entry] = ((await res.json()) as any).data.results; + expect([entry.status, entry.error.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(entry.error.message).toContain(CYCLE_MOVE); + }); + + it('cell 2: the module\'s own dashboard reads the dataset (200); CONTROL: the bare read is unchanged', async () => { + const own = await query(`?callerPackage=${REV}`); + expect(own.status, own.text).toBe(200); + expect(own.body.rows).toHaveLength(2); + const bare = await query(''); + expect(bare.status, bare.text).toBe(200); + expect(bare.body.rows).toHaveLength(2); + }); +}); + +describe('[#32929] the dependency the old sentence asked for is a cycle the kernel refuses', () => { + it('cell 3: an app package that declares its own module does not boot', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dogfood-app-reads-module-cycle-')); + let booted: VerifyStack | undefined; + try { + await expect((async () => { booted = await boot(artifactFor(true), dir); })()).rejects.toThrow(/Circular dependency detected/); + } finally { + await booted?.stop?.(); + rmSync(dir, { recursive: true, force: true }); + } + }, 300_000); +}); diff --git a/packages/spec/src/migrations/entries/semantic/18.dashboard-dataset-outside-reader-closure-refused.ts b/packages/spec/src/migrations/entries/semantic/18.dashboard-dataset-outside-reader-closure-refused.ts new file mode 100644 index 00000000000..e404e6339e5 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.dashboard-dataset-outside-reader-closure-refused.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// An accept-set narrowing of the authoring doors (#32967, ruling option two on +// #32929): a package's dashboard widget resolves its `dataset` the way the +// dataset doors do since 18.4.0, through the reading package's declared +// dependency closure (ADR-0150 D3 (c)). No D2 conversion: which package a +// dashboard or a dataset belongs to is the author's call. +export const entry: SemanticMigration = { + id: 'dashboard-dataset-outside-reader-closure-refused', + surface: + 'A dashboard widget\'s dataset in one package of a multi-package artifact (composeStacks(stacks, { manifest: ' + + '\'preserve\' }), packages[]) that names a dataset only another package of the artifact holds, when that package ' + + 'is outside the reading package\'s declared dependency closure (manifest.dependencies, transitively, plus sys), ' + + 'or two packages inside that closure hold the name; e.g. an app package\'s dashboard on a dataset its own ' + + 'module holds, the module depending on the app', + replacement: + 'Where the holding package does not depend on the reading package, declare it in the reading package\'s ' + + 'dependencies (ADR-0141). Where it already does (a module of the app), declaring it back is a dependency cycle ' + + 'the kernel refuses at boot: move the dashboard into the holding package, or move the dataset into the reading ' + + 'package. Where two packages of the closure hold the name, keep one dataset by that name, or depend on only ' + + 'one of them. A reading package that declares a dependency the artifact does not carry is reported ' + + '(widget-dataset-unknown, warning), not refused, since that package may hold the name once installed.', + reason: + 'Since 18.4.0 a package\'s dashboard resolves a dataset name in its own package, then in the one holder of its ' + + 'declared dependency closure, and the dataset doors refuse any other read 409 RESOURCE_CONFLICT (ADR-0150 D3 ' + + '(c): the release artifact is the co-ownership boundary, not a resolution scope). The per-package authoring ' + + 'pass of os validate, os build and os lint resolved the name against every package of the artifact (since 18.2.0), ' + + 'so it passed a dashboard the installed runtime refuses to serve. It now asks the runtime\'s question and ' + + 'refuses with widget-dataset-unknown (error). Not convertible: which package a dashboard or a dataset belongs ' + + 'to is a fact only the author holds.', + acceptanceCriteria: + 'os validate and os build run without a widget-dataset-unknown error. Then boot the artifact, open each ' + + 'package\'s dashboard from the Console, and confirm every widget renders its rows rather than a 409 ' + + 'RESOURCE_CONFLICT.', +};