@tjakoen/grain 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/ai/contract.test.ts +88 -1
  2. package/ai/contract.ts +96 -3
  3. package/ai/interaction-layer.test.ts +58 -0
  4. package/ai/manifest-dom.test.ts +59 -5
  5. package/ai/manifest-dom.ts +42 -11
  6. package/ai/reasoner-kit.test.ts +11 -1
  7. package/ai/reasoner-kit.ts +40 -2
  8. package/ai/reasoner.test.ts +55 -0
  9. package/ai/reasoner.ts +75 -2
  10. package/ai/vocab-reference.ts +3 -0
  11. package/assets/doc-sample.pdf +34 -0
  12. package/catalog/catalog.ts +56 -14
  13. package/components/atoms/b-check/b-check.html +27 -0
  14. package/components/atoms/b-check/b-check.md +67 -0
  15. package/components/atoms/b-checkbox/b-checkbox.css +61 -0
  16. package/components/atoms/b-checkbox/b-checkbox.html +17 -0
  17. package/components/atoms/b-checkbox/b-checkbox.md +83 -0
  18. package/components/atoms/b-choice/b-choice.html +16 -0
  19. package/components/atoms/b-choice/b-choice.md +35 -0
  20. package/components/atoms/b-field/b-field.html +17 -0
  21. package/components/atoms/b-field/b-field.md +43 -0
  22. package/components/atoms/b-input/b-input.css +20 -0
  23. package/components/atoms/b-input/b-input.html +7 -2
  24. package/components/atoms/b-input/b-input.md +27 -1
  25. package/components/atoms/b-memo/b-memo.html +21 -0
  26. package/components/atoms/b-memo/b-memo.md +34 -0
  27. package/components/atoms/b-option/b-option.html +5 -0
  28. package/components/atoms/b-option/b-option.md +13 -0
  29. package/components/atoms/b-radio/b-radio.html +17 -0
  30. package/components/atoms/b-radio/b-radio.md +57 -0
  31. package/components/atoms/b-textarea/b-textarea.css +48 -0
  32. package/components/atoms/b-textarea/b-textarea.html +15 -0
  33. package/components/atoms/b-textarea/b-textarea.md +70 -0
  34. package/components/doc-links.test.ts +1 -0
  35. package/components/form-from-data.test.ts +314 -0
  36. package/components/molecules/attachment/attachment.css +71 -0
  37. package/components/molecules/attachment/attachment.md +40 -0
  38. package/components/molecules/doc-frame/doc-frame.css +52 -0
  39. package/components/molecules/doc-frame/doc-frame.md +51 -0
  40. package/components/molecules/form-grid/form-grid.css +42 -0
  41. package/components/molecules/form-grid/form-grid.md +64 -0
  42. package/package.json +1 -1
  43. package/scripts/ai-dispatch.js +74 -4
  44. package/scripts/ai-dispatch.test.ts +68 -0
  45. package/styles/vars-defined.test.ts +1 -0
@@ -4,7 +4,10 @@
4
4
  // closed ACTIONS vocabulary (so it shows up in the manifest, see manifest-dom.test.ts), an
5
5
  // unsafe/external href is rejected, and a same-origin root-relative one is accepted.
6
6
  import { test, expect, describe } from "bun:test";
7
- import { ACTIONS, isAction, actionsForKind, isSafeNavigateHref, isValidChoiceList, isSafeFieldValue, FIELD_VALUE_CAP } from "./contract.ts";
7
+ import {
8
+ ACTIONS, BLOCK_SPANS, MOVE_DIRECTIONS, isAction, actionsForKind, isBlockSpan, isCheckedState,
9
+ isMoveDirection, isSafeFieldValue, isSafeNavigateHref, isValidChoiceList, FIELD_VALUE_CAP,
10
+ } from "./contract.ts";
8
11
 
