Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/action-engine-facade-find-filter.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
---
"@objectstack/spec": patch
---

fix(spec): `ActionEngineFacade.find` declares its second parameter as a FILTER, not an ObjectQL envelope (#14175)

`find(object, query: Record<string, unknown>)` documented nothing, and its
parameter carried the name of the envelope every other read on the platform
takes. The runtime (`buildActionEngineFacade`,
`packages/runtime/src/action-execution.ts`) treats the argument as the bare
`where` half — wrapping a non-empty one as `{ where: filter }` and passing
`{}` through unwrapped — so a handler that passed the envelope got
`{ where: { where: … } }`, matched nothing and returned `[]` with no error,
while its one unfiltered read kept working. A hand-written test double built
on the same belief passed every assertion; an application's headline action
was a silent no-op for its whole life under a green suite.

The member is now `find(object, filter: FilterCondition)` — the published
`QueryAST.where` type — with a doc comment stating the contract, the runtime's
wrap, and both limbs (envelope wrapped; empty passed through); the facade
docblock points at it. The parameter's TYPE now says what the runtime does
at the one place a handler author reads.

Compile-layer signal only, shipped as `patch` (the #12615 precedent — a
compile-time narrowing with no change in what parses or runs): no runtime
behaviour changes, nothing changes in what the facade accepts or returns, and
the narrowing bites only a primitive or a mistyped `$and` / `$or` / `$not`.
⚠️ It does NOT refuse `{ where: … }` at compile time — `FilterCondition`'s
string index signature admits `where` as a field name — so the compile-time
bar is partial and the doc comment is the contract of record. An
implementation typed with the old `Record<string, unknown>` still satisfies
the interface (method parameters are bivariant), so nothing constructing the
facade changes.
15 changes: 15 additions & 0 deletions content/docs/ui/actions.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -146,6 +146,21 @@ export async function completeTask(ctx: ActionContext): Promise<void> {
}
```

<Callout type="warn">
**`ctx.engine.find(object, filter)` takes a filter, not a query.** The second
argument is the `where` half only — `{ status: 'completed' }`, operators
(`{ amount: { $gt: 100 } }`), `$and` / `$or` / `$not` — and the runtime wraps
it in `where` itself. Passing an ObjectQL envelope
(`{ where: { status: 'completed' } }`) raises no error: it becomes
`{ where: { where: … } }`, matches no row, and returns `[]`. An empty filter
(`{}`) is passed through unwrapped, so the one unfiltered read works under
either reading and a handler can look partially alive. The parameter is typed
`FilterCondition` (`ActionEngineFacade` in `@objectstack/spec/ui`), which
refuses a primitive or a mistyped `$and` / `$or` / `$not` but still admits
`where` as a key — the sentence above is the contract, and a hand-written test
double must honour it too.
</Callout>

```typescript title="objectstack.config.ts"
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
Expand Down
76 changes: 76 additions & 0 deletions packages/spec/src/ui/action-params.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
validateActionParams,
ACTION_PARAM_BUILTIN_KEYS,
ActionSessionSchema,
type ActionEngineFacade,
type ActionSession,
type ResolvedActionParam,
} from './action-params.zod';
import type { FilterCondition } from '../data/filter.zod';
import { MIGRATIONS_BY_MAJOR } from '../migrations/registry';

const codes = (issues: ReturnType<typeof validateActionParams>) => issues.map((i) => i.code).sort();
Expand DownExpand Up@@ -392,3 +394,77 @@ describe('#5779 — ActionSession `positions` canonical + `roles` deprecated ali
expect(entry!.acceptanceCriteria).toMatch(/ctx\.session\.positions/);
});
});

// ---------------------------------------------------------------------------
// #14175 — `ActionEngineFacade.find` takes a FILTER, never an ObjectQL envelope
// ---------------------------------------------------------------------------

type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
type Assert< T extends true > = T;

// The declared slot, read off the interface — not a retyped copy of it, so a
// re-widening back to an open record, or a rename of the type behind it, fails
// HERE rather than in the first consumer to notice.
type FindFilter = Parameters<ActionEngineFacade['find']>[1];

// The type-level pin (the tsc channel, `tsc -p tsconfig.test.json`). `Eq` is
// the strict mutual-assignability test, so `Record<string, unknown>` — the type
// this slot carried before, and the one it must not drift back to — does not
// satisfy it (measured: the same `Assert` against `Record<string, unknown>` is
// a TS2344). Exported, as the sibling pins are, so `noUnusedLocals` does not
// read a type that exists only to be checked as one that is never used.
export type FindFilterIsFilterCondition = Assert< Eq< FindFilter, FilterCondition > >;

