# Agent rules

> A rule builder for AI agents: when an agent wants to act and these conditions hold, then ask, notify or block. Rows drag into and out of groups.

A policy editor for what agents may do on their own. WHEN the agent wants to run a command and the command is any of git push, npm publish or rm -rf, and a group says the branch is main or the files changed include migrations/*, THEN ask the code owners for approval, notify #deploys and expire after 30 minutes; OTHERWISE allow it and log it. Every chip is a listbox, values are tokens you add and remove, and each list is joined by a bracket whose And or Or flips with a click. Drag a row by its handle and it takes its place as it passes the others, which slide out of its way, into a group or out of one; the keyboard makes the same moves.

A React component by Bruno Delorence: https://brunodelorence.com/components/agent-rules. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: AI.

## Anatomy

1. **Header**: The rule’s name in 15/20 semibold, where it applies and when it last matched in quiet 13 px, and the On switch.
2. **Trigger**: What the agent wants to do, a listbox in a 44 px grey row: Run a command, Call an external API…
3. **Join**: The bracket at the list’s left and its word on it, And or Or. A button: a click flips it for the whole list.
4. **Condition**: A field with its tinted icon, a verb, an operator and a value or tokens. 44 px on one line; it wraps on a narrow editor.
5. **Handle**: Drag the row by it; press it for a menu of the same moves. Alt and an arrow moves the row from any of its controls.
6. **Group**: A white card of conditions with its own bracket, counted in its header, joined to the rest as one item.
7. **Token**: One value of a list field, in code type on its field’s tint, with a × to remove it; the + adds one.
8. **Action**: What happens: Ask for approval from Code owners, Notify #deploys. Same row as a condition, without the operator.

## When to use

- Setting what an agent may do on its own and what needs a person: approve a `git push` to `main`, block an edit to `migrations/*`.
- A policy that reads as a sentence, WHEN the agent wants to do something and these conditions hold, THEN these actions, OTHERWISE those.
- Conditions that mix And and Or a level deep: a group of rows joined among themselves, then with the rest.
- An admin surface where rules are written now and then and read often, so each one should be legible at a glance.

## When not to use

- Filtering a table or a search. Use a filter bar: the result is a list of rows, not an action.
- Logic deeper than one group, or with arithmetic and scripts. Offer a code editor with a schema, and show the rule it compiles to.
- A single yes or no setting (“Agents may push to main”). A switch in a settings list says it in one line.
- Rules a person will never read back. A short form with presets is faster to fill.

### Moving rows

A row moves by its handle. Dragged, it stays under the pointer and takes a place as soon as it passes a neighbour’s middle, so the others slide out of its way.

- Conditions move anywhere in WHEN: past a group’s header into it, past its last row out of it.
- Actions move within their own list, When it matches or Otherwise.
- The keyboard makes the same moves one place at a time: Alt with ↑ or ↓, or the handle’s menu (Move up, Move down, Move into group, Move out of group, Delete).

### And and Or

Each list has one join for all its items, set on its bracket. Mixed logic goes in a group: `Command is any of git push` And (`Branch is main` Or `Files changed include migrations/*`).

## Do’s and don’ts

- **Do**: Name the rule for what it guards (“Guard risky commands”) and let the rows read as a sentence.
- **Caution**: Use one group, not many: past two groups a rule is hard to read back. Split it into two rules instead.
- **Don’t**: Don’t leave Otherwise empty on a blocking rule: say what happens to everything else, even if it is Allow, and log it.

## Content

Fields and actions are nouns and verbs a reviewer knows from their tools; values are what they type.

- Field names are short nouns: `Command`, `Branch`, `Files changed`.
- Commands and paths are set in code type, exactly as typed: `rm -rf`, `migrations/*`.
- Actions start with a verb: `Ask for approval`, `Notify`, `Expire after`, `Log to`.
- The meta line says scope and recency: `Every agent in acme · Last matched 12 min ago`.

## Installation

Install it with the shadcn CLI, into components/agent-rules of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/agent-rules.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/agent-rules
```

Or copy all the source files below into one folder of your project. Either way it needs React 19 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
'use client';

import { AgentRules, defaultRule, type Rule } from './agent-rules';

export function AgentPolicy({ save }: { save: (rule: Rule) => void }) {
  return (
    <AgentRules
      title="Guard risky commands"
      meta={['Every agent in acme', 'Last matched 12 min ago']}
      defaultRule={defaultRule()}
      onChange={save}
      autoplay={false}
    />
  );
}
```

## States

- **Default**: Risky commands need a code owner’s approval: one condition and a group joined by And.
- **Joined by Or**: The top bracket flipped: any one of the items is enough. The word turns violet.
- **Switched off**: The rule rests, its body faded and desaturated, still editable.
- **No group**: Three conditions in one list, the bracket from the first row to the last.
- **One condition, one action**: A list of one has no bracket: there is nothing to join.
- **Dark**: The same tokens through light-dark(): near-black, the tints deepened.
- **Narrow**: At 360 px the gutter shrinks to 22 px and the chips wrap inside their rows.

## How it works

- The rule is plain data, a trigger, a list of conditions and groups with its join, and two lists of actions. Every edit returns a new rule, and a drag and the keyboard make their moves through the same function, which takes the row out and puts it back at a slot.
- Every slide is one FLIP pass: before a change, the editor notes where each box marked data-flip is on screen; after the new layout it puts each one back there and plays it home on the Web Animations API, 280 ms on cubic-bezier(0.2, 0.8, 0.2, 1). A row inside a moving group or section plays only its own share of the move, so the two add up.
- A dragged row keeps its place under the pointer with the translate property, apart from the FLIP transforms. It takes a new slot as soon as the pointer passes the middle of a neighbour, measured on the new layout, not on boxes still sliding, so it never flickers between two places. It lifts with a 28 px shadow and a 1.2% scale, and settles in 280 ms when dropped.
- Conditions walk every slot in reading order: past a group’s header into it, past its Add condition out of it. Actions stay within their own list. A press on the handle that moves less than 4 px is a click, and opens a menu of the same moves.
- The brackets are a bordered box from the middle of a list’s first row to its last (22 px down each, the middle of a 44 px row), measured from offsetTop after every change and on resize; their ends and the word on them move on transitions with the same timing as the rows.
- Rows are 44 px on one line and wrap their chips on a narrow editor; under 520 px (a container query) the gutter shrinks from 26 to 22 px and the margins tighten, so a 390 px phone never scrolls sideways. Popups shift left inside the editor and open upward when there is no room below.
- While on screen and untouched, a demo pointer picks what the agent wants, flips the top join to Or, drags Files changed out of the group, sets it to All of, carries Command to the bottom, then lets the rule slide back as it was. Any input stops it.
- Every colour is a token on the root with light-dark(): at night the editor turns near-black and the tints deepen, the joins keeping blue for And and violet for Or.

## API reference

- **defaultRule** (`Rule`): The rule it opens on: trigger, join, items (conditions and groups), match and otherwise actions. Without it, the risky-commands rule.
- **onChange** (`(rule: Rule) => void`): Called with the whole rule after every change, a move or an edit.
- **title** (`string`, default `'Guard risky commands'`): The rule’s name, in the header.
- **meta** (`string[]`, default `['Every agent in acme', 'Last matched 12 min ago']`): The quiet line under the title, its parts set apart by a dot.
- **defaultEnabled** (`boolean`, default `true`): Whether the rule starts switched on.
- **onEnabledChange** (`(enabled: boolean) => void`): Called when the reader flips the switch.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer edits the rule and drags rows; any input from the reader stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): A class for the stage.

## Accessibility

### Keyboard

- Every chip is a button that opens a listbox (a menu for Add action and the handles): ↓ or ↑ opens it, arrows, Home, End and the first letter move, Enter or Space picks, Escape closes and hands the focus back.
- Alt with ↑ or ↓ moves the row the focus is in, into and out of groups; the focus stays on the same control.
- Tokens: Enter adds and keeps the field open, Backspace in an empty field removes the last one, Escape closes it.

### Screen readers

- Each handle is named for its row (“Move Command condition”) and says Alt and an arrow moves it too.
- The join is a button named with its state and what a press does (“Conditions joined by And; switch to Or”).
- A polite live region says each move, drop, add, delete and join change: “Files changed moved to the rule, 3 of 3”.

### In this build

- Every chip is a real button with aria-haspopup that opens a listbox (a menu for Add action and the row handles) with aria-selected on the chosen value: ↓ or ↑ opens it, arrows, Home, End and type-ahead move, Enter or Space picks, Escape closes and gives the focus back.
- Dragging has a keyboard way: Alt with ↑ or ↓ moves the row the focus is in, one slot at a time, into and out of groups, and the focus stays on the same control. The handle’s menu offers Move up, Move down, Move into group, Move out of group and Delete.
- The join on each bracket is a button named with its state and what a press does (“Conditions joined by And; switch to Or”); the lists are labelled with their join.
- A polite live region says each move, drop, addition, deletion and join change, with where the row is now (“Files changed moved to the rule, 3 of 3”).
- The switch is role="switch" with aria-checked. Delete buttons show on hover and focus, always on touch screens. Every control shows a focus ring on keyboard focus; icons and the demo pointer are hidden from screen readers.
- With reduced motion, rows, brackets and popups change at once, without slides, and the demo does not play.

## Source

### agent-rules/agent-rules.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type MouseEvent as ReactMouseEvent,
  type PointerEvent as ReactPointerEvent,
} from 'react';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Glyph } from './glyphs';
import { ACTION_CHOICES, ActionRow, ConditionRow, type Move } from './rows';
import {
  FIELD_ORDER,
  TRIGGERS,
  action,
  condition,
  defaultRule as startingRule,
  editAction,
  editCondition,
  find,
  listName,
  place,
  remove,
  rowName,
  settle,
  step,
  uid,
  type Action,
  type ActionId,
  type Condition,
  type FieldId,
  type Group,
  type Join,
  type Rule,
  type Slot,
} from './rule';
import { DemoDriving, Popup } from './select';
import { useAutoplay } from './use-autoplay';
import styles from './agent-rules.module.css';

export type { Action, ActionId, Condition, FieldId, Group, Join, Rule } from './rule';
export { action, condition, startingRule as defaultRule };

/*
 * A rule editor for what agents may do: WHEN the agent wants to do something and these
 * conditions hold, THEN take these actions, and OTHERWISE those. Conditions are rows, or groups of
 * rows; each list is joined by And or Or, drawn as a bracket at its left with the word on it, a
 * button that flips it.
 *
 * Rows move by their handle. While a row is dragged it stays under the pointer and the rule is
 * rewritten as it goes: the moment it passes the middle of a neighbour, it takes that place, so
 * the others slide out of its way (into a group, out of one). The keyboard makes the same moves,
 * one place at a time, with Alt and an arrow or the handle's menu.
 *
 * Every slide is one FLIP pass: before the rule changes, `update` notes where each [data-flip] box
 * is on screen; after the new layout, each one is moved back there and played home on the Web
 * Animations API. A box inside another moving box plays only its own part of the move, so the two
 * add up. The brackets follow on a CSS transition of their ends, measured from the rows.
 */

/** The slide every box plays to its new place, and the drop of a dragged row. */
const SLIDE: KeyframeAnimationOptions = {
  duration: 280,
  easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)',
};

/** How far the pointer goes with the handle down before it is a drag, not a press. */
const DRAG_SLOP = 4;

/** Where a bracket's ends meet a row: the middle of its first line (7 padding + 30 / 2). */
const ANCHOR = 22;

type Drag = {
  id: string;
  /** Where the pointer holds the row, from its top, in the editor's px. */
  grab: number;
  /** The pointer's y in the editor's px. */
  y: number;
};