9
12
  describe("navigate: registered in the closed ACTIONS vocabulary", () => {
10
13
  test("is a real action, light depth, accepts the screen kind", () => {
@@ -140,6 +143,46 @@ describe("isSafeFieldValue: plain text, capped, no control chars", () => {
140
143
  });
141
144
  });
142
145
 
146
+ describe("check.set: the tick-box verb, and the kind that keeps it apart from field.set", () => {
147
+ test("is a real action, light depth, accepts the check kind, requires checked:boolean", () => {
148
+ expect(isAction("check.set")).toBe(true);
149
+ expect(ACTIONS["check.set"]).toMatchObject({ name: "check.set", depth: "light", accepts: ["check"] });
150
+ expect(ACTIONS["check.set"].payload.checked).toMatchObject({ type: "boolean", required: true });
151
+ });
152
+ test("destructive + idempotent — it REPLACES a state the human may have set; same payload → same end state", () => {
153
+ expect(ACTIONS["check.set"].hints).toMatchObject({ destructive: true, idempotent: true });
154
+ });
155
+ // The point of the whole design, and the one assertion worth reading twice: each control kind
156
+ // advertises ONLY the verb that can operate it. Were both verbs on one kind, the manifest would
157
+ // tell a reasoner that field.set is legal on a tick box — and field.set writes el.value, which on
158
+ // a tick box is what the form SUBMITS rather than whether it is ticked. The write would land,
159
+ // report success, change the form's meaning and leave the control looking untouched.
160
+ test("the two kinds do not overlap: a field advertises no tick verb, a tick box no field verb", () => {
161
+ expect(actionsForKind("check")).toEqual(["check.set"]);
162
+ expect(actionsForKind("field")).toEqual(["field.set"]);
163
+ });
164
+ test("a set, not a toggle — a toggle could not honestly carry the idempotent flag", () => {
165
+ for (const name of Object.keys(ACTIONS)) expect(name).not.toMatch(/toggle/i);
166
+ });
167
+ });
168
+
169
+ describe("isCheckedState: a real boolean, and nothing that merely looks like one", () => {
170
+ test("accepts both booleans", () => {
171
+ expect(isCheckedState(true)).toBe(true);
172
+ expect(isCheckedState(false)).toBe(true);
173
+ });
174
+ // "false" is a truthy string, so a coercing guard would TICK the box a reasoner asked to clear.
175
+ test("rejects the strings, the numbers and the absent value a model might send instead", () => {
176
+ expect(isCheckedState("true")).toBe(false);
177
+ expect(isCheckedState("false")).toBe(false);
178
+ expect(isCheckedState("checked")).toBe(false);
179
+ expect(isCheckedState(1)).toBe(false);
180
+ expect(isCheckedState(0)).toBe(false);
181
+ expect(isCheckedState(undefined)).toBe(false);
182
+ expect(isCheckedState(null)).toBe(false);
183
+ });
184
+ });
185
+
143
186
  describe("isValidChoiceList: 1–6 options, each a non-empty label", () => {
144
187
  test("accepts well-formed lists (value optional)", () => {
145
188
  expect(isValidChoiceList([{ label: "A" }])).toBe(true);
@@ -156,3 +199,47 @@ describe("isValidChoiceList: 1–6 options, each a non-empty label", () => {
156
199
  expect(isValidChoiceList(null)).toBe(false);
157
200
  });
158
201
  });
202
+
203
+ // The three block verbs (plans/block-verbs.md). A block is a kind of its own for the reason a check
204
+ // is: a kind is a promise about which verbs work, and a block's real state is the composition
205
+ // holding it rather than the element showing it.
206
+ describe("the block verbs: registered, closed-payload, and honest about idempotence", () => {
207
+ test("all three are registered against the block kind and nothing else", () => {
208
+ expect(actionsForKind("block").toSorted()).toEqual(["block.move", "block.remove", "block.span"]);
209
+ for (const name of ["block.remove", "block.span", "block.move"] as const) {
210
+ expect(ACTIONS[name].accepts).toEqual(["block"]);
211
+ expect(isAction(name)).toBe(true);
212
+ }
213
+ });
214
+
215
+ // The whole small-model argument: a payload description that NAMES its legal values is the
216
+ // difference between a 0.5B picking one and a 0.5B guessing.
217
+ test("each payload names its closed word list in the description the manifest carries", () => {
218
+ expect(ACTIONS["block.span"].payload.span).toMatchObject({ type: "string", required: true });
219
+ expect(ACTIONS["block.span"].payload.span!.note).toContain("full");
220
+ expect(ACTIONS["block.span"].payload.span!.note).toContain("third");
221
+ expect(ACTIONS["block.move"].payload.direction!.note).toContain("up");
222
+ expect(ACTIONS["block.remove"].payload).toEqual({});
223
+ });
224
+
225
+ // move is the one that is NOT idempotent, and saying so is the point: a replayed move shifts a
226
+ // second place, where a replayed remove or span lands exactly where the first one did.
227
+ test("remove and span claim idempotence; move does not", () => {
228
+ expect(ACTIONS["block.remove"].hints.idempotent).toBe(true);
229
+ expect(ACTIONS["block.span"].hints.idempotent).toBe(true);
230
+ expect(ACTIONS["block.move"].hints.idempotent).toBeUndefined();
231
+ });
232
+
233
+ // There is deliberately no verb that ADDS a block: adding goes through field.set on the page's
234
+ // own prompt, which is what keeps the model from ever naming a component.
235
+ test("no verb adds a block", () => {
236
+ expect(Object.keys(ACTIONS).filter((a) => /^block\.(add|create|insert)/.test(a))).toEqual([]);
237
+ });
238
+
239
+ test("the closed word lists refuse everything outside them", () => {
240
+ for (const ok of BLOCK_SPANS) expect(isBlockSpan(ok)).toBe(true);
241
+ for (const no of ["wide", "FULL", "", "1/2", 3, null, undefined]) expect(isBlockSpan(no)).toBe(false);
242
+ for (const ok of MOVE_DIRECTIONS) expect(isMoveDirection(ok)).toBe(true);
243
+ for (const no of ["top", "Up", "", 1, null]) expect(isMoveDirection(no)).toBe(false);
244
+ });
245
+ });
package/ai/contract.ts CHANGED
@@ -21,7 +21,25 @@ export type Surface = string; // e.g. "item:ITM-1", "refle
21
21
  // TEXTAREA); a field is addressable ONLY if the page marked it `data-surface="field:…"`, so
22
22
  // refusal on anything else is free (plans/field-set-op.md). The AI prefills; it never submits —
23
23
  // structurally: no submit verb exists in the vocabulary.
24
- export type SurfaceKind = "item" | "reflection" | "say-stream" | "screen" | "chat-log" | "notepad" | "field";
24
+ // `check` is a registered TICK BOX (check.set) — a checkbox or a radio, and deliberately NOT the
25
+ // `field` kind even though both are form controls. A kind is a PROMISE about which verbs work: were
26
+ // a tick box a `field`, the manifest would advertise `field.set` on it, and `field.set` writes
27
+ // `el.value`, which on a tick box is what the form SUBMITS rather than whether it is ticked — a
28
+ // write that lands, reports success, changes the form's meaning and leaves the control looking
29
+ // untouched. Two kinds keep each control advertising only the verb that can actually operate it
30
+ // (plans/check-set-op.md).
31
+ // `block` is one BLOCK in a composed page — a component the human (or the AI) can drop, resize or
32
+ // reorder inside an ordered list. A kind of its own for the reason `check` is one: a kind is a
33
+ // PROMISE about which verbs work. The generic `remove` op deletes an ELEMENT, and a block's real
34
+ // state is the composition holding it, so a block advertising only DOM verbs would take a delete
35
+ // that lands, reports success, and comes back on the next repaint. The three block verbs below say
36
+ // what a block can actually be told, and every one of their payloads is a closed enum, because the
37
+ // model this vocabulary is aimed at is a small one: choosing from three words is what it does
38
+ // reliably, and inventing a fourth is what it must never be given room to do.
39
+ // Note what is NOT here: there is no verb that ADDS a block. Adding goes through `field.set` on the
40
+ // page's own prompt plus a build, so the closed component set stays closed and the model never
41
+ // names a component (plans/site-builder.md).
42
+ export type SurfaceKind = "item" | "reflection" | "say-stream" | "screen" | "chat-log" | "notepad" | "field" | "check" | "block";
25
43
  export const surface = (kind: SurfaceKind, id?: string): Surface => (id ? `${kind}:${id}` : kind);
26
44
  export const surfaceKind = (s: Surface): SurfaceKind => (s.split(":")[0] ?? "") as SurfaceKind;
27
45
  export const surfaceId = (s: Surface): string => s.split(":").slice(1).join(":");
@@ -36,10 +54,19 @@ export const surfaceId = (s: Surface): string => s.split(":").slice(1).join(":")
36
54
  // navigate — a control (or a reasoner's own decision) asks to change screens; see below
37
55
  // field.set — prefill a registered form field with drafted text; the human reviews and
38
56
  // submits (the AI never submits — no submit verb exists to call)
57
+ // check.set — tick or clear a registered tick box; the sibling field.set cannot do, because
58
+ // a tick box's state is `checked` and its `value` is what it submits
59
+ // block.remove — drop one block from a composed page
60
+ // block.span — set one block's width word: full, half or third, and there is no fourth
61
+ // block.move — shift one block one place, up or down, clamped at the ends
62
+ // The three block verbs land together because a page you can add to and never edit is not a page
63
+ // you are building, it is one you are re-rolling. There is deliberately no verb that ADDS: adding
64
+ // goes through field.set on the page's own prompt, so the model never names a component.
39
65
  // The full product vocabulary lives at https://tjakoen.github.io/grain/docs/ai-interface.
40
66
  export type ActionName =
41
67
  | "item.archive" | "say.set" | "say.stream" | "demo.run" | "desk.stop" | "chat.send"
42
- | "note.append" | "note.replace" | "navigate" | "field.set";
68
+ | "note.append" | "note.replace" | "navigate" | "field.set" | "check.set"
69
+ | "block.remove" | "block.span" | "block.move";
43
70
  export type Depth = "light" | "heavy";
44
71
 
45
72
  // ---- Payload schema: the machine-readable INPUT shape a verb expects -------------
@@ -119,6 +146,32 @@ export const ACTIONS: Record<ActionName, ActionDef> = {
119
146
  description: "Prefill a registered form field with drafted text — the human reviews and submits; the AI never submits.",
120
147
  payload: { value: REQ("string", "plain text; replaces the field's current value") },
121
148
  hints: { destructive: true, idempotent: true } }, // REPLACES what the field holds (may be human-typed); same value → same end state
149
+ // A SET, not a toggle, and the distinction is the reason this verb is safe to retry: a toggle
150
+ // flips whatever is there, so a replay lands in the opposite state and the `idempotent` flag
151
+ // below would be a lie. The reasoner does not read the box before writing it; it states the
152
+ // state it wants. Same shape as field.set, one kind over.
153
+ "check.set": { name: "check.set", depth: "light", accepts: ["check"],
154
+ description: "Tick or clear a registered tick box (checkbox or radio) — the human reviews and submits; the AI never submits.",
155
+ payload: { checked: REQ("boolean", "true ticks the box, false clears it") },
156
+ hints: { destructive: true, idempotent: true } }, // REPLACES a state the human may have set; same payload → same end state
157
+ // The three block verbs. Each one is a SET rather than a nudge, for the reason check.set is: a
158
+ // toggle or a cycle lands somewhere different on a replay, and the `idempotent` hint below would
159
+ // then be a lie the reasoner's retry logic believes.
160
+ "block.remove": { name: "block.remove", depth: "light", accepts: ["block"],
161
+ description: "Drop one block from the composed page. The page keeps every other block's id, so a later verb still names what it means.",
162
+ payload: {}, hints: { destructive: true, idempotent: true } }, // removing a block already gone is the same end state
163
+ "block.span": { name: "block.span", depth: "light", accepts: ["block"],
164
+ description: "Set how wide one block sits: full, half or third. The whole layout vocabulary, and there is no fourth word.",
165
+ payload: { span: REQ("string", "one of: full, half, third") },
166
+ hints: { idempotent: true } }, // same word → same width; no cycling, so a replay is safe
167
+ // A DIRECTION rather than a target index, and the difference is the small model this is aimed at.
168
+ // An index is a number to compute against a list length, which is where a 0.5B drifts; up and down
169
+ // are the two words already written on the buttons a human presses. The arithmetic stays in code,
170
+ // where it is already tested, and the verb looks like the affordance rather than like the array.
171
+ "block.move": { name: "block.move", depth: "light", accepts: ["block"],
172
+ description: "Move one block one place earlier or later in the page. Clamped at the ends rather than wrapped.",
173
+ payload: { direction: REQ("string", "one of: up, down") },
174
+ hints: {} }, // NOT idempotent: each move shifts one more place
122
175
  };
123
176
 
124
177
  export const isAction = (s: string): s is ActionName => Object.hasOwn(ACTIONS, s);
@@ -173,7 +226,21 @@ export interface Intent {
173
226
  // `type`'s INPUT/TEXTAREA branch appends tokens and CLEARS on `done` (composer-submit physics — a
174
227
  // prefill must PERSIST for review), and `replace` swaps outerHTML (a field's value is state, not
175
228
  // markup — replacing the element would drop listeners and focus). Reuses the existing `text` field.
176
- export type RenderOpKind = "replace" | "append" | "remove" | "flash" | "type" | "spotlight" | "log" | "navigate" | "choices" | "fill";
229
+ // `tick` — check.set's effect: assign a tick box's `checked` state. A separate kind from `fill`
230
+ // rather than a boolean mode on it, for the reason `fill` is separate from `type`: an op that
231
+ // branches on which of two payload fields arrived is two ops sharing a name, and the dispatcher
232
+ // would have to guess which one it was handed. `tick` carries `checked` and nothing else, so the
233
+ // wire says what it means and each op stays conformance-testable as its own vocabulary word.
234
+ // `span` — block.span's effect: assign a block's width word. Its own kind rather than a generic
235
+ // attribute write, because an op that can set any attribute is a hole in a vocabulary whose whole
236
+ // point is that it is closed.
237
+ // `move` — block.move's effect: shift a block one place. Its own kind rather than a `replace` of the
238
+ // whole canvas, because a reasoner that had to hand back rendered markup would be a second renderer,
239
+ // which is the one thing this design refuses.
240
+ // `block.remove` deliberately emits the EXISTING `remove` op rather than a fourth kind: deleting the
241
+ // element is exactly the effect, and a new kind that did the same thing would be vocabulary for its
242
+ // own sake.
243
+ export type RenderOpKind = "replace" | "append" | "remove" | "flash" | "type" | "spotlight" | "log" | "navigate" | "choices" | "fill" | "tick" | "span" | "move";
177
244
  export type Provenance = "user" | "ai" | "system";
178
245
  export type Commit = "pending" | "committed"; // grade = commit state (DESIGN-SYSTEM §3)
179
246
 
@@ -194,6 +261,9 @@ export interface RenderOp {
194
261
  href?: string; // navigate: where to (validated — isSafeNavigateHref, below)
195
262
  prompt?: string; // choices: the question shown above the buttons (optional)
196
263
  choices?: Choice[]; // choices: the options the human picks from (validated — isValidChoiceList)
264
+ checked?: boolean; // tick: the state to assign to a registered tick box (validated — isCheckedState)
265
+ span?: BlockSpan; // span: the width word to assign to a block (validated — isBlockSpan)
266
+ direction?: MoveDirection; // move: which way to shift a block (validated — isMoveDirection)
197
267
  provenance: Provenance;
198
268
  commit: Commit;
199
269
  }
@@ -229,6 +299,29 @@ const FIELD_VALUE_BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
229
299
  export const isSafeFieldValue = (v: unknown): v is string =>
230
300
  typeof v === "string" && v.length <= FIELD_VALUE_CAP && !FIELD_VALUE_BAD_CHARS.test(v);
231
301
 
302
+ // ---- check.set's state validator — a real boolean, and nothing that merely looks like one -------
303
+ // A one-line guard rather than an inline `typeof`, for the same reason the two above are named: the
304
+ // reasoner's rejection message, the dispatcher's last-line re-check and the drift-guard test all
305
+ // need to mean the same thing by "a valid checked state". Strings are rejected on purpose — "false"
306
+ // is truthy, so a model that sends the word instead of the value would tick every box it aimed at,
307
+ // and a silent coercion is exactly the failure this whole verb exists to avoid.
308
+ export const isCheckedState = (v: unknown): v is boolean => typeof v === "boolean";
309
+
310
+ // ---- the block verbs' closed word lists -----------------------------------------
311
+ // Both are exported as arrays as well as types, because the manifest advertises them to the model:
312
+ // a payload description that can NAME its three legal values is the difference between a small
313
+ // model picking one and a small model guessing. A free string here would put the closed set back in
314
+ // prose, where nothing can check it.
315
+ export const BLOCK_SPANS = ["full", "half", "third"] as const;
316
+ export type BlockSpan = (typeof BLOCK_SPANS)[number];
317
+ export const isBlockSpan = (v: unknown): v is BlockSpan =>
318
+ typeof v === "string" && (BLOCK_SPANS as readonly string[]).includes(v);
319
+
320
+ export const MOVE_DIRECTIONS = ["up", "down"] as const;
321
+ export type MoveDirection = (typeof MOVE_DIRECTIONS)[number];
322
+ export const isMoveDirection = (v: unknown): v is MoveDirection =>
323
+ typeof v === "string" && (MOVE_DIRECTIONS as readonly string[]).includes(v);
324
+
232
325
  // ---- The reasoner's verdict ------------------------------------------------------
233
326
  export interface Decision {
234
327
  ok: boolean;
@@ -268,3 +268,61 @@ test("an AI field.set is bracketed by a spotlight on the field surface (AI as ac
268
268
  expect(spots.some((o) => o.active === true)).toBe(true);
269
269
  expect(spots.some((o) => o.active === false)).toBe(true);
270
270
  });
271
+
272
+ // --- check.set at the door: kind validation, state validation, the tick op (plans/check-set-op.md) ---
273
+ test("check.set on a check kind: validates, the reasoner emits a committed ai tick op", async () => {
274
+ const { layer, pushed } = makeLayer();
275
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "check:newsletter",
276
+ action: "check.set", payload: { checked: true } }));
277
+ expect(d.ok).toBe(true);
278
+ const tick = ops(pushed).find((o) => o.op === "tick");
279
+ expect(tick).toMatchObject({ target: "check:newsletter", checked: true, provenance: "ai", commit: "committed" });
280
+ });
281
+
282
+ // The two rejections below are the design, stated as behaviour rather than as a comment: neither
283
+ // verb can reach the other's control, so the manifest never promises a write that would land
284
+ // silently wrong. Deleting the two kinds and merging them would turn both of these green-to-red.
285
+ test("check.set on a FIELD surface: rejected with the accepts echo — a text field is not a tick box", async () => {
286
+ const { layer } = makeLayer();
287
+ const d = await layer.handleIntent(intent({ surface: "field:contact-message",
288
+ action: "check.set", payload: { checked: true } }));
289
+ expect(d.ok).toBe(false);
290
+ expect(d.ops[0]?.op).toBe("flash");
291
+ expect(d.reason).toContain("field:contact-message rejects check.set");
292
+ expect(d.reason).toContain("field.set"); // the verb that surface DOES accept, echoed back
293
+ });
294
+
295
+ test("field.set on a CHECK surface: rejected the same way — the write that would have lied", async () => {
296
+ const { layer } = makeLayer();
297
+ const d = await layer.handleIntent(intent({ surface: "check:newsletter",
298
+ action: "field.set", payload: { value: "yes" } }));
299
+ expect(d.ok).toBe(false);
300
+ expect(d.reason).toContain("check:newsletter rejects field.set");
301
+ expect(d.reason).toContain("check.set");
302
+ });
303
+
304
+ test("check.set with a non-boolean: rejected, and nothing reaches the box", async () => {
305
+ const { layer, pushed } = makeLayer();
306
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "check:newsletter",
307
+ action: "check.set", payload: { checked: "false" } }));
308
+ expect(d.ok).toBe(false);
309
+ expect(d.reason).toContain("check.set checked rejected");
310
+ expect(ops(pushed).find((o) => o.op === "tick")).toBeUndefined();
311
+ });
312
+
313
+ test("check.set clearing a box is a legal move at the door — the radio limit is the dispatcher's", async () => {
314
+ const { layer, pushed } = makeLayer();
315
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "check:newsletter",
316
+ action: "check.set", payload: { checked: false } }));
317
+ expect(d.ok).toBe(true);
318
+ expect(ops(pushed).find((o) => o.op === "tick")).toMatchObject({ checked: false });
319
+ });
320
+
321
+ test("an AI check.set is bracketed by a spotlight on the check surface (AI as actor)", async () => {
322
+ const { layer, pushed } = makeLayer();
323
+ await layer.handleIntent(intent({ source: "ai", surface: "check:newsletter",
324
+ action: "check.set", payload: { checked: true } }));
325
+ const spots = ops(pushed).filter((o) => o.op === "spotlight" && o.target === "check:newsletter");
326
+ expect(spots.some((o) => o.active === true)).toBe(true);
327
+ expect(spots.some((o) => o.active === false)).toBe(true);
328
+ });
@@ -123,7 +123,11 @@ test("manifestForReasoner: renders an 'in view' block for data-read surfaces", (
123
123
  ],
124
124
  };
