Skip to content

Commit aa8b43f

Browse files
committed
feat(objectql): purge and empty the recycle bin, and the permanent delete, as the purge operation
ObjectQL.purge(entryId) removes one recycle-bin entry and ObjectQL.empty(object) every entry of one object, scoped to the caller's organization. A by-id delete with permanent: true writes no entry. All three are dispatched as the new `purge` operation on the business object, never with an AST, so the recycle-bin manager's grant governs them; plugin-security refuses the unmapped verb for every non-system caller until it is mapped. The permanent delete is refused 400 off the by-id path, on a platform object and for a non-boolean value. `purge` advances the write epoch and names no hook pair, so beforePurge/afterPurge keep warning as before. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4czFGLnXKQd6cQjv3Pr
1 parent 2302a5f commit aa8b43f

10 files changed

Lines changed: 839 additions & 48 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/objectql': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
feat(objectql,spec): purge and empty the recycle bin, and delete a record for good (ADR-0148): `ObjectQL.purge(entryId)`, `ObjectQL.empty(object)` and `delete(object, { where: { id }, permanent: true })`, all authorized as the `purge` operation
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: added
10+
Skills-docs: follow-up #30847 — `skills/objectstack-api/SKILL.md` :268, :417 teach that there is no recycle bin; the skills lane owns that file.
11+
12+
The recycle bin's removal side. All three acts are dispatched through the middleware chain as one new operation, `purge`, on the business object the rows belong to, so one grant will govern all three: `manageRecycleBin`, the recycle-bin manager's (ADR-0148 D5). **Until `@objectstack/plugin-security` maps `purge` to that grant, it refuses `purge` for every caller that is not the system**, the fail-closed rule it already applies to the destructive verbs. So in this release only the system, or a composition without the security plugin, can purge, empty or delete for good. Restoring, the two grants and the REST doors are not in this release.
13+
14+
- **`@objectstack/spec`:** `EngineDeleteOptions` gains `permanent?: boolean`: delete for good, so the rows skip the recycle bin and cannot be restored. It is authorized as the `purge` operation, not `delete`, and is honoured on a by-id delete only.
15+
- **`@objectstack/objectql`, the permanent delete:** `delete(object, { where: { id }, permanent: true })` runs as the by-id delete does (its `beforeDelete` / `afterDelete` hooks, which read `permanent` off `input.options`, its cascade, its events), writes no recycle-bin entry, and is dispatched as `purge` with the row's id. These are refused `400 VALIDATION_ERROR` (`param: 'permanent'`) before any middleware or hook runs:
16+
- `permanent: true` on a delete that is not by id, or that asks `multi: true`;
17+
- `permanent: true` on a platform object (`sys_*`, `cloud_*`, `ai_*`), whose delete never enters the bin and is already permanent;
18+
- a `permanent` that is not a boolean.
19+
`permanent: false` is the ordinary delete.
20+
- **`@objectstack/objectql`, `purge(entryId, { context })`:** removes one recycle-bin entry and answers `true`. It answers `false` when no entry with that id is visible to the caller's organization, or when the composition registers no bin. The entry is read first, scoped to the caller's organization, for the object its rows belong to; the removal is then dispatched as `purge` on that object, with no id.
21+
- **`@objectstack/objectql`, `empty(object, { context })`:** removes every entry of one object that the caller's organization holds, and answers how many. It is one `purge` dispatch on `object`, so one authorization covers it. The object need not be registered any more, so an uninstalled package's entries can still be emptied. A platform object, or an empty name, is refused `400 VALIDATION_ERROR` (`param: 'object'`). It answers `0` when the composition registers no bin.
22+
- **Middleware authors:** `OperationContext.operation` gains `'purge'`, which never carries an `ast`. A middleware that switches on the operation exhaustively, or keys write handling on `'delete'`, sees the permanent delete as `'purge'`. `purge` advances the engine's write epoch, as `insert`, `update` and `delete` do (`WRITE_EPOCH_OPERATIONS`). `beforePurge` / `afterPurge` are not engine hook events: registering one warns that it never fires, as before.

‎packages/objectql/src/engine-middleware-operation-vocabulary.test.ts‎