export function AgentRules({
  className = '',
  autoplay = true,
  colorScheme,
  defaultRule,
  onChange,
  title = 'Guard risky commands',
  meta = ['Every agent in acme', 'Last matched 12 min ago'],
  defaultEnabled = true,
  onEnabledChange,
}: {
  className?: string;
  /** While on screen and untouched, a demo pointer edits the rule; any input stops it. */
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  /** The rule it opens on. */
  defaultRule?: Rule;
  /** Called with the whole rule after every change. */
  onChange?: (rule: Rule) => void;
  title?: string;
  /** The quiet line under the title, its parts set apart by a dot. */
  meta?: string[];
  defaultEnabled?: boolean;
  onEnabledChange?: (enabled: boolean) => void;
}) {
  const [first] = useState(() => settle(defaultRule ?? startingRule()));
  const [rule, setRule] = useState(first);
  const [enabled, setEnabled] = useState(defaultEnabled);
  const [lifted, setLifted] = useState<string | null>(null);
  const [said, setSaid] = useState('');
  const editor = useRef<HTMLDivElement>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const driving = useRef(false);
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  /** The reader's first input ends the demo, and what it does next is theirs (and said). */
  const takeOver = () => {
    driving.current = false;
    take();
  };

  /** Where each box was on screen just before a change, by its data-flip key. */
  const before = useRef<Map<string, DOMRect> | null>(null);
  /** Where each box sits in the new layout, from the editor's top, for the drag's hit test. */
  const layout = useRef(new Map<string, { top: number; bottom: number }>());
  const drag = useRef<Drag | null>(null);
  /** Set when a press on a handle became a drag, so its click doesn't open the menu. */
  const dragged = useRef(false);
  const reduced = useRef(false);
  const ruleRef = useRef(rule);
  ruleRef.current = rule;

  useEffect(() => {
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const read = () => (reduced.current = motion.matches);
    read();
    motion.addEventListener('change', read);
    return () => motion.removeEventListener('change', read);
  }, []);

  const boxes = () =>
    [...(editor.current?.querySelectorAll<HTMLElement>('[data-flip]') ?? [])].map(
      (element) => [element.dataset.flip!, element] as const,
    );

  /** Every change to the rule: notes where things are first, so the new layout can slide. */
  const update = (next: (rule: Rule) => Rule) => {
    before.current = new Map(
      boxes().map(([key, element]) => [key, element.getBoundingClientRect()]),
    );
    setRule((rule) => next(rule));
  };

  const scaleOf = () => {
    const box = editor.current!;
    return box.getBoundingClientRect().width / box.offsetWidth || 1;
  };

  /** The brackets' ends, from the first and the last row of each list. */
  const measureBrackets = () => {
    editor.current?.querySelectorAll<HTMLElement>('[data-list]').forEach((list) => {
      const rows = list.querySelector('ul')?.children;
      if (!rows || rows.length < 2) return;
      const top = (rows[0] as HTMLElement).offsetTop + ANCHOR;
      const bottom = (rows[rows.length - 1] as HTMLElement).offsetTop + ANCHOR;
      list.style.setProperty('--from', `${top}px`);
      list.style.setProperty('--to', `${bottom}px`);
    });
  };

  /** Keeps the dragged row under the pointer, from its place in the new layout. */
  const follow = () => {
    const held = drag.current;
    const element = held && editor.current?.querySelector<HTMLElement>(`[data-flip="${held.id}"]`);
    const box = held && layout.current.get(held.id);
    if (!held || !element || !box) return;
    element.style.translate = `0 ${held.y - held.grab - box.top}px`;
  };

  // The FLIP pass, after every render that changed the rule.
  useLayoutEffect(() => {
    const frame = editor.current;
    if (!frame) return;
    const old = before.current;
    before.current = null;
    const scale = scaleOf();
    const all = boxes();
    // Each box's place in the new layout: with no slide running and the dragged row let go.
    for (const [, element] of all)
      element.getAnimations().forEach((animation) => animation.id === 'flip' && animation.cancel());
    const held = drag.current?.id;
    const heldElement = held ? frame.querySelector<HTMLElement>(`[data-flip="${held}"]`) : null;
    if (heldElement) heldElement.style.translate = '';
    const origin = frame.getBoundingClientRect().top;
    const now = new Map<string, DOMRect>();
    layout.current = new Map();
    for (const [key, element] of all) {
      const rect = element.getBoundingClientRect();
      now.set(key, rect);
      layout.current.set(key, {
        top: (rect.top - origin) / scale,
        bottom: (rect.bottom - origin) / scale,
      });
    }
    measureBrackets();
    follow();
    if (!old || reduced.current) return;
    const delta = (key: string) => {
      const was = old.get(key);
      const is = now.get(key);
      return was && is ? { x: was.left - is.left, y: was.top - is.top } : null;
    };
    for (const [key, element] of all) {
      if (key === held) continue;
      const own = delta(key);
      if (!own) {
        // A new box fades in where it lands.
        element.animate(
          [
            { opacity: 0, transform: 'translateY(-4px) scale(0.98)' },
            { opacity: 1, transform: 'none' },
          ],
          { ...SLIDE, id: 'flip' },
        );
        continue;
      }
      // Only its own share of the move: the box it sits in plays the rest.
      const parent = element.parentElement?.closest<HTMLElement>('[data-flip]');
      const carried = parent ? delta(parent.dataset.flip!) : null;
      const x = (own.x - (carried?.x ?? 0)) / scale;
      const y = (own.y - (carried?.y ?? 0)) / scale;
      if (Math.abs(x) < 0.5 && Math.abs(y) < 0.5) continue;
      element.animate([{ transform: `translate(${x}px, ${y}px)` }, { transform: 'none' }], {
        ...SLIDE,
        id: 'flip',
      });
    }
  }, [rule]);

  // Rows wrap on a narrow editor, and chips change width: the brackets follow.
  useEffect(() => {
    const frame = editor.current;
    if (!frame) return;
    const observer = new ResizeObserver(() => measureBrackets());
    observer.observe(frame);
    frame.querySelectorAll('[data-list] > ul').forEach((list) => observer.observe(list));
    return () => observer.disconnect();
  }, [rule]);

  const mounted = useRef(false);
  useEffect(() => {
    if (mounted.current) onChange?.(rule);
    mounted.current = true;
    // onChange is the parent's: only the rule changing calls it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rule]);

  // The demo's own edits stay quiet: only the reader's are said. A repeat gets a no-break space,
  // so the region still changes and is read again.
  const say = (words: string) => {
    if (driving.current) return;
    setSaid((last) => (last === words ? `${words}\u00a0` : words));
  };

  /** Where a row now is, in words: `the group, 1 of 2`. */
  const placeWords = (next: Rule, id: string) => {
    const at = find(next, id);
    if (!at) return '';
    const size =
      at.list === 'root'
        ? next.items.length
        : at.list === 'match' || at.list === 'otherwise'
          ? next[at.list].length
          : (next.items.find((item) => item.id === at.list) as Group).items.length;
    return `${listName(at.list)}, ${at.index + 1} of ${size}`;
  };

  const rowOf = (id: string): Condition | Action | null => {
    for (const item of ruleRef.current.items) {
      if (item.id === id && item.kind === 'condition') return item;
      if (item.kind === 'group') for (const c of item.items) if (c.id === id) return c;
    }
    return (
      [...ruleRef.current.match, ...ruleRef.current.otherwise].find((a) => a.id === id) ?? null
    );
  };

  const moveTo = (id: string, slot: Slot | null, announce = true) => {
    if (!slot) return;
    const row = rowOf(id);
    const next = place(ruleRef.current, id, slot);
    update(() => next);
    if (announce && row) say(`${rowName(row)} moved to ${placeWords(next, id)}`);
  };

  const focusIn = (id: string, part: string) =>
    requestAnimationFrame(() =>
      editor.current
        ?.querySelector<HTMLElement>(`[data-row="${id}"] [data-part="${part}"]`)
        ?.focus({ preventScroll: true }),
    );

  const deleteRow = (id: string) => {
    const row = rowOf(id);
    const at = find(ruleRef.current, id);
    const next = remove(ruleRef.current, id);
    update(() => next);
    if (row) say(`${rowName(row)} deleted`);
    // The focus goes to the handle of the row that took its place, else the list's add button.
    requestAnimationFrame(() => {
      const frame = editor.current;
      if (!frame || !at) return;
      const list = frame.querySelector(`[data-list="${at.list}"] > ul`);
      const handles = list?.querySelectorAll<HTMLElement>(
        ':scope > li > span [data-part="handle"]',
      );
      const target =
        handles?.[Math.min(at.index, handles.length - 1)] ??
        frame.querySelector<HTMLElement>(`[data-add="${at.list}"]`);
      target?.focus({ preventScroll: true });
    });
  };

  /** What a row's handle menu offers, where it is. */
  const movesFor = (id: string): Move[] => {
    const at = find(rule, id);
    const isAction = at?.list === 'match' || at?.list === 'otherwise';
    const moves: Move[] = [
      { id: 'up', label: 'Move up', glyph: 'up', disabled: !step(rule, id, -1) },
      { id: 'down', label: 'Move down', glyph: 'down', disabled: !step(rule, id, 1) },
    ];
    if (!isAction && at?.list === 'root' && rule.items.some((item) => item.kind === 'group'))
      moves.push({ id: 'into', label: 'Move into group', glyph: 'into' });
    if (!isAction && at && at.list !== 'root')
      moves.push({ id: 'out', label: 'Move out of group', glyph: 'out' });
    moves.push({ id: 'delete', label: 'Delete', glyph: 'trash' });
    return moves;
  };

  const onMove = (id: string, move: string) => {
    const current = ruleRef.current;
    if (move === 'up' || move === 'down') moveTo(id, step(current, id, move === 'up' ? -1 : 1));
    else if (move === 'delete') deleteRow(id);
    else if (move === 'out') {
      const at = find(current, id)!;
      const group = current.items.findIndex((item) => item.id === at.list);
      moveTo(id, { list: 'root', index: group + 1 });
    } else if (move === 'into') {
      // Into the nearest group below it, or else the last one above, at its end.
      const at = find(current, id)!;
      const groups = current.items
        .map((item, index) => ({ item, index }))
        .filter(({ item }) => item.kind === 'group');
      const target = groups.find(({ index }) => index > at.index) ?? groups.at(-1);
      if (target) moveTo(id, { list: target.item.id, index: (target.item as Group).items.length });
    }
    if (move !== 'delete') {
      requestAnimationFrame(() =>
        editor.current
          ?.querySelector<HTMLElement>(`[data-row="${id}"] [data-part="handle"]`)
          ?.focus({ preventScroll: true }),
      );
    }
  };

  const onKeyMove = (id: string) => (event: ReactKeyboardEvent) => {
    if (!event.altKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) return;
    event.preventDefault();
    const focused = document.activeElement as HTMLElement | null;
    const part = focused?.dataset.part;
    moveTo(id, step(ruleRef.current, id, event.key === 'ArrowUp' ? -1 : 1));
    // The focus stays on the same control of the row, which React keeps mounted as it moves.
    if (part) focusIn(id, part);
  };

  /** The slot the pointer is over, for the dragged row `id`. */
  const slotAt = (id: string, y: number): Slot => {
    const current = ruleRef.current;
    const at = find(current, id)!;
    const mid = (key: string) => {
      const box = layout.current.get(key);
      return box ? (box.top + box.bottom) / 2 : Infinity;
    };
    if (at.list === 'match' || at.list === 'otherwise') {
      const others = current[at.list].filter((a) => a.id !== id);
      return { list: at.list, index: others.filter((a) => mid(a.id) < y).length };
    }
    // In reading order: each place a condition can go, and the height that ends it.
    const lines: { y: number; slot: Slot }[] = [];
    let index = 0;
    for (const item of current.items) {
      if (item.id === id) continue;
      if (item.kind === 'condition') lines.push({ y: mid(item.id), slot: { list: 'root', index } });
      else {
        const head = (layout.current.get(item.id)?.top ?? Infinity) + ANCHOR;
        lines.push({ y: head, slot: { list: 'root', index } });
        const rows = item.items.filter((c) => c.id !== id);
        rows.forEach((c, i) => lines.push({ y: mid(c.id), slot: { list: item.id, index: i } }));
        lines.push({ y: mid(`${item.id}:add`), slot: { list: item.id, index: rows.length } });
      }
      index += 1;
    }
    return lines.find((line) => line.y > y)?.slot ?? { list: 'root', index };
  };

  const onGrab = (id: string) => (event: ReactPointerEvent<HTMLElement>) => {
    if (event.button !== 0) return;
    const frame = editor.current;
    const row = frame?.querySelector<HTMLElement>(`[data-flip="${id}"]`);
    if (!frame || !row) return;
    const start = { x: event.clientX, y: event.clientY };
    const scale = scaleOf();
    const local = (clientY: number) => (clientY - frame.getBoundingClientRect().top) / scale;
    const top = layout.current.get(id)?.top ?? 0;
    dragged.current = false;
    const handle = event.currentTarget;

    const onMovePointer = (move: PointerEvent) => {
      if (!drag.current) {
        if (Math.hypot(move.clientX - start.x, move.clientY - start.y) < DRAG_SLOP) return;
        drag.current = { id, grab: local(start.y) - top, y: local(move.clientY) };
        dragged.current = true;
        setLifted(id);
        handle.setPointerCapture?.(move.pointerId);
      }
      move.preventDefault();
      drag.current.y = local(move.clientY);
      const slot = slotAt(id, drag.current.y);
      const at = find(ruleRef.current, id);
      if (at && (slot.list !== at.list || slot.index !== at.index)) moveTo(id, slot, false);
      else follow();
    };
    const onUp = () => {
      window.removeEventListener('pointermove', onMovePointer);
      window.removeEventListener('pointerup', onUp);
      window.removeEventListener('pointercancel', onUp);
      // The click that may follow this release is the drag's, not a press on the handle.
      window.setTimeout(() => (dragged.current = false), 0);
      const held = drag.current;
      if (!held) return;
      drag.current = null;
      setLifted(null);
      // The row settles from under the pointer into its place.
      const shift = parseFloat(row.style.translate.split(' ')[1] ?? '0') || 0;
      row.style.translate = '';
      if (!reduced.current && shift)
        row.animate([{ translate: `0 ${shift}px` }, { translate: '0 0' }], SLIDE);
      const moved = rowOf(id);
      if (moved) say(`${rowName(moved)} dropped in ${placeWords(ruleRef.current, id)}`);
    };
    window.addEventListener('pointermove', onMovePointer);
    window.addEventListener('pointerup', onUp);
    window.addEventListener('pointercancel', onUp);
  };

  /** A press that became a drag doesn't also open the handle's menu. */
  const onClickCapture = (event: ReactMouseEvent) => {
    if (!dragged.current) return;
    dragged.current = false;
    event.stopPropagation();
    event.preventDefault();
  };

  const flipJoin = (list: string) => {
    const from =
      list === 'root' ? rule.join : (rule.items.find((i) => i.id === list) as Group).join;
    const join: Join = from === 'and' ? 'or' : 'and';
    update((current) =>
      list === 'root'
        ? { ...current, join }
        : {
            ...current,
            items: current.items.map((item) =>
              item.id === list && item.kind === 'group' ? { ...item, join } : item,
            ),
          },
    );
    say(`${list === 'root' ? 'Conditions' : 'Group'} joined by ${join === 'and' ? 'And' : 'Or'}`);
  };

  const unused = (items: Condition[]): FieldId =>
    FIELD_ORDER.find((field) => !items.some((c) => c.field === field)) ?? 'branch';

  const addRule = () => {
    const fresh = condition(
      unused(rule.items.filter((item): item is Condition => item.kind === 'condition')),
    );
    update((current) => ({ ...current, items: [...current.items, fresh] }));
    say(`${rowName(fresh)} condition added`);
    focusIn(fresh.id, 'field');
  };

  const addGroup = () => {
    const fresh = condition('repository', 'Not equal to', ['acme/payments']);
    const group: Group = { kind: 'group', id: uid('g'), join: 'and', items: [fresh] };
    update((current) => ({ ...current, items: [...current.items, group] }));
    say('Group added with one condition');
    focusIn(fresh.id, 'field');
  };

  const addToGroup = (groupId: string) => {
    const group = rule.items.find((item) => item.id === groupId) as Group;
    const fresh = condition(unused(group.items));
    update((current) => ({
      ...current,
      items: current.items.map((item) =>
        item.id === groupId && item.kind === 'group'
          ? { ...item, items: [...item.items, fresh] }
          : item,
      ),
    }));
    say(`${rowName(fresh)} condition added to the group`);
    focusIn(fresh.id, 'field');
  };

  const deleteGroup = (groupId: string) => {
    update((current) => remove(current, groupId));
    say('Group deleted');
    requestAnimationFrame(() =>
      editor.current
        ?.querySelector<HTMLElement>('[data-add="root"]')
        ?.focus({ preventScroll: true }),
    );
  };

  const addAction = (list: 'match' | 'otherwise', type: string) => {
    const fresh = action(type as ActionId);
    update((current) => ({ ...current, [list]: [...current[list], fresh] }));
    say(`${rowName(fresh)} added to ${listName(list)}`);
    focusIn(fresh.id, 'action-type');
  };

  const toggle = () => {
    const next = !enabled;
    setEnabled(next);
    onEnabledChange?.(next);
  };

  const shared = (id: string) => ({
    moves: movesFor(id),
    onMove: (move: string) => onMove(id, move),
    onGrab: onGrab(id),
    onKeyMove: onKeyMove(id),
    lifted: lifted === id,
  });

  const conditionRow = (c: Condition) => (
    <ConditionRow
      key={c.id}
      condition={c}
      {...shared(c.id)}
      onChange={(next) => update((current) => editCondition(current, c.id, () => next))}
    />
  );

  /** A list's bracket and its And/Or: a button for conditions, a plain word for actions. */
  const bracket = (list: string, count: number, join: Join, flips: boolean) =>
    count > 1 && (
      <>
        <span className={styles.bracket} aria-hidden="true" />
        {flips ? (
          <button
            type="button"
            className={styles.pill}
            data-join={join}
            data-part="join"
            aria-label={`${list === 'root' ? 'Conditions' : 'Group'} joined by ${
              join === 'and' ? 'And' : 'Or'
            }; switch to ${join === 'and' ? 'Or' : 'And'}`}
            onClick={() => flipJoin(list)}
          >
            {join === 'and' ? 'And' : 'Or'}
          </button>
        ) : (
          <span className={styles.pill} data-join="and" data-static aria-hidden="true">
            And
          </span>
        )}
      </>
    );

  const actions = (list: 'match' | 'otherwise') => (
    <>
      <div className={styles.list} data-list={list}>
        {bracket(list, rule[list].length, 'and', false)}
        <ul className={styles.rows} aria-label={`${listName(list)}: all of these`}>
          {rule[list].map((a) => (
            <ActionRow
              key={a.id}
              action={a}
              {...shared(a.id)}
              onChange={(next) => update((current) => editAction(current, a.id, () => next))}
            />
          ))}
        </ul>
      </div>
      <div className={styles.addBar} data-flip={`${list}:add`}>
        <Popup
          label="Add action"
          role="menu"
          plain
          triggerClass={styles.addButton}
          trigger={
            <>
              <Glyph name="plus" />
              Add action
            </>
          }
          triggerLabel={`Add action to ${listName(list)}`}
          choices={ACTION_CHOICES}
          onPick={(type) => addAction(list, type)}
        />
      </div>
    </>
  );

  // The demo: picks what the agent wants, flips the join, drags a row out of the group and back
  // under, changes an operator, then puts the rule back as it was and goes again.
  const demo = autoplay && playing;
  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    const frame = editor.current;
    if (!demo || !stage || !arrow || !frame) return;
    driving.current = true;
    const q = (selector: string) => frame.querySelector<HTMLElement>(selector);
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      /** The middle of `element`, nudged by dx, dy, in the stage's own px. */
      const at = (element: HTMLElement | null, dx = 0, dy = 0): Point => {
        const box = stage.getBoundingClientRect();
        const scale = box.width / stage.offsetWidth || 1;
        const rect = element?.getBoundingClientRect() ?? box;
        return {
          x: (rect.left + rect.width / 2 - box.left) / scale + dx,
          y: (rect.top + rect.height / 2 - box.top) / scale + dy,
        };
      };
      const press = async (element: HTMLElement | null, ms = 620) => {
        if (!element) return;
        // Near the start of a wide chip, where the eye reads it.
        await glide(
          at(element, Math.min(24, element.offsetWidth / 2) - element.offsetWidth / 2),
          ms,
        );
        glyph('hand');
        await wait(220);
        element.click();
        await wait(260);
      };
      const choose = async (value: string) => {
        const option = q(
          `[role="listbox"] [data-value="${value}"], [role="menu"] [data-value="${value}"]`,
        );
        if (!option) return;
        await glide(at(option, -option.offsetWidth / 2 + 40), 420);
        await wait(380);
        option.click();
        await wait(300);
      };
      /** Drags the row `id` one place at a time, the pointer riding on its handle. */
      const carry = async (id: string, by: -1 | 1, steps: number) => {
        const handle = () => q(`[data-row="${id}"] [data-part="handle"]`);
        await glide(at(handle()), 620);
        glyph('hand');
        await wait(260);
        setLifted(id);
        await wait(240);
        for (let i = 0; i < steps; i += 1) {
          moveTo(id, step(ruleRef.current, id, by), false);
          await wait(30);
          await glide(at(handle()), 360);
          await wait(140);
        }
        await wait(200);
        setLifted(null);
        await wait(300);
      };
      const rest = async () => {
        glyph('arrow');
        await glide(at(frame, frame.offsetWidth * 0.42, -frame.offsetHeight * 0.05), 700);
      };

      await glide(at(frame, frame.offsetWidth * 0.3, -frame.offsetHeight * 0.3), 800);
      for (;;) {
        const start = ruleRef.current;
        await wait(700);
        // What the agent wants to do.
        await press(q('[data-part="trigger"]'));
        await choose(TRIGGERS[1]);
        await rest();
        await wait(500);
        // The top bracket's And turns to Or.
        await press(q('[data-list="root"] > [data-part="join"]'), 560);
        await wait(700);
        // A row out of the group, under the others.
        const group = start.items.find((item): item is Group => item.kind === 'group');
        const files = group?.items[1];
        if (files) {
          await carry(files.id, 1, 2);
          await wait(400);
          await press(q(`[data-row="${files.id}"] [data-part="operator"]`), 520);
          await choose('All of');
          await wait(500);
        }
        // The first row down to the bottom.
        const command = start.items[0];
        if (command?.kind === 'condition') await carry(command.id, 1, 4);
        await rest();
        await wait(1800);
        // As it was, sliding back.
        update(() => start);
        await wait(1400);
      }
    });
    return () => {
      stop();
      driving.current = false;
      setLifted(null);
    };
    // The demo's steps read the rule through ruleRef; it starts and stops with `demo`.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [demo, root]);

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={takeOver}
      onKeyDownCapture={takeOver}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') takeOver();
      }}
    >
      <DemoDriving.Provider value={driving}>
        <div
          ref={editor}
          className={styles.editor}
          data-part="editor"
          data-enabled={enabled}
          data-dragging={lifted ? true : undefined}
          onClickCapture={onClickCapture}
        >
          <header className={styles.header} data-part="header">
            <div>
              <h3 className={styles.title}>{title}</h3>
              <p className={styles.meta}>
                {meta.map((part, index) => (
                  <span key={part}>
                    {index > 0 && <span className={styles.dot} aria-hidden="true" />}
                    {part}
                  </span>
                ))}
              </p>
            </div>
            <label className={styles.toggle}>
              <span className={styles.toggleLabel}>{enabled ? 'On' : 'Off'}</span>
              <button
                type="button"
                role="switch"
                aria-checked={enabled}
                aria-label={`${title}: rule on`}
                className={styles.switch}
                data-part="switch"
                onClick={toggle}
              />
            </label>
          </header>

          <div className={styles.body}>
            <section className={styles.section} aria-label="When">
              <h4 className={styles.sectionLabel}>When</h4>
              <div className={styles.triggerRow} data-part="trigger-row">
                <Glyph name="lock" className={styles.triggerGlyph} />
                <span className={styles.verb}>Agent wants to</span>
                <Popup
                  label="Agent wants to"
                  role="listbox"
                  part="trigger"
                  value={rule.trigger}
                  choices={TRIGGERS.map((value) => ({ value, label: value }))}
                  triggerClass={`${styles.chip} ${styles.strong}`}
                  triggerLabel={`Agent wants to: ${rule.trigger}`}
                  trigger={rule.trigger}
                  onPick={(trigger) => {
                    update((current) => ({ ...current, trigger }));
                    say(`Agent wants to: ${trigger}`);
                  }}
                />
              </div>

              <div className={styles.list} data-list="root">
                {bracket('root', rule.items.length, rule.join, true)}
                <ul
                  className={styles.rows}
                  aria-label={`Conditions, joined by ${rule.join === 'and' ? 'And' : 'Or'}`}
                >
                  {rule.items.map((item) =>
                    item.kind === 'condition' ? (
                      conditionRow(item)
                    ) : (
                      <li
                        key={item.id}
                        className={styles.group}
                        data-part="group"
                        data-flip={item.id}
                        aria-label={`Group, ${item.items.length} ${
                          item.items.length === 1 ? 'condition' : 'conditions'
                        }`}
                      >
                        <div className={styles.groupHead}>
                          <span className={styles.groupName}>Group</span>
                          <span className={styles.dot} aria-hidden="true" />
                          <span className={styles.groupCount} data-part="group-count">
                            {item.items.length}{' '}
                            {item.items.length === 1 ? 'condition' : 'conditions'}
                          </span>
                          <button
                            type="button"
                            className={`${styles.remove} ${styles.groupRemove}`}
                            aria-label="Delete group"
                            onClick={() => deleteGroup(item.id)}
                          >
                            <Glyph name="trash" />
                          </button>
                        </div>
                        <div className={styles.list} data-list={item.id}>
                          {bracket(item.id, item.items.length, item.join, true)}
                          <ul
                            className={styles.rows}
                            aria-label={`Group conditions, joined by ${item.join === 'and' ? 'And' : 'Or'}`}
                          >
                            {item.items.map(conditionRow)}
                          </ul>
                          {item.items.length === 0 && (
                            <p className={styles.empty}>Drag a condition here, or add one.</p>
                          )}
                        </div>
                        <div className={styles.addBar} data-flip={`${item.id}:add`}>
                          <button
                            type="button"
                            className={styles.addButton}
                            data-add={item.id}
                            onClick={() => addToGroup(item.id)}
                          >
                            <Glyph name="addRow" />
                            Add condition
                          </button>
                        </div>
                      </li>
                    ),
                  )}
                </ul>
              </div>
              <div className={styles.addBar} data-flip="root:add">
                <button
                  type="button"
                  className={styles.addButton}
                  data-add="root"
                  onClick={addRule}
                >
                  <Glyph name="addRow" />
                  Add rule
                </button>
                <button type="button" className={styles.addButton} onClick={addGroup}>
                  <Glyph name="addGroup" />
                  Add group
                </button>
              </div>
            </section>

            <section className={styles.section} aria-label="Then" data-flip="then">
              <h4 className={styles.sectionLabel}>Then</h4>
              <p className={styles.badge} data-tone="match" data-part="match-badge">
                <Glyph name="people" />
                When it matches
              </p>
              {actions('match')}
              <div data-flip="otherwise:head">
                <p className={styles.badge} data-tone="otherwise">
                  <Glyph name="check" />
                  Otherwise
                </p>
              </div>
              {actions('otherwise')}
            </section>
          </div>
        </div>
      </DemoDriving.Provider>
      <p className={styles.hidden} aria-live="polite">
        {said}
      </p>
      <DemoPointer
        ref={pointer}
        className={styles.pointer}
        arrowClass={styles.arrow}
        handClass={styles.hand}
      />
    </div>
  );
}
```

### agent-rules/agent-rules.module.css

```css
/* Agent rules (agent-rules.tsx): a rule editor for what agents may do. A header with the rule's
   name and its switch, then WHEN (what the agent wants to do, and the conditions, in rows and
   groups) and THEN (the actions when it matches, and otherwise).

   Sizes. Rows are 44 px tall on one line (7 px around a 30 px chip) on a 12 px radius; they wrap
   their chips on a narrow editor and grow. Each list of two or more hangs a bracket in the gutter
   at its left (26 px, 22 px on a phone) from the middle of the first row's first line to the
   last's, with its And or Or on it.

   Motion. Rows and groups slide to their new places in 280 ms on cubic-bezier(0.2, 0.8, 0.2, 1),
   played from the script (FLIP); the brackets' ends and words follow on transitions with the same
   timing. A dragged row lifts with a shadow. With reduced motion, everything moves at once.

   Colours are the tokens below, light, then light-dark(light, dark) where @supports allows: the component takes the color-scheme it
   inherits from the page, or the one its colorScheme prop sets. */

