Skip to content

Commit b0458ed

Browse files
committed
test(plugin-sharing): pin the sys_assignment_rule save guard and its boot report
Claude-Session: https://claude.ai/code/session_016WV4d14C8K4gMehVb6jBvA Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4b6296e commit b0458ed

3 files changed

Lines changed: 143 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ function columnOf(path: ReadonlyArray<PropertyKey>): string {
118118
if (head === 'name') return 'name';
119119
if (head === 'object') return 'object_name';
120120
if (head !== 'entries') return '_record';
121+
if (key === 'name') return 'name'; // the one entry is named after the rule
121122
if (key === 'assignTo') return sub === 'type' ? 'recipient_type' : 'recipient_id';
122123
if (key === 'criteria' || key === 'strategy' || key === 'load') return key;
123124
return '_record';

‎packages/plugins/plugin-sharing/src/objects/sys-sharing-rule.by-object.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ describe('sharing list views — no grouping on a field that stores an object AP
5656
sys_queue: [],
5757
sys_queue_member: [],
5858
sys_assignment_cursor: [],
59+
// An organization's own assignment rule names the object it routes.
60+
sys_assignment_rule: ['object_name'],
5961
});
6062
});
6163

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

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ import {
2121
QUEUE_GUARD_PACKAGE,
2222
} from './queue-hooks.js';
2323
import { ruleRegrantQueue } from './rule-hooks.js';
24+
import {
25+
bindAssignmentRuleGuards,
26+
reportShadowedAuthoredAssignmentRules,
27+
AssignmentRuleValidationError,
28+
ASSIGNMENT_RULE_GUARD_PACKAGE,
29+
} from './assignment-rule-hooks.js';
2430

2531
type Row = Record<string, any>;
2632

