Skip to content

Commit 43fb482

Browse files
feat(plugin-sharing)!: declared sharing rules, queues and assignment rules resolve on (package, name) (#31728)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi99JCJQQzUUHvZbCS5kKcE7Y)_ Fixes #31675 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: follow-up #31735 Narrowing: (1) a bare name of a sharing rule, queue or assignment rule that two packages declare is refused, naming both (first-party: 0 names held twice); (2) a package item's bare reference whose only holder is an environment-authored item, D3 (a) (first-party: 0); (3) a package caller's bare reference whose one holder is a package outside its declared closure, per the epic seat's reading 6728487836 (first-party: 0). Sibling in the same release artifact: 0. The one package-written reference these reads carry is a declared sharing rule's queue recipient, and no first-party package declares a queue recipient or a queue. (4) The standing grants of a declared sharing rule name two packages hold are revoked by the boot orphan sweep, reported as that refusal (#31677 Q1 ruling A); reachable only through a sealed clash from before phase 1 (first-party: 0). ## 维护者速读 - 改了什么:共享插件里按名字读「声明的共享规则、队列、分配规则」的地方,全部改走 objectql 的同一个包寻址解析器。一个名字只有一个包声明时,答案和以前完全一样;两个包声明同名时,不再悄悄取第一个(`queuesOf` 原来取最后一个),而是拒绝并列出两个包。声明的共享规则把队列当接收方时,从规则所在的包去解析:本包的队列或它声明依赖的包的队列,范围外或只有环境项持有就拒绝并点名。 - 为什么改:专题 #31527 的子卡 E4(ADR-0150 D3/D4)。两个包同名时取哪个取决于注册顺序,授权和派单因此可能落到错误的包上,而且没有任何提示。 - 风险与回滚:只有「已安装两个包声明同名共享规则/队列/分配规则」的部署会看到变化:那个名字不再生效,日志 warn 一次,按名查询返回 409 列出两个包。第一方实测 0 个。组织自建的 `sys_queue`、`sys_sharing_rule`、`sys_assignment_rule` 行行为不变。回滚即 revert 本 PR。 - 先看:`packages/plugins/plugin-sharing/src/package-scoped-declarations.ts`(唯一的入口,读 R 的解析器);`ownership-queue-service.ts` 的 `resolve` / `declaredQueueNamed` / `activeDeclaredQueues`;`sharing-rule-service.ts` 的 `assertQueueRecipientReachable`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-sharing exec vitest run src/package-scoped-declarations.test.ts`,预期 17 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes Every read in `plugin-sharing` that picks a declared sharing rule, queue or assignment rule by bare name now goes through one module, `package-scoped-declarations.ts`. That module reads objectql's `resolvePackageScopedName` (child R) and resolves nothing itself: no first-registered fallback, no pick. - **The population is the listing.** The names asked about are the items `listItems(type)` lists, which hides a disabled package's items, as every one of these readers did before. One listed item of a name is that item, so there is nothing to choose. Two or more go to the resolver as a caller with no package. These reads are the platform enumerating its declarations and the Setup doors that switch or guard them, and none of them belongs to a package (ADR-0150 D3). A registry without the package-scoped slice (the kernel `metadata` service fallback on a registry-less host) gets no pick either: two holders listed means a refusal naming them. - **Declared sharing rules** (`declared-sharing-rules.ts`): `list()` serves one rule per name through the module. The old one-rule-per-name skip kept the first holder silently, on the stated premise that the registry refuses a second holder, which is false for this uncovered type. A refused name serves nothing and is logged once at `warn`, naming both packages. Its grants carry the bare name, so serving either holder would grant on a guess; the grants it already has are revoked by the boot orphan sweep and reported as that refusal, naming both. New `lookup(name)` on the source; `SharingRuleService.declaredRuleNamed` reads it and throws `PackageScopedNameRefusedError` (`409 RESOURCE_CONFLICT`, every candidate named) on a refusal. That covers the name guard on `sys_sharing_rule` writes (the name stays taken), `defineRule`, the activation door's lookup, and `getRule` / `resolveRules` by name (a refusal, never a misleading 404). - **Queues** (`ownership-queue-service.ts`): `resolve` (so `resolveQueue`, `expandMembers`, `isMember`), `declaredQueueNamed` (the activation door's lookup), and `activeDeclaredQueues` (so `queuesOf`, `hasAnyQueue`, `queuesNaming`) go through the module. A refused name resolves nowhere for a `nobody` consumer, which denies. For a `refuse` consumer it rejects with the resolver's refusal, passed through unwrapped. It stays a declared name, so no `sys_queue` row may take it (`isDeclaredQueueName` is unchanged: any holder). - **Assignment rules** (`assignment-rule-hooks.ts`): the `sys_assignment_rule` save guard asks the module. One holder gives the same message as before. Two holders still refuse, and the message now names both packages. - **A declared rule's queue recipient** (`sharing-rule-service.ts`, `assertQueueRecipientReachable`): this is the one reference in these reads that a package writes, so it resolves from the rule's package P (ADR-0150 D3): P's own queue, else the unique holder in P's declared closure plus `sys`. A refusal (outside the closure, D3 (a), or ambiguous in the closure) throws, so each recompute keeps the rule's grants and warns, as for a failed read. A name no registry item holds passes through to an organization's `sys_queue` row, unchanged. - Changeset: patch for `@objectstack/plugin-sharing`, BREAKING (narrowing), ADR-0087 `not-required (no-migration-prescription)`. ## Tests New file `src/package-scoped-declarations.test.ts` (17 cases), built on the real `SchemaRegistry` (packages through `installPackage`, items under composite slots): - `one holder` (3): sharing rule list and by-name, queue resolve, expand and `queuesOf`, and the assignment guard all answer as before. - `two holders` (9): the resolver names both; the sharing rule is served by neither path and reported once; by-name gives 409 naming both; the name guard still refuses; the queue resolves nowhere and gives 409 under `refuse`; `queuesOf` serves neither; the door lookup gives 409 and the name stays declared; the assignment guard names both; the orphan sweep revokes the name's standing grants and reports them once as the refusal naming both, apart from a vanished rule's orphans. - `listing without the slice` (1). - `queue recipient from the rule's package` (4): outside closure refused; D3 (a) refused; a declared dependency's queue served; own queue served. No existing test was edited. Package suite on head: Test Files 72 passed (72), Tests 1487 passed (1487). ## Acceptance notes - **Caller package for queues.** The queue service's contract (`IOwnershipQueueService`, spec) has no caller-package argument, so after the P-side check it still resolves the name environment-wide. A name P's closure reaches once but an unrelated package also holds is therefore refused, where D3 alone would serve P's reach. That is stricter, never looser. Threading the caller through the contract is a spec change. Accepted as an interim by the epic seat (6729421618); carrier: #31734. - **Organization-authored rows are not registry items.** `sys_queue`, `sys_sharing_rule` and `sys_assignment_rule` rows are read as before. D3 (a) applies only to environment-authored registry items (the bare slot). - **The activation door** (runtime `catalog-activation.ts`, outside this card's surface) answers a thrown lookup with `503`, quoting the refusal, which names both packages. Carrier: G1 #31691 (the door's `409`); S1 owns the ledger's package column. - **Grants of a refused sharing-rule name.** Under the maintainer's ruling on #31677 Q1 (A: a name two packages hold is refused and declared) a refused rule is served to nobody, so its standing grants must not keep answering. The boot orphan sweep revokes them, and reports it as a refusal, not an orphan: one `warn` per name naming every candidate package and saying the grants come back once the rule is addressed by package. Only a vanished rule's grants are counted in the sweep's orphan line. Reachable only through a sealed clash from before phase 1; first-party count 0. ## Verification Head `b24fd3bca` (the Q2 change of the epic seat's revised ruling, merged with main). - `pnpm --filter @objectstack/plugin-sharing test` (under `os-verify-lock`): 72 files / 1487 tests passed; new file 17/17. `typecheck` exit 0; `eslint --no-inline-config src` exit 0. - `pnpm build` (whole workspace, under the lock): exit 0. A first attempt failed in `@object-ui/fields` (`Cannot find module '@objectstack/formula'`), a dependency main added that this worktree had not linked; `pnpm install --frozen-lockfile` then the build passed. - `dispatch-gates --ran`: 72 derived, 72 run, 0 NOT-MEASURED, 0 UNRUN, every one exit 0. - Dogfood, full battery on `b24fd3bca` under the lock: Test Files 440 passed, 3 skipped (443); Tests 3652 passed, 41 skipped (3693); VERDICT command-exit 0. - CI on `b24fd3bca`: every check run success or skipped (50 runs). - First-party counts (showcase): 2 declared sharing rules, 0 queues, 0 assignment rules. Names held twice: 0. D3 (a): 0. Outside the closure: 0. Sibling in the same release artifact: 0. Pre-phase-1 sealed clash: 0. <details><summary>Step 0, main at b126c13: two packages declaring one name, every reader</summary> Probe on the same fixture (ALPHA then BETA, each declaring sharing rule `emea_share`, queue `triage`, assignment rule `route_accounts`), source restored from `b126c130`: | Reader | main | this PR | |:--|:--|:--| | declared sharing rules `list()` | ALPHA's rule only (first) | neither; one `warn` naming both | | `declaredRuleNamed` (name guard, door lookup, `defineRule`) | ALPHA's rule | 409 `RESOURCE_CONFLICT`, both named | | sharing name guard on insert | 409 (declared) | 409 (refusal naming both) | | `resolveQueue` | ALPHA (first) | `null` | | `expandMembers` | `["u_alpha"]` | `[]` | | `expandMembers` under `refuse` | `["u_alpha"]` | 409, both named | | `declaredQueueNamed` (activation door) | ALPHA | 409, both named | | `queuesOf(u_alpha)` / `queuesOf(u_beta)` | `[]` / `["triage"]` (LAST holder's members) | `[]` / `[]` | | assignment guard | refused, no holder named | refused, both named | </details> <details><summary>Ablation: four legs, each red, each restored (scripts/ablation-replace.mjs)</summary> The tests import plugin-sharing source directly; objectql (dist) is not mutated. Each leg: anchor 1 to 0, blob changed, run red, restore proved by blob == HEAD and an empty `git diff HEAD`. - A1, the resolver's refusal answered as the first listed holder (`package-scoped-declarations.ts`): 7 red, every `two holders` refusal pin. The name-guard pin stays green, as a preservation pin should: the name is refused either way. - A2, the listing refusal answered as the first holder: 1 red (`a listing that cannot be asked …`). - A3, the P-side queue recipient check skipped: 2 red (outside closure; D3 (a)). - A4, the orphan sweep's refusal report removed (`this.reportSweptRefusal(refusal)`): 1 red (the sweep pin). </details> <details><summary>ADR-0150's four readings</summary> - (a) Phase-1 one-holder tests: no phase-1 file is touched (`bare-name-one-holder.ts`, its tests, the registry). The three types here are uncovered by phase 1, and their one-holder answers are pinned unchanged in the `one holder` block. - (b) Bare-name behaviour for a name with one holder is unchanged on every read (`one holder` block), and no URL, MCP or SDK shape changes. The declared narrowings stand in for two holders, for a holder outside the rule package's closure, and for an environment-only holder. - (c) No migration in this PR. - (d) `Clause-②: no (narrowing)`. No protocol change, so no ADR-0087 entry (changeset marker `not-required (no-migration-prescription)`; `check-adr-0087-registration` exit 0). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRDzfKpRLg4QnQqPAz)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: domain:server#3 · os-steve · session_01ADHkmRDzfKpRLg4QnQqPAz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f65c36f commit 43fb482

8 files changed

Lines changed: 869 additions & 41 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/plugin-sharing': patch
3+
---
4+
5+
feat(plugin-sharing)!: declared sharing rules, queues and assignment rules are read on (package, name), and a name two packages declare is refused, naming both
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) nothing an author writes is renamed, removed or re-shaped; the change is which declared item a bare name reads at runtime, so there is no stored or authored shape for objectstack migrate meta to rewrite -->
11+
12+
**BREAKING**, narrowly, for a deployment that already installs two packages declaring a sharing rule, a queue or an assignment rule under the same name. Who is affected: such a deployment only. Measured first-party: none (the showcase declares two sharing rules, no queue and no assignment rule; no two packages share a name).
13+
14+
The three declared types are addressed by `(package, name)` (ADR-0150). Every place the sharing plugin reads one of them by bare name now goes through objectql's shared package-scoped resolver:
15+
16+
- A name one package declares answers exactly what it answered before.
17+
- A name two packages declare used to answer the first package registered, or, for a user's queues and the session's queue flag, the last. It is now refused: the declared sharing rule is not served and grants nothing, the queue resolves nowhere (a refusal naming both packages for a caller that asked for one), and a lookup by that name answers `409 RESOURCE_CONFLICT` naming both packages. The name stays taken: no organization's own rule or queue may take it. The refusal is logged once at `warn`, naming every holder. Grants the name already holds stop answering: the boot sweep of orphaned rule grants revokes them and reports it once as that refusal, naming every holder; they come back once the rule is addressed by package.
18+
- A declared sharing rule's queue recipient is read from the rule's own package: its own queue, or the one queue its declared dependencies hold. A queue only an unrelated package holds, or only an environment-authored registry item holds, is refused, naming the holder, where it used to be served. An organization's own queue (a `sys_queue` row) is served as before.
19+
20+
What to do if you see the refusal: keep one of the two packages' items under that name. If a declared rule's queue lives in another package, declare a dependency on that package.