Lines changed: 80 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22
//
3-
// [#7809] The engine's MIDDLEWARE DISPATCH VOCABULARY is fixed, and it contains
4-
// no destructive lifecycle verb (`purge` / `transfer` / `restore`).
3+
// [#7809] The engine's MIDDLEWARE DISPATCH VOCABULARY is fixed. Of the
4+
// destructive lifecycle verbs (`purge` / `transfer` / `restore`) it contains
5+
// `purge` alone (#30237, the recycle bin), and `purge` never carries an AST.
56
//
67
// ── Why a pin here, in objectql, for a finding filed against plugin-security ──
78
//
@@ -18,10 +19,14 @@
1819
// the same select-only object is scoped (#7665).
1920
//
2021
// The finding's own first question was whether those verbs can reach that path
21-
// at all. They cannot — not on the AST path, and not on ANY path:
22+
// at all. They cannot reach the AST path. `transfer` and `restore` reach no
23+
// path; `purge` reaches the by-id and object-level ones only:
2224
//
23-
// 1. `OperationContext['operation']` is the 7-member union pinned below.
24-
// No destructive lifecycle verb is a member.
25+
// 1. `OperationContext['operation']` is the 8-member union pinned below.
26+
// Of the destructive lifecycle verbs, `purge` alone is a member (#30237),
27+
// and every dispatch of it is built without an `ast`: the permanent by-id
28+
// delete (`permanent: true`, refused on any delete that is not by id),
29+
// `purge(entryId)` and `empty(object)`.
2530
// 2. Middleware is invoked from exactly one place — the PRIVATE
2631
// `executeWithMiddleware(ctx: OperationContext, …)`. There is no other
2732
// caller, and no public seam that hands a middleware a context the engine
@@ -30,12 +35,13 @@
3035
// `operation` is a member of that union by construction.
3136
//
3237
// So step 3 passing `opCtx.operation` raw is SAFE TODAY — not by accident, but
33-
// because the vocabulary cannot deliver a verb it fails to handle. This file
34-
// exists so that stays true by assertion rather than by luck: the day a recycle
35-
// bin (#3146, parked — `enable.trash` was retired in #2377/ADR-0049, which is
36-
// why `API_METHOD_DERIVATION` gives `restore`/`purge` a permanent
37-
// `flag: () => false`) makes one of these verbs dispatchable, this pin goes red
38-
// and names the two sites that must normalise first.
38+
// because the vocabulary cannot deliver a verb it fails to handle ON THAT PATH.
39+
// This file exists so that stays true by assertion rather than by luck. The
40+
// recycle bin (ADR-0148, #30237) made `purge` dispatchable, and kept it off the
41+
// AST path, which the AST-set lock below proves; the by-id permanent delete is
42+
// judged by step 2.7, which normalises `purge -> delete`. The day a destructive
43+
// verb reaches the AST path, this pin goes red and names the two sites that
44+
// must normalise first.
3945
//
4046
// ⚠️ Note the vocabularies are deliberately DIFFERENT and must not be conflated:
4147
// `ExplainOperationSchema` (spec/security/explain.zod.ts) is a 7-verb
@@ -119,6 +125,8 @@ const DISPATCHED_OPERATIONS = [
119125
'delete',
120126
'count',
121127
'aggregate',
128+
// [#30237] The recycle bin's removal verb: the permanent delete, purge, empty.
129+
'purge',
122130
] as const;
123131

