Skip to content

Commit 4b6296e

Browse files
committed
feat(objectql,plugin-sharing): an organization authors its own assignment rules as sys_assignment_rule records
An organization's own rules are evaluated first, ascending by sort_order and then by name, with the rules packages declare as the fallback. A user target owns the row only while the user is an active member of the row's organization; a lapsed one leaves the row ownerless and warns once, never refusing the insert. The sys_assignment_rule save guard refuses a row whose name a package rule holds, whose object cannot be routed, whose entry shape the stack schema refuses, whose criteria or load the engine's CEL paths cannot compile, whose user target is not an active member, or that lands in no organization. Claude-Session: https://claude.ai/code/session_016WV4d14C8K4gMehVb6jBvA Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6ef7f58 commit 4b6296e

10 files changed

Lines changed: 1087 additions & 25 deletions

File tree

‎packages/objectql/src/assignment-rules.ts‎

Lines changed: 277 additions & 19 deletions
Large diffs are not rendered by default.

‎packages/objectql/src/engine.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6200,11 +6200,12 @@ export class ObjectQL implements IObjectQLEngine {
62006200
// An engine-owned producer like the two above, so the post-hook `check`
62016201
// (judged above, on the row as the hooks left it) does not see the owner
62026202
// a rule picks — that owner is the platform's routing, not the caller's
6203-
// steering. Free for every object no rule names (`rulesFor` is a registry
6204-
// read).
6203+
// steering. Free for every object no rule can name (`mayRoute` is a
6204+
// registry read: a declared rule names the object, or organizations can
6205+
// author rules and the object carries the queue column they route by).
62056206
{
62066207
const evaluator = this.assignment();
6207-
if (evaluator.rulesFor(object).length > 0) {
6208+
if (evaluator.mayRoute(object)) {
62086209
const activeOrg = opCtx.context?.tenantId ? String(opCtx.context.tenantId) : null;
62096210
const candidates = [];
62106211
for (let i = 0; i < rows.length; i++) {

‎packages/objectql/src/federated-injected-column-readers.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,14 @@ const READERS: Record<string, Row> = {
435435
disposition: 'not-a-read',
436436
why: 'keys the sys_assignment_cursor row, a platform table the engine itself reads and writes',
437437
},
438+
'assignment-rules.ts#authoredRules :: organization_id': {
439+
disposition: 'not-a-read',
440+
why: "keys an organization's sys_assignment_rule rows, a platform table plugin-sharing owns",
441+
},
442+
'assignment-rules.ts#organizationMemberStanding :: organization_id': {
443+
disposition: 'not-a-read',
444+
why: 'keys the sys_member row a user target is a member by, a platform table',
445+
},
438446
'assignment-rules.ts#route :: queue': {
439447
disposition: 'not-a-read',
440448
why: 'names the queue in a log entry; the row written is the one in hand',

‎packages/objectql/src/index.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,3 +766,15 @@ export type { AuthzInvalidationBridgeOptions } from './authz-invalidation-bridge
766766
// package's published surface is exactly what it was.
767767
export { resolveArtifactPackageOrder } from '@objectstack/core';
768768
export type { ArtifactPackageError } from '@objectstack/core';
769+
770+
// [ADR-0142 D5, ruling A on organization-authored routing] What the save guard
771+
// of an organization's own `sys_assignment_rule` row (`@objectstack/plugin-sharing`)
772+
// asks of the assignment seam, so the row is judged by the paths the engine
773+
// evaluates it by: the table name, the CEL compile of `criteria` / `load`, and
774+
// the one "active member of the organization" predicate for a user target.
775+
export {
776+
ASSIGNMENT_RULE_OBJECT,
777+
assignmentExpressionRefusals,
778+
organizationMemberStanding,
779+
} from './assignment-rules.js';
780+
export type { OrganizationMemberStanding } from './assignment-rules.js';

‎packages/objectql/src/ownership-queue.test.ts‎

Lines changed: 262 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
1414
import { QUEUE_FIELD_DEF } from '@objectstack/spec/data';
1515
import { ObjectQL } from './engine.js';
1616
import { applySystemFields, objectQueueColumnRefusal } from './registry.js';
17-
import { OWNERSHIP_QUEUE_SOURCE_SLOT, describeMissingOwnershipQueueService, nextMember } from './assignment-rules.js';
17+
import { OWNERSHIP_QUEUE_SOURCE_SLOT, assignmentExpressionRefusals, describeMissingOwnershipQueueService, nextMember } from './assignment-rules.js';
1818

1919
type Row = Record<string, unknown>;
2020

@@ -127,6 +127,44 @@ const CURSOR = {
127127
},
128128
};
129129

130+
/** The organization membership table, as the platform ships it (only the keys the seam reads). */
131+
const MEMBER = {
132+
name: 'sys_member',
133+
label: 'Member',
134+
fields: {
135+
user_id: { type: 'text', label: 'User' },
136+
role: { type: 'text', label: 'Role' },
137+
},
138+
};
139+
140+
/** The user table's ban columns, which a user target's standing reads. */
141+
const USER = {
142+
name: 'sys_user',
143+
label: 'User',
144+
fields: {
145+
name: { type: 'text', label: 'Name' },
146+
banned: { type: 'boolean', label: 'Banned' },
147+
ban_expires: { type: 'datetime', label: 'Ban Expires' },
148+
},
149+
};
150+
151+
/** An organization's own assignment rules, as plugin-sharing ships them (only the keys the seam reads). */
152+
const AUTHORED_RULE = {
153+
name: 'sys_assignment_rule',
154+
label: 'Assignment Rule',
155+
fields: {
156+
name: { type: 'text', label: 'Name' },
157+
object_name: { type: 'text', label: 'Object' },
158+
criteria: { type: 'textarea', label: 'Condition' },
159+
sort_order: { type: 'number', label: 'Order' },
160+
recipient_type: { type: 'text', label: 'Assign To' },
161+
recipient_id: { type: 'text', label: 'Queue or User' },
162+
strategy: { type: 'text', label: 'Strategy' },
163+
load: { type: 'textarea', label: 'Open Work' },
164+
active: { type: 'boolean', label: 'Active' },
165+
},
166+
};
167+
130168
const SYS = { isSystem: true, tenantId: 'org_a', positions: [], permissions: [] } as any;
131169

132170
// ─── D3: the column and its refusal ────────────────────────────────────────
@@ -284,6 +322,8 @@ describe('[ADR-0142 D5] the assignment seam', () => {
284322
await engine.init();
285323
engine.registry.registerObject(TICKET as any, 'pkg');
286324
engine.registry.registerObject(CURSOR as any, 'plugin-sharing');
325+
engine.registry.registerObject(MEMBER as any, 'platform');
326+
d.storeFor('sys_member').set('m_lead', { id: 'm_lead', user_id: 'u_lead', organization_id: 'org_a' });
287327
engine.registerApp({ id: 'com.acme.support', name: 'support', queues, assignmentRules: rules });
288328
(engine as any)[OWNERSHIP_QUEUE_SOURCE_SLOT] = () => ({
289329
resolveQueue: async (name: string, org: string | null) =>
@@ -427,6 +467,227 @@ describe('[ADR-0142 D5] the assignment seam', () => {
427467
});
428468
});
429469

470+
// ─── D5: user targets, and an organization's own rules ─────────────────────
471+
472+
describe('[ADR-0142 D5] a user target owns the row only while the user is an active member', () => {
473+
let engine: ObjectQL;
474+
let d: ReturnType<typeof makeDriver>;
475+
let warn: ReturnType<typeof vi.spyOn>;
476+
477+
async function boot(opts: { members?: boolean; users?: boolean } = {}) {
478+
engine = new ObjectQL();
479+
d = makeDriver();
480+
engine.registerDriver(d.driver, true);
481+
await engine.init();
482+
engine.registry.registerObject(TICKET as any, 'pkg');
483+
if (opts.members !== false) engine.registry.registerObject(MEMBER as any, 'platform');
484+
if (opts.users !== false) engine.registry.registerObject(USER as any, 'platform');
485+
engine.registerApp({
486+
id: 'com.acme.support', name: 'support', queues: [],
487+
assignmentRules: [{ name: 'ticket_owner', object: 'ticket', active: true, entries: [{ name: 'all', assignTo: { type: 'user', value: 'u_lead' } }] }],
488+
});
489+
warn = vi.spyOn((engine as any).logger, 'warn');
490+
}
491+
492+
const insert = (org = 'org_a') => engine.insert('ticket', { subject: 'A', organization_id: org }, { context: { ...SYS, tenantId: org } });
493+
494+
it('a member of the row\'s organization, not banned, owns it', async () => {
495+
await boot();
496+
d.storeFor('sys_member').set('m1', { id: 'm1', user_id: 'u_lead', organization_id: 'org_a' });
497+
d.storeFor('sys_user').set('u_lead', { id: 'u_lead', banned: false });
498+
expect((await insert()).owner_id).toBe('u_lead');
499+
});
500+
501+
it('a user who is not a member of the row\'s organization owns nothing, the insert lands, and the lapse warns once', async () => {
502+
await boot();
503+
d.storeFor('sys_member').set('m1', { id: 'm1', user_id: 'u_lead', organization_id: 'org_b' });
504+
d.storeFor('sys_user').set('u_lead', { id: 'u_lead', banned: false });
505+
const a = await insert();
506+
await insert();
507+
expect(a.owner_id ?? null).toBeNull();
508+
expect(a.queue ?? null).toBeNull();
509+
expect(warn.mock.calls.filter((c: unknown[]) => /assigns to user 'u_lead', who is not a member of organization 'org_a'/.test(String(c[0])))).toHaveLength(1);
510+
// The other organization, where the user is a member, still routes.
511+
expect((await insert('org_b')).owner_id).toBe('u_lead');
512+
});
513+
514+
it('a banned member owns nothing; a ban whose expiry passed binds no longer', async () => {
515+
await boot();
516+
d.storeFor('sys_member').set('m1', { id: 'm1', user_id: 'u_lead', organization_id: 'org_a' });
517+
d.storeFor('sys_user').set('u_lead', { id: 'u_lead', banned: true });
518+
expect((await insert()).owner_id ?? null).toBeNull();
519+
expect(warn.mock.calls.some((c: unknown[]) => /whose account is banned/.test(String(c[0])))).toBe(true);
520+
d.storeFor('sys_user').set('u_lead', { id: 'u_lead', banned: true, ban_expires: '2000-01-01T00:00:00Z' });
521+
expect((await insert()).owner_id).toBe('u_lead');
522+
});
523+
524+
it('no membership table registered: no user can be confirmed, so none is assigned, and it says why once', async () => {
525+
await boot({ members: false });
526+
const a = await insert();
527+
await insert();
528+
expect(a.owner_id ?? null).toBeNull();
529+
expect(warn.mock.calls.filter((c: unknown[]) => /no organization membership table \('sys_member'\) is registered/.test(String(c[0])))).toHaveLength(1);
530+
});
531+
532+
it('a membership read that fails writes the row as it stood, never refused', async () => {
533+
await boot();
534+
const find = d.driver.find.bind(d.driver);
535+
d.driver.find = async (object: string, ast: any) => {
536+
if (object === 'sys_member') throw new Error('members down');
537+
return find(object, ast);
538+
};
539+
const a = await insert();
540+
expect(a.owner_id ?? null).toBeNull();
541+
expect(warn.mock.calls.some((c: unknown[]) => /membership could not be read/.test(String(c[0])))).toBe(true);
542+
});
543+
});
544+
545+
describe('[ADR-0142 D5] an organization\'s own rules (`sys_assignment_rule`) go first, the declared rules are the fallback', () => {
546+
let members: Record<string, string[]>;
547+
let engine: ObjectQL;
548+
let d: ReturnType<typeof makeDriver>;
549+
let warn: ReturnType<typeof vi.spyOn>;
550+
551+
async function boot(declared: unknown[] = [], opts: { authoredTable?: boolean } = {}) {
552+
engine = new ObjectQL();
553+
d = makeDriver();
554+
engine.registerDriver(d.driver, true);
555+
await engine.init();
556+
engine.registry.registerObject(TICKET as any, 'pkg');
557+
engine.registry.registerObject(CURSOR as any, 'plugin-sharing');
558+
engine.registry.registerObject(MEMBER as any, 'platform');
559+
if (opts.authoredTable !== false) engine.registry.registerObject(AUTHORED_RULE as any, 'plugin-sharing');
560+
engine.registerApp({
561+
id: 'com.acme.support', name: 'support',
562+
queues: [{ name: 'support', label: 'Support', members: [] }, { name: 'vip', label: 'VIP', members: [] }],
563+
assignmentRules: declared,
564+
});
565+
(engine as any)[OWNERSHIP_QUEUE_SOURCE_SLOT] = () => ({
566+
resolveQueue: async (name: string, org: string | null) =>
567+
name in members && (org === 'org_a' || org === 'org_b') ? { name, label: name, source: 'declared', organizationId: null, members: [] } : null,
568+
expandMembers: async (name: string) => [...(members[name] ?? [])].sort(),
569+
});
570+
warn = vi.spyOn((engine as any).logger, 'warn');
571+
}
572+
573+
const author = (id: string, row: Row) =>
574+
d.storeFor('sys_assignment_rule').set(id, { id, organization_id: 'org_a', object_name: 'ticket', active: true, sort_order: 0, ...row });
575+
const insert = (data: Row, org = 'org_a') =>
576+
engine.insert('ticket', { organization_id: org, ...data }, { context: { ...SYS, tenantId: org } });
577+
const fallback = [{ name: 'ticket_intake', object: 'ticket', active: true, entries: [{ name: 'all', assignTo: { type: 'queue', value: 'support' } }] }];
578+
579+
beforeEach(() => {
580+
members = { support: ['u_a', 'u_b'], vip: ['u_v1', 'u_v2'] };
581+
});
582+
583+
it('an organization rule wins over a declared rule that also matches; an unmatched row falls back to the declared rule', async () => {
584+
await boot(fallback);
585+
author('r1', { name: 'vip_tickets', criteria: 'record.priority == "high"', recipient_type: 'queue', recipient_id: 'vip' });
586+
expect(await insert({ subject: 'A', priority: 'high' })).toMatchObject({ queue: 'vip' });
587+
expect(await insert({ subject: 'B', priority: 'low' })).toMatchObject({ queue: 'support' });
588+
});
589+
590+
it('routes with no declared rule at all, and only for the organization that authored it', async () => {
591+
await boot();
592+
author('r1', { name: 'all_tickets', recipient_type: 'queue', recipient_id: 'vip' });
593+
expect(await insert({ subject: 'A' })).toMatchObject({ queue: 'vip' });
594+
const other = await insert({ subject: 'B' }, 'org_b');
595+
expect(other.queue ?? null).toBeNull();
596+
expect(other.owner_id ?? null).toBeNull();
597+
});
598+
599+
it('several organization rules are tried by `sort_order`, then by name; an inactive one is skipped', async () => {
600+
await boot(fallback);
601+
author('r1', { name: 'b_rule', sort_order: 1, recipient_type: 'queue', recipient_id: 'support' });
602+
author('r2', { name: 'a_rule', sort_order: 1, recipient_type: 'queue', recipient_id: 'vip' });
603+
author('r3', { name: 'z_rule', sort_order: 0, recipient_type: 'queue', recipient_id: 'support', active: false });
604+
expect(await insert({ subject: 'A' })).toMatchObject({ queue: 'vip' }); // a_rule before b_rule; z_rule is off
605+
author('r4', { name: 'first', sort_order: -5, criteria: 'record.priority == "low"', recipient_type: 'queue', recipient_id: 'support' });
606+
expect(await insert({ subject: 'B', priority: 'low' })).toMatchObject({ queue: 'support' });
607+
});
608+
609+
it('a strategy rotates over the queue, its cursor keyed by the rule, its one entry (named after it) and the organization', async () => {
610+
await boot();
611+
author('r1', { name: 'rotate', recipient_type: 'queue', recipient_id: 'vip', strategy: 'round_robin' });
612+
const owners = [];
613+
for (const s of ['A', 'B', 'C']) owners.push((await insert({ subject: s })).owner_id);
614+
expect(owners).toEqual(['u_v1', 'u_v2', 'u_v1']);
615+
const cursor = [...d.storeFor('sys_assignment_cursor').values()];
616+
expect(cursor).toHaveLength(1);
617+
expect(cursor[0]).toMatchObject({ rule: 'rotate', entry: 'rotate', organization_id: 'org_a' });
618+
});
619+
620+
it('a user target of an organization rule owns the row only while the user is a member there', async () => {
621+
await boot(fallback);
622+
author('r1', { name: 'to_lead', recipient_type: 'user', recipient_id: 'u_lead' });
623+
const lapsed = await insert({ subject: 'A' });
624+
expect(lapsed.owner_id ?? null).toBeNull();
625+
expect(lapsed.queue ?? null).toBeNull(); // the first match decides, even lapsed — no fall-through
626+
d.storeFor('sys_member').set('m1', { id: 'm1', user_id: 'u_lead', organization_id: 'org_a' });
627+
expect((await insert({ subject: 'B' })).owner_id).toBe('u_lead');
628+
});
629+
630+
it('an organization rule under a declared rule\'s name is not evaluated — one name, one rule — and warns once', async () => {
631+
await boot(fallback);
632+
author('r1', { name: 'ticket_intake', recipient_type: 'queue', recipient_id: 'vip' });
633+
expect(await insert({ subject: 'A' })).toMatchObject({ queue: 'support' });
634+
await insert({ subject: 'B' });
635+
expect(warn.mock.calls.filter((c: unknown[]) => /named 'ticket_intake', which is the name of a rule an installed app declares/.test(String(c[0])))).toHaveLength(1);
636+
});
637+
638+
it('organization rules that cannot be read route the row by no rule — never by the fallback they overtake', async () => {
639+
await boot(fallback);
640+
const find = d.driver.find.bind(d.driver);
641+
d.driver.find = async (object: string, ast: any) => {
642+
if (object === 'sys_assignment_rule') throw new Error('rules down');
643+
return find(object, ast);
644+
};
645+
const row = await insert({ subject: 'A' });
646+
expect(row.queue ?? null).toBeNull();
647+
expect(row.owner_id ?? null).toBeNull();
648+
expect(warn.mock.calls.some((c: unknown[]) => /assignment rules of organization 'org_a' could not be read/.test(String(c[0])))).toBe(true);
649+
});
650+
651+
it('a stored row that does not read as a rule routes nothing and warns once; the next rule decides', async () => {
652+
await boot(fallback);
653+
author('r1', { name: 'broken', recipient_type: 'team', recipient_id: 'x' });
654+
expect(await insert({ subject: 'A' })).toMatchObject({ queue: 'support' });
655+
await insert({ subject: 'B' });
656+
expect(warn.mock.calls.filter((c: unknown[]) => /rule 'broken' that does not read as a rule/.test(String(c[0])))).toHaveLength(1);
657+
});
658+
659+
it('the cheap path: with no table and no declared rule, an insert reads no rule at all', async () => {
660+
await boot([], { authoredTable: false });
661+
const seen: string[] = [];
662+
const find = d.driver.find.bind(d.driver);
663+
d.driver.find = async (object: string, ast: any) => { seen.push(object); return find(object, ast); };
664+
const row = await insert({ subject: 'A' });
665+
expect(row.queue ?? null).toBeNull();
666+
expect(seen).not.toContain('sys_assignment_rule');
667+
expect((engine as any).assignment().mayRoute('ticket')).toBe(false);
668+
});
669+
});
670+
671+
describe('[ADR-0142 D5] assignmentExpressionRefusals — the save guard compiles by the paths the seam evaluates by', () => {
672+
it('a condition and an open-work predicate the engine can run are not refused; absent ones neither', () => {
673+
expect(assignmentExpressionRefusals({ criteria: 'record.priority == "high"', load: 'record.status != "closed"' })).toEqual([]);
674+
expect(assignmentExpressionRefusals({ criteria: { dialect: 'cel', source: 'record.priority == "high"' } })).toEqual([]);
675+
expect(assignmentExpressionRefusals({})).toEqual([]);
676+
});
677+
678+
it('a condition that does not parse is refused at `criteria`', () => {
679+
expect(assignmentExpressionRefusals({ criteria: 'record.priority == (' })).toEqual([
680+
{ field: 'criteria', message: expect.any(String) },
681+
]);
682+
});
683+
684+
it('an open-work predicate the pushdown compiler cannot lower is refused at `load` — the shape the seam would park on', () => {
685+
expect(assignmentExpressionRefusals({ load: 'size(record.subject) > 3' })).toEqual([
686+
{ field: 'load', message: expect.any(String) },
687+
]);
688+
});
689+
});
690+
430691
describe('[ADR-0142 D5] nextMember', () => {
431692
it('takes the member after the last one by id, wrapping, and survives a changed member set', () => {
432693
expect(nextMember(['a', 'b', 'c'], null)).toBe('a');

0 commit comments

Comments
 (0)