describe('#14175 — ActionEngineFacade.find takes a FILTER (the `where` half), never an ObjectQL envelope', () => {
it('types the second parameter as the published `FilterCondition` (the tsc channel)', () => {
// The value-level half of `FindFilterIsFilterCondition` above: a literal
// annotated with the slot type, so the runtime run exercises the same
// declaration the type pin reads.
const filter: FindFilter = { position_code: 'qa_lead', active: true };
expect(Object.keys(filter)).toEqual(['position_code', 'active']);
});

it('positive control — every shape a handler legitimately passes compiles, the empty filter included', () => {
const implicitEquality: FindFilter = { status: 'completed' };
const explicitOperator: FindFilter = { position_code: { $in: ['qa_lead', 'qa_manager'] }, active: true };
const logical: FindFilter = {
$and: [{ active: true }, { $or: [{ tier: 'a' }, { tier: 'b' }] }],
$not: { archived: true },
};
// The runtime passes THIS one through unwrapped — the unfiltered read, and
// the one call that kept working in the reporting app under either belief.
const unfiltered: FindFilter = {};

expect([implicitEquality, explicitOperator, logical, unfiltered].every((f) => typeof f === 'object')).toBe(true);
});

it('refuses at compile time what `FilterCondition` refuses — a primitive and a mistyped logical operator', () => {
// Each `@ts-expect-error` is itself checked: if the type ever ADMITS one of
// these, the directive goes unused and `tsc -p tsconfig.test.json` reds.
// @ts-expect-error — a filter is an object; a bare string is not a `where` half.
const primitive: FindFilter = 'position_code = qa_lead';
// @ts-expect-error — `$and` is `FilterCondition[]`; a string is refused.
const andNotArray: FindFilter = { $and: 'active' };
// @ts-expect-error — `$or` is `FilterCondition[]`; a bare object is refused.
const orNotArray: FindFilter = { $or: { active: true } };
// @ts-expect-error — `$not` is a `FilterCondition`; a string is refused.
const notNotFilter: FindFilter = { $not: 'archived' };

expect([primitive, andNotArray, orNotArray, notNotFilter]).toHaveLength(4);
});

it('MEASURED GAP — the exact envelope mistake still compiles; the doc comment, not the type, is the contract', () => {
// `FilterCondition`'s string index signature is what lets a field NAME be a
// key, and `where` is a string — so the shape that returned `[]` in silence
// in the reporting app (`{ where: { position_code: 'qa_lead' } }`) is
// admitted by the type, one level down too. This pin RECORDS that
// measurement rather than hiding it: a later narrowing that refuses `where`
// at the top level turns it red on purpose, so the member's "does NOT
// refuse `{ where: … }`" sentence is updated with the type instead of
// drifting from it.
const envelope: FindFilter = { where: { position_code: 'qa_lead' } };
const nested: FindFilter = { where: { where: { position_code: 'qa_lead' } } };

expect('where' in envelope && 'where' in nested).toBe(true);
});
});
41 changes: 40 additions & 1 deletion packages/spec/src/ui/action-params.zod.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@
import { z } from 'zod';

import { valueSchemaFor } from '../data/field-value.zod';
import type { FilterCondition } from '../data/filter.zod';
import type { FieldErrorCode } from '../api/errors.zod';
import { lazySchema } from '../shared/lazy-schema';

Expand DownExpand Up@@ -229,12 +230,50 @@ export function validateActionParams(
* The slim engine facade an action handler's `ctx.engine` exposes. TRUSTED —
* context-less, RLS/FLS-bypassing by design (#2849); the boundary is enforced
* at invoke time (`ai.exposed` + the ADR-0066 D4 capability gate), not here.
*
* `find` is the one member whose argument shape the signature alone never
* settled: it takes a bare FILTER — the `where` half of a query — and never
* an ObjectQL query envelope; read its doc comment before writing a handler
* or a test double against it (#14175).
*/
export interface ActionEngineFacade {
insert(object: string, data: Record<string, unknown>): Promise<{ id: string }>;
update(object: string, id: string, data: Record<string, unknown>): Promise<void>;
delete(object: string, id: string): Promise<void>;
find(object: string, query: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
/**
* Read the rows of `object` that match `filter`.
*
* `filter` is a FILTER — the `where` HALF of an ObjectQL query, the same
* {@link FilterCondition} that `QueryAST.where` carries: implicit equality
* `{ field: value }`, explicit operators `{ field: { $in: [...] } }`,
* `$and` / `$or` / `$not`. It is NOT the query ENVELOPE
* (`{ where, fields, orderBy, limit }`) that `DataEngine.find` and ObjectQL's
* own `engine.find` take — the shape this parameter's former name, `query`,
* invited. The runtime builds the envelope itself: `buildActionEngineFacade`'s
* `find` arm (`packages/runtime/src/action-execution.ts`, `:1183` on
* `369da918`) wraps a non-empty filter as `{ where: filter }` and passes an
* EMPTY filter (`{}`) through unwrapped — the unfiltered read.
*
* Two consequences, both silent (#14175):
*
* - An envelope passed here becomes `{ where: { where: … } }`. No object has
* a field named `where`, so the read matches nothing and resolves to `[]`
* with no error. A handler that made this mistake ran to completion over
* zero rows for as long as it shipped, and its own hand-written test
* double — written to the same belief, reading `query.where` — passed
* every assertion.
* - Because `{}` skips the wrap, an unfiltered call works under EITHER
* reading, so a handler mixing one unfiltered read with envelope-shaped
* ones looks partially alive rather than uniformly dead.
*
* What the type buys, exactly: `FilterCondition` refuses a primitive and a
* mistyped logical operator (`$and` / `$or` not arrays, `$not` not a
* filter). It does NOT refuse `{ where: … }` — its string index signature is
* what lets any field name stand as a key, and `where` is a string — so the
* envelope mistake still compiles, and this doc comment, not the type, is
* the contract of record. Both halves are pinned in `action-params.test.ts`.
*/
find(object: string, filter: FilterCondition): Promise<Array<Record<string, unknown>>>;
}

/**
Expand Down
Loading