Skip to content

Commit 6e0b16a

Browse files
feat(objectql,metadata-protocol,rest,spec): the object read names the objects a delete can cascade into (#28451)
domain:server#2 · os-project-manager · session_0186vfjHHMsRXC9EUT9hTFMo <!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XBu9BsFDDrJayyDodXhfHC4)_ Part of #28001 (the server half of ruling B; the ui half, the delete confirmations that read this key, is its own `domain:ui` card, blocked by this PR). Clause-②: yes (widening) — a new optional key served beside the object read (`cascadeDeleteObjects`, both item doors and the app bundle's object entries), a new optional `IObjectQLEngine` member and a new public `ObjectQL` method. Nothing is refused that ran before. Metadata-protocol: added — the served key `cascadeDeleteObjects` moves the `api` authorable-surface shard (`packages/spec/authorable-surface/api.json`), which `scripts/check-changeset-no-major.mjs` reads as an added protocol key; `@objectstack/spec` is graded `minor` (the #27842 / #27964 shape). Nothing an author can write moves: the key is served beside `item`, never inside it, and has no authorable spelling. Skills-docs: none — a served-only key; no `skills/**` text names `cascadeDeleteObjects` or `disabledActions`. ## 维护者速读 - **改了什么**:`GET /api/v1/meta/object/:name`(缓存默认门与非缓存门,以及 app bundle 里每个对象条目)在 `item` 旁边多返回一个 `cascadeDeleteObjects`:删除这个对象的一条记录时会被级联一起删掉的对象名列表(主从子对象默认算,lookup/tree 只有声明 `deleteBehavior: 'cascade'` 才算,孙辈对象也算,`restrict` / `set_null` 不算)。列表由引擎 `ObjectQL.getCascadeDeleteObjects` 给出,它和删除流程共用同一个「哪些关系会级联」的扫描函数。 - **为什么改**:#28001 裁决 B:删除确认框要加一行说明「这还会删掉哪些子对象」,列表必须来自服务端、不能在前端复制一份引擎规则;服务端这一半先落。HotCRM 里删一条线索会悄悄删掉它的活动成员记录。 - **风险与回滚**:只加不减;删除本身行为不变(现有级联删除测试照旧绿)。只读注册表、不读任何行,所以不会泄露记录或数量;只给对象名、不给字段名(字段可能被另一对象的 ADR-0106 掩码隐藏)。缓存门把列表折进 ETag,后注册的级联对象会让 ETag 变。回滚即 revert。 - **先看**:`packages/objectql/src/engine-delete-cascade.ts`(`cascadeRelationsInto` 抽出与 `collectCascadeDeleteObjects`);`packages/metadata-protocol/src/protocol.ts`(`resolveCascadeDeleteObjects` 与 `getMetaItemCached` 的 304 退让);`packages/rest/src/meta-item-read-routes.ts`(ETag 折叠)。 - **两分钟验证**:`pnpm --filter @objectstack/objectql exec vitest run src/engine-cascade-delete-objects.test.ts` → 7 passed,其中 `cd_parent` 答 `['cd_child', 'cd_grandchild']`,restrict / set_null 兄弟不在列。 - **需要你做的**:无,席位落地(触及 `packages/spec/**`,席位先做合约评审)。 ## What changes ### The shape, measured and chosen - **Object-level, not record-level.** The confirmation names child *objects*. `ObjectQL.getCascadeDeleteObjects(object)` reads the registry and no row, so it says what a delete MAY remove, never which records or how many. `inspectCascadeDelete` (record-level, reads as SYSTEM with no organization) is untouched and is not exposed anywhere. - **Transitive, the walk's own closure.** Breadth-first from the object through every relation whose resolved behaviour is `cascade`, each object named once at the first depth that reaches it and expanded once, so a cycle (a self-cascading `tree`, two objects cascading into each other) terminates. The object itself is named only when a cascading relation leads back to it. - **One rule.** The collection walk's scan of "which relations cascade into this object" (`cascadingInto` inside `collectCascadeDeleteSet`) is lifted out unedited as `cascadeRelationsInto`, and both `collectCascadeDeleteSet` and the new `collectCascadeDeleteObjects` call it. It reads `cascadeRelationBehavior(target, child, fieldName, fdef) === 'cascade'`, the predicate the delete runs. No copy of the rule lives in rest, runtime, metadata-protocol or spec. - **Where it is served: beside the object item read, on `disabledActions`' (#27842 / #28044) terms.** The console's grid and record page read `GET /meta/object/:name` (`ObjectStackAdapter.getObjectSchema`) or the app bundle's object entries, so a key on that answer needs no second request; a new read route would add a route-ledger row and a second round trip. Precisely as `disabledActions` does: - the protocol reads the engine's optional `IObjectQLEngine.getCascadeDeleteObjects` through the kernel's service table by name (`objectql`), per call, and imports no engine; - served face only: absent on the execution face and on a draft read; absent on the list read (`GET /meta/object`), since the confirmations read the item; - absent where no engine answered (no engine, an engine without the member, an object the registry does not hold), `[]` where the engine answered that nothing cascades; - on the cached default door too: `getMetaItemCached` carries it beside `data` and stands its own 304 down for a read that carries it; the REST door folds the served list into the object read's ETag, so an unchanged object with an unchanged cascade revalidates to 304, and an object registered later that cascades into it moves the ETag. An object no engine answered for keeps its old validator byte for byte. - The app bundle's object entries are item answers (`getMetaItem` through `createMetaItemAnswer`), so they carry the key with no change to the bundle route. - **Object names, not fields.** The order's hypothesis was one entry per object with the field carrying the edge. Measured: a field of another object can be withheld from this caller by that object's ADR-0106 mask (D1 removes an unreadable field whole, its existence included), while an object read withholds no object (`createMetaItemReadGate`'s `object` arm prunes only `listViews`; measured on this tree, a member with no nav reach to `secret_deal` is answered `200` on `GET /meta/object/secret_deal`). Serving field names would disclose masked fields; serving object names discloses nothing an object read does not. One entry per object also absorbs an object reached by two fields. The ui half shows object labels, which the client resolves from names; no translated text is served. - **Typed in spec.** `GetMetaItemResponseSchema` and `GetMetaItemCachedResponseSchema` gain the optional `cascadeDeleteObjects: string[]`, documented beside `disabledActions`. `IObjectQLEngine` gains the optional `getCascadeDeleteObjects?(objectName): string[] | undefined`. ### Files - `packages/objectql/src/engine-delete-cascade.ts`: `cascadeRelationsInto` (lifted from `collectCascadeDeleteSet`), `collectCascadeDeleteObjects`. - `packages/objectql/src/engine.ts`: public `getCascadeDeleteObjects`. - `packages/spec/src/contracts/objectql-engine.ts`, `packages/spec/src/api/protocol.zod.ts`: the member and the key. - `packages/metadata-protocol/src/protocol.ts`: `resolveCascadeDeleteObjects`, the item read's envelope, `getMetaItemCached`. - `packages/rest/src/meta-item-read-routes.ts`: the cached arm carries it and folds it into the ETag. - `content/docs/references/api/protocol.mdx`, `app-bundle.mdx`: regenerated (`gen:docs`). - Tests: `packages/objectql/src/engine-cascade-delete-objects.test.ts`, `packages/metadata-protocol/src/protocol.object-cascade-delete-objects.test.ts`, `packages/rest/src/meta-object-cached-cascade-delete-objects.test.ts`, a `[#28001]` block in `packages/rest/src/meta-app-bundle-routes.test.ts` and in `packages/spec/src/api/meta-item-response-shapes.test.ts`. - `.changeset/28001-cascade-delete-objects-beside-item.md`: `minor` for spec; `patch` for objectql, metadata-protocol, rest. ## Tests - **Red first** (production sources restored to `origin/main` `4bc077d2`, objectql and metadata-protocol `dist/` rebuilt from them, tests kept): `engine-cascade-delete-objects.test.ts` 7/7 failed; `protocol.object-cascade-delete-objects.test.ts` 5 failed, 4 passed (the four controls: no key without an engine, other types, execution face, the list); `meta-object-cached-cascade-delete-objects.test.ts` 3 failed, 3 passed (the no-key control and the unchanged-validator 304 controls); `meta-item-response-shapes.test.ts` 4 failed, 28 passed. The restore leg's `git diff HEAD` was empty. - **Green** on head: the fixture `cd_parent` ← `cd_child` (master_detail, default cascade) ← `cd_grandchild` (lookup, `deleteBehavior: 'cascade'`), with a `restrict` sibling (`cd_pin`), a `set_null` sibling (`cd_tag`) and a default-`set_null` lookup on the child (`cd_note`): `cd_parent` answers `['cd_child', 'cd_grandchild']`, `cd_child` answers `['cd_grandchild']`; the self-cascading `cd_folder` answers `['cd_folder']`; `cd_loner` answers `[]`; an unknown object `undefined`. The real protocol over the real engine serves the same list on both doors, `[]` for `cd_loner`, nothing on the execution face, and an object registered later that cascades into `cd_loner` is on the next read. - **Agreement with the delete:** a real `delete()` of a `cd_parent` record empties exactly `cd_child` and `cd_grandchild`, leaves the `set_null` holders standing, and equals the served list. - **Ablation** (`scripts/ablation-replace.mjs`, src-resolved suite, restore proven `blob == HEAD`, `git diff HEAD` empty): replacing `cascadeRelationsInto.call(this, target, objects)` in `collectCascadeDeleteObjects` with a hand-written lookup-only filter (`type === 'lookup' && deleteBehavior === 'cascade'`) reds the master_detail case (`expected [] to deeply equal [ 'cd_child', 'cd_grandchild' ]`) and the self-cascading tree case, while `engine-cascade-delete.test.ts` (the delete itself) stays green. The protocol-door rows of that run read a stale base `dist/` from the red leg and are not counted. - **Controls:** the delete is unchanged (`engine-cascade-delete.test.ts`, `engine-inspect-cascade-delete.test.ts` green); an object with no cascading children answers `[]`; no engine answer serves no key and keeps the old ETag. ## Acceptance notes - ~~`Metadata-protocol: none` with `patch` everywhere~~ [Edit by the seat: the contract review (6546633648) ruled option B. The changeset gate refuses `none` whenever an authorable-surface shard moves, so head 7f3638c declares `Metadata-protocol: added` and grades `@objectstack/spec` `minor`, as the `disabledActions` precedent did.] - The list read (`GET /meta/object`) does not carry the key. The confirmations read the item; adding it to the list is a widening with no reader yet. - Order-of-reach is the walk's breadth-first order; the ui half may sort by label. ## Verification Local runs. The package suites and the first 88 derived gates ran on `81f57815`; the last commit, `8bfac916`, adds only the engine-double ledger pin, after which `check:engine-double-contract` and the 30 families it added to the derivation ran on `8bfac916`: - `pnpm --filter @objectstack/objectql run test` exit 0, 9836 passed; `typecheck` exit 0. - `pnpm --filter @objectstack/metadata-protocol run test` exit 0, 21881 passed, 26 skipped; `typecheck` exit 0. - `pnpm --filter @objectstack/rest run test` exit 0, 6870 passed, 332 skipped; `typecheck` exit 0. - `pnpm --filter @objectstack/spec run test` exit 0, 22834 passed, 1 todo; `typecheck` exit 0. - `@objectstack/runtime` `src/domains/meta-list-projection-parity.test.ts` and `src/domains/meta*`: 29 files, 1425 passed. - `pnpm --filter @objectstack/spec check:generated`: `check:docs` stale before `gen:docs`, regenerated and committed; the other 13 artifacts up to date. - Derived gates (`node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`): reconciled with `--ran`, `118 derived famil(ies) accounted for — 117 run, 1 NOT-MEASURED`. Every run family exit 0, after two fixes in this PR: `check:engine-double-contract` first answered exit 1 (`RETAINED [findOne]` for the new metadata-protocol double: new coverage the ledger must learn), fixed by `node scripts/check-engine-double-contract.mjs --write` (`scripts/engine-double-contract.pinned.json`, +1 row) and re-run exit 0; `check-plugin-teardown-shape.mjs --self-test` first answered exit 3 on the shallow clone and exit 0 after fetching its positive-control commit. - NOT MEASURED: `pnpm check:dual-build-cjs-loads` (exit 3, PREREQUISITE NOT MET: it needs every package's `dist/`, this worktree built only the touched closures). CI runs it. - `pnpm exec eslint --no-inline-config packages/objectql packages/metadata-protocol packages/rest packages/spec`: exit 0. - Dogfood battery: not run (no `!` in the title, no `(narrowing)` arm). `test:repo` projects: declared to CI (Test Core). --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pEcJ17rvFVfE3NXzN)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 36436fa commit 6e0b16a

16 files changed

Lines changed: 950 additions & 24 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/objectql': patch
4+
'@objectstack/metadata-protocol': patch
5+
'@objectstack/rest': patch
6+
---
7+
8+
feat: the object read names the objects a delete can cascade into, beside the item
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: added
12+
Skills-docs: none — `cascadeDeleteObjects` is a served-only key beside the object read with no authorable spelling; no file under `skills/**` teaches the object read's envelope keys (a `git grep` of `skills/` for `cascadeDeleteObjects` and `disabledActions` names nothing), and every taught `deleteBehavior` use stays true.
13+
14+
- **Served beside the object** (`@objectstack/metadata-protocol`, `@objectstack/rest`). `GET /api/v1/meta/object/:name` serves `cascadeDeleteObjects` beside `item`: the names of the objects that deleting a record of this object can also delete. That is every object whose relation into it cascades (a `master_detail` by default, a `lookup` or `tree` that declares `deleteBehavior: 'cascade'`), and the objects that cascade into those in turn, each once. A `restrict` or `set_null` relation removes nothing and is not named. The default cached door carries it too, and the list is folded into that door's ETag, so an object registered later that cascades into this one changes the ETag. The key is absent where no engine answered, on a draft read, on the list read and on every type other than `object`; `[]` means nothing cascades. `item` is unchanged. A delete confirmation can now name what else a delete removes without keeping its own copy of the rule.
15+
- **The fact it serves** (`@objectstack/objectql`). `ObjectQL.getCascadeDeleteObjects(object)` answers that list from the delete walk's own relation scan, which the delete and this read now share. It reads the registry and no row, so it never says which records or how many. It returns `undefined` for an object the registry does not hold.
16+
- **The declaration** (`@objectstack/spec`). `GetMetaItemResponseSchema` and `GetMetaItemCachedResponseSchema` gain the optional `cascadeDeleteObjects` (an array of object names), and `IObjectQLEngine` gains the optional member `getCascadeDeleteObjects(objectName)`, which the metadata read calls through the kernel's service table. Nothing about it is authorable.

‎content/docs/references/api/app-bundle.mdx‎

Lines changed: 5 additions & 0 deletions
Large diffs are not rendered by default.

‎content/docs/references/api/protocol.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,7 @@ This schema accepts one of the following structures:
13351335
| **version** | `string` | optional | Metadata version identifier |
13361336
| **registration** | `{ state: 'registered' } \| { state: 'refused'; reason: object } \| { state: 'unregistered' }` | optional | The automation engine's verdict on the flow in `data`, read live on every call and never part of `etag` (see `FlowRegistrationSchema`). Present only for a `flow` read answered by a process that runs an automation service; a read that carries it is never answered `notModified`. Absent otherwise, and absence means no engine judged it, never `registered`. |
13371337
| **disabledActions** | `string[]` | optional | The names in the `actions` of the object in `data` that this deployment's activation ledger switches off (a call to any of them is refused 409 `ACTION_DISABLED`), read live on every call and never part of `etag`. Present only for an `object` read answered by a process whose data engine has an activation ledger attached, `[]` when none is switched off; this method never answers `notModified` for a read that carries it (the REST door folds the served list into the ETag it checks instead, so its 304 comes back only while the switched-off set is unchanged). Absent otherwise, and absence means no ledger answered, never that nothing is switched off. |
1338+
| **cascadeDeleteObjects** | `string[]` | optional | The objects, by name, that deleting a record of the object in `data` can also delete (the item read's `cascadeDeleteObjects`), read live on every call and never part of `etag`. Present only for an `object` read answered by a process whose data engine answers it, `[]` when nothing cascades; this method never answers `notModified` for a read that carries it (the REST door folds the served list into the ETag it checks instead). Absent otherwise, and absence means no engine answered, never that nothing cascades. |
13381339

13391340
### Nested Shape: `GetMetaItemCachedResponse.etag`
13401341

@@ -1462,6 +1463,7 @@ This schema accepts one of the following structures:
14621463
| **version** | `string \| null` | optional | ADR-0008 version token of the STORED row a save to this item compares against, at this read's scope (the environment's partition and `?package=`) and lifecycle (`?state=draft` reads the draft row, the plain read the active row). The same keyed token a save receipt's `version` serves for that row: send it back as the `If-Match` request header on `PUT /meta/:type/:name` (with `?mode=draft` for the draft) and a concurrent edit is refused 409 `METADATA_CONFLICT` instead of overwritten. `null` when no stored row is there — an item served from code or a package artifact, or from a row in another scope (a package-less row a package read falls back to) — so the next save creates one: pin it with `If-None-Match: *`. A `null` beside `editable: false` is no such invitation: that item takes no save at this address, so no pin is prescribed for it. ABSENT on the cached published-value branch and on a `?preview=draft` read, which publish no version: absence means "not published here", never "no row". Opaque — echo it verbatim, never parse it. |
14631464
| **registration** | `{ state: 'registered' } \| { state: 'refused'; reason: object } \| { state: 'unregistered' }` | optional | The automation engine's verdict on this flow (see `FlowRegistrationSchema`): `registered`, or `refused` with the engine's `reason` verbatim, or `unregistered`. Present only on a `flow` read answered by a process that runs an automation service; absent otherwise, and absence means no engine judged it, never `registered`. Unlike the protection keys it is published by the cached branch too, read live and never part of the ETag, so a cached read that carries it is never answered 304; it is absent on a draft read, whose pending body no engine holds. The verdict is the answering process's engine. Beside `item`, never inside it: the item's `status` stays what its author declared. |
14641465
| **disabledActions** | `string[]` | optional | The names in `item.actions` that this deployment's activation ledger switches off (an administrator turned them off under Setup › Packaged automation): a call to any of them is refused 409 `ACTION_DISABLED`. Present only on an `object` read answered by a process whose data engine has an activation ledger attached, and then `[]` when none of this object's actions is switched off. Absent otherwise, and absence means no ledger answered, never that nothing is switched off. Unlike the protection keys it is published by the cached branch too, read live and folded into the ETag, so a cached read revalidates to 304 only while the switched-off set is unchanged; it is absent on a draft read. The ledger is the answering process's engine's. Beside `item`, never inside it: `item.actions` is served as declared, a switched-off action included. |
1466+
| **cascadeDeleteObjects** | `string[]` | optional | The objects, by name, that deleting a record of this object can also delete: every object whose relation into it cascades (a `master_detail` by default, a `lookup` or `tree` that declares `deleteBehavior: 'cascade'`), and the objects that cascade into those in turn, each once, in the order the delete reaches them. This object itself is named only when a cascading relation leads back to it. A `restrict` or `set_null` relation removes nothing and is not named. Read from the rule the delete runs, and object-level: it never says which records or how many. Present only on an `object` read answered by a process whose data engine answers it, and then `[]` when nothing cascades. Absent otherwise, and absence means no engine answered, never that nothing cascades. Unlike the protection keys it is published by the cached branch too, read live and folded into the ETag; it is absent on a draft read. Beside `item`, never inside it: it is derived from other objects' definitions and is not authorable. |
14651467
| **draftChanges** | `{ path: string[]; by: Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>; actor: string \| null; client?: object; … }[]` | optional | Per-key provenance of the pending draft: which authoring surface last changed each key path of `item`, under which actor, and when. The draft save records it: each draft save is compared with the body that save replaced (the previous draft, or the stored published row for the draft's first save; a draft of an item with no stored published row is recorded as `[]`, the whole body). A `migrate-stored` rewrite of a draft row records nothing, since it is not authoring. The entries are kept from the first recorded save until the draft is published or discarded, which remove the draft row and the entries with it; and no two entries share a path: a save replaces every entry at or under each path it changes, so the last write to change a key is the entry whose `path` is the longest prefix of that key's path, and entries under a key's path are changes inside it. The entries name which writes changed what; they are not a list of every difference from the published body (compare the two bodies for that). Served only on a `?state=draft` read that answers a stored draft row. ABSENT on the active read, the cached branch and a `?preview=draft` read, and for a draft row whose saves recorded none: absence means "not recorded", never "no changes". |
14661468

14671469
### Nested Shape: `GetMetaItemResponse.sortability`
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28001] The `object` item read serves, beside the item, the objects a
5+
* delete of one of its records can cascade into: `cascadeDeleteObjects` on
6+
* both doors. It takes `disabledActions`' (#27842) four positions:
7+
*
8+
* - read through the kernel's service table by name (`objectql`), for the
9+
* optional member the engine declares on `IObjectQLEngine`
10+
* (`getCascadeDeleteObjects`) — this package imports no engine and holds no
11+
* copy of which relations cascade;
12+
* - absent where no engine answered (no engine, an engine without the
13+
* member, or one that does not hold the object), never `[]` there;
14+
* - `[]` where the engine answered that nothing cascades;
15+
* - on the cached default door too, never in its ETag, and a read that
16+
* carries it is never answered 304 (the REST door folds it instead).
17+
*
18+
* `item` is served as stored: the list is beside it, never in it.
19+
*
20+
* The engine double answers the way `ObjectQL` does (pinned on the real
21+
* engine, with the real protocol, in `@objectstack/objectql`'s
22+
* `engine-cascade-delete-objects.test.ts`).
23+
*/
24+
import { describe, expect, it, vi } from 'vitest';
25+
import { assertEngineFindOnePredicate } from '@objectstack/metadata-core';
26+
import { ObjectStackProtocolImplementation } from './protocol.js';
27+
28+
interface StoredRow {
29+
id: string;
30+
type: string;
31+
name: string;
32+
package_id: string | null;
33+
state: string;
34+
metadata: string;
35+
}
36+
37+
const storedRow = (type: string, name: string, body: unknown, extra: Partial<StoredRow> = {}): StoredRow => ({
38+
id: `r_${type}_${name}_${extra.state ?? 'active'}`,
39+
type,
40+
name,
41+
package_id: null,
42+
state: 'active',
43+
metadata: JSON.stringify(body),
44+
...extra,
45+
});
46+
47+
/** [#24371] One `where` value as the store reads it: `{ $in: [...] }` or equality. */
48+
const whereValueMatches = (actual: unknown, want: unknown): boolean =>
49+
want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in)
50+
? (want as { $in: unknown[] }).$in.includes(actual)
51+
: actual === want;
52+
53+
const TASK = {
54+
name: 'showcase_task',
55+
label: 'Task',
56+
fields: { title: { name: 'title', type: 'text', label: 'Title' } },
57+
actions: [
58+
{ name: 'showcase_mark_done', label: 'Mark Done', type: 'script', locations: ['record_header'] },
59+
{ name: 'showcase_snooze', label: 'Snooze', type: 'script', locations: ['record_header'] },
60+
],
61+
};
62+
const PROJECT = {
63+
name: 'showcase_project',
64+
label: 'Project',
65+
fields: { title: { name: 'title', type: 'text', label: 'Title' } },
66+
actions: [{ name: 'showcase_archive', label: 'Archive', type: 'script' }],
67+
};
68+
const NOTE = { name: 'showcase_note', label: 'Note', fields: { body: { name: 'body', type: 'text', label: 'Body' } } };
69+
const ROWS = [storedRow('object', TASK.name, TASK), storedRow('object', PROJECT.name, PROJECT), storedRow('object', NOTE.name, NOTE)];
70+
71+
/**
72+
* The store double: `find` / `findOne` over `sys_metadata` rows, and a
73+
* registry that holds nothing of its own. ⛔ No write verb — the reads under
74+
* test issue none.
75+
*/
76+
function harness(rows: StoredRow[], services: Map<string, unknown> = new Map()) {
77+
const matching = (where: Record<string, unknown>) => {
78+
for (const k of Object.keys(where)) {
79+
if (k.startsWith('$')) throw new Error(`[test double] unsupported WHERE combinator '${k}'`);
80+
}
81+
return rows.filter((r) =>
82+
Object.entries(where).every(([k, v]) => v === undefined || whereValueMatches((r as unknown as Record<string, unknown>)[k], v)),
83+
);
84+
};
85+
const engine: any = {
86+
async find(table: string, opts?: { where?: Record<string, unknown>; limit?: number }) {
87+
if (table !== 'sys_metadata') return [];
88+
const matched = matching(opts?.where ?? {});
89+
// `check:objectql-double-limit` — the caller's bound, applied after the filter.
90+
return opts?.limit === undefined ? matched : matched.slice(0, opts.limit);
91+
},
92+
async findOne(table: string, opts?: { where?: Record<string, unknown> }) {
93+
// `check:engine-double-contract` — refuses what the real engine refuses.
94+
assertEngineFindOnePredicate(table, opts);
95+
if (table !== 'sys_metadata') return null;
96+
return matching(opts?.where ?? {})[0] ?? null;
97+
},
98+
registry: {
99+
listItems: () => [],
100+
getItem: () => undefined,
101+
getArtifactItem: () => undefined,
102+
getObject: () => undefined,
103+
registerItem: () => undefined,
104+
registerObject: () => undefined,
105+
getPackage: () => undefined,
106+
isPackageDisabled: () => false,
107+
applyNavContributions: (app: unknown) => app,
108+
},
109+
};
110+
return new ObjectStackProtocolImplementation(engine, () => services as Map<string, any>);
111+
}
112+
113+
/** The engine's answer: the cascade per object name, `undefined` for an object it does not hold. */
114+
function engineDouble(cascades: Record<string, string[]>) {
115+
return {
116+
getCascadeDeleteObjects: vi.fn((objectName: string): string[] | undefined =>
117+
Object.prototype.hasOwnProperty.call(cascades, objectName) ? [...cascades[objectName]!] : undefined),
118+
};
119+
}
120+
121+
const CASCADES = { [TASK.name]: ['showcase_subtask', 'showcase_checklist_item'], [PROJECT.name]: [] };
122+
const withEngine = (cascades: Record<string, string[]> = CASCADES) =>
123+
new Map<string, unknown>([['objectql', engineDouble(cascades)]]);
124+
125+
describe('[#28001] the item read: `cascadeDeleteObjects` beside `item`, the engine\'s answer or nothing', () => {
126+
it('names what a delete of this object cascades into, and serves `item` as stored', async () => {
127+
const plain: any = await harness(ROWS).getMetaItem({ type: 'object', name: TASK.name });
128+
const judged: any = await harness(ROWS, withEngine()).getMetaItem({ type: 'object', name: TASK.name });
129+
130+
expect(judged.cascadeDeleteObjects).toEqual(['showcase_subtask', 'showcase_checklist_item']);
131+
expect(JSON.stringify(judged.item)).toBe(JSON.stringify(plain.item));
132+
expect(judged.item).not.toHaveProperty('cascadeDeleteObjects');
133+
expect(judged).toHaveProperty('lock');
134+
});
135+
136+
it('`[]` when the engine answered that nothing cascades', async () => {
137+
expect((await harness(ROWS, withEngine()).getMetaItem({ type: 'object', name: PROJECT.name }) as any).cascadeDeleteObjects)
138+
.toEqual([]);
139+
});
140+
141+
it('control: no key where no engine answered — no engine, an engine without the member, an object it does not hold', async () => {
142+
const cases: Array<[Map<string, unknown>, string]> = [
143+
[new Map<string, unknown>(), TASK.name],
144+
[new Map<string, unknown>([['objectql', { find: async () => [] }]]), TASK.name],
145+
[withEngine(), NOTE.name],
146+
];
147+
for (const [services, name] of cases) {
148+
const read: any = await harness(ROWS, services).getMetaItem({ type: 'object', name });
149+
expect(read.item.name).toBe(name);
150+
expect(read).not.toHaveProperty('cascadeDeleteObjects');
151+
}
152+
});
153+
154+
it('the plural spelling of the type is folded first and answers the same', async () => {
155+
const read: any = await harness(ROWS, withEngine()).getMetaItem({ type: 'objects', name: TASK.name });
156+
expect(read.cascadeDeleteObjects).toEqual(['showcase_subtask', 'showcase_checklist_item']);
157+
});
158+
159+
it('a type other than `object` reads no key, and the engine is never asked', async () => {
160+
const services = withEngine();
161+
const read: any = await harness(
162+
[...ROWS, storedRow('view', 'task_board', { name: 'task_board', label: 'Board' })], services,
163+
).getMetaItem({ type: 'view', name: 'task_board' });
164+
165+
expect(read).not.toHaveProperty('cascadeDeleteObjects');
166+
expect((services.get('objectql') as ReturnType<typeof engineDouble>).getCascadeDeleteObjects).not.toHaveBeenCalled();
167+
});
168+
169+
it('the execution face carries none', async () => {
170+
const read: any = await harness(ROWS, withEngine()).getMetaItemForExecution({ type: 'object', name: TASK.name });
171+
expect(read).not.toHaveProperty('cascadeDeleteObjects');
172+
});
173+
174+
it('the list carries none: the item read is the one the delete confirmations read', async () => {
175+
const list: any = await harness(ROWS, withEngine()).getMetaItems({ type: 'object' });
176+
expect(list.items.length).toBe(3);
177+
expect(list).not.toHaveProperty('cascadeDeleteObjects');
178+
for (const item of list.items) expect(item).not.toHaveProperty('cascadeDeleteObjects');
179+
});
180+
});
181+
182+
describe('[#28001] the cached read — the default door — carries it beside `data`, never in the ETag', () => {
183+
it('serves the engine\'s answer beside the document, with an ETag over the document alone', async () => {
184+
const judged: any = await harness(ROWS, withEngine()).getMetaItemCached({ type: 'object', name: TASK.name });
185+
const unjudged: any = await harness(ROWS).getMetaItemCached({ type: 'object', name: TASK.name });
186+
187+
expect(judged.cascadeDeleteObjects).toEqual(['showcase_subtask', 'showcase_checklist_item']);
188+
expect(judged.data).not.toHaveProperty('cascadeDeleteObjects');
189+
expect(judged.etag).toEqual(unjudged.etag);
190+
expect(unjudged).not.toHaveProperty('cascadeDeleteObjects');
191+
});
192+
193+
it('a read that carries the key is never answered 304; control: one where no engine answered still is', async () => {
194+
const first: any = await harness(ROWS, withEngine()).getMetaItemCached({ type: 'object', name: TASK.name });
195+
const revalidate = { type: 'object', name: TASK.name, cacheRequest: { ifNoneMatch: `"${first.etag.value}"` } };
196+
197+
const judged: any = await harness(ROWS, withEngine()).getMetaItemCached(revalidate);
198+
expect(judged.notModified).toBe(false);
199+
expect(judged.cascadeDeleteObjects).toEqual(['showcase_subtask', 'showcase_checklist_item']);
200+
201+
const unjudged: any = await harness(ROWS, new Map()).getMetaItemCached(revalidate);
202+
expect(unjudged.notModified).toBe(true);
203+
});
204+
});

0 commit comments

Comments
 (0)