@@ -759,3 +765,137 @@ describe('[ADR-0142 D7] queue-recipient rules recompute on a queue-membership wr
759765
await ruleRegrantQueue.whenIdle();
760766
});
761767
});
768+
769+
// ─── ADR-0142 D5: an organization's own assignment rules, judged on save ─────
770+
771+
describe('[ADR-0142 D5] the sys_assignment_rule save guard', () => {
772+
const DECLARED_RULES = [{ name: 'ticket_intake', object: 'ticket', entries: [] }];
773+
const SCHEMAS: Record<string, any> = {
774+
ticket: { name: 'ticket', fields: {} }, // an owned object: the platform injects the queue column
775+
catalog: { name: 'catalog', ownership: 'org', fields: {} }, // no owner, so no queue column
776+
sys_member: { name: 'sys_member', fields: {} },
777+
sys_user: { name: 'sys_user', fields: {} },
778+
};
779+
let engine: ReturnType<typeof makeEngine>;
780+
781+
beforeEach(() => {
782+
engine = makeEngine({
783+
schemas: SCHEMAS,
784+
tables: {
785+
sys_member: [
786+
{ id: 'm1', user_id: 'u_lead', organization_id: 'org_a' },
787+
{ id: 'm2', user_id: 'u_banned', organization_id: 'org_a' },
788+
{ id: 'm3', user_id: 'u_elsewhere', organization_id: 'org_b' },
789+
],
790+
sys_user: [{ id: 'u_lead' }, { id: 'u_banned', banned: true }, { id: 'u_elsewhere' }],
791+
},
792+
});
793+
const listItems = engine.registry.listItems;
794+
engine.registry.listItems = (type: string) => (type === 'assignment_rule' ? DECLARED_RULES : listItems(type));
795+
bindAssignmentRuleGuards(engine as any);
796+
});
797+
798+
const valid = (extra: Row = {}): Row => ({
799+
name: 'vip_tickets', label: 'VIP tickets', object_name: 'ticket', criteria: 'record.priority == "high"',
800+
recipient_type: 'queue', recipient_id: 'vip', ...extra,
801+
});
802+
const save = (data: Row, session: Row | null = { organizationId: 'org_a' }) =>
803+
engine.fire('beforeInsert', 'sys_assignment_rule', { input: { data }, ...(session ? { session } : {}) });
804+
const refusal = async (p: Promise<unknown>) => {
805+
try {
806+
await p;
807+
} catch (err) {
808+
return err as AssignmentRuleValidationError;
809+
}
810+
throw new Error('expected the save to be refused');
811+
};
812+
813+
it('a well-formed rule saves, queue or member target, with or without a strategy', async () => {
814+
await expect(save(valid())).resolves.toBeUndefined();
815+
await expect(save(valid({ recipient_type: 'user', recipient_id: 'u_lead' }))).resolves.toBeUndefined();
816+
await expect(save(valid({ strategy: 'least_loaded', load: 'record.status != "closed"' }))).resolves.toBeUndefined();
817+
await expect(save(valid({ criteria: null, strategy: 'round_robin' }))).resolves.toBeUndefined();
818+
});
819+
820+
it('refuses a declared rule\'s name — one name, one rule — and a name that is not a machine name', async () => {
821+
const taken = await refusal(save(valid({ name: 'ticket_intake' })));
822+
expect(taken).toBeInstanceOf(AssignmentRuleValidationError);
823+
expect(taken).toMatchObject({ code: 'VALIDATION_FAILED', name: 'ValidationError', fields: [{ field: 'name', code: 'invalid_value' }] });
824+
expect((await refusal(save(valid({ name: 'VIP Tickets' })))).fields).toEqual([expect.objectContaining({ field: 'name', code: 'invalid_format' })]);
825+
});
826+
827+
it('refuses an object that does not exist, and one whose records have no owner to set', async () => {
828+
expect((await refusal(save(valid({ object_name: 'tickets' })))).fields).toEqual([expect.objectContaining({ field: 'object_name', code: 'reference_not_found' })]);
829+
expect((await refusal(save(valid({ object_name: 'catalog' })))).fields).toEqual([expect.objectContaining({ field: 'object_name', code: 'invalid_value' })]);
830+
});
831+
832+
it('refuses the entry shapes the stack schema refuses for a declared entry', async () => {
833+
expect((await refusal(save(valid({ recipient_type: 'user', recipient_id: 'u_lead', strategy: 'round_robin' })))).fields)
834+
.toEqual([expect.objectContaining({ field: 'strategy' })]);
835+
expect((await refusal(save(valid({ strategy: 'least_loaded' })))).fields).toEqual([expect.objectContaining({ field: 'load' })]);
836+
expect((await refusal(save(valid({ load: 'record.status != "closed"' })))).fields).toEqual([expect.objectContaining({ field: 'load' })]);
837+
expect((await refusal(save(valid({ recipient_id: 'VIP Queue' })))).fields).toEqual([expect.objectContaining({ field: 'recipient_id' })]);
838+
expect((await refusal(save(valid({ recipient_type: 'team' })))).fields).toEqual([expect.objectContaining({ field: 'recipient_type' })]);
839+
});
840+
841+
it('refuses a condition or an open-work expression the engine\'s CEL paths cannot compile', async () => {
842+
expect((await refusal(save(valid({ criteria: 'record.priority == (' })))).fields).toEqual([expect.objectContaining({ field: 'criteria', code: 'invalid_value' })]);
843+
expect((await refusal(save(valid({ strategy: 'least_loaded', load: 'size(record.subject) > 3' })))).fields)
844+
.toEqual([expect.objectContaining({ field: 'load', code: 'invalid_value' })]);
845+
});
846+
847+
it('refuses a user target who is not an active member of the rule\'s organization', async () => {
848+
expect((await refusal(save(valid({ recipient_type: 'user', recipient_id: 'u_elsewhere' })))).fields)
849+
.toEqual([expect.objectContaining({ field: 'recipient_id', code: 'reference_not_found' })]);
850+
expect((await refusal(save(valid({ recipient_type: 'user', recipient_id: 'u_banned' })))).fields)
851+
.toEqual([expect.objectContaining({ field: 'recipient_id', code: 'reference_user_banned' })]);
852+
// The same user saves in the organization they are a member of.
853+
await expect(save(valid({ recipient_type: 'user', recipient_id: 'u_elsewhere' }), { organizationId: 'org_b' })).resolves.toBeUndefined();
854+
});
855+
856+
it('refuses a rule that would land in no organization', async () => {
857+
expect((await refusal(save(valid(), null))).fields).toEqual([expect.objectContaining({ field: 'organization_id', code: 'required' })]);
858+
await expect(save(valid({ organization_id: 'org_a' }), null)).resolves.toBeUndefined();
859+
});
860+
861+
it('names every field at fault in one refusal', async () => {
862+
const err = await refusal(save(valid({ name: 'ticket_intake', object_name: 'catalog', criteria: 'record.x == (' })));
863+
expect(err.fields.map((f) => f.field).sort()).toEqual(['criteria', 'name', 'object_name']);
864+
});
865+
866+
it('an update is judged on the merged row when it touches a judged column, and not re-judged otherwise', async () => {
867+
const previous = { id: 'r1', organization_id: 'org_a', ...valid({ recipient_type: 'user', recipient_id: 'u_lead' }) };
868+
const update = (data: Row) => engine.fire('beforeUpdate', 'sys_assignment_rule', { input: { data }, previous, session: { organizationId: 'org_a' } });
869+
await expect(update({ label: 'Renamed', active: false, sort_order: 3 })).resolves.toBeUndefined();
870+
expect((await refusal(update({ recipient_id: 'u_elsewhere' }))).fields).toEqual([expect.objectContaining({ field: 'recipient_id' })]);
871+
// The merged row carries the pre-image's user target, so a strategy alone is refused.
872+
expect((await refusal(update({ strategy: 'round_robin' }))).fields).toEqual([expect.objectContaining({ field: 'strategy' })]);
873+
});
874+
875+
it('a membership read that fails refuses the save, saying it could not judge — never a pass', async () => {
876+
const failing = makeEngine({ schemas: SCHEMAS, failOn: ['sys_member'] });
877+
bindAssignmentRuleGuards(failing as any);
878+
await expect(failing.fire('beforeInsert', 'sys_assignment_rule', {
879+
input: { data: valid({ recipient_type: 'user', recipient_id: 'u_lead' }) }, session: { organizationId: 'org_a' },
880+
})).rejects.toThrow(/could not be read, so the assignment rule cannot be judged and is not saved/);
881+
});
882+
883+
it('re-binding replaces, never stacks', () => {
884+
const before = engine.hooks.filter((h) => h.packageId === ASSIGNMENT_RULE_GUARD_PACKAGE).length;
885+
expect(before).toBe(2);
886+
bindAssignmentRuleGuards(engine as any);
887+
expect(engine.hooks.filter((h) => h.packageId === ASSIGNMENT_RULE_GUARD_PACKAGE).length).toBe(before);
888+
});
889+
890+
it('a boot report names every authored rule a declaration now shadows, at error', async () => {
891+
engine._tables.sys_assignment_rule = [
892+
{ id: 'r1', name: 'ticket_intake', organization_id: 'org_a' },
893+
{ id: 'r2', name: 'vip_tickets', organization_id: 'org_a' },
894+
];
895+
const logger = { warn: vi.fn(), error: vi.fn() };
896+
await reportShadowedAuthoredAssignmentRules(engine as any, logger);
897+
expect(logger.error).toHaveBeenCalledTimes(1);
898+
expect(logger.error.mock.calls[0][0]).toMatch(/assignment rule 'ticket_intake' is shadowed/);
899+
expect(logger.error.mock.calls[0][1]).toEqual({ rule: 'ticket_intake', organization: 'org_a' });
900+
});
901+
});

0 commit comments

Comments
 (0)