feat(436): arbitrary-depth rule-builder group nesting #584

Merged
timothy merged 1 commits from feat/436-deeper-nesting into main 2026-07-25 11:47:15 +02:00
12 changed files with 305 additions and 62 deletions
+44 -41
View File
@@ -122,7 +122,6 @@ in-file entries.
- [2026-07-17 — Auto-Tune per-channel overrides reuse the Channel Builder advanced-options DTO; weights + bug-colour logo split out to #425 (#385)](#2026-07-17--auto-tune-per-channel-overrides-reuse-the-channel-builder-advanced-options-dto-weights--bug-colour-logo-split-out-to-425-385)
- [2026-07-17 — Health-check remediation is server-declared `{Kind, Target}` on an additive DTO; the SPA acts on it (#164)](#2026-07-17--health-check-remediation-is-server-declared-kind-target-on-an-additive-dto-the-spa-acts-on-it-164)
- [2026-07-18 — Auto-Tune DetailPanel SPA: reusable `SlideOver` + shared advanced-options model; decorative panes dropped to match the backend (#386)](#2026-07-18--auto-tune-detailpanel-spa-reusable-slideover--shared-advanced-options-model-decorative-panes-dropped-to-match-the-backend-386)
- [2026-07-18 — SmartCollection rule builder: compile-only closed subset, no stored AST, one-level nesting (#176)](#2026-07-18--smartcollection-rule-builder-compile-only-closed-subset-no-stored-ast-one-level-nesting-176)
- [2026-07-18 — Auto-Tune per-source weights ride #70's MultiCollection machinery; created at tune time, not a post-hoc PUT (#425)](#2026-07-18--auto-tune-per-source-weights-ride-70s-multicollection-machinery-created-at-tune-time-not-a-post-hoc-put-425)
- [2026-07-18 — Search all-items is paged to cap DoS exposure; SPA add-all pages to completeness (#293)](#2026-07-18--search-all-items-is-paged-to-cap-dos-exposure-spa-add-all-pages-to-completeness-293)
- [2026-07-18 — Unsupported PlaybackOrder is loud at build time; a declared support matrix and tripwire test make new orders safe by construction (#403)](#2026-07-18--unsupported-playbackorder-is-loud-at-build-time-a-declared-support-matrix-and-tripwire-test-make-new-orders-safe-by-construction-403)
@@ -139,6 +138,7 @@ in-file entries.
- [2026-07-21 — Check the worked issue before the decision corpus; a closed tracker's comments need no retrofit (#524)](#2026-07-21--check-the-worked-issue-before-the-decision-corpus-a-closed-trackers-comments-need-no-retrofit-524)
- [2026-07-21 — Work-ahead slots are claimed atomically by the caller, released by the transcode it hands them to (#536)](#2026-07-21--work-ahead-slots-are-claimed-atomically-by-the-caller-released-by-the-transcode-it-hands-them-to-536)
- [2026-07-21 — Session end fast-forwards the shared checkout; a stale tree serves stale FILES (#541)](#2026-07-21--session-end-fast-forwards-the-shared-checkout-a-stale-tree-serves-stale-files-541)
- [2026-07-25 — Rule-builder group nesting is bounded-arbitrary depth (`MAX_GROUP_DEPTH`), not one level (#436)](#2026-07-25--rule-builder-group-nesting-is-bounded-arbitrary-depth-max_group_depth-not-one-level-436)
---
@@ -1886,46 +1886,6 @@ never presents a control with nowhere to send its value.
`AutoTuneScreen` draft state until bulk-create, so closing the panel keeps them (an "Edited" row badge
makes that visible) and only screen navigation / full-page unload with uncommitted edits confirms.
## 2026-07-18 — SmartCollection rule builder: compile-only closed subset, no stored AST, one-level nesting (#176)
`key: spa.smartcollection-rule-builder` · `status: active` · `since: 2026-07-18` · `supersedes: none` · `superseded-by: none`
**Rule:** The SmartCollection visual rule builder compiles to/from a closed subset of the Lucene grammar over the existing stored query string — no new AST, one level of group nesting.
**Signals:** SmartCollection, rule builder, Lucene compile/parse · paths: `web/src/builder/rules/`, `compile.ts`, `parse.ts`, `roundtrip.test.ts` · issues: #176, #69
**Mechanics:** `GET /api/v1/search/fields`; api-conventions.md; spa-conventions.md §12
The SmartCollection create/edit dialog gained a visual rule builder (`web/src/builder/rules/`)
alongside the existing raw-Lucene textarea. **The SmartCollection still stores a plain Lucene query
string — no new stored rule AST, no schema change.** The builder compiles its in-memory rule tree
into a **closed subset** of the Lucene grammar (`compile.ts`) and parses exactly that subset back out
(`parse.ts`, the exact inverse — returns `null`, not a best-effort guess, for anything outside the
subset); escaping is total, so any builder-authored query round-trips losslessly, proven by a 500-tree
property test (`roundtrip.test.ts`, including Lucene special characters). Opening an existing
SmartCollection tries the parse first and falls back to raw-text mode on `null` (fuzzy queries,
boosts, mixed AND/OR at one nesting level, or nesting deeper than one level).
**Why compile-only over persisting an authoritative rule AST**: an AST would still need a
Lucene→rules parser to open every *pre-existing* free-text query — including every query the
Auto-Tune feature (#69) generates — so the AST would buy almost nothing (it still can't represent
arbitrary hand-written Lucene) while costing a dual-provider EF migration and a second source of
truth to keep in sync with the Lucene grammar. Compile-only keeps the query string as the single
source of truth and treats the builder as a structured *editor* over it, not a new storage model.
**One-level-nesting "Kodi" model.** `types.ts` defines a top `Group` (`match: all|any`) over `Rule`s
and/or **one level** of sub-`Group`s — enough to express `type:movie AND (genre:Horror OR
genre:Thriller)`, which covers the smart-playlist patterns Kodi-style rule builders are known for.
Arbitrary/recursive nesting was scoped out as YAGNI; revisit only if a real query needs it.
**Field vocabulary comes from a new catalog endpoint, not a hardcoded list.** `GET
/api/v1/search/fields` (read-only, MCP-introspectable; see `api-conventions.md`) returns the curated,
typed, labeled field set derived from `LuceneSearchIndex` — name/label/type/group/values — and is the
single source of truth the builder's field pickers (`fieldCatalog.ts`'s `useSearchFields` hook) and
operator/value-input choices are driven from, so the builder's vocabulary can't drift from what the
index actually supports.
**Deferred as separate follow-up issues** (explicitly out of scope for #176): facet-value typeahead
for value inputs, relative-date operators, nesting deeper than one level, and inline adoption of
`RuleBuilder` by ChannelBuilder / Auto-Tune (it was built reusable for exactly that reuse — see
`spa-conventions.md` §12).
## 2026-07-18 — Auto-Tune per-source weights ride #70's MultiCollection machinery; created at tune time, not a post-hoc PUT (#425)
`key: sched.autotune-per-source-weights` · `status: active` · `since: 2026-07-18` · `supersedes: none` · `superseded-by: none`
**Rule:** Auto-Tune per-source rotation weights and query corrections are supplied at bulk-create time via #70's MultiCollection/SmartCollection machinery, not a post-hoc PUT.
@@ -3634,3 +3594,46 @@ just another point in the same closed grammar subset, proven by the same compile
**The assessable gate distinguishes absence signals from presence signals.** `NeverBuilt`/`EmptyUpcoming` are inferred from *missing* content and are suppressed for `PlayoutMode == OnDemand` (an idle on-demand playout legitimately has no fresh build and drains its timeline between tune-ins — without suppression this is a false-positive storm across every on-demand channel; a suppressed absence signal contributes `Unknown`, not a false `Problems`). `BuildFailed`/`BrokenSource` are proven by content that *is* there and is bad, so they stay live in every `PlayoutMode` — they only fire when the bad thing actually exists and so cannot false-positive on legitimate idleness.
**Server owns the rollup so SPA and MCP read one verdict.** `health` rides the same `list channels`/`get channel` response both clients already fetch — no second endpoint to correlate by id, and no client re-deriving policy from raw facts (the thing the superseded record explicitly avoided freezing before the taxonomy existed). `PlayoutCount` is retained unchanged on the DTO for backward compatibility (additive-only `/api/v1` freeze); the SPA's "Problems" filter (`web/src/screens/ChannelsScreen.tsx`, `hasProblems`, replacing the old single-fault `willNeverPlay`/"No playout" filter) and per-row badges read `health.status`/`health.faults` instead.
## 2026-07-25 — Rule-builder group nesting is bounded-arbitrary depth (`MAX_GROUP_DEPTH`), not one level (#436)
`key: spa.rulebuilder-nesting` · `status: active` · `since: 2026-07-25` · `supersedes: spa.smartcollection-rule-builder@2026-07-18` · `superseded-by: none`
**Rule:** The visual rule builder's `Group` nests recursively to a single shared cap, `MAX_GROUP_DEPTH` (`types.ts`, currently 5, root group = depth 0) — read by the UI's "Add group" gate, `parse.ts` and the round-trip property-test generator alike; everything else about the builder is unchanged from #176 (compile-only closed Lucene subset over the stored query string, no stored rule AST, field vocabulary from `GET /api/v1/search/fields`).
**Signals:** rule builder nesting depth, MAX_GROUP_DEPTH, nested groups, Kodi one-level model reversed, recursive Group, compile parenthesization, parse recursion, closed subset, SmartCollection query, ChannelBuilder smart query · paths: `web/src/builder/rules/types.ts`, `parse.ts`, `compile.ts`, `RuleBuilder.tsx`, `roundtrip.test.ts` · issues: #436, #176, #437, #438
**Mechanics:** `spa-conventions.md` §12; superseded predecessor in `docs/decisions/archive/spa.md`
#176 shipped the builder with a deliberate one-level "Kodi" nesting cap (`type:movie AND (genre:Horror
OR genre:Thriller)`) and scoped recursive nesting out as YAGNI, "revisit only if a real query needs
it". #436 is that revisit. **What is reversed is only the cap** — the compile-only closed-subset
stance, the no-stored-AST stance and the catalog-driven field vocabulary all carry forward verbatim
from the archived record.
**Bounded, not unbounded.** The `Group` type is structurally recursive (it always was — `children:
Array<Rule | Group>`), and `compile.ts` already parenthesized recursively, so the honest change is a
*policy* one: how deep may a tree be? Truly unbounded nesting buys nothing a 5-deep tree can't express
while making the UI illegible (each level insets 12px inside a fixed-width dialog) and admitting
pathological hand-written input into the compiler. `MAX_GROUP_DEPTH = 5` is a judgment call sized to
"deeper than any smart-playlist query anyone has actually asked for", not a technical limit.
**One constant, three consumers — never re-hardcode a depth.** `MAX_GROUP_DEPTH` lives in `types.ts`
and is read by (a) `RuleBuilder.tsx`'s "Add group" gate (`depth < MAX_GROUP_DEPTH`, replacing `depth
=== 0`), (b) `parse.ts`, which returns `null` for input nested deeper than the cap, and (c)
`roundtrip.test.ts`'s tree generator. A second hardcoded depth anywhere would silently desynchronize
the UI from the parser and break the round-trip invariant the whole module rests on.
**`parse` stays the exact inverse of `compile`, including at the cap.** Anything deeper than
`MAX_GROUP_DEPTH` is *out of subset* and yields `null` — the existing, well-defined degradation to
raw-text editing — rather than a truncated or best-effort tree, which is the same rule that already
covers fuzzy queries, boosts and mixed AND/OR at one level. Generalizing the recursion also tightened
the sub-group detection: a part is a sub-group only when its leading `(` is the one closed by its
trailing `)` (quote- and escape-aware), so adjacent groups like `(a)x(b)` can no longer be mistaken
for one wrapped group.
**The property test asserts depth coverage, not just the invariant.** `roundtrip.test.ts` generates
500 trees to the full cap and additionally asserts the generated corpus actually *reached*
`MAX_GROUP_DEPTH` — a generator that silently stopped nesting would otherwise keep passing every
round-trip assertion while testing nothing new (the "fan-out needs count-guards" lesson applied to a
generator). Explicit depth-3 cases live in `compile.test.ts` / `parse.test.ts` / `validation.test.ts`
so a regression is diagnosable without decoding a random seed.
**No backend change.** Nesting depth is entirely a client-side model concern; the stored query string
is still plain Lucene, so nothing about `/api/v1`, the search index or the MCP surface moves.
+1 -1
View File
@@ -152,9 +152,9 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `spa.playback-troubleshoot-poll` | The playback-troubleshooting screen reports FFmpeg completion by polling `GET /api/troubleshoot/playback/status` (~2s) rather than a server push channel. | 2026-07-09 | [link](../decisions.md#2026-07-09--playback-troubleshooting-completion-feedback-poll-status-no-push-channel) |
| `spa.playout-reset-button` | The SPA keeps a single Reset action (server picks the default build mode) and drops Blazor's separate "Schedule reset" button since its capability already exists via the playout's Edit-details flow. | 2026-07-09 | [link](../decisions.md#2026-07-09--per-playout-schedule-reset-button-dropped-reset-uses-the-server-default-build-mode) |
| `spa.playouts-screen-extraction` | The Playouts domain (including its unguarded `PlayoutsRouteScreen` route wrapper with local pathname/popstate state) moved as one unit into `web/src/screens/PlayoutsScreen.tsx`, keeping its screen-specific sub-path route ownership colocated with the base screen; a pure structural move with no API/route/CSS/behavior change. | 2026-07-14 | [link](spa-modularization.md#2026-07-14--playouts-screen-extraction-245-screen-owned-route-wrapper-epic-243-phase-2) |
| `spa.rulebuilder-nesting` | The visual rule builder's `Group` nests recursively to a single shared cap, `MAX_GROUP_DEPTH` (`types.ts`, currently 5, root group = depth 0) — read by the UI's "Add group" gate, `parse.ts` and the round-trip property-test generator alike; everything else about the builder is unchanged from #176 (compile-only closed Lucene subset over the stored query string, no stored rule AST, field vocabulary from `GET /api/v1/search/fields`). | 2026-07-25 | [link](../decisions.md#2026-07-25--rule-builder-group-nesting-is-bounded-arbitrary-depth-max_group_depth-not-one-level-436) |
| `spa.schedules-editor-draft-save` | The schedules SPA editor mutates a local draft and flushes one explicit Save (`PUT /api/schedules/{id}/items`) instead of instant-persisting each action; Copy deep-copies all source references (fixing a Blazor omission); the shuffled-schedule GET's `EnforceProperties` lossy normalization is preserved and mirrored in the SPA's option lists. | 2026-07-11 | [link](../decisions.md#2026-07-11--schedules-spa-editor-draftexplicit-save-over-instant-persist-copy-includes-multismartrerun-shuffled-get-normalization-preserved) |
| `spa.sidebar-collapsible-accordions` | The shell sidebar's collapse + nav-group-accordion state persists under two hyphenated `ctv-sidebar-*` localStorage keys (matching the repo's `ctv-` convention, not the prototype's dotted names); labeled groups default-collapsed. | 2026-07-18 | [link](../decisions.md#2026-07-18--collapsible-sidebar--nav-group-accordions-two-ctv-sidebar--localstorage-keys-labeled-groups-default-collapsed-396) |
| `spa.smartcollection-rule-builder` | The SmartCollection visual rule builder compiles to/from a closed subset of the Lucene grammar over the existing stored query string — no new AST, one level of group nesting. | 2026-07-18 | [link](../decisions.md#2026-07-18--smartcollection-rule-builder-compile-only-closed-subset-no-stored-ast-one-level-nesting-176) |
| `spa.spa-rebuild-decision` | The UI is a full React SPA (ChicoryTV) rebuild over the REST API, not a Blazor Server reskin. | 2026-06 | [link](../decisions.md#2026-06--ui-rebuild-is-a-react-spa-chicorytv-on-the-rest-api-not-a-blazor-reskin) |
| `spa.templates-editor-table` | The SPA templates editor renders day/block assignment as a table, not Blazor's drag-and-drop calendar grid — an accepted, deliberate parity deviation. | 2026-07 | [link](../decisions.md#2026-07--templates-editor-in-the-spa-is-a-table-not-blazors-drag-calendar) |
| `spa.topbar-primary-action` | The TopBar's primary-action "+" button renders only when the active route declares a non-empty `primaryAction`, is wired (via a shared `usePrimaryAction` hook) only on single-unambiguous-create-flow list screens, and is dropped everywhere else rather than left as a dead/no-op button. | 2026-07-12 | [link](../decisions.md#2026-07-12--topbar-primary-action-button-wire-creates-drop-the-rest-238) |
+48
View File
@@ -0,0 +1,48 @@
# Archive — SPA / rule-builder conventions
Superseded/retired records for ChicoryTV SPA client-side conventions. See
`docs/decisions/archive/README.md` for the archive's general rules (rationale kept verbatim, never
in the active read-path). Active successor for the rule builder: `spa.rulebuilder-nesting` in
`docs/decisions.md`.
---
## 2026-07-18 — SmartCollection rule builder: compile-only closed subset, no stored AST, one-level nesting (#176)
`key: spa.smartcollection-rule-builder` · `status: superseded` · `since: 2026-07-18` · `supersedes: none` · `superseded-by: spa.rulebuilder-nesting@2026-07-25`
**Rule:** (superseded) The SmartCollection visual rule builder compiles to/from a closed subset of the Lucene grammar over the existing stored query string — no new AST, one level of group nesting.
**Signals:** SmartCollection, rule builder, Lucene compile/parse · paths: `web/src/builder/rules/`, `compile.ts`, `parse.ts`, `roundtrip.test.ts` · issues: #176, #69
**Mechanics:** superseded by `spa.rulebuilder-nesting` (ersatztv#436) — the compile-only closed-subset and field-catalog stances carry forward there; only the one-level nesting cap was reversed. See `docs/decisions.md` → that record; `spa-conventions.md` §12
The SmartCollection create/edit dialog gained a visual rule builder (`web/src/builder/rules/`)
alongside the existing raw-Lucene textarea. **The SmartCollection still stores a plain Lucene query
string — no new stored rule AST, no schema change.** The builder compiles its in-memory rule tree
into a **closed subset** of the Lucene grammar (`compile.ts`) and parses exactly that subset back out
(`parse.ts`, the exact inverse — returns `null`, not a best-effort guess, for anything outside the
subset); escaping is total, so any builder-authored query round-trips losslessly, proven by a 500-tree
property test (`roundtrip.test.ts`, including Lucene special characters). Opening an existing
SmartCollection tries the parse first and falls back to raw-text mode on `null` (fuzzy queries,
boosts, mixed AND/OR at one nesting level, or nesting deeper than one level).
**Why compile-only over persisting an authoritative rule AST**: an AST would still need a
Lucene→rules parser to open every *pre-existing* free-text query — including every query the
Auto-Tune feature (#69) generates — so the AST would buy almost nothing (it still can't represent
arbitrary hand-written Lucene) while costing a dual-provider EF migration and a second source of
truth to keep in sync with the Lucene grammar. Compile-only keeps the query string as the single
source of truth and treats the builder as a structured *editor* over it, not a new storage model.
**One-level-nesting "Kodi" model.** `types.ts` defines a top `Group` (`match: all|any`) over `Rule`s
and/or **one level** of sub-`Group`s — enough to express `type:movie AND (genre:Horror OR
genre:Thriller)`, which covers the smart-playlist patterns Kodi-style rule builders are known for.
Arbitrary/recursive nesting was scoped out as YAGNI; revisit only if a real query needs it.
**Field vocabulary comes from a new catalog endpoint, not a hardcoded list.** `GET
/api/v1/search/fields` (read-only, MCP-introspectable; see `api-conventions.md`) returns the curated,
typed, labeled field set derived from `LuceneSearchIndex` — name/label/type/group/values — and is the
single source of truth the builder's field pickers (`fieldCatalog.ts`'s `useSearchFields` hook) and
operator/value-input choices are driven from, so the builder's vocabulary can't drift from what the
index actually supports.
**Deferred as separate follow-up issues** (explicitly out of scope for #176): facet-value typeahead
for value inputs, relative-date operators, nesting deeper than one level, and inline adoption of
`RuleBuilder` by ChannelBuilder / Auto-Tune (it was built reusable for exactly that reuse — see
`spa-conventions.md` §12).
+9 -3
View File
@@ -483,13 +483,19 @@ dialog (#176) and built as a **standalone, controlled component module** — not
screen concern — so it can be embedded by later screens without duplicating the rule model.
- **`types.ts`** — the rule tree: `Rule` (field/operator/value), `Group` (`match: all|any` over
`Rule`s and/or one level of sub-`Group`s, the "Kodi" one-level-nesting model — see
`docs/decisions.md` 2026-07-18), `Operator`, `FieldType`, and an `isGroup` narrowing helper.
`Rule`s and/or **recursively nested** sub-`Group`s), `Operator`, `FieldType`, an `isGroup`
narrowing helper, and **`MAX_GROUP_DEPTH`** — the authoring cap on nesting (root group = depth 0,
so up to `MAX_GROUP_DEPTH` levels of sub-groups below it; currently 5). #436 replaced #176's
one-level "Kodi" model with bounded-arbitrary depth — see the `spa.rulebuilder-nesting` decision.
`MAX_GROUP_DEPTH` is the **single** source of truth: the UI's "Add group" gate
(`RuleBuilder.tsx`), `parse.ts` (anything deeper is out of subset ⇒ `null` ⇒ raw-text fallback)
and `roundtrip.test.ts`'s generator all read it — never re-hardcode a depth.
- **`compile.ts`** / **`parse.ts`** — `compile(group)` turns a rule tree into a query string covering
a **closed subset** of the Lucene grammar; `parse(input, fieldTypes)` is its exact inverse, returning
`null` (never a lossy best-effort tree) for any query outside that subset. Escaping is total, so a
compile→parse round-trip is lossless for any builder-authored value, including Lucene special
characters — pinned by a 500-tree property test (`roundtrip.test.ts`).
characters — pinned by a 500-tree property test (`roundtrip.test.ts`, which generates trees to the
full `MAX_GROUP_DEPTH` and asserts the corpus actually reached that depth).
- **`fieldCatalog.ts`** — `useSearchFields()` wraps `GET /api/v1/search/fields` and exposes a clean,
non-null `RuleField[]` (plus a `fieldTypes` lookup and a `byGroup` grouping) for field pickers; this
is the only place the raw API response shape is unwrapped.
+40 -2
View File
@@ -3,7 +3,7 @@ import { cleanup, render, screen, fireEvent, act } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest';
import { RuleBuilder } from './RuleBuilder';
import type { RuleField } from './fieldCatalog';
import type { Group } from './types';
import { MAX_GROUP_DEPTH, type Group } from './types';
const getSearchFieldValues = vi.fn().mockResolvedValue([]);
vi.mock('../../api/search', () => ({
@@ -59,7 +59,7 @@ describe('RuleBuilder', () => {
expect(onChange).toHaveBeenCalledWith({ match: 'all', children: [] });
});
it('adds a nested group only at top level', () => {
it('adds a nested group', () => {
const { onChange } = setup({ match: 'all', children: [] });
fireEvent.click(screen.getByText('Add group'));
// The new nested group has a single child, so the builder's onChange path normalizes its
@@ -69,6 +69,44 @@ describe('RuleBuilder', () => {
);
});
// #436: nesting is no longer capped at one level — every group up to MAX_GROUP_DEPTH offers
// "Add group", and only a group sitting at the cap stops offering it.
it('offers "Add group" at every level up to MAX_GROUP_DEPTH, and not beyond', () => {
const rule = { field: 'genre', operator: 'is' as const, value: 'Horror' };
const nest = (levels: number): Group => {
let g: Group = { match: 'all', children: [rule] };
for (let i = 0; i < levels; i++) g = { match: 'all', children: [g] };
return g;
};
// A tree whose deepest group is one level shy of the cap: every group (root + each sub-group)
// still offers "Add group".
setup(nest(MAX_GROUP_DEPTH - 1));
expect(screen.getAllByText('Add group')).toHaveLength(MAX_GROUP_DEPTH);
cleanup();
// At the cap, the deepest group drops the affordance; its ancestors keep it.
setup(nest(MAX_GROUP_DEPTH));
expect(screen.getAllByText('Add group')).toHaveLength(MAX_GROUP_DEPTH);
});
it('adds a sub-group from inside a nested group', () => {
const { onChange } = setup({
match: 'all',
children: [{ field: 'genre', operator: 'is', value: 'Horror' }, { match: 'all', children: [] }]
});
// A group's own button row renders after its children, so the nested group's "Add group"
// comes first in DOM order and the root's second.
fireEvent.click(screen.getAllByText('Add group')[0]);
expect(onChange).toHaveBeenCalledWith({
match: 'all',
children: [
{ field: 'genre', operator: 'is', value: 'Horror' },
{ match: 'all', children: [{ match: 'all', children: [{ field: 'genre', operator: 'is', value: '' }] }] }
]
});
});
it('shows enum values as a dropdown', () => {
setup({ match: 'all', children: [{ field: 'type', operator: 'is', value: 'movie' }] });
expect(screen.getByRole('option', { name: 'episode' })).toBeInTheDocument();
+15 -2
View File
@@ -3,7 +3,16 @@ import { Plus, Trash2 } from 'lucide-react';
import { Badge, Button, IconButton } from '../../components';
import { getSearchFieldValues } from '../../api/search';
import type { RuleField } from './fieldCatalog';
import { isGroup, OPERATORS_BY_TYPE, type DateUnit, type FieldType, type Group, type Operator, type Rule } from './types';
import {
isGroup,
MAX_GROUP_DEPTH,
OPERATORS_BY_TYPE,
type DateUnit,
type FieldType,
type Group,
type Operator,
type Rule
} from './types';
import { normalizeGroup, ruleError, topGroupAllNegative } from './validation';
const OP_LABEL: Record<Operator, string> = {
@@ -246,6 +255,9 @@ function GroupEditor({
style={{
border: depth > 0 ? '1px solid var(--ctv-border, #333)' : 'none',
borderRadius: 8,
// No global box-sizing reset (spa-conventions §1): without this, each nesting level's 12px
// padding would add to the width and a deep tree would overflow its container horizontally.
boxSizing: 'border-box',
padding: depth > 0 ? 12 : 0,
marginBottom: 8
}}
@@ -276,7 +288,8 @@ function GroupEditor({
>
Add rule
</Button>
{depth === 0 && (
{/* #436: sub-groups nest to MAX_GROUP_DEPTH levels; the cap is shared with parse.ts. */}
{depth < MAX_GROUP_DEPTH && (
<Button
size="sm"
variant="secondary"
+28
View File
@@ -53,6 +53,34 @@ describe('compile', () => {
};
expect(compile(g)).toBe('type:"movie" AND (genre:"Horror" OR genre:"Thriller")');
});
it('parenthesizes three levels of nesting (#436)', () => {
const g: Group = {
match: 'all',
children: [
{ field: 'type', operator: 'is', value: 'movie' },
{
match: 'any',
children: [
{ field: 'genre', operator: 'is', value: 'Horror' },
{
match: 'all',
children: [
{ field: 'genre', operator: 'is', value: 'Thriller' },
{ match: 'any', children: [
{ field: 'title', operator: 'contains', value: 'ghost' },
{ field: 'minutes', operator: 'gt', value: '90' }
] }
]
}
]
}
]
};
expect(compile(g)).toBe(
'type:"movie" AND (genre:"Horror" OR (genre:"Thriller" AND (title:*ghost* OR minutes:{90 TO *})))'
);
});
});
describe('compile — #438 guards + #435 relative dates', () => {
+33 -2
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { parse } from './parse';
import { compile } from './compile';
import type { FieldType } from './types';
import { MAX_GROUP_DEPTH, type FieldType, type Group } from './types';
const FIELDS: Record<string, FieldType> = {
genre: 'text', title: 'text', plot: 'fulltext', type: 'enum', minutes: 'number', release_date: 'date'
@@ -55,11 +55,42 @@ describe('parse', () => {
});
});
it('parses three levels of nesting (#436)', () => {
expect(parse('type:"movie" AND (genre:"Horror" OR (genre:"Thriller" AND (minutes:{90 TO *})))', FIELDS)).toEqual({
match: 'all',
children: [
{ field: 'type', operator: 'is', value: 'movie' },
{ match: 'any', children: [
{ field: 'genre', operator: 'is', value: 'Horror' },
{ match: 'all', children: [
{ field: 'genre', operator: 'is', value: 'Thriller' },
{ match: 'all', children: [{ field: 'minutes', operator: 'gt', value: '90' }] }
] }
] }
]
});
});
it('round-trips a tree at the maximum nesting depth, and rejects one level deeper (#436)', () => {
const leaf = (v: string) => ({ field: 'genre', operator: 'is' as const, value: v });
const nest = (levels: number): Group => {
let g: Group = { match: 'any', children: [leaf('deep-a'), leaf('deep-b')] };
for (let i = 0; i < levels; i++) g = { match: 'all', children: [leaf(`lvl${i}`), g] };
return g;
};
// `nest(n)` puts the innermost group at depth n, so MAX_GROUP_DEPTH is exactly at the cap.
const atCap = nest(MAX_GROUP_DEPTH);
expect(parse(compile(atCap), FIELDS)).toEqual(atCap);
// One level deeper is out of subset — null, not a lossy best-effort tree.
expect(parse(compile(nest(MAX_GROUP_DEPTH + 1)), FIELDS)).toBeNull();
});
it('returns null on out-of-subset input', () => {
expect(parse('genre:"a" AND genre:"b" OR genre:"c"', FIELDS)).toBeNull(); // mixed AND/OR at one level
expect(parse('unknown_field:"x"', FIELDS)).toBeNull(); // unknown field
expect(parse('genre:"a" AND (type:"movie" AND (genre:"b"))', FIELDS)).toBeNull(); // two levels of nesting
expect(parse('title:jo~2', FIELDS)).toBeNull(); // fuzzy — not in subset
expect(parse('(genre:"a")x(genre:"b")', FIELDS)).toBeNull(); // adjacent groups, not one wrapped group
expect(parse('(genre:"a"', FIELDS)).toBeNull(); // unbalanced
});
});
+30 -7
View File
@@ -1,8 +1,8 @@
import type { FieldType, Group, Operator, Rule } from './types';
import { MAX_GROUP_DEPTH, type FieldType, type Group, type Operator, type Rule } from './types';
import { parseRelative, RELATIVE_SYNTHETIC } from './dateMacro';
// Split a group body into top-level parts separated by a single connective, respecting quotes and
// one level of parens. Returns the parts and the connective, or null if the split is malformed or the
// parens to any depth. Returns the parts and the connective, or null if the split is malformed or the
// connectives are mixed (mixed AND/OR at one level is out of subset).
function splitTopLevel(input: string): { parts: string[]; match: 'all' | 'any' } | null {
const parts: string[] = [];
@@ -121,16 +121,39 @@ function mk(field: string, operator: Operator, value: string, value2?: string):
return value2 === undefined ? { field, operator, value } : { field, operator, value, value2 };
}
function parseGroup(input: string, fieldTypes: Record<string, FieldType>, allowNested: boolean): Group | null {
// True iff the leading '(' is closed by the trailing ')' — i.e. the whole part is one parenthesized
// sub-group, not two adjacent ones (`(a)x(b)`). Quote- and escape-aware, mirroring splitTopLevel.
function isParenWrapped(s: string): boolean {
if (!s.startsWith('(') || !s.endsWith(')') || s.length < 2) return false;
let depth = 0;
let quoted = false;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === '\\') { i++; continue; }
if (ch === '"') { quoted = !quoted; continue; }
if (quoted) continue;
if (ch === '(') depth++;
else if (ch === ')') {
depth--;
if (depth === 0) return i === s.length - 1; // the opener closed here
if (depth < 0) return false;
}
}
return false;
}
// `depth` is the nesting depth of the group being parsed (root = 0). A sub-group is in subset only
// while its own depth stays within MAX_GROUP_DEPTH — the same cap the builder UI authors within.
function parseGroup(input: string, fieldTypes: Record<string, FieldType>, depth: number): Group | null {
const split = splitTopLevel(input.trim());
if (!split) return null;
const children: Array<Rule | Group> = [];
for (const part of split.parts) {
const p = part.trim();
if (p.startsWith('(') && p.endsWith(')')) {
if (!allowNested) return null; // deeper than one level
const inner = parseGroup(p.slice(1, -1), fieldTypes, false);
if (isParenWrapped(p)) {
if (depth + 1 > MAX_GROUP_DEPTH) return null; // deeper than the authoring cap
const inner = parseGroup(p.slice(1, -1), fieldTypes, depth + 1);
if (!inner) return null;
children.push(inner);
} else {
@@ -145,5 +168,5 @@ function parseGroup(input: string, fieldTypes: Record<string, FieldType>, allowN
export function parse(input: string, fieldTypes: Record<string, FieldType>): Group | null {
if (!input.trim()) return null;
return parseGroup(input, fieldTypes, true);
return parseGroup(input, fieldTypes, 0);
}
+18 -4
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import { compile } from './compile';
import { parse } from './parse';
import { normalizeGroup } from './validation';
import type { DateUnit, FieldType, Group, Operator, Rule } from './types';
import { isGroup, MAX_GROUP_DEPTH, type DateUnit, type FieldType, type Group, type Operator, type Rule } from './types';
const FIELDS: Record<string, FieldType> = {
genre: 'text', title: 'text', plot: 'fulltext', type: 'enum', minutes: 'number',
@@ -62,25 +62,39 @@ function makeRule(rng: () => number): Rule {
return { field, operator, value: token(rng) };
}
function makeGroup(rng: () => number, allowNested: boolean): Group {
// #436: groups nest to MAX_GROUP_DEPTH levels below the root (which is depth 0), so the generator
// recurses on the same shared cap the UI and parser use rather than a hardcoded one level.
function makeGroup(rng: () => number, depth: number): Group {
const match = rng() < 0.5 ? 'all' : 'any';
const count = 2 + Math.floor(rng() * 3); // >= 2 children
const children: Array<Rule | Group> = [];
for (let i = 0; i < count; i++) {
if (allowNested && rng() < 0.25) children.push(makeGroup(rng, false));
if (depth < MAX_GROUP_DEPTH && rng() < 0.35) children.push(makeGroup(rng, depth + 1));
else children.push(makeRule(rng));
}
return { match, children };
}
function maxDepth(group: Group, depth = 0): number {
return group.children.reduce(
(acc, c) => (isGroup(c) ? Math.max(acc, maxDepth(c, depth + 1)) : acc),
depth
);
}
describe('round-trip: parse(compile(tree)) === tree', () => {
it('holds over 500 generated trees', () => {
const rng = lcg(12345);
let deepest = 0;
for (let i = 0; i < 500; i++) {
const tree = makeGroup(rng, true);
const tree = makeGroup(rng, 0);
deepest = Math.max(deepest, maxDepth(tree));
const text = compile(tree);
const back = parse(text, FIELDS);
expect(back, `seed-iter ${i} failed for: ${text}`).toEqual(normalizeGroup(tree));
}
// Completeness guard: a generator that silently stopped nesting would still pass every
// assertion above, so pin that the corpus actually reached the full cap.
expect(deepest).toBe(MAX_GROUP_DEPTH);
});
});
+9
View File
@@ -18,11 +18,20 @@ export interface Rule {
unit?: DateUnit; // unit for `inLast`/`notInLast` (#435)
}
// A group is recursive: its children are rules and/or further groups, to arbitrary depth (#436,
// superseding #176's one-level "Kodi" model).
export interface Group {
match: Match;
children: Array<Rule | Group>;
}
// Authoring cap on nesting depth: the root group is depth 0, so up to MAX_GROUP_DEPTH levels of
// sub-groups may sit below it. The `Group` type itself is unbounded — this is a deliberate cap that
// keeps the builder UI legible and pathological trees out of the compiler, and it is the SINGLE
// source of truth shared by the UI's "Add group" gate (`RuleBuilder.tsx`), `parse.ts` (anything
// deeper is out of subset ⇒ `null` ⇒ raw-text editing) and the round-trip property-test generator.
export const MAX_GROUP_DEPTH = 5;
export function isGroup(node: Rule | Group): node is Group {
return (node as Group).children !== undefined;
}
+30
View File
@@ -56,4 +56,34 @@ describe('normalizeGroup', () => {
expect(n.match).toBe('any');
expect((n.children[1] as Group).match).toBe('all');
});
it('recurses all the way down a deeply nested tree (#436)', () => {
const g: Group = {
match: 'any',
children: [
r({}),
{ match: 'any', children: [r({}), r({}), { match: 'any', children: [{ match: 'any', children: [r({})] }] }] }
]
};
const n = normalizeGroup(g);
const lvl1 = n.children[1] as Group;
const lvl2 = lvl1.children[2] as Group;
const lvl3 = lvl2.children[0] as Group;
expect(n.match).toBe('any'); // 2 children
expect(lvl1.match).toBe('any'); // 3 children
expect(lvl2.match).toBe('all'); // 1 child — coerced
expect(lvl3.match).toBe('all'); // 1 child — coerced
});
});
describe('groupHasErrors at depth (#436)', () => {
it('finds an invalid rule four levels down', () => {
const deep: Group = {
match: 'all',
children: [
r({}),
{ match: 'all', children: [{ match: 'all', children: [{ match: 'all', children: [r({ value: '' })] }] }] }
]
};
expect(groupHasErrors(deep)).toBe(true);
});
});