‎packages/plugins/plugin-sharing/src/assignment-rule-hooks.ts‎

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,10 @@ import { resolveInjectedColumnProvenance } from '@objectstack/spec/data';
3737
import {
3838
ASSIGNMENT_RULE_OBJECT,
3939
assignmentExpressionRefusals,
40+
describePackageScopedHolder,
4041
organizationMemberStanding,
4142
} from '@objectstack/objectql';
43+
import { resolveDeclaredName, type DeclaredNameAnswer } from './package-scoped-declarations.js';
4244

4345
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;
4446

@@ -97,21 +99,35 @@ function present(v: unknown): string | null {
9799
return s.trim() === '' ? null : s;
98100
}
99101

100-
/** Every declared assignment rule's name, switched on or off. */
101-
function declaredRuleNames(engine: MinimalEngine): Set<string> {
102-
const names = new Set<string>();
103-
let items: unknown[] = [];
102+
/** Every declared assignment rule, switched on or off, as the registry lists it. */
103+
function declaredRuleItems(engine: MinimalEngine): unknown[] {
104104
try {
105-
items = engine.registry?.listItems?.(ASSIGNMENT_RULE_TYPE) ?? [];
105+
const items = engine.registry?.listItems?.(ASSIGNMENT_RULE_TYPE) ?? [];
106+
return Array.isArray(items) ? items : [];
106107
} catch {
107-
return names;
108+
return [];
108109
}
109-
for (const item of Array.isArray(items) ? items : []) {
110+
}
111+
112+
/** Every declared assignment rule's name, switched on or off. */
113+
function declaredRuleNames(engine: MinimalEngine): Set<string> {
114+
const names = new Set<string>();
115+
for (const item of declaredRuleItems(engine)) {
110116
if (isRecord(item) && typeof item.name === 'string') names.add(item.name);
111117
}
112118
return names;
113119
}
114120

121+
/**
122+
* [ADR-0150 D3/D4, child E4] The declared assignment rule a bare `name`
123+
* addresses, through the shared resolver (`package-scoped-declarations.ts`):
124+
* one holder's, `not-found`, or a refusal naming every package that declares
125+
* it. Either of the first and last means the name is taken.
126+
*/
127+
function declaredRuleAnswer(engine: MinimalEngine, name: string): DeclaredNameAnswer<unknown> {
128+
return resolveDeclaredName(engine.registry, ASSIGNMENT_RULE_TYPE, name, declaredRuleItems(engine));
129+
}
130+
115131
/** The column an `AssignmentRuleSchema` issue path names, for the one-entry row. */
116132
function columnOf(path: ReadonlyArray<PropertyKey>): string {
117133
const [head, , key, sub] = path;
@@ -151,14 +167,27 @@ export async function assignmentRuleRowIssues(
151167
code: 'invalid_format',
152168
message: `An assignment rule name is a machine name — lowercase letters, digits and underscores, starting with a letter (got ${JSON.stringify(name)}).`,
153169
});
154-
} else if (name !== null && declaredRuleNames(engine).has(name)) {
155-
issues.push({
156-
field: 'name',
157-
code: 'invalid_value',
158-
message:
159-
`'${name}' is the name of an assignment rule an installed app provides, and one name means one rule. ` +
160-
'Choose another name for your own rule.',
161-
});
170+
} else if (name !== null) {
171+
const declared = declaredRuleAnswer(engine, name);
172+
if (declared.status === 'resolved') {
173+
issues.push({
174+
field: 'name',
175+
code: 'invalid_value',
176+
message:
177+
`'${name}' is the name of an assignment rule an installed app provides, and one name means one rule. ` +
178+
'Choose another name for your own rule.',
179+
});
180+
} else if (declared.status === 'refused') {
181+
// Two apps declare it: still taken, and every holder is named.
182+
issues.push({
183+
field: 'name',
184+
code: 'invalid_value',
185+
message:
186+
`'${name}' is the name of an assignment rule ${declared.refusal.candidates.length} installed apps provide ` +
187+
`(${declared.refusal.candidates.map(describePackageScopedHolder).join('; ')}), and one name means one rule. ` +
188+
'Choose another name for your own rule.',
189+
});
190+
}
162191
}
163192

164193
const object = present(row.object_name);

‎packages/plugins/plugin-sharing/src/declared-sharing-rules.ts‎

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@
2323
* 2. The kernel `metadata` service (`list('sharing_rule')`), only when the
2424
* registry holds no rule at all — the registry-less host.
2525
*
26+
* A sharing rule is addressed by `(package, name)` (ADR-0150 D1 bucket 2), so
27+
* two packages may each declare a rule of one name. A name is served once,
28+
* resolved through `package-scoped-declarations.ts` (objectql's shared
29+
* resolver): one holder's rule, or none — the name refused, naming every
30+
* holder, and reported once. It is never served as the first holder.
31+
*
2632
* `sharing_rule` needs no registered metadata kind for either read: the
2733
* registry keys items by the type string `METADATA_ARRAY_KEYS` maps
2834
* `sharingRules` to, and the metadata service binds the type through its
@@ -53,6 +59,13 @@ import { compileCelToFilter } from '@objectstack/formula';
5359
import type { CelFilterFailReason } from '@objectstack/formula';
5460
import { isMatchAllCriteria } from './rule-criteria.js';
5561
import { FIELD_NAME_GRAMMAR } from './sharing-rule-service.js';
62+
import {
63+
reportRefusedDeclaration,
64+
resolveDeclaredName,
65+
servedDeclarations,
66+
type DeclaredNameAnswer,
67+
} from './package-scoped-declarations.js';
68+
import type { PackageScopedRefusal } from '@objectstack/objectql';
5669

5770
type Logger = { info?: (m: string, meta?: any) => void; warn?: (m: string, meta?: any) => void };
5871

@@ -236,13 +249,36 @@ export function translateDeclaredSharingRule(
236249
/** Where enforcement reads declared rules. Read on every call: the registry is the authority, never a snapshot of it. */
237250
export interface DeclaredSharingRuleSource {
238251
list(): Promise<DeclaredSharingRule[]>;
252+
/**
253+
* [ADR-0150 D3, child E4] The declared rule a bare `name` addresses: the one
254+
* holder's, `not-found`, or the resolver's refusal naming every package that
255+
* holds it. A name two packages hold is never answered as either one. A
256+
* rule whose declaration the runtime cannot serve (the skips above) is
257+
* `not-found`, as `list()` leaves it out.
258+
*/
259+
lookup?(name: string): Promise<DeclaredNameAnswer<DeclaredSharingRule>>;
260+
/**
261+
* [ADR-0150 D3, child E4] Every declared name the resolver refuses (two or
262+
* more holders), with its refusal. The orphaned-grant sweep reads it to
263+
* report a refused name's revoked grants as a refusal, naming every holder,
264+
* never as a vanished rule. Reports nothing itself; `list()` is the reader
265+
* that reports.
266+
*/
267+
refused?(): Promise<PackageScopedRefusal[]>;
239268
}
240269

241270
/** The registry, as this read uses it — ObjectQL's `SchemaRegistry` (`engine.registry`) satisfies it. */
242271
interface DeclaredRuleRegistry {
243272
listItems(type: string): readonly unknown[] | undefined;
244273
}
245274

275+
/** Where the declarations were read, and so what can resolve a name among them. */
276+
interface DeclaredRuleRead {
277+
defs: unknown[];
278+
/** The registry the defs came from — `undefined` for the metadata-service fallback. */
279+
registry: unknown;
280+
}
281+
246282
/** The kernel `metadata` service, as this read uses it. */
247283
interface DeclaredRuleMetadataService {
248284
list(type: string): unknown;
@@ -312,25 +348,46 @@ export function createDeclaredSharingRuleSource(opts: DeclaredSharingRuleSourceO
312348
opts.logger?.warn?.(SKIP_WARN[skip.kind], meta);
313349
};
314350

351+
const refusedReported = new Set<string>();
352+
const read = async (): Promise<DeclaredRuleRead> => {
353+
const fromRegistry = readRegistry();
354+
if (fromRegistry.length > 0) return { defs: fromRegistry, registry: opts.engine?.registry };
355+
return { defs: await readMetadata(), registry: undefined };
356+
};
357+
315358
return {
316359
async list(): Promise<DeclaredSharingRule[]> {
317-
let defs = readRegistry();
318-
if (defs.length === 0) defs = await readMetadata();
360+
const { defs, registry } = await read();
319361
const out: DeclaredSharingRule[] = [];
320-
const names = new Set<string>();
321-
for (const def of defs) {
362+
// [ADR-0150 D3/D4, child E4] One rule per NAME, resolved: two packages
363+
// may each declare a rule of one name (the registry keys them apart), and
364+
// such a name is refused, naming both, never served as the first one
365+
// registered — its grants carry the bare name, so serving both, or one
366+
// of them, would grant on a guess.
367+
for (const def of servedDeclarations(registry, 'sharing_rule', defs, (refusal) =>
368+
reportRefusedDeclaration(opts.logger, refusedReported, refusal),
369+
)) {
322370
const translated = translate(def);
323371
if (translated.skip) {
324372
warnOnce(def, translated.skip);
325373
continue;
326374
}
327-
// One rule per name: the registry already refuses a second package
328-
// registering a held name, so a duplicate here is the same item twice.
329-
if (names.has(translated.rule.name)) continue;
330-
names.add(translated.rule.name);
331375
out.push(translated.rule);
332376
}
333377
return out;
334378
},
379+
async lookup(name: string): Promise<DeclaredNameAnswer<DeclaredSharingRule>> {
380+
const { defs, registry } = await read();
381+
const answer = resolveDeclaredName(registry, 'sharing_rule', name, defs);
382+
if (answer.status !== 'resolved') return answer;
383+
const translated = translate(answer.item);
384+
return translated.rule ? { status: 'resolved', item: translated.rule } : { status: 'not-found' };
385+
},
386+
async refused(): Promise<PackageScopedRefusal[]> {
387+
const { defs, registry } = await read();
388+
const out: PackageScopedRefusal[] = [];
389+
servedDeclarations(registry, 'sharing_rule', defs, (refusal) => out.push(refusal));
390+
return out;
391+
},
335392
};
336393
}

‎packages/plugins/plugin-sharing/src/ownership-queue-service.ts‎

Lines changed: 64 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@
1919
* naming the queue (any of the five set-valued kinds), whichever source the
2020
* queue has.
2121
*
22+
* ## One declared holder per name (ADR-0150 D3/D4, child E4)
23+
*
24+
* A queue is addressed by `(package, name)` (ADR-0150 D1 bucket 2): two
25+
* packages may each declare a queue of one name. Every read of a declared
26+
* queue by name — resolution, the activation door's lookup, the active set
27+
* the session flag, the look-through and the user's queues read — goes
28+
* through `package-scoped-declarations.ts` (objectql's shared resolver), so a
29+
* name two packages declare is refused, naming both, and reported once; it is
30+
* never answered as the first (or, as `queuesOf` once did, the last) holder
31+
* listed. It stays a declared name: no `sys_queue` row may take it.
32+
*
2233
* ## One expander
2334
*
2435
* {@link OwnershipQueueService.expandMembers} is the function the access path,
@@ -86,6 +97,13 @@ import type { SharingEngine } from './sharing-service.js';
8697
import { TeamGraphService, readMembershipToCompletion, teamHasMember } from './team-graph.js';
8798
import { PositionGraphService } from './position-graph.js';
8899
import { BusinessUnitGraphService } from './business-unit-graph.js';
100+
import {
101+
PackageScopedNameRefusedError,
102+
reportRefusedDeclaration,
103+
resolveDeclaredName,
104+
servedDeclarations,
105+
type DeclaredNameAnswer,
106+
} from './package-scoped-declarations.js';
89107

90108
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;
91109

@@ -211,6 +229,8 @@ export class OwnershipQueueService implements IOwnershipQueueService {
211229
private readonly engine: () => OwnershipQueueEngine | null | undefined;
212230
private readonly logger?: OptionalSharingLogger;
213231
private readonly warned = new Set<string>();
232+
/** [ADR-0150, child E4] Declared queue names already reported as held by two or more packages. */
233+
private readonly refusedReported = new Set<string>();
214234

215235
constructor(options: OwnershipQueueServiceOptions) {
216236
this.engine = options.engine;
@@ -232,7 +252,16 @@ export class OwnershipQueueService implements IOwnershipQueueService {
232252
private async resolve(name: string, organizationId: string | null, refuse: boolean): Promise<ResolvedQueue | null> {
233253
const engine = this.engine();
234254
if (!engine || !name) return null;
235-
const declared = await this.declaredQueueItem(name);
255+
const answer = this.declaredQueueAnswer(name);
256+
if (answer.status === 'refused') {
257+
// [ADR-0150 D3, child E4] Two packages declare this name: it is neither
258+
// of them, and — a declared name — never an authored row either. Under
259+
// 'refuse' the caller is told so, naming every holder; otherwise it
260+
// resolves nowhere, which for every 'nobody' consumer denies.
261+
if (refuse) throw new PackageScopedNameRefusedError(answer.refusal);
262+
return null;
263+
}
264+
const declared = answer.status === 'resolved' ? await this.switchedOnDeclared(answer.item) : null;
236265
if (declared) {
237266
const authoredMembers = await this.authoredMemberSpecs(engine, [name], organizationId, refuse);
238267
return {
@@ -248,7 +277,7 @@ export class OwnershipQueueService implements IOwnershipQueueService {
248277
}
249278
// A declared name switched off in the ledger resolves nowhere — not even to
250279
// an authored row, which may not take a declared queue's name.
251-
if (this.declaredItems().some((q) => q.name === name)) return null;
280+
if (answer.status === 'resolved') return null;
252281
const row = await this.authoredQueueRow(engine, name, organizationId, refuse);
253282
if (!row) return null;
254283
const authoredMembers = await this.authoredMemberSpecs(engine, [name], organizationId, refuse);
@@ -274,7 +303,7 @@ export class OwnershipQueueService implements IOwnershipQueueService {
274303
} catch (err) {
275304
// Only a call under 'refuse' gets here: under 'nobody' every read
276305
// behind the queue answers nobody in place (module header).
277-
if (!pass.refuse) throw err;
306+
if (!pass.refuse || err instanceof PackageScopedNameRefusedError) throw err;
278307
throw queueReadRefusal(name, organizationId, err);
279308
}
280309
}
@@ -292,7 +321,7 @@ export class OwnershipQueueService implements IOwnershipQueueService {
292321
if (!queue) return false;
293322
return await this.specsReachUser(queue.members, userId, organizationId, pass);
294323
} catch (err) {
295-
if (!pass.refuse) throw err;
324+
if (!pass.refuse || err instanceof PackageScopedNameRefusedError) throw err;
296325
throw queueReadRefusal(name, organizationId, err);
297326
}
298327
}
@@ -347,17 +376,33 @@ export class OwnershipQueueService implements IOwnershipQueueService {
347376
* could never switch it back on. {@link resolveQueue} reads the ledger.
348377
*/
349378
async declaredQueueNamed(name: string): Promise<{ name: string; packageId?: string } | null> {
350-
const item = this.declaredItems().find((q) => q.name === name);
351-
if (!item) return null;
379+
const answer = this.declaredQueueAnswer(name);
380+
// [ADR-0150 D3, child E4] A name two packages declare names one queue of
381+
// neither: the door refuses (409, every holder named) rather than switch
382+
// the first one listed.
383+
if (answer.status === 'refused') throw new PackageScopedNameRefusedError(answer.refusal);
384+
if (answer.status === 'not-found') return null;
385+
const item = answer.item;
352386
const packageId = str(item._packageId ?? item.packageId);
353387
return { name: item.name, ...(packageId ? { packageId } : {}) };
354388
}
355389

356-
private async declaredQueueItem(name: string): Promise<DeclaredQueueItem | null> {
357-
const item = this.declaredItems().find((q) => q.name === name);
358-
if (!item) return null;
359-
const off = await this.switchedOff(QUEUE_ACTIVATION_TYPE, [name]);
360-
return off.has(name) ? null : item;
390+
/**
391+
* [ADR-0150 D3/D4, child E4] The declared queue a bare `name` addresses —
392+
* one holder's, `not-found`, or the shared resolver's refusal naming every
393+
* package that declares it (`package-scoped-declarations.ts`). Switched on
394+
* or off: the ledger is read by the caller. A refusal is reported once.
395+
*/
396+
private declaredQueueAnswer(name: string): DeclaredNameAnswer<DeclaredQueueItem> {
397+
const answer = resolveDeclaredName(this.engine()?.registry, 'queue', name, this.declaredItems());
398+
if (answer.status === 'refused') reportRefusedDeclaration(this.logger, this.refusedReported, answer.refusal);
399+
return answer;
400+
}
401+
402+
/** `item`, unless the activation ledger switches its name off. */
403+
private async switchedOnDeclared(item: DeclaredQueueItem): Promise<DeclaredQueueItem | null> {
404+
const off = await this.switchedOff(QUEUE_ACTIVATION_TYPE, [item.name]);
405+
return off.has(item.name) ? null : item;
361406
}
362407

363408
/** Is `name` a declared queue's name, switched on or off? The authored-row guard's question. */
@@ -546,8 +591,15 @@ export class OwnershipQueueService implements IOwnershipQueueService {
546591
return items.filter((q): q is DeclaredQueueItem => isRecord(q) && typeof q.name === 'string' && q.name !== '');
547592
}
548593

594+
/**
595+
* Every declared queue switched on, one per name (ADR-0150 D3/D4, child E4):
596+
* a name two packages declare is refused and serves neither — never the
597+
* first or the last one listed.
598+
*/
549599
private async activeDeclaredQueues(): Promise<DeclaredQueueItem[]> {
550-
const items = this.declaredItems();
600+
const items = servedDeclarations(this.engine()?.registry, 'queue', this.declaredItems(), (refusal) =>
601+
reportRefusedDeclaration(this.logger, this.refusedReported, refusal),
602+
);
551603
if (items.length === 0) return [];
552604
const off = await this.switchedOff(QUEUE_ACTIVATION_TYPE, items.map((q) => q.name));
553605
return items.filter((q) => !off.has(q.name));

0 commit comments

Comments
 (0)