From 52d0d319d52292e5c9da2c8569e1315b571da079 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:14:32 +0000 Subject: [PATCH 1/5] feat(plugins): resolve webhook, connector and email template names through the package-scoped resolver (ADR-0150 E5) Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude --- packages/plugins/plugin-email/package.json | 2 +- .../plugin-email/src/template-loader.ts | 75 +++++++- packages/plugins/plugin-webhooks/package.json | 2 +- .../plugin-webhooks/src/declared-webhooks.ts | 161 +++++++++++++++++- .../services/service-automation/package.json | 2 +- .../src/connector-package-scope.ts | 61 +++++++ .../services/service-automation/src/plugin.ts | 38 +++++ pnpm-lock.yaml | 18 +- 8 files changed, 333 insertions(+), 26 deletions(-) create mode 100644 packages/services/service-automation/src/connector-package-scope.ts diff --git a/packages/plugins/plugin-email/package.json b/packages/plugins/plugin-email/package.json index 4b279612df8..ec2fd77d911 100644 --- a/packages/plugins/plugin-email/package.json +++ b/packages/plugins/plugin-email/package.json @@ -28,12 +28,12 @@ "dependencies": { "@objectstack/core": "workspace:*", "@objectstack/formula": "workspace:*", + "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/spec": "workspace:*", "nodemailer": "^10.1.4" }, "devDependencies": { - "@objectstack/objectql": "workspace:*", "@objectstack/service-queue": "workspace:*", "@objectstack/service-settings": "workspace:*", "@types/node": "^26.6.5", diff --git a/packages/plugins/plugin-email/src/template-loader.ts b/packages/plugins/plugin-email/src/template-loader.ts index 054c9ef7a89..f47430edd88 100644 --- a/packages/plugins/plugin-email/src/template-loader.ts +++ b/packages/plugins/plugin-email/src/template-loader.ts @@ -28,8 +28,28 @@ * Language-only prefix matching (`zh` → `zh-CN`) is deliberately NOT here: no * contract declares it, and inventing it would put a resolution rule in the * code that no spec, doc or form describes. + * + * ## The name rule: `(package, name)` (ADR-0150 D3/D4) + * + * An email template is addressed by `(package, name)`. Before a bundle is + * read, the name is resolved by the ONE package-scoped resolver + * (`resolvePackageScopedName`, `@objectstack/objectql`) over the ObjectQL + * registry, as a caller with no package: `SendTemplateInput` names no + * package, so every send is context-free — the environment's own item, else + * the unique package holder (the built-ins rank below it, ADR-0150 D3 (b)), + * else a refusal naming every candidate, which fails the send + * ({@link EmailTemplateAmbiguousError}). ⛔ Never a first-listed pick. While + * phase 1's one-holder refusal stands (`email_template` is one of its types) + * no two packages hold a name, so every name resolves as before, and the + * layered list below answers the bundle exactly as it did. */ +import { + resolvePackageScopedName, + type PackageScopedHolder, + type PackageScopedRefusal, + type PackageScopedRegistry, +} from '@objectstack/objectql'; import { stripReadDecorations } from '@objectstack/spec/kernel'; import { EmailTemplateDefinitionSchema, type EmailTemplateDefinitionParsed } from '@objectstack/spec/system'; import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow, type TemplateLoader, type TemplateBundleLocales } from './email-service.js'; @@ -42,7 +62,7 @@ import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow export const BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID = 'com.objectstack.service.email'; /** The metadata type the loader reads. */ -const EMAIL_TEMPLATE_TYPE = 'email_template'; +const EMAIL_TEMPLATE_TYPE = 'email_template' as const; /** * The reads {@link createRegistryEmailTemplateLoader} resolves through, looked @@ -58,12 +78,47 @@ export interface EmailTemplateRegistrySources { */ protocol?: { getMetaItemsForExecution(request: { type: string }): Promise<{ items?: unknown[] }> }; /** - * The ObjectQL `SchemaRegistry`. Read ONLY when no `protocol` is - * registered: such a host has no metadata door, so no environment item can - * exist and the code declarations the registry holds are already the - * effective set. + * The ObjectQL `SchemaRegistry`. Its items are read ONLY when no `protocol` + * is registered: such a host has no metadata door, so no environment item + * can exist and the code declarations the registry holds are already the + * effective set. When it carries the package-scoped slice + * ({@link PackageScopedRegistry}), every name is resolved over it first + * (module doc, "The name rule"). */ - registry?: { listItems(type: string): unknown[] }; + registry?: { listItems(type: string): unknown[] } & Partial; +} + +/** + * [ADR-0150 D3, epic #31527 red line 2] A template name that resolves to no + * single template: two packages ship it, and nothing picks one. `code` + + * `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the status + * ADR-0150 D5 gives an ambiguous bare name); `candidates` names every holder, + * and so does the message. + */ +export class EmailTemplateAmbiguousError extends Error { + readonly code = 'RESOURCE_CONFLICT'; + readonly status = 409; + /** The template name. */ + readonly template: string; + /** Every holder of the name, in the resolver's order. */ + readonly candidates: readonly PackageScopedHolder[]; + constructor(refusal: PackageScopedRefusal) { + super(`email template '${refusal.name}' cannot be sent: ${refusal.message}`); + this.name = 'EmailTemplateAmbiguousError'; + this.template = refusal.name; + this.candidates = refusal.candidates; + } +} + +/** The registry, when it carries the slice the package-scoped resolver reads. */ +function packageScopedRegistryOf(registry: EmailTemplateRegistrySources['registry']): PackageScopedRegistry | undefined { + return typeof registry?.packageScopedHoldersOf === 'function' + && typeof registry.getPackageScopedItem === 'function' + && typeof registry.getEnvironmentScopedItem === 'function' + && typeof registry.getPackage === 'function' + && typeof registry.getAllPackages === 'function' + ? (registry as PackageScopedRegistry) + : undefined; } /** An item's locale as the bundle key reads it: the schema default when it declares none. */ @@ -138,6 +193,14 @@ export function createRegistryEmailTemplateLoader( const readBundle = async (name: string): Promise[]> => { const { protocol, registry } = resolveSources() ?? {}; + // [ADR-0150 D3] The name first: a send names no package, so it resolves + // as a caller with no package. A refusal fails the send, naming every + // candidate; any other answer leaves the bundle to the read below. + const scoped = packageScopedRegistryOf(registry); + if (scoped) { + const resolved = resolvePackageScopedName(scoped, { type: EMAIL_TEMPLATE_TYPE, name }); + if (resolved.status === 'refused') throw new EmailTemplateAmbiguousError(resolved); + } let items: unknown[]; if (typeof protocol?.getMetaItemsForExecution === 'function') { const listed = await protocol.getMetaItemsForExecution({ type: EMAIL_TEMPLATE_TYPE }); diff --git a/packages/plugins/plugin-webhooks/package.json b/packages/plugins/plugin-webhooks/package.json index 15e99c53e9a..194684e0e03 100644 --- a/packages/plugins/plugin-webhooks/package.json +++ b/packages/plugins/plugin-webhooks/package.json @@ -37,6 +37,7 @@ }, "dependencies": { "@objectstack/core": "workspace:*", + "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/spec": "workspace:*", @@ -45,7 +46,6 @@ "devDependencies": { "@objectstack/driver-sql": "workspace:*", "@objectstack/metadata-core": "workspace:*", - "@objectstack/objectql": "workspace:*", "@types/node": "^26.6.5", "hono": "^4.13.9", "tsx": "^4.23.15", diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts index 0b503f4a85f..fc716c06c97 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts @@ -33,6 +33,24 @@ * applied, a malformed item skipped with one warning per name per process, * never a crashed refresh. * + * ## One declaration per name, by `(package, name)` (ADR-0150 D3/D4) + * + * A webhook is addressed by `(package, name)`. Which declaration a name + * serves is answered by the ONE package-scoped resolver + * (`resolvePackageScopedName`, `@objectstack/objectql`), never by list order: + * every reader here (the dispatcher, the redelivery veto, the activation door, + * the name guard) is context-free, so it asks as a caller with no package — + * the environment's own item, else the unique package holder, else a refusal + * naming every candidate. A refused name is not dispatched (reported once per + * name per process), and {@link DeclaredWebhookReader.declaredWebhookNamed} + * throws {@link DeclaredWebhookAmbiguousError} for it, so no door reads "not + * declared" for a name two packages declare. While phase 1's one-holder + * refusal stands (`webhook` is one of its types) no two packages hold a name, + * so this answers every name as before. Items the registry does not hold (the + * metadata service's, on a host whose registry holds no webhook) have no + * package coordinate to resolve: one item per name serves, and a name listed + * twice is refused the same way, never first-picked. + * * ## The switch: regime C (ADR-0131 D6) * * A declared webhook is read-only. It is switched on or off for the deployment @@ -78,6 +96,13 @@ import { WebhookSchema, type WebhookParsed } from '@objectstack/spec/automation'; import { METADATA_ACTIVATION_TABLE } from '@objectstack/core'; +import { + packageScopedRefusalMessage, + resolvePackageScopedName, + type PackageScopedHolder, + type PackageScopedRefusal, + type PackageScopedRegistry, +} from '@objectstack/objectql'; /** System read context — the dispatcher reads its own configuration. */ const SYSTEM_CTX = { isSystem: true } as const; @@ -132,10 +157,94 @@ export interface DeclaredWebhook { export interface DeclaredWebhookReader { /** Every valid declaration, each with its switch resolved. */ list(): Promise; - /** The declaration named `name`, switched on or off, or `null` when nothing declares it. */ + /** + * The declaration named `name`, switched on or off, or `null` when nothing + * declares it. Throws {@link DeclaredWebhookAmbiguousError} when the name + * resolves to no single declaration (ADR-0150 D3). + */ declaredWebhookNamed(name: string): Promise; } +/** + * [ADR-0150 D3, epic #31527 red line 2] A declared webhook name that resolves + * to no single declaration: two packages declare it, and nothing picks one. + * `code` + `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the + * catalogue's code for a 409, the status ADR-0150 D5 gives an ambiguous bare + * name); `candidates` names every holder, and so does the message. + */ +export class DeclaredWebhookAmbiguousError extends Error { + readonly code = 'RESOURCE_CONFLICT'; + readonly status = 409; + /** The declared webhook name. */ + readonly webhook: string; + /** Every holder of the name, in the resolver's order. */ + readonly candidates: readonly PackageScopedHolder[]; + constructor(refusal: PackageScopedRefusal) { + super(refusal.message); + this.name = 'DeclaredWebhookAmbiguousError'; + this.webhook = refusal.name; + this.candidates = refusal.candidates; + } +} + +/** The engine's `SchemaRegistry`, when it carries the slice the package-scoped resolver reads. */ +function packageScopedRegistryOf(engine: unknown): PackageScopedRegistry | undefined { + let reg: unknown; + try { + reg = (engine as { _registry?: unknown } | undefined)?._registry; + } catch { + return undefined; + } + const r = reg as Partial> | undefined; + return typeof r?.packageScopedHoldersOf === 'function' + && typeof r.getPackageScopedItem === 'function' + && typeof r.getEnvironmentScopedItem === 'function' + && typeof r.getPackage === 'function' + && typeof r.getAllPackages === 'function' + ? (reg as PackageScopedRegistry) + : undefined; +} + +/** + * Which raw declaration serves `name` (ADR-0150 D3, a caller with no + * package): the resolver's answer when the registry holds the name; else the + * one listed item; else a refusal naming every listed holder. + */ +function chooseDeclaration( + name: string, + listed: readonly unknown[], + registry: PackageScopedRegistry | undefined, +): { item: unknown } | { refusal: PackageScopedRefusal } { + if (registry) { + const resolved = resolvePackageScopedName(registry, { type: 'webhook', name }); + if (resolved.status === 'resolved') return { item: resolved.item }; + if (resolved.status === 'refused') return { refusal: resolved }; + // not-found: the listed items are not the registry's (the metadata service's). + } + if (listed.length === 1) return { item: listed[0] }; + const candidates: PackageScopedHolder[] = []; + const seen = new Set(); + for (const item of listed) { + const pkg = (item as { _packageId?: unknown })?._packageId; + const holder: PackageScopedHolder = typeof pkg === 'string' && pkg !== '' && pkg !== 'sys_metadata' + ? { kind: 'package', packageId: pkg } + : { kind: 'environment' }; + const key = holder.kind === 'package' ? holder.packageId : ''; + if (seen.has(key)) continue; + seen.add(key); + candidates.push(holder); + } + const refusal = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: 'webhook' as const, + name, + callerPackageId: null, + candidates, + }; + return { refusal: { ...refusal, message: packageScopedRefusalMessage(refusal) } }; +} + /** * The raw declared `webhook` items, registry first, metadata service second. * Never throws: a reader that cannot answer yields nothing from that reader. @@ -181,6 +290,10 @@ export function readDeclaredWebhookNames(engine: unknown, metadataService: unkno export class DeclaredWebhookSource implements DeclaredWebhookReader { /** Names already reported as failing validation — said once per process. */ private readonly invalidReported = new Set(); + /** Names already reported as resolving to no single declaration — said once per process. */ + private readonly refusalReported = new Set(); + /** The names the last read refused (ADR-0150 D3), each with its refusal. */ + private refusals = new Map(); constructor( private readonly engine: unknown, @@ -201,13 +314,48 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader { async declaredWebhookNamed(name: string): Promise { if (!name) return null; - return (await this.list()).find((d) => d.webhook.name === name) ?? null; + const declared = await this.list(); + const refusal = this.refusals.get(name); + if (refusal) throw new DeclaredWebhookAmbiguousError(refusal); + return declared.find((d) => d.webhook.name === name) ?? null; } private parseDeclared(): Array<{ webhook: WebhookParsed; packageId?: string }> { const out: Array<{ webhook: WebhookParsed; packageId?: string }> = []; - const seen = new Set(); - for (const raw of readDeclaredWebhookItems(this.engine, this.metadataService)) { + const raws = readDeclaredWebhookItems(this.engine, this.metadataService); + const listedByName = new Map(); + for (const raw of raws) { + const name = (raw as { name?: unknown })?.name; + if (typeof name !== 'string' || name === '') continue; + const listed = listedByName.get(name); + if (listed) listed.push(raw); + else listedByName.set(name, [raw]); + } + const registry = packageScopedRegistryOf(this.engine); + const refusals = new Map(); + const answered = new Set(); + for (const listedRaw of raws) { + let raw = listedRaw; + const listedName = (listedRaw as { name?: unknown })?.name; + // A name serves ONE declaration (ADR-0150 D3): asked once, at its + // first listing; a nameless item goes on to fail validation below. + if (typeof listedName === 'string' && listedName !== '') { + if (answered.has(listedName)) continue; + answered.add(listedName); + const chosen = chooseDeclaration(listedName, listedByName.get(listedName) ?? [listedRaw], registry); + if ('refusal' in chosen) { + refusals.set(listedName, chosen.refusal); + if (!this.refusalReported.has(listedName)) { + this.refusalReported.add(listedName); + this.logger?.warn?.( + `[webhook] declared webhook '${listedName}' is not dispatched: ${chosen.refusal.message}`, + { name: listedName, candidates: chosen.refusal.candidates }, + ); + } + continue; + } + raw = chosen.item; + } let webhook: WebhookParsed; try { webhook = WebhookSchema.parse(raw); @@ -222,13 +370,10 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader { } continue; } - // Two registrations of one name: the first wins, as the seeder's - // name-keyed upsert let the first one hold the row. - if (seen.has(webhook.name)) continue; - seen.add(webhook.name); const pkg = (raw as { _packageId?: unknown })._packageId; out.push({ webhook, ...(typeof pkg === 'string' && pkg ? { packageId: pkg } : {}) }); } + this.refusals = refusals; return out; } } diff --git a/packages/services/service-automation/package.json b/packages/services/service-automation/package.json index 8ff9a0fb62a..a7b520278e0 100644 --- a/packages/services/service-automation/package.json +++ b/packages/services/service-automation/package.json @@ -30,6 +30,7 @@ "@objectstack/formula": "workspace:*", "@objectstack/metadata-core": "workspace:*", "@objectstack/metadata-protocol": "workspace:*", + "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/plugin-auth": "workspace:*", "@objectstack/spec": "workspace:*", @@ -38,7 +39,6 @@ "devDependencies": { "@objectstack/driver-sql": "workspace:*", "@objectstack/metadata-core": "workspace:*", - "@objectstack/objectql": "workspace:*", "@objectstack/plugin-audit": "workspace:*", "@objectstack/plugin-security": "workspace:*", "@objectstack/plugin-sharing": "workspace:*", diff --git a/packages/services/service-automation/src/connector-package-scope.ts b/packages/services/service-automation/src/connector-package-scope.ts new file mode 100644 index 00000000000..d0425f2d56b --- /dev/null +++ b/packages/services/service-automation/src/connector-package-scope.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3/D4, epic #31527 child E5] Which declared connector instance a + * name means — answered by the ONE package-scoped resolver + * (`resolvePackageScopedName`, `@objectstack/objectql`), never by list order. + * + * A connector is addressed by `(package, name)`. The engine keeps one live + * instance per name, and the reconcile that materializes declared instances + * is context-free: it reads the whole environment's declaration, so it asks + * as a caller with no package — the environment's own item, else the unique + * package holder, else a refusal naming every candidate. A refused name is not + * materialized: the reconcile reports the refusal (the boot fails loudly on a + * host-declared entry, as it does for a duplicate name) and tears down what + * it materialized before, so no flow dispatches to one of the candidates on a + * guess. Every other answer leaves the name to the reconcile as it stood. + * + * While phase 1's one-holder refusal stands (`connector` is one of its types) + * no two packages hold a connector name, so this refuses nothing on a booted + * deployment; it is the reader the type's trailing backstop child (ADR-0150 + * D9) narrows that refusal behind. + * + * A connector a plugin registers in code (`engine.registerConnector`) is no + * registry item: the resolver answers not-found for it, and it keeps the + * engine's own ADR-0097 §4 one-origin rule. + */ + +import { + resolvePackageScopedName, + type PackageScopedRefusal, + type PackageScopedRegistry, +} from '@objectstack/objectql'; + +/** The registry, when it carries the slice the package-scoped resolver reads. */ +export function packageScopedRegistryOf(registry: unknown): PackageScopedRegistry | undefined { + const r = registry as Partial> | null | undefined; + return typeof r?.packageScopedHoldersOf === 'function' + && typeof r.getPackageScopedItem === 'function' + && typeof r.getEnvironmentScopedItem === 'function' + && typeof r.getPackage === 'function' + && typeof r.getAllPackages === 'function' + ? (registry as PackageScopedRegistry) + : undefined; +} + +/** + * The refusal of every declared connector name in `names` that resolves to no + * single holder (ADR-0150 D3, a caller with no package), keyed by name. A name + * the resolver answers — or does not hold at all — is absent. + */ +export function refusedConnectorNames( + registry: PackageScopedRegistry, + names: Iterable, +): Map { + const refused = new Map(); + for (const name of new Set(names)) { + const resolved = resolvePackageScopedName(registry, { type: 'connector', name }); + if (resolved.status === 'refused') refused.set(name, resolved); + } + return refused; +} diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 1d4f72bd940..1f859d64735 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -68,6 +68,8 @@ import { } from './connector-credentials.js'; import { CONNECTOR_CREDENTIAL_SOURCE_SERVICE } from '@objectstack/types'; import { createConnectorCredentialSource } from './connector-credential-source.js'; +import { packageScopedRegistryOf, refusedConnectorNames } from './connector-package-scope.js'; +import type { PackageScopedRefusal, PackageScopedRegistry } from '@objectstack/objectql'; import { createConnectorRequestSigner } from './request-signing/index.js'; import { ConnectorConnectionStore, type ConnectorConnectionRecord } from './connector-connections.js'; import { @@ -2594,6 +2596,31 @@ export class AutomationServicePlugin implements Plugin { * `objectql` service is registered: then no door has registered a package * in this kernel either. */ + /** + * [ADR-0150 D3] The refusal of every enabled provider-bound declared + * connector name that resolves to no single holder, read over the ObjectQL + * registry ({@link refusedConnectorNames}). A composition with no registry + * has no package coordinate to resolve against, and refuses nothing here. + */ + private refusedDeclaredConnectorNames(ctx: PluginContext, declared: readonly unknown[]): Map { + let registry: PackageScopedRegistry | undefined; + try { + registry = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry); + } catch { + registry = undefined; // no registry service + } + if (!registry) return new Map(); + const names: string[] = []; + for (const raw of declared) { + const entry = raw as DeclaredConnectorItem; + if (typeof entry?.name !== 'string' || entry.name.length === 0) continue; + if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue; + if (entry.enabled === false) continue; + names.push(entry.name); + } + return refusedConnectorNames(registry, names); + } + private declaringPackageReadersOrNone(ctx: PluginContext): DeclaringPackageReaders | undefined { let ql: { registry?: { @@ -2893,6 +2920,16 @@ export class AutomationServicePlugin implements Plugin { ctx.logger.error(msg, undefined, cause === undefined ? undefined : describeThrownForLog(cause)); }; + // [ADR-0150 D3, epic #31527 child E5] A declared name that resolves to + // no single holder (two packages declare it) is refused, naming every + // candidate, and never materialized: no instance is picked by list + // order ({@link refusedConnectorNames}). + const refusedNames = this.refusedDeclaredConnectorNames(ctx, declared); + for (const [name, refusal] of refusedNames) { + const stored = declared.some((raw) => (raw as DeclaredConnectorItem)?.name === name && storedEntry(raw)); + fail(`[Automation] connector instance '${name}' is not materialized: ${refusal.message}`, undefined, stored); + } + // Build the desired set: enabled provider-bound instances, keyed by name. // A descriptor (no `provider`) or an `enabled: false` instance is not // desired — if we materialized it before, it is torn down below. @@ -2903,6 +2940,7 @@ export class AutomationServicePlugin implements Plugin { if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue; const bound = entry as DeclaredConnectorItem & { name: string; provider: string }; if (bound.enabled === false) continue; + if (refusedNames.has(bound.name)) continue; // [#28713] Held until every plugin has started ({@link holdStoredEntries}). if (this.holdStoredEntries && storedEntry(bound)) { this.storedEntriesHeld = true; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ae1a87a2f3..bcdcc6273b6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2061,6 +2061,9 @@ importers: '@objectstack/formula': specifier: workspace:* version: link:../../formula + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2071,9 +2074,6 @@ importers: specifier: ^10.1.4 version: 10.2.1 devDependencies: - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@objectstack/service-queue': specifier: workspace:* version: link:../../services/service-queue @@ -2270,6 +2270,9 @@ importers: '@objectstack/core': specifier: workspace:* version: link:../../core + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2289,9 +2292,6 @@ importers: '@objectstack/metadata-core': specifier: workspace:* version: link:../../metadata-core - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@types/node': specifier: ^26.6.5 version: 26.6.5 @@ -2801,6 +2801,9 @@ importers: '@objectstack/metadata-protocol': specifier: workspace:* version: link:../../metadata-protocol + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2817,9 +2820,6 @@ importers: '@objectstack/driver-sql': specifier: workspace:* version: link:../../drivers/driver-sql - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@objectstack/plugin-audit': specifier: workspace:* version: link:../../plugins/plugin-audit From 1d4def9d313984e4308b1af6ff4176b3a20f33f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:18:54 +0000 Subject: [PATCH 2/5] test(plugins): pin the package-scoped name refusal for webhooks, connectors and email templates Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude --- .../plugin-email/src/template-loader.test.ts | 44 +++++++++ .../src/declared-webhooks.test.ts | 92 +++++++++++++++++++ .../src/connector-materialization.test.ts | 42 ++++++++- 3 files changed, 177 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-email/src/template-loader.test.ts b/packages/plugins/plugin-email/src/template-loader.test.ts index 30dfa49cd7f..3a4f771f57e 100644 --- a/packages/plugins/plugin-email/src/template-loader.test.ts +++ b/packages/plugins/plugin-email/src/template-loader.test.ts @@ -31,8 +31,10 @@ */ import { describe, expect, it } from 'vitest'; +import { SchemaRegistry } from '@objectstack/objectql'; import { BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID, + EmailTemplateAmbiguousError, createRegistryEmailTemplateLoader, } from './template-loader.js'; @@ -284,3 +286,45 @@ describe('createRegistryEmailTemplateLoader — a malformed item is refused, nev await expect(loader.load('ops.digest', 'en-US')).rejects.toThrow(/ops\.digest/); }); }); + +describe('createRegistryEmailTemplateLoader — the name resolves by (package, name) (ADR-0150 D3)', () => { + const OTHER_PACKAGE = 'com.example.other'; + + /** A real registry: each id installed as a code package, shipping `items` in its composite slot. */ + function registryShipping(shipped: Array<[string, AnyRecord]>): SchemaRegistry { + const reg = new SchemaRegistry(); + reg.logLevel = 'silent'; + for (const [id, item] of shipped) { + if (!reg.getPackage(id)) { + reg.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + } + const { _packageId: _drop, ...body } = item; + reg.registerItem('email_template', body, 'name' as never, id); + } + return reg; + } + + it('one package holder beside the built-in: resolves, and the layered list answers as before', async () => { + const reg = registryShipping([[BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID, builtin()], [APP_PACKAGE, declared()]]); + const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([builtin(), declared()]), registry: reg }); + expect((await loader.load('auth.password_reset', 'en-US'))?.subject).toBe(AUTHORED); + }); + + it('two package holders: the send is refused with the 409 conflict naming both — never the first listed', async () => { + const other = declared({ subject: 'Other wording', _packageId: OTHER_PACKAGE }); + const reg = registryShipping([[APP_PACKAGE, declared()], [OTHER_PACKAGE, other]]); + const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([declared(), other]), registry: reg }); + + const err = await loader.load('auth.password_reset', 'en-US').then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(EmailTemplateAmbiguousError); + expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, template: 'auth.password_reset' }); + expect((err as EmailTemplateAmbiguousError).candidates).toEqual([ + { kind: 'package', packageId: APP_PACKAGE }, + { kind: 'package', packageId: OTHER_PACKAGE }, + ]); + expect((err as Error).message).toContain(`"${APP_PACKAGE}"`); + expect((err as Error).message).toContain(`"${OTHER_PACKAGE}"`); + // No locale escapes it: the name is refused before any bundle is read. + await expect(loader.load('auth.password_reset', undefined)).rejects.toBeInstanceOf(EmailTemplateAmbiguousError); + }); +}); diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts index d50867e133e..ffcec8c32fc 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts @@ -27,10 +27,12 @@ import { describe, expect, it, vi } from 'vitest'; import { AutoEnqueuer, type HttpEnqueueFn } from './auto-enqueuer.js'; import { + DeclaredWebhookAmbiguousError, DeclaredWebhookSource, WEBHOOK_ACTIVATION_TYPE, declaredWebhookRefId, } from './declared-webhooks.js'; +import { SchemaRegistry } from '@objectstack/objectql'; import { createWebhookRedeliverGuard } from './redeliver-guard.js'; import { bindWebhookProvenanceStamp } from './webhook-provenance.js'; import { WebhookOutboxPlugin } from './webhook-outbox-plugin.js'; @@ -609,3 +611,93 @@ describe('declared webhooks — the redelivery veto', () => { expect(await guardFor(engine)({ source: 'webhook', refId: 'whk_seeded' })).toBeUndefined(); }); }); + +// --------------------------------------------------------------------------- +// 4. One declaration per name, by (package, name) — ADR-0150 D3 (epic #31527 child E5) +// --------------------------------------------------------------------------- + +describe('declared webhooks — a name resolves by (package, name) (ADR-0150 D3)', () => { + const A = 'com.acme.alpha'; + const B = 'com.acme.beta'; + + /** A real registry with each id installed as a code package shipping `wh` in its own composite slot. */ + function registryShipping(packages: Array<[string, any]>): SchemaRegistry { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const [id, wh] of packages) { + if (!registry.getPackage(id)) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + } + registry.registerItem('webhook', { ...wh }, 'name' as never, id); + } + return registry; + } + + /** The fake engine, its `_registry` the real one. */ + function engineOver(registry: SchemaRegistry, seed?: { rows?: Record }): FakeEngine { + const engine = newEngine(seed); + Object.defineProperty(engine, '_registry', { get: () => registry }); + return engine; + } + + it('one package holder: the declaration dispatches, carrying its package', async () => { + const engine = engineOver(registryShipping([[A, declaredWebhook()]])); + const source = new DeclaredWebhookSource(engine, undefined); + expect((await source.list()).map((d) => [d.webhook.name, d.packageId])).toEqual([['task_changed', A]]); + expect((await source.declaredWebhookNamed('task_changed'))?.packageId).toBe(A); + + const { enqueuer, realtime, calls } = await startEnqueuer(engine); + await realtime.publish(taskCreated()); + await flush(); + expect(calls).toHaveLength(1); + await enqueuer.stop(); + }); + + it('two package holders: neither is dispatched, and the refusal names both, once', async () => { + const engine = engineOver(registryShipping([ + [A, declaredWebhook({ url: 'https://hooks.example/alpha' })], + [B, declaredWebhook({ url: 'https://hooks.example/beta' })], + ])); + const warn = vi.fn(); + const { enqueuer, realtime, calls, declaredWebhooks } = await startEnqueuer(engine, { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() }); + await realtime.publish(taskCreated()); + await flush(); + expect(calls).toEqual([]); + expect(await declaredWebhooks.list()).toEqual([]); + await enqueuer.stop(); + + const refusals = warn.mock.calls.filter(([msg]) => String(msg).includes(`declared webhook 'task_changed' is not dispatched`)); + expect(refusals).toHaveLength(1); + expect(refusals[0][0]).toContain(`"${A}"`); + expect(refusals[0][0]).toContain(`"${B}"`); + }); + + it('two package holders: the by-name read throws the 409 conflict naming both, never "not declared"', async () => { + const engine = engineOver(registryShipping([[A, declaredWebhook()], [B, declaredWebhook()]])); + const source = new DeclaredWebhookSource(engine, undefined); + const err = await source.declaredWebhookNamed('task_changed').then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(DeclaredWebhookAmbiguousError); + expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, webhook: 'task_changed' }); + expect((err as DeclaredWebhookAmbiguousError).candidates).toEqual([ + { kind: 'package', packageId: A }, + { kind: 'package', packageId: B }, + ]); + + // The redelivery veto propagates it: "we could not check" never reads as "allowed". + const guard = createWebhookRedeliverGuard(engine as any, 'sys_webhook', source); + await expect(guard({ source: 'webhook', refId: declaredWebhookRefId('task_changed') })) + .rejects.toBeInstanceOf(DeclaredWebhookAmbiguousError); + }); + + it('with no registry to resolve against, a name the metadata service lists twice is refused, never first-picked', async () => { + const engine = newEngine(); + const metadata = { + list: (type: string) => (type === 'webhook' + ? [{ ...declaredWebhook(), _packageId: A }, { ...declaredWebhook({ url: 'https://hooks.example/beta' }), _packageId: B }] + : []), + }; + const source = new DeclaredWebhookSource(engine, metadata); + expect(await source.list()).toEqual([]); + await expect(source.declaredWebhookNamed('task_changed')).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + }); +}); diff --git a/packages/services/service-automation/src/connector-materialization.test.ts b/packages/services/service-automation/src/connector-materialization.test.ts index b2489c6b56c..45a3fb631cd 100644 --- a/packages/services/service-automation/src/connector-materialization.test.ts +++ b/packages/services/service-automation/src/connector-materialization.test.ts @@ -29,6 +29,7 @@ import { type CredentialResolver, } from './plugin.js'; import type { AutomationEngine } from './engine.js'; +import { SchemaRegistry } from '@objectstack/objectql'; import { computeAliyunAcs3Signature } from './request-signing/aliyun-acs3-hmac-sha256.js'; import { computeAlipayV3Signature, readAlipayPrivateKey } from './request-signing/alipay-v3.js'; @@ -109,6 +110,11 @@ interface BootOptions { registered?: unknown[]; /** Collects every `logger.error` record the boot writes (#28594: the soft path's record). */ logged?: Array<{ msg: string; meta?: unknown }>; + /** + * A real `SchemaRegistry` to serve as the objectql registry instead of the + * double over `declared` (ADR-0150 E5: the package-scoped resolver reads it). + */ + schemaRegistry?: SchemaRegistry; } /** `SchemaRegistry.getArtifactItem('connector', name, packageId)` over `registered` (#28594). */ @@ -136,7 +142,7 @@ async function boot(declared: unknown[], opts: BootOptions = {}): Promise (type === 'connector' ? declared : []), getPackage: (id: string) => opts.packages?.[id], getArtifactItem: artifactReader(opts.registered), @@ -418,6 +424,40 @@ describe('ADR-0097 — declarative connector materialization', () => { }); }); +describe('ADR-0150 D3 — a declared connector name resolves by (package, name) (epic #31527 child E5)', () => { + const A = 'com.acme.billing_a'; + const B = 'com.acme.billing_b'; + /** A real registry: each id installed as a code package, each shipping `billing` in its own composite slot. */ + function registryShipping(...packageIds: string[]): SchemaRegistry { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of packageIds) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + registry.registerItem('connector', providerConnector('billing', { label: `billing from ${id}` }), 'name' as never, id); + } + return registry; + } + + it('one package holder: the instance materializes, as before', async () => { + const { factory, calls } = makeFakeProvider(); + const kernel = await boot([], { providerFactory: factory, schemaRegistry: registryShipping(A) }); + expect(automationOf(kernel).getRegisteredConnectors()).toContain('billing'); + expect(calls.map((c) => c.label)).toEqual([`billing from ${A}`]); + }); + + it('two package holders: the boot refuses, naming both — no instance is picked by list order', async () => { + const { factory, calls } = makeFakeProvider(); + const err = await boot([], { providerFactory: factory, schemaRegistry: registryShipping(A, B) }).then( + () => undefined, + (e: Error) => e, + ); + expect(err?.message).toContain(`connector instance 'billing' is not materialized`); + expect(err?.message).toContain(`"${A}"`); + expect(err?.message).toContain(`"${B}"`); + expect(calls).toEqual([]); + }); +}); + describe('ADR-0097 — runtime re-materialization on metadata:reloaded (F1)', () => { it('materializes an instance published after boot', async () => { const { factory, calls } = makeClosableProvider(); From da3bc28e72e17d9251cc7378fd216f695707b03e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:20:00 +0000 Subject: [PATCH 3/5] chore(changeset): package-scoped name resolution for webhooks, connectors and email templates Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude --- ...scoped-webhook-connector-email-template.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/31677-package-scoped-webhook-connector-email-template.md diff --git a/.changeset/31677-package-scoped-webhook-connector-email-template.md b/.changeset/31677-package-scoped-webhook-connector-email-template.md new file mode 100644 index 00000000000..99dacd2c188 --- /dev/null +++ b/.changeset/31677-package-scoped-webhook-connector-email-template.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-webhooks': patch +'@objectstack/plugin-email': patch +'@objectstack/service-automation': patch +--- + +feat: webhooks, declared connector instances and email templates resolve their names by (package, name) through the shared package-scoped resolver (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +Which declared webhook a name dispatches, which declared connector instance a name materializes and which email template a send renders are now answered by `resolvePackageScopedName` from `@objectstack/objectql`, never by list order. Every one of these readers is context-free (a send names no package, the dispatcher and the connector reconcile read the whole environment), so each asks as a caller with no package: the environment's own item, else the unique package holder (the email service's built-in templates rank below an app's), else a refusal that names every candidate. + +Who is affected: nobody today. Phase 1's one-holder refusal still holds for all three types, so no two installed packages can ship the same webhook, connector or email template name, and every name resolves exactly as before. Once a type's backstop narrows (its own later release), a name two packages ship is refused instead of silently taking the first one: + +- a declared webhook is not dispatched, the refusal is logged once naming both packages, and the by-name reads (activation door, redelivery veto, name guard) answer a `409 RESOURCE_CONFLICT` naming them instead of "not declared"; +- a declared connector instance is not materialized, and boot fails naming both packages, as it already did for a duplicate instance name; +- an email template send fails with a `409 RESOURCE_CONFLICT` naming both packages. + +The three packages now depend on `@objectstack/objectql` at runtime (it was a dev dependency). From 47f5d0c034546a8f629b5f9cb43761d315203bad Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:46:59 +0000 Subject: [PATCH 4/5] refactor(plugins): narrow this change to declared connector instances The webhook and email template readers leave this change: the webhook half waits on a ruling about names two packages held before phase 1, and the email half waits on the resolver counting a dependent's added locale as a second holder. Both stay recoverable from the previous commit. Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude --- ...1677-package-scoped-connector-instances.md | 14 ++ ...scoped-webhook-connector-email-template.md | 20 --- packages/plugins/plugin-email/package.json | 2 +- .../plugin-email/src/template-loader.test.ts | 44 ----- .../plugin-email/src/template-loader.ts | 75 +------- packages/plugins/plugin-webhooks/package.json | 2 +- .../src/declared-webhooks.test.ts | 92 ---------- .../plugin-webhooks/src/declared-webhooks.ts | 161 +----------------- pnpm-lock.yaml | 12 +- 9 files changed, 36 insertions(+), 386 deletions(-) create mode 100644 .changeset/31677-package-scoped-connector-instances.md delete mode 100644 .changeset/31677-package-scoped-webhook-connector-email-template.md diff --git a/.changeset/31677-package-scoped-connector-instances.md b/.changeset/31677-package-scoped-connector-instances.md new file mode 100644 index 00000000000..77f72d632c1 --- /dev/null +++ b/.changeset/31677-package-scoped-connector-instances.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-automation': patch +--- + +feat: a declared connector instance's name resolves by (package, name) through the shared package-scoped resolver (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +Which declared connector instance a name materializes is now answered by `resolvePackageScopedName` from `@objectstack/objectql`, never by list order. The connector reconcile reads the whole environment's declaration, so it asks as a caller with no package: the environment's own item, else the unique package holder, else a refusal that names every candidate. + +Who is affected: nobody today. Phase 1's one-holder refusal still holds for `connector`, so no two installed packages can ship the same connector instance name, and every name resolves exactly as before. Once that backstop narrows (its own later release), a name two packages ship is not materialized, and boot fails naming both packages, as it already did for a duplicate instance name (which named no candidates). + +`@objectstack/service-automation` now depends on `@objectstack/objectql` at runtime (it was a dev dependency). diff --git a/.changeset/31677-package-scoped-webhook-connector-email-template.md b/.changeset/31677-package-scoped-webhook-connector-email-template.md deleted file mode 100644 index 99dacd2c188..00000000000 --- a/.changeset/31677-package-scoped-webhook-connector-email-template.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -'@objectstack/plugin-webhooks': patch -'@objectstack/plugin-email': patch -'@objectstack/service-automation': patch ---- - -feat: webhooks, declared connector instances and email templates resolve their names by (package, name) through the shared package-scoped resolver (ADR-0150 D3/D4) - -Clause-②: no -Metadata-protocol: none - -Which declared webhook a name dispatches, which declared connector instance a name materializes and which email template a send renders are now answered by `resolvePackageScopedName` from `@objectstack/objectql`, never by list order. Every one of these readers is context-free (a send names no package, the dispatcher and the connector reconcile read the whole environment), so each asks as a caller with no package: the environment's own item, else the unique package holder (the email service's built-in templates rank below an app's), else a refusal that names every candidate. - -Who is affected: nobody today. Phase 1's one-holder refusal still holds for all three types, so no two installed packages can ship the same webhook, connector or email template name, and every name resolves exactly as before. Once a type's backstop narrows (its own later release), a name two packages ship is refused instead of silently taking the first one: - -- a declared webhook is not dispatched, the refusal is logged once naming both packages, and the by-name reads (activation door, redelivery veto, name guard) answer a `409 RESOURCE_CONFLICT` naming them instead of "not declared"; -- a declared connector instance is not materialized, and boot fails naming both packages, as it already did for a duplicate instance name; -- an email template send fails with a `409 RESOURCE_CONFLICT` naming both packages. - -The three packages now depend on `@objectstack/objectql` at runtime (it was a dev dependency). diff --git a/packages/plugins/plugin-email/package.json b/packages/plugins/plugin-email/package.json index ec2fd77d911..4b279612df8 100644 --- a/packages/plugins/plugin-email/package.json +++ b/packages/plugins/plugin-email/package.json @@ -28,12 +28,12 @@ "dependencies": { "@objectstack/core": "workspace:*", "@objectstack/formula": "workspace:*", - "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/spec": "workspace:*", "nodemailer": "^10.1.4" }, "devDependencies": { + "@objectstack/objectql": "workspace:*", "@objectstack/service-queue": "workspace:*", "@objectstack/service-settings": "workspace:*", "@types/node": "^26.6.5", diff --git a/packages/plugins/plugin-email/src/template-loader.test.ts b/packages/plugins/plugin-email/src/template-loader.test.ts index 3a4f771f57e..30dfa49cd7f 100644 --- a/packages/plugins/plugin-email/src/template-loader.test.ts +++ b/packages/plugins/plugin-email/src/template-loader.test.ts @@ -31,10 +31,8 @@ */ import { describe, expect, it } from 'vitest'; -import { SchemaRegistry } from '@objectstack/objectql'; import { BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID, - EmailTemplateAmbiguousError, createRegistryEmailTemplateLoader, } from './template-loader.js'; @@ -286,45 +284,3 @@ describe('createRegistryEmailTemplateLoader — a malformed item is refused, nev await expect(loader.load('ops.digest', 'en-US')).rejects.toThrow(/ops\.digest/); }); }); - -describe('createRegistryEmailTemplateLoader — the name resolves by (package, name) (ADR-0150 D3)', () => { - const OTHER_PACKAGE = 'com.example.other'; - - /** A real registry: each id installed as a code package, shipping `items` in its composite slot. */ - function registryShipping(shipped: Array<[string, AnyRecord]>): SchemaRegistry { - const reg = new SchemaRegistry(); - reg.logLevel = 'silent'; - for (const [id, item] of shipped) { - if (!reg.getPackage(id)) { - reg.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); - } - const { _packageId: _drop, ...body } = item; - reg.registerItem('email_template', body, 'name' as never, id); - } - return reg; - } - - it('one package holder beside the built-in: resolves, and the layered list answers as before', async () => { - const reg = registryShipping([[BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID, builtin()], [APP_PACKAGE, declared()]]); - const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([builtin(), declared()]), registry: reg }); - expect((await loader.load('auth.password_reset', 'en-US'))?.subject).toBe(AUTHORED); - }); - - it('two package holders: the send is refused with the 409 conflict naming both — never the first listed', async () => { - const other = declared({ subject: 'Other wording', _packageId: OTHER_PACKAGE }); - const reg = registryShipping([[APP_PACKAGE, declared()], [OTHER_PACKAGE, other]]); - const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([declared(), other]), registry: reg }); - - const err = await loader.load('auth.password_reset', 'en-US').then(() => undefined, (e: unknown) => e); - expect(err).toBeInstanceOf(EmailTemplateAmbiguousError); - expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, template: 'auth.password_reset' }); - expect((err as EmailTemplateAmbiguousError).candidates).toEqual([ - { kind: 'package', packageId: APP_PACKAGE }, - { kind: 'package', packageId: OTHER_PACKAGE }, - ]); - expect((err as Error).message).toContain(`"${APP_PACKAGE}"`); - expect((err as Error).message).toContain(`"${OTHER_PACKAGE}"`); - // No locale escapes it: the name is refused before any bundle is read. - await expect(loader.load('auth.password_reset', undefined)).rejects.toBeInstanceOf(EmailTemplateAmbiguousError); - }); -}); diff --git a/packages/plugins/plugin-email/src/template-loader.ts b/packages/plugins/plugin-email/src/template-loader.ts index f47430edd88..054c9ef7a89 100644 --- a/packages/plugins/plugin-email/src/template-loader.ts +++ b/packages/plugins/plugin-email/src/template-loader.ts @@ -28,28 +28,8 @@ * Language-only prefix matching (`zh` → `zh-CN`) is deliberately NOT here: no * contract declares it, and inventing it would put a resolution rule in the * code that no spec, doc or form describes. - * - * ## The name rule: `(package, name)` (ADR-0150 D3/D4) - * - * An email template is addressed by `(package, name)`. Before a bundle is - * read, the name is resolved by the ONE package-scoped resolver - * (`resolvePackageScopedName`, `@objectstack/objectql`) over the ObjectQL - * registry, as a caller with no package: `SendTemplateInput` names no - * package, so every send is context-free — the environment's own item, else - * the unique package holder (the built-ins rank below it, ADR-0150 D3 (b)), - * else a refusal naming every candidate, which fails the send - * ({@link EmailTemplateAmbiguousError}). ⛔ Never a first-listed pick. While - * phase 1's one-holder refusal stands (`email_template` is one of its types) - * no two packages hold a name, so every name resolves as before, and the - * layered list below answers the bundle exactly as it did. */ -import { - resolvePackageScopedName, - type PackageScopedHolder, - type PackageScopedRefusal, - type PackageScopedRegistry, -} from '@objectstack/objectql'; import { stripReadDecorations } from '@objectstack/spec/kernel'; import { EmailTemplateDefinitionSchema, type EmailTemplateDefinitionParsed } from '@objectstack/spec/system'; import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow, type TemplateLoader, type TemplateBundleLocales } from './email-service.js'; @@ -62,7 +42,7 @@ import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow export const BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID = 'com.objectstack.service.email'; /** The metadata type the loader reads. */ -const EMAIL_TEMPLATE_TYPE = 'email_template' as const; +const EMAIL_TEMPLATE_TYPE = 'email_template'; /** * The reads {@link createRegistryEmailTemplateLoader} resolves through, looked @@ -78,47 +58,12 @@ export interface EmailTemplateRegistrySources { */ protocol?: { getMetaItemsForExecution(request: { type: string }): Promise<{ items?: unknown[] }> }; /** - * The ObjectQL `SchemaRegistry`. Its items are read ONLY when no `protocol` - * is registered: such a host has no metadata door, so no environment item - * can exist and the code declarations the registry holds are already the - * effective set. When it carries the package-scoped slice - * ({@link PackageScopedRegistry}), every name is resolved over it first - * (module doc, "The name rule"). + * The ObjectQL `SchemaRegistry`. Read ONLY when no `protocol` is + * registered: such a host has no metadata door, so no environment item can + * exist and the code declarations the registry holds are already the + * effective set. */ - registry?: { listItems(type: string): unknown[] } & Partial; -} - -/** - * [ADR-0150 D3, epic #31527 red line 2] A template name that resolves to no - * single template: two packages ship it, and nothing picks one. `code` + - * `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the status - * ADR-0150 D5 gives an ambiguous bare name); `candidates` names every holder, - * and so does the message. - */ -export class EmailTemplateAmbiguousError extends Error { - readonly code = 'RESOURCE_CONFLICT'; - readonly status = 409; - /** The template name. */ - readonly template: string; - /** Every holder of the name, in the resolver's order. */ - readonly candidates: readonly PackageScopedHolder[]; - constructor(refusal: PackageScopedRefusal) { - super(`email template '${refusal.name}' cannot be sent: ${refusal.message}`); - this.name = 'EmailTemplateAmbiguousError'; - this.template = refusal.name; - this.candidates = refusal.candidates; - } -} - -/** The registry, when it carries the slice the package-scoped resolver reads. */ -function packageScopedRegistryOf(registry: EmailTemplateRegistrySources['registry']): PackageScopedRegistry | undefined { - return typeof registry?.packageScopedHoldersOf === 'function' - && typeof registry.getPackageScopedItem === 'function' - && typeof registry.getEnvironmentScopedItem === 'function' - && typeof registry.getPackage === 'function' - && typeof registry.getAllPackages === 'function' - ? (registry as PackageScopedRegistry) - : undefined; + registry?: { listItems(type: string): unknown[] }; } /** An item's locale as the bundle key reads it: the schema default when it declares none. */ @@ -193,14 +138,6 @@ export function createRegistryEmailTemplateLoader( const readBundle = async (name: string): Promise[]> => { const { protocol, registry } = resolveSources() ?? {}; - // [ADR-0150 D3] The name first: a send names no package, so it resolves - // as a caller with no package. A refusal fails the send, naming every - // candidate; any other answer leaves the bundle to the read below. - const scoped = packageScopedRegistryOf(registry); - if (scoped) { - const resolved = resolvePackageScopedName(scoped, { type: EMAIL_TEMPLATE_TYPE, name }); - if (resolved.status === 'refused') throw new EmailTemplateAmbiguousError(resolved); - } let items: unknown[]; if (typeof protocol?.getMetaItemsForExecution === 'function') { const listed = await protocol.getMetaItemsForExecution({ type: EMAIL_TEMPLATE_TYPE }); diff --git a/packages/plugins/plugin-webhooks/package.json b/packages/plugins/plugin-webhooks/package.json index 194684e0e03..15e99c53e9a 100644 --- a/packages/plugins/plugin-webhooks/package.json +++ b/packages/plugins/plugin-webhooks/package.json @@ -37,7 +37,6 @@ }, "dependencies": { "@objectstack/core": "workspace:*", - "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/spec": "workspace:*", @@ -46,6 +45,7 @@ "devDependencies": { "@objectstack/driver-sql": "workspace:*", "@objectstack/metadata-core": "workspace:*", + "@objectstack/objectql": "workspace:*", "@types/node": "^26.6.5", "hono": "^4.13.9", "tsx": "^4.23.15", diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts index ffcec8c32fc..d50867e133e 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts @@ -27,12 +27,10 @@ import { describe, expect, it, vi } from 'vitest'; import { AutoEnqueuer, type HttpEnqueueFn } from './auto-enqueuer.js'; import { - DeclaredWebhookAmbiguousError, DeclaredWebhookSource, WEBHOOK_ACTIVATION_TYPE, declaredWebhookRefId, } from './declared-webhooks.js'; -import { SchemaRegistry } from '@objectstack/objectql'; import { createWebhookRedeliverGuard } from './redeliver-guard.js'; import { bindWebhookProvenanceStamp } from './webhook-provenance.js'; import { WebhookOutboxPlugin } from './webhook-outbox-plugin.js'; @@ -611,93 +609,3 @@ describe('declared webhooks — the redelivery veto', () => { expect(await guardFor(engine)({ source: 'webhook', refId: 'whk_seeded' })).toBeUndefined(); }); }); - -// --------------------------------------------------------------------------- -// 4. One declaration per name, by (package, name) — ADR-0150 D3 (epic #31527 child E5) -// --------------------------------------------------------------------------- - -describe('declared webhooks — a name resolves by (package, name) (ADR-0150 D3)', () => { - const A = 'com.acme.alpha'; - const B = 'com.acme.beta'; - - /** A real registry with each id installed as a code package shipping `wh` in its own composite slot. */ - function registryShipping(packages: Array<[string, any]>): SchemaRegistry { - const registry = new SchemaRegistry(); - registry.logLevel = 'silent'; - for (const [id, wh] of packages) { - if (!registry.getPackage(id)) { - registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); - } - registry.registerItem('webhook', { ...wh }, 'name' as never, id); - } - return registry; - } - - /** The fake engine, its `_registry` the real one. */ - function engineOver(registry: SchemaRegistry, seed?: { rows?: Record }): FakeEngine { - const engine = newEngine(seed); - Object.defineProperty(engine, '_registry', { get: () => registry }); - return engine; - } - - it('one package holder: the declaration dispatches, carrying its package', async () => { - const engine = engineOver(registryShipping([[A, declaredWebhook()]])); - const source = new DeclaredWebhookSource(engine, undefined); - expect((await source.list()).map((d) => [d.webhook.name, d.packageId])).toEqual([['task_changed', A]]); - expect((await source.declaredWebhookNamed('task_changed'))?.packageId).toBe(A); - - const { enqueuer, realtime, calls } = await startEnqueuer(engine); - await realtime.publish(taskCreated()); - await flush(); - expect(calls).toHaveLength(1); - await enqueuer.stop(); - }); - - it('two package holders: neither is dispatched, and the refusal names both, once', async () => { - const engine = engineOver(registryShipping([ - [A, declaredWebhook({ url: 'https://hooks.example/alpha' })], - [B, declaredWebhook({ url: 'https://hooks.example/beta' })], - ])); - const warn = vi.fn(); - const { enqueuer, realtime, calls, declaredWebhooks } = await startEnqueuer(engine, { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() }); - await realtime.publish(taskCreated()); - await flush(); - expect(calls).toEqual([]); - expect(await declaredWebhooks.list()).toEqual([]); - await enqueuer.stop(); - - const refusals = warn.mock.calls.filter(([msg]) => String(msg).includes(`declared webhook 'task_changed' is not dispatched`)); - expect(refusals).toHaveLength(1); - expect(refusals[0][0]).toContain(`"${A}"`); - expect(refusals[0][0]).toContain(`"${B}"`); - }); - - it('two package holders: the by-name read throws the 409 conflict naming both, never "not declared"', async () => { - const engine = engineOver(registryShipping([[A, declaredWebhook()], [B, declaredWebhook()]])); - const source = new DeclaredWebhookSource(engine, undefined); - const err = await source.declaredWebhookNamed('task_changed').then(() => undefined, (e: unknown) => e); - expect(err).toBeInstanceOf(DeclaredWebhookAmbiguousError); - expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, webhook: 'task_changed' }); - expect((err as DeclaredWebhookAmbiguousError).candidates).toEqual([ - { kind: 'package', packageId: A }, - { kind: 'package', packageId: B }, - ]); - - // The redelivery veto propagates it: "we could not check" never reads as "allowed". - const guard = createWebhookRedeliverGuard(engine as any, 'sys_webhook', source); - await expect(guard({ source: 'webhook', refId: declaredWebhookRefId('task_changed') })) - .rejects.toBeInstanceOf(DeclaredWebhookAmbiguousError); - }); - - it('with no registry to resolve against, a name the metadata service lists twice is refused, never first-picked', async () => { - const engine = newEngine(); - const metadata = { - list: (type: string) => (type === 'webhook' - ? [{ ...declaredWebhook(), _packageId: A }, { ...declaredWebhook({ url: 'https://hooks.example/beta' }), _packageId: B }] - : []), - }; - const source = new DeclaredWebhookSource(engine, metadata); - expect(await source.list()).toEqual([]); - await expect(source.declaredWebhookNamed('task_changed')).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); - }); -}); diff --git a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts index fc716c06c97..0b503f4a85f 100644 --- a/packages/plugins/plugin-webhooks/src/declared-webhooks.ts +++ b/packages/plugins/plugin-webhooks/src/declared-webhooks.ts @@ -33,24 +33,6 @@ * applied, a malformed item skipped with one warning per name per process, * never a crashed refresh. * - * ## One declaration per name, by `(package, name)` (ADR-0150 D3/D4) - * - * A webhook is addressed by `(package, name)`. Which declaration a name - * serves is answered by the ONE package-scoped resolver - * (`resolvePackageScopedName`, `@objectstack/objectql`), never by list order: - * every reader here (the dispatcher, the redelivery veto, the activation door, - * the name guard) is context-free, so it asks as a caller with no package — - * the environment's own item, else the unique package holder, else a refusal - * naming every candidate. A refused name is not dispatched (reported once per - * name per process), and {@link DeclaredWebhookReader.declaredWebhookNamed} - * throws {@link DeclaredWebhookAmbiguousError} for it, so no door reads "not - * declared" for a name two packages declare. While phase 1's one-holder - * refusal stands (`webhook` is one of its types) no two packages hold a name, - * so this answers every name as before. Items the registry does not hold (the - * metadata service's, on a host whose registry holds no webhook) have no - * package coordinate to resolve: one item per name serves, and a name listed - * twice is refused the same way, never first-picked. - * * ## The switch: regime C (ADR-0131 D6) * * A declared webhook is read-only. It is switched on or off for the deployment @@ -96,13 +78,6 @@ import { WebhookSchema, type WebhookParsed } from '@objectstack/spec/automation'; import { METADATA_ACTIVATION_TABLE } from '@objectstack/core'; -import { - packageScopedRefusalMessage, - resolvePackageScopedName, - type PackageScopedHolder, - type PackageScopedRefusal, - type PackageScopedRegistry, -} from '@objectstack/objectql'; /** System read context — the dispatcher reads its own configuration. */ const SYSTEM_CTX = { isSystem: true } as const; @@ -157,94 +132,10 @@ export interface DeclaredWebhook { export interface DeclaredWebhookReader { /** Every valid declaration, each with its switch resolved. */ list(): Promise; - /** - * The declaration named `name`, switched on or off, or `null` when nothing - * declares it. Throws {@link DeclaredWebhookAmbiguousError} when the name - * resolves to no single declaration (ADR-0150 D3). - */ + /** The declaration named `name`, switched on or off, or `null` when nothing declares it. */ declaredWebhookNamed(name: string): Promise; } -/** - * [ADR-0150 D3, epic #31527 red line 2] A declared webhook name that resolves - * to no single declaration: two packages declare it, and nothing picks one. - * `code` + `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the - * catalogue's code for a 409, the status ADR-0150 D5 gives an ambiguous bare - * name); `candidates` names every holder, and so does the message. - */ -export class DeclaredWebhookAmbiguousError extends Error { - readonly code = 'RESOURCE_CONFLICT'; - readonly status = 409; - /** The declared webhook name. */ - readonly webhook: string; - /** Every holder of the name, in the resolver's order. */ - readonly candidates: readonly PackageScopedHolder[]; - constructor(refusal: PackageScopedRefusal) { - super(refusal.message); - this.name = 'DeclaredWebhookAmbiguousError'; - this.webhook = refusal.name; - this.candidates = refusal.candidates; - } -} - -/** The engine's `SchemaRegistry`, when it carries the slice the package-scoped resolver reads. */ -function packageScopedRegistryOf(engine: unknown): PackageScopedRegistry | undefined { - let reg: unknown; - try { - reg = (engine as { _registry?: unknown } | undefined)?._registry; - } catch { - return undefined; - } - const r = reg as Partial> | undefined; - return typeof r?.packageScopedHoldersOf === 'function' - && typeof r.getPackageScopedItem === 'function' - && typeof r.getEnvironmentScopedItem === 'function' - && typeof r.getPackage === 'function' - && typeof r.getAllPackages === 'function' - ? (reg as PackageScopedRegistry) - : undefined; -} - -/** - * Which raw declaration serves `name` (ADR-0150 D3, a caller with no - * package): the resolver's answer when the registry holds the name; else the - * one listed item; else a refusal naming every listed holder. - */ -function chooseDeclaration( - name: string, - listed: readonly unknown[], - registry: PackageScopedRegistry | undefined, -): { item: unknown } | { refusal: PackageScopedRefusal } { - if (registry) { - const resolved = resolvePackageScopedName(registry, { type: 'webhook', name }); - if (resolved.status === 'resolved') return { item: resolved.item }; - if (resolved.status === 'refused') return { refusal: resolved }; - // not-found: the listed items are not the registry's (the metadata service's). - } - if (listed.length === 1) return { item: listed[0] }; - const candidates: PackageScopedHolder[] = []; - const seen = new Set(); - for (const item of listed) { - const pkg = (item as { _packageId?: unknown })?._packageId; - const holder: PackageScopedHolder = typeof pkg === 'string' && pkg !== '' && pkg !== 'sys_metadata' - ? { kind: 'package', packageId: pkg } - : { kind: 'environment' }; - const key = holder.kind === 'package' ? holder.packageId : ''; - if (seen.has(key)) continue; - seen.add(key); - candidates.push(holder); - } - const refusal = { - status: 'refused' as const, - reason: 'ambiguous-in-environment' as const, - type: 'webhook' as const, - name, - callerPackageId: null, - candidates, - }; - return { refusal: { ...refusal, message: packageScopedRefusalMessage(refusal) } }; -} - /** * The raw declared `webhook` items, registry first, metadata service second. * Never throws: a reader that cannot answer yields nothing from that reader. @@ -290,10 +181,6 @@ export function readDeclaredWebhookNames(engine: unknown, metadataService: unkno export class DeclaredWebhookSource implements DeclaredWebhookReader { /** Names already reported as failing validation — said once per process. */ private readonly invalidReported = new Set(); - /** Names already reported as resolving to no single declaration — said once per process. */ - private readonly refusalReported = new Set(); - /** The names the last read refused (ADR-0150 D3), each with its refusal. */ - private refusals = new Map(); constructor( private readonly engine: unknown, @@ -314,48 +201,13 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader { async declaredWebhookNamed(name: string): Promise { if (!name) return null; - const declared = await this.list(); - const refusal = this.refusals.get(name); - if (refusal) throw new DeclaredWebhookAmbiguousError(refusal); - return declared.find((d) => d.webhook.name === name) ?? null; + return (await this.list()).find((d) => d.webhook.name === name) ?? null; } private parseDeclared(): Array<{ webhook: WebhookParsed; packageId?: string }> { const out: Array<{ webhook: WebhookParsed; packageId?: string }> = []; - const raws = readDeclaredWebhookItems(this.engine, this.metadataService); - const listedByName = new Map(); - for (const raw of raws) { - const name = (raw as { name?: unknown })?.name; - if (typeof name !== 'string' || name === '') continue; - const listed = listedByName.get(name); - if (listed) listed.push(raw); - else listedByName.set(name, [raw]); - } - const registry = packageScopedRegistryOf(this.engine); - const refusals = new Map(); - const answered = new Set(); - for (const listedRaw of raws) { - let raw = listedRaw; - const listedName = (listedRaw as { name?: unknown })?.name; - // A name serves ONE declaration (ADR-0150 D3): asked once, at its - // first listing; a nameless item goes on to fail validation below. - if (typeof listedName === 'string' && listedName !== '') { - if (answered.has(listedName)) continue; - answered.add(listedName); - const chosen = chooseDeclaration(listedName, listedByName.get(listedName) ?? [listedRaw], registry); - if ('refusal' in chosen) { - refusals.set(listedName, chosen.refusal); - if (!this.refusalReported.has(listedName)) { - this.refusalReported.add(listedName); - this.logger?.warn?.( - `[webhook] declared webhook '${listedName}' is not dispatched: ${chosen.refusal.message}`, - { name: listedName, candidates: chosen.refusal.candidates }, - ); - } - continue; - } - raw = chosen.item; - } + const seen = new Set(); + for (const raw of readDeclaredWebhookItems(this.engine, this.metadataService)) { let webhook: WebhookParsed; try { webhook = WebhookSchema.parse(raw); @@ -370,10 +222,13 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader { } continue; } + // Two registrations of one name: the first wins, as the seeder's + // name-keyed upsert let the first one hold the row. + if (seen.has(webhook.name)) continue; + seen.add(webhook.name); const pkg = (raw as { _packageId?: unknown })._packageId; out.push({ webhook, ...(typeof pkg === 'string' && pkg ? { packageId: pkg } : {}) }); } - this.refusals = refusals; return out; } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bcdcc6273b6..c54d8102e75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2061,9 +2061,6 @@ importers: '@objectstack/formula': specifier: workspace:* version: link:../../formula - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2074,6 +2071,9 @@ importers: specifier: ^10.1.4 version: 10.2.1 devDependencies: + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@objectstack/service-queue': specifier: workspace:* version: link:../../services/service-queue @@ -2270,9 +2270,6 @@ importers: '@objectstack/core': specifier: workspace:* version: link:../../core - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2292,6 +2289,9 @@ importers: '@objectstack/metadata-core': specifier: workspace:* version: link:../../metadata-core + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@types/node': specifier: ^26.6.5 version: 26.6.5 From 785a7428c169810953a4d75e71f91e848409c6d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:19:51 +0000 Subject: [PATCH 5/5] docs(service-automation): keep each connector reader's JSDoc on its own method Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude --- .../services/service-automation/src/plugin.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 1f859d64735..2ff161ede91 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2588,14 +2588,6 @@ export class AutomationServicePlugin implements Plugin { this.reloadedConnectors = { items, owners }; } - /** - * [#28534] The readers {@link nonHostDeclaringPackageOf} judges a - * connector entry's origin with, off the `objectql` engine the declared - * items are listed out of ({@link readDeclaredConnectorItems}): its package - * registry's rows and its residual-owner record. `undefined` when no - * `objectql` service is registered: then no door has registered a package - * in this kernel either. - */ /** * [ADR-0150 D3] The refusal of every enabled provider-bound declared * connector name that resolves to no single holder, read over the ObjectQL @@ -2621,6 +2613,14 @@ export class AutomationServicePlugin implements Plugin { return refusedConnectorNames(registry, names); } + /** + * [#28534] The readers {@link nonHostDeclaringPackageOf} judges a + * connector entry's origin with, off the `objectql` engine the declared + * items are listed out of ({@link readDeclaredConnectorItems}): its package + * registry's rows and its residual-owner record. `undefined` when no + * `objectql` service is registered: then no door has registered a package + * in this kernel either. + */ private declaringPackageReadersOrNone(ctx: PluginContext): DeclaringPackageReaders | undefined { let ql: { registry?: {