124132
type Declared = (typeof DISPATCHED_OPERATIONS)[number];
@@ -180,11 +188,14 @@ function readDispatchedUnionFromEngineSource(): string[] {
180188
/**
181189
* The verbs #7809 is about. `plugin-security`'s step-2.7 gate normalises these
182190
* onto `update`/`delete` before deriving row scope; its step-3 AST path and the
183-
* ADR-0090 D10 delegator half do NOT. Keeping them out of the dispatch
184-
* vocabulary is what makes that difference unobservable.
191+
* ADR-0090 D10 delegator half do NOT. Keeping them off the AST path is what
192+
* makes that difference unobservable.
185193
*/
186194
const DESTRUCTIVE_LIFECYCLE_VERBS = ['purge', 'transfer', 'restore'] as const;
187195

196+
/** [#30237] The one destructive lifecycle verb the engine dispatches, never with an AST. */
197+
const DISPATCHED_DESTRUCTIVE_VERBS = ['purge'] as const;
198+
188199
const NOTE_SCHEMA = {
189200
name: 'note',
190201
fields: {
@@ -202,6 +213,20 @@ const NOTE_SCHEMA = {
202213
*/
203214
const ROW = { id: 'n1', title: 'x', owner: 'me' };
204215

216+
/**
217+
* [#30237] The recycle bin, registered so the probe reaches its three `purge`
218+
* dispatches: an entry the driver always has, of a `note`.
219+
*/
220+
const BIN_SCHEMA = {
221+
name: 'sys_recycle_bin',
222+
fields: {
223+
id: { type: 'text' },
224+
object_name: { type: 'text' },
225+
record_id: { type: 'text' },
226+
},
227+
};
228+
const ENTRY = { id: 'e1', object_name: 'note', record_id: 'n1' };
229+
205230
// `any` on the double itself, matching the sibling read-filter test: this is a
206231
// deliberately PARTIAL driver (the engine only reaches the members listed), and
207232
// annotating it `IDataDriver` would demand the whole surface for no assertion.
@@ -214,7 +239,7 @@ function makeDriver(): any {
214239
supports: {},
215240
connect: vi.fn().mockResolvedValue(undefined),
216241
disconnect: vi.fn().mockResolvedValue(undefined),
217-
find: vi.fn(async () => [{ ...ROW }]),
242+
find: vi.fn(async (object: string) => [object === 'sys_recycle_bin' ? { ...ENTRY } : { ...ROW }]),
218243
findOne: vi.fn(async () => ({ ...ROW })),
219244
count: vi.fn(async () => 1),
220245
aggregate: vi.fn(async () => []),
@@ -229,11 +254,13 @@ function makeDriver(): any {
229254
interface Seen {
230255
operation: string;
231256
hasAst: boolean;
257+
/** A scalar `options.where.id`: the live row a by-id write names. */
258+
hasId: boolean;
232259
}
233260

234261
async function makeEngine() {
235262
vi.mocked((SchemaRegistry as any).getObject).mockImplementation((name: string) =>
236-
name === 'note' ? NOTE_SCHEMA : undefined,
263+
name === 'note' ? NOTE_SCHEMA : name === 'sys_recycle_bin' ? BIN_SCHEMA : undefined,
237264
);
238265
const ql = new ObjectQL();
239266
ql.registerDriver(makeDriver(), true);
@@ -244,7 +271,8 @@ async function makeEngine() {
244271
// precisely why that plugin can compare against verbs the union does not
245272
// contain without TypeScript ever objecting.
246273
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
247-
seen.push({ operation: opCtx.operation, hasAst: !!opCtx.ast });
274+
const id = opCtx.options?.where?.id;
275+
seen.push({ operation: opCtx.operation, hasAst: !!opCtx.ast, hasId: typeof id === 'string' || typeof id === 'number' });
248276
await next();
249277
});
250278
return { ql, seen };
@@ -285,6 +313,10 @@ async function driveEveryPublicMethod(ql: ObjectQL): Promise<void> {
285313
await ql.update('note', { title: 'bulk' }, { multi: true, where: { owner: 'me' }, context: ctx } as any);
286314
await ql.delete('note', { where: { id: 'n1' }, context: ctx } as any);
287315
await ql.delete('note', { multi: true, where: { owner: 'me' }, context: ctx } as any);
316+
// [#30237] The recycle bin's three `purge` dispatches, in this order.
317+
await ql.delete('note', { where: { id: 'n1' }, permanent: true, context: ctx });
318+
await ql.purge('e1', { context: ctx });
319+
await ql.empty('note', { context: ctx });
288320
}
289321

290322
describe('[#7809] engine middleware dispatch vocabulary', () => {
@@ -297,34 +329,56 @@ describe('[#7809] engine middleware dispatch vocabulary', () => {
297329
expect(fromSource.slice().sort()).toEqual([...DISPATCHED_OPERATIONS].sort());
298330
});
299331

300-
it('the engine union declares no destructive lifecycle verb', () => {
332+
it('the engine union declares `purge` and no other destructive lifecycle verb', () => {
301333
const fromSource = readDispatchedUnionFromEngineSource();
302334
const destructive = fromSource.filter((op) =>
303335
(DESTRUCTIVE_LIFECYCLE_VERBS as readonly string[]).includes(op),
304336
);
305337
// Asserted against the SOURCE list, not against `DISPATCHED_OPERATIONS` —
306338
// checking this file's own array against this file's own array would prove
307339
// nothing.
308-
expect(destructive).toEqual([]);
340+
expect(destructive).toEqual([...DISPATCHED_DESTRUCTIVE_VERBS]);
309341
});
310342

311-
it('a real engine driven through every public method dispatches exactly the 7', async () => {
343+
it('a real engine driven through every public method dispatches exactly the 8', async () => {
312344
const { ql, seen } = await makeEngine();
313345
await driveEveryPublicMethod(ql);
314346

315347
const observed = [...new Set(seen.map((s) => s.operation))].sort();
316348
expect(observed).toEqual([...DISPATCHED_OPERATIONS].sort());
317349
});
318350

319-
it('no destructive lifecycle verb reaches a middleware, on any path', async () => {
351+
it('of the destructive lifecycle verbs, only `purge` reaches a middleware, and never with an AST', async () => {
320352
const { ql, seen } = await makeEngine();
321353
await driveEveryPublicMethod(ql);
322354

323355
expect(seen.length).toBeGreaterThan(0);
324356
const destructive = seen.filter((s) =>
325357
(DESTRUCTIVE_LIFECYCLE_VERBS as readonly string[]).includes(s.operation),
326358
);
327-
expect(destructive).toEqual([]);
359+
// [#30237] The permanent delete, `purge` and `empty`, in the order driven.
360+
// Only the permanent delete names a live row: step 2.7 judges that row
361+
// as a delete (`purge -> delete`); `purge` and `empty` are object-level.
362+
expect(destructive).toEqual([
363+
{ operation: 'purge', hasAst: false, hasId: true },
364+
{ operation: 'purge', hasAst: false, hasId: false },
365+
{ operation: 'purge', hasAst: false, hasId: false },
366+
]);
367+
});
368+
369+
it('[#30237] `permanent: true` off the by-id path is refused before any middleware runs', async () => {
370+
const { ql, seen } = await makeEngine();
371+
const ctx: ExecutionContext = { userId: 'u1', isSystem: true };
372+
373+
// A delete by filter: it would carry its `where` as an AST.
374+
await expect(
375+
ql.delete('note', { multi: true, where: { owner: 'me' }, permanent: true, context: ctx }),
376+
).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
377+
// A by-id delete asked as a predicate one: the bin never takes it.
378+
await expect(
379+
ql.delete('note', { multi: true, where: { id: 'n1' }, permanent: true, context: ctx }),
380+
).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
381+
expect(seen).toEqual([]);
328382
});
329383

330384
it('every AST-carrying dispatch — the #7809 path — carries a handled operation', async () => {
@@ -355,10 +409,14 @@ describe('[#7809] engine middleware dispatch vocabulary', () => {
355409
const astOperations = [...new Set(astCarrying.map((s) => s.operation))].sort();
356410
expect(astOperations).toEqual(['aggregate', 'count', 'delete', 'find', 'findOne', 'update']);
357411

358-
// The by-id write branches, conversely, must NOT carry an ast.
412+
// The by-id write branches, conversely, must NOT carry an ast; nor does
413+
// any `purge` (#30237: the permanent delete, `purge`, `empty`).
359414
expect(seen.filter((s) => !s.hasAst).map((s) => s.operation).sort()).toEqual([
360415
'delete',
361416
'insert',
417+
'purge',
418+
'purge',
419+
'purge',
362420
'update',
363421
]);
364422
});

‎packages/objectql/src/engine-top-level.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -137,34 +137,42 @@ const DISPATCHABLE_HOOK_EVENTS: ReadonlySet<string> = new Set([
137137
* [#17713] Every verb the engine can put on an {@link OperationContext}, as
138138
* DATA rather than as a second hand-written list.
139139
*
140-
* The type annotation is the weld: `Record<Union, true>` is exhaustive in both
141-
* directions, so a new engine method that widens `OperationContext['operation']`
140+
* The type annotation is the weld: `Record<Union, boolean>` is exhaustive in
141+
* both directions, so a new engine method that widens `OperationContext['operation']`
142142
* fails to compile here until the verb is added, and a verb dropped from the
143-
* union makes its entry an excess property. `pnpm typecheck` compiles this file
143+
* union makes its entry an excess property. The value says whether the verb
144+
* names a `before`/`after` hook pair. `pnpm typecheck` compiles this file
144145
* (it is `src`, not the test layer), so the weld is enforced by the package's
145146
* own type check and not only by a test.
146147
*
147148
* It exists so {@link UNDISPATCHED_LIFECYCLE_HOOK_EVENTS} below is DERIVED. A
148149
* hand-written list of "the events we refuse" would be this card's own defect
149150
* one layer up: it would go stale the moment a verb is added, and silently.
150151
*/
151-
const ENGINE_OPERATION_VERBS: Record<OperationContext['operation'], true> = {
152+
const ENGINE_OPERATION_VERBS: Record<OperationContext['operation'], boolean> = {
152153
find: true,
153154
findOne: true,
154155
insert: true,
155156
update: true,
156157
delete: true,
157158
count: true,
158159
aggregate: true,
160+
// [#30237] The recycle bin's removal verb names no hook pair. `beforePurge` /
161+
// `afterPurge` stay outside the lifecycle namespace, where they were before
162+
// the verb existed: inside it they would be refused at registration, a
163+
// narrowing of `registerHook` this verb does not make. The permanent delete
164+
// still fires `beforeDelete` / `afterDelete`.
165+
purge: false,
159166
};
160167

161168
/**
162169
* [#17713] The engine's own lifecycle-event NAMESPACE — `before`/`after` × every
163-
* verb in {@link ENGINE_OPERATION_VERBS}. Fourteen names, of which
164-
* {@link DISPATCHABLE_HOOK_EVENTS} is the eight the engine actually dispatches.
170+
* verb in {@link ENGINE_OPERATION_VERBS} that names a hook pair. Fourteen names,
171+
* of which {@link DISPATCHABLE_HOOK_EVENTS} is the eight the engine actually
172+
* dispatches.
165173
*/
166174
const ENGINE_LIFECYCLE_HOOK_EVENTS: ReadonlySet<string> = new Set(
167-
Object.keys(ENGINE_OPERATION_VERBS).flatMap((verb) => {
175+
Object.keys(ENGINE_OPERATION_VERBS).filter((verb) => ENGINE_OPERATION_VERBS[verb as OperationContext['operation']]).flatMap((verb) => {
168176
const suffix = `${verb.charAt(0).toUpperCase()}${verb.slice(1)}`;
169177
return [`before${suffix}`, `after${suffix}`];
170178
}),
@@ -321,7 +329,7 @@ const ENGINE_UPDATE_OPTION_KEYS: ReadonlySet<string> = new Set([
321329
...ENGINE_DRIVER_PASSTHROUGH_KEYS,
322330
]);
323331
const ENGINE_DELETE_OPTION_KEYS: ReadonlySet<string> = new Set([
324-
'context', 'where', 'multi',
332+
'context', 'where', 'multi', 'permanent',
325333
...ENGINE_DRIVER_PASSTHROUGH_KEYS,
326334
]);
327335
// `search` / `searchFields` are READ by `count` and `aggregate` through the
@@ -3659,7 +3667,16 @@ export interface FunctionRegistrationOptions {
36593667
*/
36603668
export interface OperationContext {
36613669
object: string;
3662-
operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';
3670+
/**
3671+
* The verb the middleware chain authorizes. `purge` [#30237, ADR-0148] is the
3672+
* recycle bin's removal verb, dispatched on the business object the rows
3673+
* belong to: a by-id `delete` with `permanent: true` (its `where.id` the live
3674+
* row's), `purge(entryId)` and `empty(object)` (no id). It never carries an
3675+
* `ast`, so `@objectstack/plugin-security`'s AST path (step 3), which hands the
3676+
* verb to the RLS compiler raw, never sees it (#7809,
3677+
* `engine-middleware-operation-vocabulary.test.ts`).
3678+
*/
3679+
operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate' | 'purge';
36633680
ast?: QueryAST;
36643681
data?: any;
36653682
options?: any;

0 commit comments

Comments
 (0)