125
125
  const text = manifestForReasoner(doc);
126
- expect(text).toContain('in view: (1)\n- reflection [reflection] "Noted: buy milk"');
126
+ expect(text).toContain('in view: (1) — current state only; these are NOT targets and no verb acts on them\n reflection = "Noted: buy milk"');
127
+ // shaped so it cannot be read as another target line. `- reflection [reflection]` is legitimately
128
+ // in the TARGETS list (reflection is a registered kind), so the check is on the state line's own
129
+ // shape: a dash-and-bracket line ending in quoted text is the collision, and it is gone.
130
+ expect(text).not.toMatch(/^- .+ \[.+] ".*"$/m);
127
131
  });
128
132
 
129
133
  test("manifestForReasoner: deterministic, prompt-ready text — same fixed DOM in, same string out", () => {
@@ -149,13 +153,63 @@ test("manifestForReasoner: deterministic, prompt-ready text — same fixed DOM i
149
153
  // behaviour hints ride along in braces so the reasoner can retry/choose safely
150
154
  expect(first).toContain("- note.replace [light] (text*:string (markdown)) — Rewrite the whole notepad from one markdown body. {destructive, idempotent}");
151
155
  expect(first).toContain("- navigate [light] (href*:string (root-relative path, e.g. /notes)) — Change screens — same-origin, root-relative href only (validated at the door). {read");
152
- // the targets tail is exact and comes after the actions block
156
+ // the targets tail is exact and comes after the actions block. `console` accepts no verb, so it
157
+ // is NOT listed — the count says two of three so the omission is stated rather than hidden.
153
158
  expect(first.endsWith(
154
- "targets: (3)\n" +
159
+ "targets: (2 of 3 accept a verb)\n" +
155
160
  "- item:ITM-1 [item] -> item.archive\n" +
156
- "- chat-log [chat-log] -> chat.send\n" +
157
- "- console [console] -> (no verb currently targets this)"
161
+ "- chat-log [chat-log] -> chat.send"
158
162
  )).toBe(true);
163
+ expect(first).not.toContain("console");
164
+ });
165
+
166
+ test("manifestForReasoner: a screen with nothing push-only is byte-identical to before the narrowing", () => {
167
+ // The fleet guarantee. Narrowing must be a no-op wherever there was no noise to cut, which is why
168
+ // the count keeps its bare "(n)" form when nothing was omitted.
169
+ const doc = {
170
+ body: el({ "data-screen": "notes" }),
171
+ querySelectorAll: () => [
172
+ el({ "data-surface": "item:ITM-1", "data-kind": "item", "data-accepts": "item.archive" }),
173
+ el({ "data-surface": "chat-log" }),
174
+ ],
175
+ };
176
+ expect(manifestForReasoner(doc).endsWith(
177
+ "targets: (2)\n" +
178
+ "- item:ITM-1 [item] -> item.archive\n" +
179
+ "- chat-log [chat-log] -> chat.send"
180
+ )).toBe(true);
181
+ });
182
+
183
+ test("manifestForReasoner: chat messages pile up in domManifest and never reach the prompt", () => {
184
+ // The measured case, in miniature. On /builder 17 of 53 targets were chat-msg ids: `chat-msg` is
185
+ // no registered SurfaceKind, so every one is push-only, and the 0.5B picked out of that list
186
+ // rather than the blocks. The JSON manifest still carries them (validation reads that one).
187
+ const surfaces = [
188
+ el({ "data-surface": "block:b1", "data-kind": "block" }),
189
+ ...Array.from({ length: 5 }, (_, i) => el({ "data-surface": `chat-msg:run-${i}` })),
190
+ ];
191
+ const doc = { body: el({ "data-screen": "builder" }), querySelectorAll: () => surfaces };
192
+
193
+ expect(domManifest(doc).targets).toHaveLength(6); // the whole page, for validation
194
+ const text = manifestForReasoner(doc);
195
+ expect(text).not.toContain("chat-msg"); // none of them in the prompt
196
+ expect(text).toContain("targets: (1 of 6 accept a verb)");
197
+ expect(text).toContain("- block:b1 [block] -> block.remove, block.span, block.move");
198
+ });
199
+
200
+ test("manifestForReasoner: surfaces but no verbs — says so, and still reads their state", () => {
201
+ // A page can declare surfaces that no verb reaches. "(none)" would claim it declares nothing,
202
+ // which is a different sentence, and `in view` must survive: push-only is not unreadable.
203
+ const doc = {
204
+ body: el({ "data-screen": "log" }),
205
+ querySelectorAll: () => [
206
+ el({ "data-surface": "console", "data-read": "" }, "build finished"),
207
+ el({ "data-surface": "plan" }),
208
+ ],
209
+ };
210
+ const text = manifestForReasoner(doc);
211
+ expect(text).toContain("targets: (0 of 2 accept a verb — nothing on this page can be acted on)");
212
+ expect(text).toContain(' console = "build finished"');
159
213
  });
160
214
 
161
215
  test("manifestForReasoner: a screen-kind surface lists navigate among its accepted verbs", () => {
@@ -136,7 +136,11 @@ export function domManifest(doc: DomDoc): Manifest {
136
136
  * this is just its prose form). Built ON `domManifest`, not a second harvest: one truth, two
137
137
  * shapes (JSON for code, text for a prompt). Deterministic: the same DOM in always yields the
138
138
  * same string out — target order follows `harvestTargets`' DOM walk (document order), never a
139
- * Set/Map/Object whose iteration order could vary across engines. Pure — no DOM writes, no I/O. */
139
+ * Set/Map/Object whose iteration order could vary across engines. Pure — no DOM writes, no I/O.
140
+ *
141
+ * NARROWER than `domManifest`: only targets that accept at least one verb are listed, because a
142
+ * target no verb reaches is not a move a reasoner can make and a long list of them is what a small
143
+ * model picks out of. See `manifestToText` for the measurement that prompted it. */
140
144
  export function manifestForReasoner(doc: DomDoc): string {
141
145
  return manifestToText(domManifest(doc));
142
146
  }
@@ -163,14 +167,27 @@ export function manifestToText(m: Manifest): string {
163
167
  lines.push(`- ${a.name} [${a.depth}] (${args}) — ${a.description}${hints}`);
164
168
  }
165
169
 
166
- if (!m.targets.length) {
167
- lines.push("targets: (none — this page declares no [data-surface] elements)");
168
- return lines.join("\n");
169
- }
170
- lines.push(`targets: (${m.targets.length})`);
171
- for (const t of m.targets) {
172
- const verbs = t.accepts.length ? t.accepts.join(", ") : "(no verb currently targets this)";
173
- lines.push(`- ${t.id} [${t.kind}] -> ${verbs}`);
170
+ // TARGETS, NARROWED TO THE OPERABLE ONES. A target whose accepts list is empty cannot be a legal
171
+ // move: `validateMove` refuses any target that does not carry the verb, so a reasoner that picks
172
+ // one has lost the turn before it starts. Listing it can only mislead, and the cost is not
173
+ // theoretical — measured on /builder 2026-08-14, 17 of 53 targets were `chat-msg:` ids, and the
174
+ // 0.5B reliably answered with a plausible-looking surface that accepts nothing rather than a
175
+ // block. Chat messages are the surface whose count grows without bound, so the noise grows with
176
+ // the conversation. This narrows the PROMPT only: `domManifest` still carries every target, so
177
+ // validation, the x-ray overlay, the terminal's `context` command and the MCP tool's JSON all
178
+ // still see the whole page. A screen with nothing push-only emits the exact string it did before.
179
+ const operable = m.targets.filter((t) => t.accepts.length > 0);
180
+ const omitted = m.targets.length - operable.length;
181
+
182
+ if (!operable.length) {
183
+ // Said plainly rather than silently: a page with surfaces but no verbs is a real state, and
184
+ // "(none)" alone would read as "this page declares nothing", which is a different claim.
185
+ lines.push(m.targets.length
186
+ ? `targets: (0 of ${m.targets.length} accept a verb — nothing on this page can be acted on)`
187
+ : "targets: (none — this page declares no [data-surface] elements)");
188
+ } else {
189
+ lines.push(omitted ? `targets: (${operable.length} of ${m.targets.length} accept a verb)` : `targets: (${operable.length})`);
190
+ for (const t of operable) lines.push(`- ${t.id} [${t.kind}] -> ${t.accepts.join(", ")}`);
174
191
  }
175
192
 
176
193
  // IN VIEW: the current readable STATE of every surface that opted in with data-read (the MCP
@@ -178,10 +195,24 @@ export function manifestToText(m: Manifest): string {
178
195
  // yields the exact same string as before, so the block never adds noise where there's no state.
179
196
  // This is the "read the result" half of the observe loop: after acting, the reasoner sees not
180
197
  // just what it can do next but what the surfaces now SAY.
198
+ //
199
+ // The target narrowing above deliberately does NOT reach here. A surface being push-only says no
200
+ // verb acts on it, which is the opposite of saying it is not worth reading: a console feed, a
201
+ // status line and a summary are all push-only and all worth reading before deciding. `data-read`
202
+ // is already the author's opt-in, and it is the one that governs this block.
203
+ //
204
+ // It is FORMATTED so it cannot be misread as a target list, which is not a hypothetical. With the
205
+ // targets narrowed to eight on /builder, the 0.5B stopped picking a wrong target and started
206
+ // answering with `builder-said` instead — an id that appears nowhere but here (measured
207
+ // 2026-08-15). An old in-view line read `- id [kind] "text"` against a target's `- id [kind] ->
208
+ // verbs`: same dash, same brackets, differing only in what follows. So the dash and the brackets
209
+ // go, the heading says in words that these are not targets, and the kind goes with them — it is
210
+ // recoverable from the targets list for any surface that has one, and for a push-only surface it
211
+ // only ever repeated the id.
181
212
  const readable = (m.inView.readable as ReadableSurface[] | undefined) ?? [];
182
213
  if (readable.length) {
183
- lines.push(`in view: (${readable.length})`);
184
- for (const r of readable) lines.push(`- ${r.id} [${r.kind}] "${r.text}"`);
214
+ lines.push(`in view: (${readable.length}) — current state only; these are NOT targets and no verb acts on them`);
215
+ for (const r of readable) lines.push(` ${r.id} = "${r.text}"`);
185
216
  }
186
217
  return lines.join("\n");
187
218
  }
@@ -3,7 +3,7 @@
3
3
  import { test, expect, describe } from "bun:test";
4
4
  import {
5
5
  esc, chatBubble, chatBody, narrationLine, thinkingDots, choiceGroup,
6
- userMessageOp, aiBubbleOp, typeToken, settleOp, replaceBodyOp, narrateOp, spotlightOp, navigateOp, fillOp,
6
+ userMessageOp, aiBubbleOp, typeToken, settleOp, replaceBodyOp, narrateOp, spotlightOp, navigateOp, fillOp, tickOp,
7
7
  thinkingOp, choicesOp,
8
8
  notepadEntry, notepadBody, noteAppendOp, noteReplaceOp,
9
9
  renderMarkdown,
@@ -71,6 +71,16 @@ describe("op-builders", () => {
71
71
  expect(() => fillOp("field:contact-message", "x".repeat(2001))).toThrow();
72
72
  expect(() => fillOp("field:contact-message", "null\x00byte")).toThrow();
73
73
  });
74
+ test("tickOp: a boolean becomes a committed ai tick op — the state persists for human review", () => {
75
+ expect(tickOp("check:newsletter", true))
76
+ .toMatchObject({ target: "check:newsletter", op: "tick", checked: true, provenance: "ai", commit: "committed" });
77
+ expect(tickOp("check:newsletter", false)).toMatchObject({ op: "tick", checked: false });
78
+ });
79
+ test("tickOp: a non-boolean throws here, at compose time — a truthy string would tick what it meant to clear", () => {
80
+ expect(() => tickOp("check:newsletter", "false" as unknown as boolean)).toThrow();
81
+ expect(() => tickOp("check:newsletter", 1 as unknown as boolean)).toThrow();
82
+ expect(() => tickOp("check:newsletter", undefined as unknown as boolean)).toThrow();
83
+ });
74
84
  test("renderMarkdown is re-exported from the kit (same module ai/markdown.ts exports)", () => {
75
85
  expect(renderMarkdown("**hi**")).toContain("<strong>hi</strong>");
76
86
  });
@@ -5,8 +5,11 @@
5
5
  // primitives first-class and EXPORTED; the stub dogfoods them (reasoner.ts), so the kit and the
6
6
  // shipped behaviour can never diverge. CLIENT-SAFE (§19.2): pure, no DOM, relative import only.
7
7
 
8
- import type { RenderOp, Surface } from "./contract.ts";
9
- import { PUSH_SURFACES, isSafeNavigateHref, isSafeFieldValue, FIELD_VALUE_CAP } from "./contract.ts";
8
+ import type { BlockSpan, MoveDirection, RenderOp, Surface } from "./contract.ts";
9
+ import {
10
+ BLOCK_SPANS, MOVE_DIRECTIONS, PUSH_SURFACES, isBlockSpan, isCheckedState, isMoveDirection,
11
+ isSafeFieldValue, isSafeNavigateHref, FIELD_VALUE_CAP,
12
+ } from "./contract.ts";
10
13
  // Imported for the notepad markup helpers below (they render markdown source to sanitized HTML) AND
11
14
  // re-exported so a consumer building on the kit finds settle-time markdown rendering right next to
12
15
  // the op-builders it pairs with, without a second import path to remember. Canonical home + tests:
@@ -132,6 +135,41 @@ export const fillOp = (target: Surface, value: string): RenderOp => {
132
135
  return { target, op: "fill", text: value, provenance: "ai", commit: "committed" };
133
136
  };
134
137
 
138
+ /** Set a registered tick box's state (`check:` surface) — the `tick` op. Same contract as fillOp
139
+ * one kind over: the state PERSISTS for human review and the AI never submits. Throws on a
140
+ * non-boolean RIGHT HERE rather than letting a truthy string reach the dispatcher and tick a box
141
+ * the reasoner meant to clear (lesson #3/#5 — the dispatcher's guard is defense-in-depth). */
142
+ export const tickOp = (target: Surface, checked: boolean): RenderOp => {
143
+ if (!isCheckedState(checked))
144
+ throw new Error(`tickOp: checked must be a boolean, got ${JSON.stringify(checked)}`);
145
+ return { target, op: "tick", checked, provenance: "ai", commit: "committed" };
146
+ };
147
+
148
+ /** Drop one block from a composed page — the existing `remove` op, aimed at a `block:` surface.
149
+ * No new op kind: deleting the element IS the effect, and a second kind that did the same thing
150
+ * would be vocabulary for its own sake. `committed` because the delete is complete in one op. */
151
+ export const removeBlockOp = (target: Surface): RenderOp =>
152
+ ({ target, op: "remove", provenance: "ai", commit: "committed" });
153
+
154
+ /** Set one block's width word — the `span` op. Throws on a word outside the closed three RIGHT
155
+ * HERE, at the compose point, like fillOp and tickOp above (lesson #3/#5 — the dispatcher's own
156
+ * guard is defense-in-depth, not the first line). A fourth word reaching a stylesheet that has no
157
+ * rule for it would render a block at some default width and report success. */
158
+ export const spanOp = (target: Surface, span: BlockSpan): RenderOp => {
159
+ if (!isBlockSpan(span))
160
+ throw new Error(`spanOp: span must be one of ${BLOCK_SPANS.join(", ")}, got ${JSON.stringify(span)}`);
161
+ return { target, op: "span", span, provenance: "ai", commit: "committed" };
162
+ };
163
+
164
+ /** Move one block one place — the `move` op. Throws on anything but up or down at the compose
165
+ * point, for the reason spanOp does. Deliberately NOT idempotent and the op says so by omission:
166
+ * each move shifts one more place, so a replay is a second move rather than the same one. */
167
+ export const moveOp = (target: Surface, direction: MoveDirection): RenderOp => {
168
+ if (!isMoveDirection(direction))
169
+ throw new Error(`moveOp: direction must be one of ${MOVE_DIRECTIONS.join(", ")}, got ${JSON.stringify(direction)}`);
170
+ return { target, op: "move", direction, provenance: "ai", commit: "committed" };
171
+ };
172
+
135
173
  /** Replace a bubble body with the animated "thinking" dots, pending — the AI is working but hasn't a
136
174
  * token to show yet. Reuses replaceBodyOp so the caret/settle lifecycle is identical to any stream. */
137
175
  export const thinkingOp = (surface: Surface): RenderOp => replaceBodyOp(surface, thinkingDots(), "pending");
@@ -225,3 +225,58 @@ test("note.append with empty text: rejected with a flash, nothing written (never
225
225
  expect(d.ok).toBe(false);
226
226
  expect(d.ops[0]!.op).toBe("flash");
227
227
  });
228
+
229
+ // The three block verbs, deterministic and model-free — the same shape check.set has, one kind over.
230
+ // A block is a kind of its own because a kind is a promise about which verbs work, and a block's
231
+ // real state is the composition holding it rather than the element showing it.
232
+ const blockIntent = (action: Intent["action"], payload: Record<string, unknown>, id = "b2") =>
233
+ intent({ action, surface: `block:${id}`, payload });
234
+
235
+ test("block.remove emits the EXISTING remove op rather than a fourth kind", async () => {
236
+ const { tools } = fakeTools();
237
+ const d = await reasoner.decide(blockIntent("block.remove", {}), tools);
238
+ expect(d.ok).toBe(true);
239
+ expect(d.ops.filter((o) => o.op !== "spotlight" && o.op !== "log").map((o) => o.op)).toEqual(["remove"]);
240
+ });
241
+
242
+ test("block.span sets the width word it was given, on the block it was aimed at", async () => {
243
+ const { tools } = fakeTools();
244
+ const d = await reasoner.decide(blockIntent("block.span", { span: "full" }, "b3"), tools);
245
+ expect(d.ok).toBe(true);
246
+ expect(d.ops.find((o) => o.op === "span")).toMatchObject({ target: "block:b3", span: "full", provenance: "ai" });
247
+ });
248
+
249
+ // The rejection ECHOES the legal words rather than saying "invalid": the model this is aimed at is
250
+ // small, and a rejection it can act on is the difference between a retry and a dead end.
251
+ test("a fourth width word is refused, and the refusal names the three that exist", async () => {
252
+ const { tools } = fakeTools();
253
+ const d = await reasoner.decide(blockIntent("block.span", { span: "wide" }), tools);
254
+ expect(d.ok).toBe(false);
255
+ expect(d.reason).toContain("full");
256
+ expect(d.reason).toContain("third");
257
+ expect(d.ops.some((o) => o.op === "flash")).toBe(true);
258
+ });
259
+
260
+ test("block.move takes a DIRECTION, and refuses the index a model might reach for", async () => {
261
+ const { tools } = fakeTools();
262
+ const ok = await reasoner.decide(blockIntent("block.move", { direction: "up" }), tools);
263
+ expect(ok.ok).toBe(true);
264
+ expect(ok.ops.find((o) => o.op === "move")).toMatchObject({ direction: "up" });
265
+
266
+ const byIndex = await reasoner.decide(blockIntent("block.move", { direction: 2 }), tools);
267
+ expect(byIndex.ok).toBe(false);
268
+ expect(byIndex.reason).toContain("up");
269
+ });
270
+
271
+ // A reasoner that had to hand back rendered markup for a move would be a second renderer, which is
272
+ // the one thing this design refuses.
273
+ test("no block op carries markup", async () => {
274
+ const { tools } = fakeTools();
275
+ for (const [action, payload] of [
276
+ ["block.remove", {}], ["block.span", { span: "half" }], ["block.move", { direction: "down" }],
277
+ ] as const) {
278
+ const d = await reasoner.decide(blockIntent(action, payload), tools);
279
+ for (const op of d.ops.filter((o) => ["remove", "span", "move"].includes(o.op)))
280
+ expect(op.html).toBeUndefined();
281
+ }
282
+ });