.root {
  --surface: #fff;
  --ink: #1d1d1f;
  --chip-ink: #3a3a3d;
  --soft: #76767c;
  --muted: #9b9ba1;
  --row: #f6f6f7;
  --row-active: #efeff1;
  --chip: #fff;
  --chip-edge: rgb(0 0 0 / 0.07);
  --chip-shadow: rgb(0 0 0 / 0.05);
  --line: #d9d9de;
  --grip: #b9b9bf;
  --group: #fff;
  --group-edge: rgb(0 0 0 / 0.08);
  --group-shadow: rgb(0 0 0 / 0.05);
  --lift: rgb(20 20 30 / 0.14);
  --popup-shadow: rgb(20 20 30 / 0.12);
  /* The joins: And blue, Or violet. */
  --and: #e8f0fe;
  --and-ink: #2d64cc;
  --or: #efe8fd;
  --or-ink: #7041d4;
  /* The THEN badges. */
  --match: #fcf1db;
  --match-ink: #94610f;
  --otherwise: #e2f5e7;
  --otherwise-ink: #22834a;
  --switch-off: #d6d6db;
  --switch-on: #1fae8c;
  --knob: #fff;
  --focus: #387bff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);
  /* The icon tiles and tokens: a soft fill and its ink, per tint. */
  --green: #e1f4eb;
  --green-ink: #178a5f;
  --teal: #ddf2f0;
  --teal-ink: #11806f;
  --orange: #fdebdb;
  --orange-ink: #c25e1c;
  --grey: #efeff1;
  --grey-ink: #3a3a3d;
  --violet: #eee8fd;
  --violet-ink: #6c45d3;
  --amber: #fcefd5;
  --amber-ink: #b97a0d;
  --blue: #e7effd;
  --blue-ink: #3a6dd4;
  --sky: #e3f0fb;
  --sky-ink: #2a7fc0;
  --red: #fde5e4;
  --red-ink: #cf3a36;
  --gutter: 26px;
  --slide: 280ms cubic-bezier(0.2, 0.8, 0.2, 1);

  position: relative;
  container-type: inline-size;
  overflow: clip;
  border-radius: 18px;
  background: var(--surface);
  color: var(--ink);
  font:
    400 13px / 1.35 -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -webkit-tap-highlight-color: transparent;
}
/* The night pairs: inside @supports, which the build leaves as written. */
@supports (color: light-dark(#fff, #000)) {
  .root {
    --surface: light-dark(#fff, #131315);
    --ink: light-dark(#1d1d1f, #f2f2f4);
    --chip-ink: light-dark(#3a3a3d, #dcdce0);
    --soft: light-dark(#76767c, #9a9aa1);
    --muted: light-dark(#9b9ba1, #7c7c84);
    --row: light-dark(#f6f6f7, #1d1d20);
    --row-active: light-dark(#efeff1, #26262a);
    --chip: light-dark(#fff, #2a2a2e);
    --chip-edge: light-dark(rgb(0 0 0 / 0.07), rgb(255 255 255 / 0.07));
    --chip-shadow: light-dark(rgb(0 0 0 / 0.05), rgb(0 0 0 / 0.3));
    --line: light-dark(#d9d9de, #3b3b41);
    --grip: light-dark(#b9b9bf, #5d5d64);
    --group: light-dark(#fff, #18181b);
    --group-edge: light-dark(rgb(0 0 0 / 0.08), rgb(255 255 255 / 0.08));
    --group-shadow: light-dark(rgb(0 0 0 / 0.05), rgb(0 0 0 / 0.4));
    --lift: light-dark(rgb(20 20 30 / 0.14), rgb(0 0 0 / 0.55));
    --popup-shadow: light-dark(rgb(20 20 30 / 0.12), rgb(0 0 0 / 0.5));
    --and: light-dark(#e8f0fe, #1c2944);
    --and-ink: light-dark(#2d64cc, #91b4ff);
    --or: light-dark(#efe8fd, #2b2144);
    --or-ink: light-dark(#7041d4, #c4a8ff);
    --match: light-dark(#fcf1db, #382b13);
    --match-ink: light-dark(#94610f, #f2c472);
    --otherwise: light-dark(#e2f5e7, #13301e);
    --otherwise-ink: light-dark(#22834a, #7fd9a1);
    --switch-off: light-dark(#d6d6db, #45454c);
    --green: light-dark(#e1f4eb, #143024);
    --green-ink: light-dark(#178a5f, #6fd6a8);
    --teal: light-dark(#ddf2f0, #10302d);
    --teal-ink: light-dark(#11806f, #6bd3c4);
    --orange: light-dark(#fdebdb, #3a2414);
    --orange-ink: light-dark(#c25e1c, #f3a26a);
    --grey: light-dark(#efeff1, #2c2c31);
    --grey-ink: light-dark(#3a3a3d, #d0d0d5);
    --violet: light-dark(#eee8fd, #29203f);
    --violet-ink: light-dark(#6c45d3, #bda4ff);
    --amber: light-dark(#fcefd5, #3a2c12);
    --amber-ink: light-dark(#b97a0d, #f1c26a);
    --blue: light-dark(#e7effd, #1b2843);
    --blue-ink: light-dark(#3a6dd4, #93b4ff);
    --sky: light-dark(#e3f0fb, #142a3c);
    --sky-ink: light-dark(#2a7fc0, #84c2f2);
    --red: light-dark(#fde5e4, #3d1717);
    --red-ink: light-dark(#cf3a36, #ff8f8a);
  }
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.editor {
  position: relative;
  max-width: 720px;
  margin: 0 auto;
  padding: 36px 36px 40px calc(30px + var(--gutter));
}

/* The rule's name, where it applies, and its switch. */
.header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
}
.title {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  line-height: 20px;
  letter-spacing: -0.01em;
}
.meta {
  display: flex;
  flex-wrap: wrap;
  margin: 4px 0 0;
  color: var(--muted);
  line-height: 18px;
}
.dot {
  display: inline-block;
  width: 3px;
  height: 3px;
  margin: 0 8px;
  border-radius: 50%;
  background: currentColor;
  vertical-align: middle;
  opacity: 0.7;
}
.toggle {
  display: flex;
  flex: none;
  align-items: center;
  gap: 10px;
  margin-top: 2px;
  cursor: pointer;
}
.toggleLabel {
  color: var(--soft);
}
.switch {
  position: relative;
  width: 36px;
  height: 20px;
  padding: 0;
  border: 0;
  border-radius: 10px;
  background: var(--switch-off);
  cursor: pointer;
  transition: background-color 200ms ease;
}
.switch::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--knob);
  box-shadow: 0 1px 2px rgb(0 0 0 / 0.2);
  transition: translate 220ms cubic-bezier(0.3, 1.4, 0.5, 1);
}
.switch[aria-checked='true'] {
  background: var(--switch-on);
}
.switch[aria-checked='true']::after {
  translate: 16px 0;
}

/* Switched off, the rule reads as resting, still editable. */
.body {
  transition:
    opacity 200ms ease,
    filter 200ms ease;
}
.editor[data-enabled='false'] .body {
  opacity: 0.55;
  filter: saturate(0.3);
}

.section {
  position: relative;
}
.section:has([data-open]) {
  z-index: 5;
}
.sectionLabel {
  margin: 30px 0 12px;
  color: var(--soft);
  font-size: 12px;
  font-weight: 500;
  line-height: 16px;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

/* What the agent wants to do. */
.triggerRow {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 10px;
  min-height: 44px;
  padding: 7px 12px;
  border-radius: 12px;
  background: var(--row);
}
.triggerGlyph {
  flex: none;
  width: 15px;
  height: 15px;
  color: var(--muted);
}

/* A list of rows, its bracket and its join in the gutter at its left. */
.list {
  position: relative;
  margin-top: 8px;
}
.rows {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.bracket {
  position: absolute;
  top: var(--from, 22px);
  left: calc(6px - var(--gutter));
  width: calc(var(--gutter) - 6px);
  height: calc(var(--to, 22px) - var(--from, 22px));
  border: 1.5px solid var(--line);
  border-right: 0;
  border-radius: 9px 0 0 9px;
  pointer-events: none;
  transition:
    top var(--slide),
    height var(--slide);
}
.pill {
  position: absolute;
  z-index: 1;
  top: calc((var(--from, 22px) + var(--to, 22px)) / 2);
  left: calc(6px - var(--gutter));
  display: inline-flex;
  align-items: center;
  height: 22px;
  padding: 0 8px;
  border: 0;
  border-radius: 11px;
  background: var(--and);
  color: var(--and-ink);
  font: inherit;
  font-size: 12px;
  font-weight: 600;
  line-height: 1;
  translate: -50% -50%;
  transition:
    top var(--slide),
    background-color 180ms ease,
    color 180ms ease;
}
.pill[data-join='or'] {
  background: var(--or);
  color: var(--or-ink);
}
button.pill {
  cursor: pointer;
}
button.pill:hover {
  filter: brightness(0.97);
  box-shadow: 0 0 0 1px currentColor inset;
}
button.pill:active {
  scale: 0.96;
}

/* One condition or action. */
.row {
  display: flex;
  align-items: flex-start;
  gap: 4px;
  min-height: 44px;
  padding: 7px 7px 7px 4px;
  border-radius: 12px;
  background: var(--row);
  transition:
    box-shadow 200ms ease,
    background-color 200ms ease,
    scale 200ms ease;
}
.row:has([data-open]) {
  position: relative;
  z-index: 5;
}
.row[data-lifted] {
  position: relative;
  z-index: 6;
  background: var(--chip);
  box-shadow:
    0 0 0 1px var(--chip-edge),
    0 10px 28px var(--lift);
  scale: 1.012;
}
.editor[data-dragging],
.editor[data-dragging] * {
  cursor: grabbing !important;
  user-select: none;
}
.handleSlot {
  display: flex;
  flex: none;
}
.handle {
  display: grid;
  place-items: center;
  width: 22px;
  height: 30px;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--grip);
  cursor: grab;
  touch-action: none;
}
.handle:hover,
.handle[aria-expanded='true'] {
  background: var(--row-active);
  color: var(--soft);
}
.handle svg {
  width: 14px;
  height: 14px;
}
.rowBody {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px 8px;
  min-width: 0;
}
.verb {
  color: var(--soft);
  white-space: nowrap;
}

/* A chip that opens a list. */
.chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 30px;
  max-width: 100%;
  padding: 0 8px 0 10px;
  border: 0;
  border-radius: 9px;
  background: var(--chip);
  box-shadow:
    0 0 0 1px var(--chip-edge),
    0 1px 2px var(--chip-shadow);
  color: var(--chip-ink);
  font: inherit;
  font-weight: 500;
  white-space: nowrap;
  cursor: pointer;
  transition: box-shadow 150ms ease;
}
.chip:hover,
.chip[aria-expanded='true'] {
  box-shadow:
    0 0 0 1px var(--line),
    0 1px 3px var(--chip-shadow);
}
.chip:has(.tile) {
  padding-left: 5px;
}
.strong {
  color: var(--ink);
  font-weight: 560;
}
.chevron {
  flex: none;
  width: 12px;
  height: 12px;
  margin-left: 1px;
  color: var(--muted);
  transition: rotate 180ms ease;
}
[aria-expanded='true'] > .chevron {
  rotate: 180deg;
}
.inline {
  flex: none;
  width: 14px;
  height: 14px;
  color: var(--soft);
}
.mono {
  font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
  font-size: 12px;
  font-weight: 500;
}

.tile {
  display: grid;
  flex: none;
  place-items: center;
  width: 20px;
  height: 20px;
  border-radius: 6px;
}
.tile svg {
  width: 13px;
  height: 13px;
}
.root [data-tint='green'] {
  background: var(--green);
  color: var(--green-ink);
}
.root [data-tint='teal'] {
  background: var(--teal);
  color: var(--teal-ink);
}
.root [data-tint='orange'] {
  background: var(--orange);
  color: var(--orange-ink);
}
.root [data-tint='grey'] {
  background: var(--grey);
  color: var(--grey-ink);
}
.root [data-tint='violet'] {
  background: var(--violet);
  color: var(--violet-ink);
}
.root [data-tint='amber'] {
  background: var(--amber);
  color: var(--amber-ink);
}
.root [data-tint='blue'] {
  background: var(--blue);
  color: var(--blue-ink);
}
.root [data-tint='sky'] {
  background: var(--sky);
  color: var(--sky-ink);
}
.root [data-tint='red'] {
  background: var(--red);
  color: var(--red-ink);
}

/* A list field's values. */
.tokens {
  display: inline-flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 3px;
  min-height: 30px;
  max-width: 100%;
  padding: 3px;
  border-radius: 9px;
  background: var(--chip);
  box-shadow:
    0 0 0 1px var(--chip-edge),
    0 1px 2px var(--chip-shadow);
}
.token {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  height: 24px;
  padding: 0 2px 0 8px;
  border-radius: 6px;
  white-space: nowrap;
}
.tokenRemove,
.tokenAdd {
  display: grid;
  place-items: center;
  width: 20px;
  height: 20px;
  padding: 0;
  border: 0;
  border-radius: 5px;
  background: none;
  color: inherit;
  cursor: pointer;
  opacity: 0.65;
}
.tokenRemove:hover,
.tokenAdd:hover {
  opacity: 1;
  background: rgb(127 127 127 / 0.14);
}
.tokenRemove svg {
  width: 11px;
  height: 11px;
}
.tokenAdd {
  width: 24px;
  height: 24px;
  color: var(--soft);
}
.tokenAdd svg {
  width: 13px;
  height: 13px;
}
.tokenInput {
  height: 24px;
  min-width: 0;
  max-width: 100%;
  padding: 0 6px;
  border: 0;
  border-radius: 6px;
  outline: 0;
  background: var(--row);
  color: var(--ink);
  font: inherit;
}
.tokenInput:focus-visible {
  box-shadow: 0 0 0 2px var(--focus);
}

/* The delete button at a row's end: on hover and focus, always on a touch screen. */
.remove {
  display: grid;
  flex: none;
  place-items: center;
  width: 28px;
  height: 30px;
  margin-left: auto;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--muted);
  cursor: pointer;
  opacity: 0;
  transition: opacity 150ms ease;
}
.remove svg {
  width: 14px;
  height: 14px;
}
.remove:hover {
  background: var(--row-active);
  color: var(--red-ink);
}
.row:hover > .remove,
.row:focus-within > .remove,
.groupHead:hover > .remove,
.remove:focus-visible {
  opacity: 1;
}
@media (hover: none) {
  .remove {
    opacity: 1;
  }
}

/* A group: a card of rows with its own bracket, joined to the rest as one item. */
.group {
  --gutter: 26px;
  padding: 12px 10px 10px 14px;
  border-radius: 14px;
  background: var(--group);
  box-shadow:
    0 0 0 1px var(--group-edge),
    0 1px 3px var(--group-shadow),
    0 6px 18px var(--group-shadow);
}
.group:has([data-open]) {
  position: relative;
  z-index: 5;
}
.groupHead {
  display: flex;
  align-items: center;
  height: 20px;
  margin-bottom: 10px;
}
.groupName {
  font-weight: 500;
}
.groupCount {
  color: var(--muted);
}
.groupRemove {
  height: 26px;
}
.group > .list {
  margin-left: var(--gutter);
}
.group > .addBar {
  margin-left: var(--gutter);
}
.empty {
  margin: 0;
  padding: 12px;
  border: 1.5px dashed var(--line);
  border-radius: 12px;
  color: var(--muted);
}

/* Add rule, Add group, Add condition, Add action. */
.addBar {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 10px;
}
.addButton {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 30px;
  padding: 0 10px 0 8px;
  border: 0;
  border-radius: 9px;
  background: var(--surface);
  box-shadow:
    0 0 0 1px var(--chip-edge),
    0 1px 2px var(--chip-shadow);
  color: var(--chip-ink);
  font: inherit;
  font-weight: 500;
  cursor: pointer;
}
.group .addButton {
  background: var(--group);
}
.addButton:hover {
  box-shadow:
    0 0 0 1px var(--line),
    0 1px 3px var(--chip-shadow);
}
.addButton svg {
  width: 14px;
  height: 14px;
  color: var(--soft);
}

/* When it matches, Otherwise. */
.badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 24px;
  margin: 0;
  padding: 0 9px 0 7px;
  border-radius: 12px;
  font-weight: 500;
}
.badge svg {
  width: 13px;
  height: 13px;
}
.badge[data-tone='match'] {
  background: var(--match);
  color: var(--match-ink);
}
.badge[data-tone='otherwise'] {
  margin-top: 22px;
  background: var(--otherwise);
  color: var(--otherwise-ink);
}
.badge + .list {
  margin-top: 12px;
}
[data-flip='otherwise:head'] + .list {
  margin-top: 12px;
}

/* The popups: a listbox or a menu under its chip. */
.popupAnchor {
  position: relative;
  display: inline-flex;
  max-width: 100%;
}
.popupAnchor[data-open] {
  z-index: 10;
}
.popup {
  position: absolute;
  z-index: 10;
  top: calc(100% + 6px);
  left: 0;
  display: flex;
  flex-direction: column;
  gap: 1px;
  min-width: max(100%, 170px);
  padding: 4px;
  border-radius: 12px;
  background: var(--chip);
  box-shadow:
    0 0 0 1px var(--chip-edge),
    0 12px 32px var(--popup-shadow);
  outline: 0;
  transform-origin: top left;
  animation: pop 140ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.popup[data-up] {
  top: auto;
  bottom: calc(100% + 6px);
  transform-origin: bottom left;
}
@keyframes pop {
  from {
    opacity: 0;
    scale: 0.96;
  }
}
.option {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 32px;
  padding: 0 8px;
  border-radius: 8px;
  color: var(--ink);
  white-space: nowrap;
  cursor: pointer;
  outline: 0;
}
.option[data-active] {
  background: var(--row-active);
}
.option:focus-visible {
  box-shadow: inset 0 0 0 2px var(--focus);
}
.option[aria-disabled] {
  color: var(--muted);
  cursor: default;
}
.option[aria-disabled][data-active] {
  background: none;
}
.optionLabel {
  flex: 1;
}
.optionCheck,
.optionGlyph {
  flex: none;
  width: 14px;
  height: 14px;
}
.optionCheck {
  margin-left: 12px;
  color: var(--ink);
}
.optionGlyph {
  color: var(--soft);
}

/* A phone: a narrower gutter and margins, chips wrap inside their rows. */
@container (max-width: 520px) {
  .root {
    --gutter: 22px;
  }
  .editor {
    padding: 20px 10px 24px calc(8px + var(--gutter));
  }
  /* The meta line's parts stack, without their dots. */
  .meta {
    flex-direction: column;
  }
  .meta .dot {
    display: none;
  }
  .group {
    --gutter: 24px;
    padding: 12px 6px 8px 8px;
  }
  .row {
    padding-right: 4px;
  }
  .sectionLabel {
    margin-top: 24px;
  }
}

/* The demo pointer, over everything; one of its glyphs shows at a time. */
.pointer {
  width: 22px;
  height: 22px;
  z-index: 20 !important;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

.hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  .bracket,
  .pill,
  .switch,
  .switch::after,
  .row,
  .chevron,
  .body {
    transition: none;
  }
  .popup {
    animation: none;
  }
}
```

### agent-rules/rule.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The rule an agent policy is made of, as plain data, and the pure edits on it: what the agent
 * wants to do (the trigger), the conditions that must hold (rows, and groups of rows, each list
 * joined by And or Or), and the actions taken when it matches and when it doesn't.
 *
 * Nothing here knows about the DOM. The editor (agent-rules.tsx) draws a Rule and hands every
 * change back as a new Rule, so the moves a drag makes and the moves the keyboard makes are the
 * same function: `place`.
 */

export type Join = 'and' | 'or';

export type FieldId = 'command' | 'branch' | 'files' | 'repository' | 'agent';

/** One test on what the agent is about to do: `Command is Any of git push, rm -rf`. */
export type Condition = {
  kind: 'condition';
  id: string;
  field: FieldId;
  /** The operator: `Any of`, `Equal to`… one of its field's operators. */
  op: string;
  /** Tokens for a list field, one value for the others. */
  values: string[];
};

/** Conditions joined among themselves, then with the rest as one item. One level deep. */
export type Group = { kind: 'group'; id: string; join: Join; items: Condition[] };

export type Item = Condition | Group;

export type ActionId = 'approve' | 'notify' | 'expire' | 'allow' | 'block' | 'log';

export type Action = { kind: 'action'; id: string; type: ActionId; value: string };

export type Rule = {
  trigger: string;
  join: Join;
  items: Item[];
  match: Action[];
  otherwise: Action[];
};

/** What a field looks like and offers. `tokens` fields take a free list, the rest one value. */
export type FieldSpec = {
  label: string;
  /** The word between the field and its operator: `is`, `include`. */
  verb: string;
  ops: string[];
  tokens: boolean;
  /** The values a single-value field offers, or the tokens a new list row starts with. */
  values: string[];
  /** The field's tint, a key of the stylesheet's icon colours. */
  tint: 'green' | 'teal' | 'orange' | 'grey' | 'violet';
  /** Values set in code type (mono), like commands and paths. */
  mono: boolean;
};

export const FIELDS: Record<FieldId, FieldSpec> = {
  command: {
    label: 'Command',
    verb: 'is',
    ops: ['Any of', 'None of'],
    tokens: true,
    values: ['git push'],
    tint: 'green',
    mono: true,
  },
  branch: {
    label: 'Branch',
    verb: 'is',
    ops: ['Equal to', 'Not equal to', 'Matching'],
    tokens: false,
    values: ['main', 'develop', 'release/*'],
    tint: 'teal',
    mono: true,
  },
  files: {
    label: 'Files changed',
    verb: 'include',
    ops: ['Any of', 'All of'],
    tokens: true,
    values: ['migrations/*'],
    tint: 'orange',
    mono: true,
  },
  repository: {
    label: 'Repository',
    verb: 'is',
    ops: ['Equal to', 'Not equal to'],
    tokens: false,
    values: ['acme/payments', 'acme/web', 'acme/infra'],
    tint: 'grey',
    mono: false,
  },
  agent: {
    label: 'Agent',
    verb: 'is',
    ops: ['Equal to', 'Not equal to'],
    tokens: false,
    values: ['Builder', 'Reviewer', 'Release helper'],
    tint: 'violet',
    mono: false,
  },
};

export const FIELD_ORDER: FieldId[] = ['command', 'branch', 'files', 'repository', 'agent'];

export const TRIGGERS = [
  'Run a command',
  'Call an external API',
  'Edit files',
  'Open a pull request',
];

export type ActionSpec = {
  label: string;
  /** The word before the value, if any: `from`. */
  verb?: string;
  values: string[];
  tint: 'amber' | 'blue' | 'sky' | 'green' | 'red' | 'grey';
  /** The value is a channel, drawn with a hash. */
  channel?: boolean;
};

export const ACTIONS: Record<ActionId, ActionSpec> = {
  approve: {
    label: 'Ask for approval',
    verb: 'from',
    values: ['Code owners', 'Team leads', 'On-call'],
    tint: 'amber',
  },
  notify: {
    label: 'Notify',
    values: ['deploys', 'security', 'on-call'],
    tint: 'blue',
    channel: true,
  },
  expire: { label: 'Expire after', values: ['10 minutes', '30 minutes', '1 hour'], tint: 'sky' },
  allow: { label: 'Allow', values: ['Without asking', 'With a note'], tint: 'green' },
  block: { label: 'Block', values: ['And stop the run', 'And keep going'], tint: 'red' },
  log: { label: 'Log to', values: ['Audit trail', 'Run history'], tint: 'grey' },
};

export const ACTION_ORDER: ActionId[] = ['approve', 'notify', 'expire', 'allow', 'block', 'log'];

let counter = 0;
/** A fresh id for a new row: unique within the page, stable across renders. */
export const uid = (prefix: string) => `new-${prefix}${(counter += 1).toString(36)}`;

export const condition = (field: FieldId, op?: string, values?: string[]): Condition => ({
  kind: 'condition',
  id: uid('c'),
  field,
  op: op ?? FIELDS[field].ops[0],
  values: values ?? [FIELDS[field].values[0]],
});

export const action = (type: ActionId, value?: string): Action => ({
  kind: 'action',
  id: uid('a'),
  type,
  value: value ?? ACTIONS[type].values[0],
});

/** The rule the editor opens on: risky commands need an owner's approval. */
export function defaultRule(): Rule {
  return {
    trigger: 'Run a command',
    join: 'and',
    items: [
      condition('command', 'Any of', ['git push', 'npm publish', 'rm -rf']),
      {
        kind: 'group',
        id: uid('g'),
        join: 'or',
        items: [
          condition('branch', 'Equal to', ['main']),
          condition('files', 'Any of', ['migrations/*']),
        ],
      },
    ],
    match: [
      action('approve', 'Code owners'),
      action('notify', 'deploys'),
      action('expire', '30 minutes'),
    ],
    otherwise: [action('allow', 'Without asking'), action('log', 'Audit trail')],
  };
}

/**
 * The rule with ids from its rows' places (`i0`, `i1.0`, `m2`): the same on the server and in the
 * browser, so the markup hydrates whatever ids the rule was built with. New rows get `uid`s.
 */
export function settle(rule: Rule): Rule {
  return {
    ...rule,
    items: rule.items.map((item, i) =>
      item.kind === 'condition'
        ? { ...item, id: `i${i}` }
        : { ...item, id: `i${i}`, items: item.items.map((c, j) => ({ ...c, id: `i${i}.${j}` })) },
    ),
    match: rule.match.map((a, i) => ({ ...a, id: `m${i}` })),
    otherwise: rule.otherwise.map((a, i) => ({ ...a, id: `o${i}` })),
  };
}

/** Where a row sits: `root`, a group's id, `match` or `otherwise`, and its index there. */
export type Slot = { list: string; index: number };

/** The row's slot, or null. */
export function find(rule: Rule, id: string): Slot | null {
  const lists: [string, { id: string }[]][] = [
    ['root', rule.items],
    ['match', rule.match],
    ['otherwise', rule.otherwise],
  ];
  for (const item of rule.items) if (item.kind === 'group') lists.push([item.id, item.items]);
  for (const [list, items] of lists) {
    const index = items.findIndex((item) => item.id === id);
    if (index >= 0) return { list, index };
  }
  return null;
}

/** Every slot a condition could move to, in reading order, once it is taken out of the rule. */
export function conditionSlots(items: Item[]): Slot[] {
  const slots: Slot[] = [{ list: 'root', index: 0 }];
  items.forEach((item, index) => {
    if (item.kind === 'group') {
      for (let i = 0; i <= item.items.length; i += 1) slots.push({ list: item.id, index: i });
    }
    slots.push({ list: 'root', index: index + 1 });
  });
  return slots;
}

/** The rule with the row `id` taken out, and the row. */
function take(rule: Rule, id: string): [Rule, Condition | Action | null] {
  let taken: Condition | Action | null = null;
  const pick = <T extends { id: string }>(items: T[]) =>
    items.filter((item) => {
      if (item.id !== id) return true;
      taken = item as unknown as Condition | Action;
      return false;
    });
  const items = pick(rule.items).map((item) =>
    item.kind === 'group' ? { ...item, items: pick(item.items) } : item,
  );
  return [{ ...rule, items, match: pick(rule.match), otherwise: pick(rule.otherwise) }, taken];
}

const insert = <T>(items: T[], index: number, item: T) => [
  ...items.slice(0, index),
  item,
  ...items.slice(index),
];

/** The rule with the row `id` moved to `slot` (a slot counted with the row taken out). */
export function place(rule: Rule, id: string, slot: Slot): Rule {
  const [rest, row] = take(rule, id);
  if (!row) return rule;
  if (row.kind === 'action') {
    if (slot.list !== 'match' && slot.list !== 'otherwise') return rule;
    return { ...rest, [slot.list]: insert(rest[slot.list], slot.index, row) };
  }
  if (slot.list === 'root') return { ...rest, items: insert(rest.items, slot.index, row as Item) };
  return {
    ...rest,
    items: rest.items.map((item) =>
      item.kind === 'group' && item.id === slot.list
        ? { ...item, items: insert(item.items, slot.index, row) }
        : item,
    ),
  };
}

/**
 * Where the keyboard moves a row one step up (-1) or down (1), or null at an end: conditions step
 * through every slot, into and out of groups; actions only within their own list.
 */
export function step(rule: Rule, id: string, by: -1 | 1): Slot | null {
  const at = find(rule, id);
  if (!at) return null;
  if (at.list === 'match' || at.list === 'otherwise') {
    const index = at.index + by;
    return index < 0 || index >= rule[at.list].length ? null : { list: at.list, index };
  }
  const [rest] = take(rule, id);
  const slots = conditionSlots(rest.items);
  const here = slots.findIndex((slot) => slot.list === at.list && slot.index === at.index);
  return slots[here + by] ?? null;
}

/** The rule with `fn` applied to the condition `id`. */
export function editCondition(rule: Rule, id: string, fn: (c: Condition) => Condition): Rule {
  const edit = (item: Item): Item =>
    item.kind === 'condition'
      ? item.id === id
        ? fn(item)
        : item
      : { ...item, items: item.items.map((c) => (c.id === id ? fn(c) : c)) };
  return { ...rule, items: rule.items.map(edit) };
}

/** The rule with `fn` applied to the action `id`. */
export function editAction(rule: Rule, id: string, fn: (a: Action) => Action): Rule {
  const edit = (a: Action) => (a.id === id ? fn(a) : a);
  return { ...rule, match: rule.match.map(edit), otherwise: rule.otherwise.map(edit) };
}

/** The rule without the row or group `id`. */
export function remove(rule: Rule, id: string): Rule {
  const items = rule.items.filter((item) => item.id !== id);
  return take({ ...rule, items }, id)[0];
}

/** A short name for a row, for the live region and the handles: `Command`, `Notify`. */
export function rowName(row: Condition | Action) {
  return row.kind === 'condition' ? FIELDS[row.field].label : ACTIONS[row.type].label;
}

/** A list's name for the live region: `the rule`, `the group`, `When it matches`. */
export function listName(list: string) {
  if (list === 'root') return 'the rule';
  if (list === 'match') return 'When it matches';
  if (list === 'otherwise') return 'Otherwise';
  return 'the group';
}
```

### agent-rules/rows.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
} from 'react';
import { Glyph, type GlyphName } from './glyphs';
import {
  ACTION_ORDER,
  ACTIONS,
  FIELD_ORDER,
  FIELDS,
  type Action,
  type ActionId,
  type Condition,
  type FieldId,
} from './rule';
import { Popup, type Choice } from './select';
import styles from './agent-rules.module.css';

/*
 * One row of the rule: a condition (field, verb, operator, value or tokens) or an action (what,
 * and with what). Each starts with its handle, a button you drag the row by; pressed without a
 * drag, it opens a menu of the same moves for the keyboard and touch. The row's delete button
 * shows on hover and focus, always on a touch screen.
 */

const FIELD_GLYPH: Record<FieldId, GlyphName> = {
  command: 'terminal',
  branch: 'branch',
  files: 'file',
  repository: 'repo',
  agent: 'agent',
};

const ACTION_GLYPH: Record<ActionId, GlyphName> = {
  approve: 'people',
  notify: 'bell',
  expire: 'clock',
  allow: 'shield',
  block: 'stop',
  log: 'log',
};

/** The tinted square an icon sits in, in its field's or action's colour. */
export const Tile = ({ glyph, tint }: { glyph: GlyphName; tint: string }) => (
  <span className={styles.tile} data-tint={tint}>
    <Glyph name={glyph} />
  </span>
);

const FIELD_CHOICES: Choice[] = FIELD_ORDER.map((field) => ({
  value: field,
  label: FIELDS[field].label,
  icon: <Tile glyph={FIELD_GLYPH[field]} tint={FIELDS[field].tint} />,
}));

const ACTION_CHOICES: Choice[] = ACTION_ORDER.map((type) => ({
  value: type,
  label: ACTIONS[type].label,
  icon: <Tile glyph={ACTION_GLYPH[type]} tint={ACTIONS[type].tint} />,
}));

export { ACTION_CHOICES };

const plain = (values: string[]): Choice[] => values.map((value) => ({ value, label: value }));

/** What the row's handle offers: moves, and delete. */
export type Move = { id: string; label: string; glyph: GlyphName; disabled?: boolean };

type Shared = {
  moves: Move[];
  onMove: (move: string) => void;
  /** A press on the handle, which may become a drag. */
  onGrab: (event: ReactPointerEvent<HTMLElement>) => void;
  onKeyMove: (event: ReactKeyboardEvent) => void;
  lifted: boolean;
};

function Row({
  name,
  moves,
  onMove,
  onGrab,
  onKeyMove,
  lifted,
  part,
  id,
  children,
}: Shared & { name: string; part: string; id: string; children: ReactNode }) {
  return (
    // The row only listens for Alt and an arrow from the controls inside it, to move it.
    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
    <li
      className={styles.row}
      data-flip={id}
      data-part={part}
      data-row={id}
      data-lifted={lifted || undefined}
      onKeyDown={onKeyMove}
    >
      <span className={styles.handleSlot} onPointerDown={onGrab}>
        <Popup
          label={`Move ${name}`}
          role="menu"
          plain
          part="handle"
          triggerClass={styles.handle}
          triggerLabel={`Move ${name}. Alt and an arrow key moves it too.`}
          trigger={<Glyph name="grip" />}
          choices={moves.map((move) => ({
            value: move.id,
            label: move.label,
            disabled: move.disabled,
            icon: <Glyph name={move.glyph} className={styles.optionGlyph} />,
          }))}
          onPick={onMove}
        />
      </span>
      <div className={styles.rowBody}>{children}</div>
      <button
        type="button"
        className={styles.remove}
        aria-label={`Delete ${name}`}
        onClick={() => onMove('delete')}
      >
        <Glyph name="trash" />
      </button>
    </li>
  );
}

export function ConditionRow({
  condition,
  onChange,
  ...shared
}: Shared & { condition: Condition; onChange: (next: Condition) => void }) {
  const spec = FIELDS[condition.field];
  const name = `${spec.label} condition`;
  return (
    <Row {...shared} name={name} part="condition" id={condition.id}>
      <Popup
        label="Field"
        role="listbox"
        part="field"
        value={condition.field}
        choices={FIELD_CHOICES}
        triggerLabel={`Field: ${spec.label}`}
        trigger={
          <>
            <Tile glyph={FIELD_GLYPH[condition.field]} tint={spec.tint} />
            {spec.label}
          </>
        }
        onPick={(field) =>
          onChange({
            ...condition,
            field: field as FieldId,
            op: FIELDS[field as FieldId].ops[0],
            values: [FIELDS[field as FieldId].values[0]],
          })
        }
      />
      <span className={styles.verb}>{spec.verb}</span>
      <Popup
        label="Operator"
        role="listbox"
        part="operator"
        value={condition.op}
        choices={plain(spec.ops)}
        triggerLabel={`Operator: ${condition.op}`}
        trigger={condition.op}
        onPick={(op) => onChange({ ...condition, op })}
      />
      {spec.tokens ? (
        <Tokens
          values={condition.values}
          mono={spec.mono}
          tint={spec.tint}
          noun={spec.label === 'Command' ? 'command' : 'path'}
          onChange={(values) => onChange({ ...condition, values })}
        />
      ) : (
        <Popup
          label="Value"
          role="listbox"
          part="value"
          value={condition.values[0]}
          choices={plain(spec.values).map((choice) =>
            condition.field === 'repository'
              ? { ...choice, icon: <Glyph name="repo" className={styles.optionGlyph} /> }
              : choice,
          )}
          triggerClass={`${styles.chip} ${styles.strong}`}
          triggerLabel={`Value: ${condition.values[0]}`}
          trigger={
            <>
              {condition.field === 'repository' && <Glyph name="repo" className={styles.inline} />}
              <span className={spec.mono ? styles.mono : undefined}>{condition.values[0]}</span>
            </>
          }
          onPick={(value) => onChange({ ...condition, values: [value] })}
        />
      )}
    </Row>
  );
}

export function ActionRow({
  action,
  onChange,
  ...shared
}: Shared & { action: Action; onChange: (next: Action) => void }) {
  const spec = ACTIONS[action.type];
  const shown = (value: string) => (spec.channel ? `#${value}` : value);
  return (
    <Row {...shared} name={`${spec.label} action`} part="action" id={action.id}>
      <Popup
        label="Action"
        role="listbox"
        part="action-type"
        value={action.type}
        choices={ACTION_CHOICES}
        triggerLabel={`Action: ${spec.label}`}
        trigger={
          <>
            <Tile glyph={ACTION_GLYPH[action.type]} tint={spec.tint} />
            {spec.label}
          </>
        }
        onPick={(type) =>
          onChange({
            ...action,
            type: type as ActionId,
            value: ACTIONS[type as ActionId].values[0],
          })
        }
      />
      {spec.verb && <span className={styles.verb}>{spec.verb}</span>}
      <Popup
        label={spec.label}
        role="listbox"
        part="action-value"
        value={action.value}
        choices={spec.values.map((value) => ({
          value,
          label: shown(value),
          icon: spec.channel ? <Glyph name="hash" className={styles.optionGlyph} /> : undefined,
        }))}
        triggerClass={`${styles.chip} ${styles.strong}`}
        triggerLabel={`${spec.label}: ${shown(action.value)}`}
        trigger={
          <>
            {spec.channel && <Glyph name="hash" className={styles.inline} />}
            {spec.channel ? action.value : shown(action.value)}
          </>
        }
        onPick={(value) => onChange({ ...action, value })}
      />
    </Row>
  );
}

/** A list field's values: chips you remove with their ×, and a + that opens a field for one more. */
function Tokens({
  values,
  mono,
  tint,
  noun,
  onChange,
}: {
  values: string[];
  mono: boolean;
  tint: string;
  noun: string;
  onChange: (values: string[]) => void;
}) {
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState('');
  const plus = useRef<HTMLButtonElement>(null);
  const box = useRef<HTMLSpanElement>(null);

  const commit = (keepOpen: boolean) => {
    const value = draft.trim();
    if (value && !values.includes(value)) onChange([...values, value]);
    setDraft('');
    if (!keepOpen) {
      setAdding(false);
      requestAnimationFrame(() => plus.current?.focus({ preventScroll: true }));
    }
  };

  const drop = (index: number) => {
    onChange(values.filter((_, i) => i !== index));
    // The focus goes to the next chip's ×, or to the +.
    requestAnimationFrame(() => {
      const buttons = box.current?.querySelectorAll<HTMLElement>('[data-part="token-remove"]');
      (buttons?.[Math.min(index, (buttons?.length ?? 1) - 1)] ?? plus.current)?.focus({
        preventScroll: true,
      });
    });
  };

  return (
    <span ref={box} className={styles.tokens} data-part="tokens" role="group" aria-label="Values">
      {values.map((value, index) => (
        <span key={value} className={styles.token} data-tint={tint} data-part="token">
          <span className={mono ? styles.mono : undefined}>{value}</span>
          <button
            type="button"
            className={styles.tokenRemove}
            data-part="token-remove"
            aria-label={`Remove ${value}`}
            onClick={() => drop(index)}
          >
            <Glyph name="x" />
          </button>
        </span>
      ))}
      {adding ? (
        <input
          className={`${styles.tokenInput} ${mono ? styles.mono : ''}`}
          aria-label={`Add a ${noun}`}
          ref={(input) => input?.focus({ preventScroll: true })}
          value={draft}
          size={Math.max(6, draft.length + 1)}
          onChange={(event) => setDraft(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              event.preventDefault();
              commit(true);
            } else if (event.key === 'Escape') {
              event.preventDefault();
              event.stopPropagation();
              setDraft('');
              setAdding(false);
              requestAnimationFrame(() => plus.current?.focus({ preventScroll: true }));
            } else if (event.key === 'Backspace' && !draft && values.length) {
              onChange(values.slice(0, -1));
            }
          }}
          onBlur={() => commit(false)}
        />
      ) : (
        <button
          ref={plus}
          type="button"
          className={styles.tokenAdd}
          aria-label={`Add a ${noun}`}
          onClick={() => setAdding(true)}
        >
          <Glyph name="plus" />
        </button>
      )}
    </span>
  );
}
```

### agent-rules/select.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  createContext,
  useContext,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type MouseEvent as ReactMouseEvent,
  type ReactNode,
  type RefObject,
} from 'react';
import { Glyph } from './glyphs';
import styles from './agent-rules.module.css';

/*
 * Every chip that opens a list: a button and its popup, a listbox when it picks a value (Command,
 * Any of, Code owners), a menu when it runs a command (Add action, a row's handle). The popup hangs
 * under its button inside the editor, shifted left when it would pass the editor's right edge and
 * flipped above when there is no room below, in the editor's own px (a gallery card scales the
 * whole editor). Arrows, Home, End and the first letter move between items; Enter or Space picks;
 * Escape closes and hands the focus back; Tab or a press elsewhere closes.
 */

export type Choice = { value: string; label: string; icon?: ReactNode; disabled?: boolean };

/**
 * True while the demo drives the editor: its clicks open popups without pulling the reader's
 * focus into them.
 */
export const DemoDriving = createContext<RefObject<boolean> | null>(null);

export function Popup({
  label,
  role,
  choices,
  value,
  onPick,
  trigger,
  triggerClass,
  triggerLabel,
  part,
  plain,
}: {
  /** The popup's name: `Field`, `Operator`. */
  label: string;
  role: 'listbox' | 'menu';
  choices: Choice[];
  /** The chosen value, for a listbox. */
  value?: string;
  onPick: (value: string) => void;
  /** What the button shows. */
  trigger: ReactNode;
  triggerClass?: string;
  /** The button's accessible name, when its text isn't enough: `Field: Command`. */
  triggerLabel?: string;
  part?: string;
  /** No chevron. */
  plain?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const [shift, setShift] = useState({ x: 0, up: false });
  const button = useRef<HTMLButtonElement>(null);
  const list = useRef<HTMLDivElement>(null);
  const focusOnOpen = useRef(true);
  const driving = useContext(DemoDriving);
  const id = useId();

  const enabled = choices
    .map((choice, index) => (choice.disabled ? -1 : index))
    .filter((i) => i >= 0);
  const chosen = Math.max(
    0,
    choices.findIndex((choice) => choice.value === value),
  );

  const show = (at: number) => {
    focusOnOpen.current = !driving?.current;
    setActive(enabled.includes(at) ? at : (enabled[0] ?? 0));
    setShift({ x: 0, up: false });
    setOpen(true);
  };
  const close = (back: boolean) => {
    setOpen(false);
    if (back) button.current?.focus({ preventScroll: true });
  };

  // Placed once it has a size: kept inside the editor's right edge, above when there's no room.
  useLayoutEffect(() => {
    const popup = list.current;
    const editor = button.current?.closest<HTMLElement>('[data-part="editor"]');
    if (!open || !popup || !editor) return;
    const frame = editor.getBoundingClientRect();
    const scale = frame.width / editor.offsetWidth || 1;
    const box = popup.getBoundingClientRect();
    const anchor = button.current!.getBoundingClientRect();
    const over = (box.right - frame.right) / scale + 8;
    const below = (box.bottom - frame.bottom) / scale + 8;
    const room = (anchor.top - frame.top) / scale - 8;
    setShift({ x: over > 0 ? -over : 0, up: below > 0 && room > box.height / scale });
  }, [open]);

  useLayoutEffect(() => {
    if (!open || !focusOnOpen.current) return;
    list.current
      ?.querySelector<HTMLElement>(`[data-index="${active}"]`)
      ?.focus({ preventScroll: true });
  }, [open, active]);

  // A press anywhere else closes it.
  useEffect(() => {
    if (!open) return;
    const onDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (list.current?.contains(target) || button.current?.contains(target)) return;
      setOpen(false);
    };
    document.addEventListener('pointerdown', onDown, true);
    return () => document.removeEventListener('pointerdown', onDown, true);
  }, [open]);

  const pick = (index: number) => {
    const choice = choices[index];
    if (!choice || choice.disabled) return;
    onPick(choice.value);
    close(focusOnOpen.current);
  };

  const onButtonKey = (event: ReactKeyboardEvent) => {
    // Alt with an arrow moves the row instead (agent-rules.tsx).
    if (event.altKey) return;
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault();
      show(role === 'listbox' ? chosen : event.key === 'ArrowUp' ? enabled.at(-1)! : enabled[0]);
    }
  };

  const onListKey = (event: ReactKeyboardEvent) => {
    const at = enabled.indexOf(active);
    const go = (index: number) => {
      event.preventDefault();
      setActive(enabled[(index + enabled.length) % enabled.length]);
    };
    if (event.key === 'ArrowDown') go(at + 1);
    else if (event.key === 'ArrowUp') go(at - 1);
    else if (event.key === 'Home') go(0);
    else if (event.key === 'End') go(enabled.length - 1);
    else if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      pick(active);
    } else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      close(true);
    } else if (event.key === 'Tab') setOpen(false);
    else if (event.key.length === 1 && /\S/.test(event.key)) {
      // Type-ahead: the next item that starts with the letter.
      const letter = event.key.toLowerCase();
      const next = [...enabled.slice(at + 1), ...enabled.slice(0, at + 1)].find((index) =>
        choices[index].label.toLowerCase().startsWith(letter),
      );
      if (next !== undefined) {
        event.preventDefault();
        setActive(next);
      }
    }
  };

  const onButtonClick = (event: ReactMouseEvent) => {
    event.stopPropagation();
    if (open) close(false);
    else show(role === 'listbox' ? chosen : (enabled[0] ?? 0));
  };

  const item = role === 'listbox' ? 'option' : 'menuitem';
  return (
    <span className={styles.popupAnchor} data-open={open || undefined}>
      <button
        ref={button}
        type="button"
        className={triggerClass ?? styles.chip}
        data-part={part}
        aria-haspopup={role}
        aria-expanded={open}
        aria-controls={open ? id : undefined}
        aria-label={triggerLabel}
        onClick={onButtonClick}
        onKeyDown={onButtonKey}
      >
        {trigger}
        {!plain && <Glyph name="chevron" className={styles.chevron} />}
      </button>
      {open && (
        // A listbox or a menu: the role is the prop's, which the linter can't read.
        // eslint-disable-next-line jsx-a11y/no-static-element-interactions
        <div
          ref={list}
          id={id}
          role={role}
          aria-label={label}
          className={styles.popup}
          data-up={shift.up || undefined}
          style={{ translate: `${shift.x}px 0` }}
          onKeyDown={onListKey}
        >
          {choices.map((choice, index) => {
            const selected = role === 'listbox' && choice.value === value;
            return (
              // An option or a menu item, its keys handled by the list around it.
              // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
              <div
                key={choice.value}
                role={item}
                tabIndex={-1}
                data-index={index}
                data-value={choice.value}
                data-active={index === active || undefined}
                aria-selected={role === 'listbox' ? selected : undefined}
                aria-disabled={choice.disabled || undefined}
                className={styles.option}
                onPointerMove={() => !choice.disabled && setActive(index)}
                onClick={() => pick(index)}
              >
                {choice.icon}
                <span className={styles.optionLabel}>{choice.label}</span>
                {selected && <Glyph name="check" className={styles.optionCheck} />}
              </div>
            );
          })}
        </div>
      )}
    </span>
  );
}
```

### agent-rules/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The editor's icons, drawn here on a 16-unit grid with a 1.4 stroke in currentColor, so each
 * takes the colour of its chip or button. All are decorative: the text next to them names the
 * control.
 */

const PATHS = {
  chevron: <path d="M5 6.5l3 3 3-3" />,
  lock: (
    <>
      <rect x="3.5" y="7" width="9" height="6.5" rx="1.8" />
      <path d="M5.5 7V5.2a2.5 2.5 0 015 0V7M8 9.6v1.4" />
    </>
  ),
  grip: (
    <g fill="currentColor" stroke="none">
      <circle cx="6" cy="4" r="1.1" />
      <circle cx="10" cy="4" r="1.1" />
      <circle cx="6" cy="8" r="1.1" />
      <circle cx="10" cy="8" r="1.1" />
      <circle cx="6" cy="12" r="1.1" />
      <circle cx="10" cy="12" r="1.1" />
    </g>
  ),
  terminal: (
    <>
      <rect x="2" y="3" width="12" height="10" rx="2" />
      <path d="M5 6.5l1.8 1.5L5 9.5M8.5 10h2.5" />
    </>
  ),
  branch: (
    <>
      <circle cx="5" cy="3.8" r="1.5" />
      <circle cx="5" cy="12.2" r="1.5" />
      <circle cx="11" cy="5.2" r="1.5" />
      <path d="M5 5.3v5.4M11 6.7c0 2.6-2.3 3-6 4" />
    </>
  ),
  file: (
    <>
      <path d="M4 2.5h5l3 3v8H4z" />
      <path d="M9 2.5v3h3M6 9h4M6 11h3" />
    </>
  ),
  /* A plain box of code: the repository, with no host's mark. */
  repo: (
    <>
      <path d="M4 3.5A1.5 1.5 0 015.5 2H12v10H5.5A1.5 1.5 0 004 13.5z" />
      <path d="M4 13.5A1.5 1.5 0 005.5 15H12v-3M7 5l-1.3 1.3L7 7.6M9.2 5l1.3 1.3-1.3 1.3" />
    </>
  ),
  agent: (
    <>
      <rect x="3" y="5" width="10" height="8" rx="2.5" />
      <path d="M8 5V3M6.2 8.6v.8M9.8 8.6v.8" />
      <circle cx="8" cy="2.4" r=".6" fill="currentColor" />
    </>
  ),
  people: (
    <>
      <circle cx="6" cy="5.5" r="2.2" />
      <path d="M2 13c.4-2.3 2-3.6 4-3.6s3.6 1.3 4 3.6" />
      <path d="M10.5 3.6a2 2 0 010 3.8M11.6 9.6c1.3.4 2.1 1.6 2.4 3.4" />
    </>
  ),
  bell: (
    <>
      <path d="M4 11V7.3a4 4 0 018 0V11l1 1.3H3z" />
      <path d="M6.7 14a1.4 1.4 0 002.6 0" />
    </>
  ),
  clock: (
    <>
      <circle cx="8" cy="8" r="5.8" />
      <path d="M8 4.8V8l2.2 1.4" />
    </>
  ),
  shield: (
    <>
      <path d="M8 2l5 1.8v4c0 3-2.1 5.2-5 6.2-2.9-1-5-3.2-5-6.2v-4z" />
    </>
  ),
  stop: (
    <>
      <path d="M8 2.5l6 10.5H2z" />
      <path d="M8 6.6v2.8M8 11.2v.2" />
    </>
  ),
  log: (
    <>
      <rect x="3" y="2.5" width="10" height="11" rx="2" />
      <path d="M5.8 6h4.4M5.8 8.5h4.4M5.8 11h2.6" />
    </>
  ),
  hash: <path d="M6.3 2.5l-1.3 11M11 2.5l-1.3 11M3 6h10.5M2.5 10H13" />,
  plus: <path d="M8 3.5v9M3.5 8h9" />,
  x: <path d="M4.5 4.5l7 7M11.5 4.5l-7 7" />,
  trash: (
    <>
      <path d="M3 4.5h10M6.3 4.5V3h3.4v1.5M4.5 4.5l.6 9h5.8l.6-9" />
    </>
  ),
  check: <path d="M3.5 8.4l3 3 6-6.8" />,
  /* A row branching off a line: add a condition, or a rule. */
  addRow: (
    <>
      <path d="M4 2.5v8.2c0 .9.6 1.3 1.4 1.3H8M2 4.5h4" />
      <rect x="8" y="9.5" width="5.5" height="5" rx="1.3" />
    </>
  ),
  /* A folder with a plus: add a group. */
  addGroup: (
    <>
      <path d="M2.5 12V4.2c0-.6.4-1 1-1h2.8l1.4 1.5h4.8c.6 0 1 .4 1 1V8" />
      <path d="M2.5 12c0 .6.4 1 1 1H8M11.5 9.5v4.5M9.3 11.75h4.4" />
    </>
  ),
  up: <path d="M8 12.5v-9M4.5 7L8 3.5 11.5 7" />,
  down: <path d="M8 3.5v9M4.5 9L8 12.5 11.5 9" />,
  into: <path d="M3 3.5v4.5c0 1 .6 1.5 1.5 1.5H13M10 6.5l3 3-3 3" />,
  out: <path d="M13 3.5v4.5c0 1-.6 1.5-1.5 1.5H3M6 6.5l-3 3 3 3" />,
};

export type GlyphName = keyof typeof PATHS;

export function Glyph({ name, className }: { name: GlyphName; className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 16 16"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      {PATHS[name]}
    </svg>
  );
}
```

### agent-rules/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (agent-rules.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over a control. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### agent-rules/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```