@tjakoen/grain 0.1.12

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 (181) hide show
  1. package/LICENSE +202 -0
  2. package/PLAN.md +27 -0
  3. package/README.md +243 -0
  4. package/ai/accepts.test.ts +69 -0
  5. package/ai/accepts.ts +57 -0
  6. package/ai/ai.css +127 -0
  7. package/ai/client-door.test.ts +70 -0
  8. package/ai/client-door.ts +56 -0
  9. package/ai/contract.test.ts +158 -0
  10. package/ai/contract.ts +285 -0
  11. package/ai/interaction-layer.test.ts +270 -0
  12. package/ai/interaction-layer.ts +138 -0
  13. package/ai/manifest-dom.test.ts +176 -0
  14. package/ai/manifest-dom.ts +187 -0
  15. package/ai/manifest.test.ts +71 -0
  16. package/ai/manifest.ts +57 -0
  17. package/ai/markdown.test.ts +68 -0
  18. package/ai/markdown.ts +74 -0
  19. package/ai/model-chat.test.ts +131 -0
  20. package/ai/model-chat.ts +151 -0
  21. package/ai/model-reasoner.test.ts +152 -0
  22. package/ai/model-reasoner.ts +146 -0
  23. package/ai/model.test.ts +148 -0
  24. package/ai/model.ts +200 -0
  25. package/ai/reasoner-kit.test.ts +142 -0
  26. package/ai/reasoner-kit.ts +159 -0
  27. package/ai/reasoner.test.ts +227 -0
  28. package/ai/reasoner.ts +446 -0
  29. package/ai/timeline-log.test.ts +55 -0
  30. package/ai/timeline-log.ts +50 -0
  31. package/ai/vocab-reference.test.ts +43 -0
  32. package/ai/vocab-reference.ts +107 -0
  33. package/ai/webllm.test.ts +79 -0
  34. package/ai/webllm.ts +125 -0
  35. package/assets/figure-sample.svg +14 -0
  36. package/assets/sprite.svg +22 -0
  37. package/catalog/catalog.test.ts +37 -0
  38. package/catalog/catalog.ts +424 -0
  39. package/components/atoms/action-badge/action-badge.css +17 -0
  40. package/components/atoms/action-badge/action-badge.html +6 -0
  41. package/components/atoms/action-badge/action-badge.md +23 -0
  42. package/components/atoms/b-badge/b-badge.css +15 -0
  43. package/components/atoms/b-badge/b-badge.html +2 -0
  44. package/components/atoms/b-badge/b-badge.md +16 -0
  45. package/components/atoms/b-button/b-button.ai.md +22 -0
  46. package/components/atoms/b-button/b-button.css +87 -0
  47. package/components/atoms/b-button/b-button.html +5 -0
  48. package/components/atoms/b-button/b-button.md +77 -0
  49. package/components/atoms/b-icon/b-icon.css +10 -0
  50. package/components/atoms/b-icon/b-icon.html +5 -0
  51. package/components/atoms/b-icon/b-icon.md +36 -0
  52. package/components/atoms/b-icon-button/b-icon-button.ai.md +11 -0
  53. package/components/atoms/b-icon-button/b-icon-button.css +43 -0
  54. package/components/atoms/b-icon-button/b-icon-button.html +8 -0
  55. package/components/atoms/b-icon-button/b-icon-button.md +33 -0
  56. package/components/atoms/b-input/b-input.css +36 -0
  57. package/components/atoms/b-input/b-input.html +8 -0
  58. package/components/atoms/b-input/b-input.md +59 -0
  59. package/components/atoms/b-kbd/b-kbd.css +11 -0
  60. package/components/atoms/b-kbd/b-kbd.html +3 -0
  61. package/components/atoms/b-kbd/b-kbd.md +13 -0
  62. package/components/atoms/b-list/b-list.css +21 -0
  63. package/components/atoms/b-list/b-list.html +6 -0
  64. package/components/atoms/b-list/b-list.md +24 -0
  65. package/components/atoms/b-meter/b-meter.css +39 -0
  66. package/components/atoms/b-meter/b-meter.md +44 -0
  67. package/components/atoms/b-select/b-select.css +35 -0
  68. package/components/atoms/b-select/b-select.md +75 -0
  69. package/components/atoms/b-switch/b-switch.css +61 -0
  70. package/components/atoms/b-switch/b-switch.html +6 -0
  71. package/components/atoms/b-switch/b-switch.md +40 -0
  72. package/components/atoms/b-text/b-text.ai.md +29 -0
  73. package/components/atoms/b-text/b-text.css +2 -0
  74. package/components/atoms/b-text/b-text.html +3 -0
  75. package/components/atoms/b-text/b-text.md +23 -0
  76. package/components/atoms/code-block/code-block.css +42 -0
  77. package/components/atoms/code-block/code-block.md +23 -0
  78. package/components/examples.test.ts +23 -0
  79. package/components/molecules/callout/callout.css +19 -0
  80. package/components/molecules/callout/callout.md +15 -0
  81. package/components/molecules/card/card.css +28 -0
  82. package/components/molecules/card/card.md +30 -0
  83. package/components/molecules/chat-message/chat-message.css +83 -0
  84. package/components/molecules/chat-message/chat-message.md +52 -0
  85. package/components/molecules/chip-group/chip-group.css +35 -0
  86. package/components/molecules/chip-group/chip-group.md +42 -0
  87. package/components/molecules/content-index/content-index.css +87 -0
  88. package/components/molecules/content-index/content-index.md +27 -0
  89. package/components/molecules/content-source/content-source.css +6 -0
  90. package/components/molecules/content-source/content-source.md +13 -0
  91. package/components/molecules/figure/figure.css +19 -0
  92. package/components/molecules/figure/figure.md +20 -0
  93. package/components/molecules/lede/lede.css +17 -0
  94. package/components/molecules/lede/lede.md +17 -0
  95. package/components/molecules/made-with/made-with.css +25 -0
  96. package/components/molecules/made-with/made-with.md +35 -0
  97. package/components/molecules/nav-item/nav-item.css +19 -0
  98. package/components/molecules/nav-item/nav-item.md +21 -0
  99. package/components/molecules/stat-tile/stat-tile.css +34 -0
  100. package/components/molecules/stat-tile/stat-tile.md +50 -0
  101. package/components/molecules/status-list/status-list.css +47 -0
  102. package/components/molecules/status-list/status-list.md +62 -0
  103. package/components/molecules/tab/tab.css +32 -0
  104. package/components/molecules/tab/tab.md +27 -0
  105. package/components/molecules/table/table.css +23 -0
  106. package/components/molecules/table/table.md +18 -0
  107. package/components/organisms/activity-bar/activity-bar.css +36 -0
  108. package/components/organisms/activity-bar/activity-bar.md +43 -0
  109. package/components/organisms/app-shell/app-shell.css +193 -0
  110. package/components/organisms/app-shell/app-shell.md +58 -0
  111. package/components/organisms/app-shell/app-shell.test.ts +74 -0
  112. package/components/organisms/app-window/app-window.css +111 -0
  113. package/components/organisms/app-window/app-window.md +53 -0
  114. package/components/organisms/chat-log/chat-log.css +5 -0
  115. package/components/organisms/chat-log/chat-log.md +14 -0
  116. package/components/organisms/code-editor/code-editor.ai.md +31 -0
  117. package/components/organisms/code-editor/code-editor.css +111 -0
  118. package/components/organisms/code-editor/code-editor.md +122 -0
  119. package/components/organisms/console/console.css +112 -0
  120. package/components/organisms/console/console.md +66 -0
  121. package/components/organisms/file-tree/file-tree.css +85 -0
  122. package/components/organisms/file-tree/file-tree.md +49 -0
  123. package/components/organisms/note/note.css +19 -0
  124. package/components/organisms/note/note.md +20 -0
  125. package/components/organisms/notepad/notepad.css +60 -0
  126. package/components/organisms/notepad/notepad.md +40 -0
  127. package/components/organisms/side-rail/side-rail.css +55 -0
  128. package/components/organisms/side-rail/side-rail.md +24 -0
  129. package/components/organisms/sidebar-panel/sidebar-panel.css +69 -0
  130. package/components/organisms/sidebar-panel/sidebar-panel.md +47 -0
  131. package/components/organisms/status-bar/status-bar.css +33 -0
  132. package/components/organisms/status-bar/status-bar.md +28 -0
  133. package/components/organisms/tab-bar/tab-bar.css +48 -0
  134. package/components/organisms/tab-bar/tab-bar.md +26 -0
  135. package/components/organisms/timeline/timeline.css +51 -0
  136. package/components/organisms/timeline/timeline.md +42 -0
  137. package/components/organisms/topbar/topbar.css +8 -0
  138. package/components/organisms/topbar/topbar.md +26 -0
  139. package/components/responsive-polish.test.ts +43 -0
  140. package/components/tokens.test.ts +39 -0
  141. package/fonts/redaction-35-400.woff2 +0 -0
  142. package/fonts/redaction-400.woff2 +0 -0
  143. package/fonts/redaction-50-400.woff2 +0 -0
  144. package/fonts/redaction-70-400.woff2 +0 -0
  145. package/package.json +46 -0
  146. package/scripts/ai-dispatch.js +583 -0
  147. package/scripts/ai-dispatch.test.ts +85 -0
  148. package/scripts/ai-spotlight.d.ts +23 -0
  149. package/scripts/ai-spotlight.js +139 -0
  150. package/scripts/ai-spotlight.test.ts +31 -0
  151. package/scripts/catalog-peek.js +156 -0
  152. package/scripts/catalog-peek.test.ts +31 -0
  153. package/scripts/cmdk.js +159 -0
  154. package/scripts/demo-box.js +53 -0
  155. package/scripts/handoff.js +64 -0
  156. package/scripts/handoff.test.ts +36 -0
  157. package/scripts/lightbox.js +144 -0
  158. package/scripts/lightbox.test.ts +23 -0
  159. package/scripts/made-with.d.ts +2 -0
  160. package/scripts/made-with.js +22 -0
  161. package/scripts/made-with.test.ts +25 -0
  162. package/scripts/notepad.js +100 -0
  163. package/scripts/shell.js +204 -0
  164. package/scripts/shell.test.ts +50 -0
  165. package/scripts/tabs.js +127 -0
  166. package/scripts/tabs.test.ts +40 -0
  167. package/scripts/terminal.js +271 -0
  168. package/scripts/terminal.test.ts +36 -0
  169. package/scripts/theme-boot.js +15 -0
  170. package/scripts/theme.js +87 -0
  171. package/scripts/type-effect.js +25 -0
  172. package/scripts/xray.js +79 -0
  173. package/scripts/xray.test.ts +43 -0
  174. package/styles/cmdk.css +65 -0
  175. package/styles/global.css +80 -0
  176. package/styles/grain.css +47 -0
  177. package/styles/lightbox.css +78 -0
  178. package/styles/themes/_template.css +48 -0
  179. package/styles/themes/baguette.css +30 -0
  180. package/styles/themes/brioche.css +30 -0
  181. package/styles/variables.css +217 -0
@@ -0,0 +1,146 @@
1
+ // grain/ai/model-reasoner.ts — a REAL reasoner built on the transport-agnostic core (model.ts).
2
+ //
3
+ // The stub (reasoner.ts) is scripted choreography; this is the M★ shape: on a natural-language turn it
4
+ // reads the LIVE manifest, asks a `Model` to pick ONE move in the vocabulary, VALIDATES that move
5
+ // against the contract + the on-screen surfaces (model.ts), then executes it through the SAME kit
6
+ // op-builders the stub dogfoods (reasoner-kit.ts) — so a real model and the stub emit byte-identical
7
+ // markup. Any `Model` plugs in (local WebLLM, a cloud API, a test fake): the reasoner is
8
+ // transport-agnostic, exactly as the human asked ("grain needs to be flexible").
9
+ //
10
+ // The manifest is supplied by a PROVIDER the composition root injects — in the browser
11
+ // `() => domManifest(document)`, on a server the built manifest — so grain stays DOM-free and the
12
+ // transport/wiring stays the root's choice (the same principle as the OpChannel + client-door seams).
13
+ //
14
+ // CLIENT-SAFE (§19.2): pure imports (the core, the kit, the contract), no DOM, no secrets.
15
+
16
+ import type { Intent, Decision, RenderOp } from "./contract.ts";
17
+ import { surfaceId } from "./contract.ts";
18
+ import type { Reasoner, ReasonTools } from "./reasoner.ts";
19
+ import type { Manifest } from "./manifest.ts";
20
+ import { manifestToText } from "./manifest-dom.ts";
21
+ import { buildReasonerPrompt, parseModelMove, validateMove, type Model, type ValidatedMove } from "./model.ts";
22
+ import {
23
+ esc, userMessageOp, aiBubbleOp, typeToken, settleOp, replaceBodyOp,
24
+ noteAppendOp, noteReplaceOp, navigateOp,
25
+ } from "./reasoner-kit.ts";
26
+
27
+ export interface ModelReasonerOptions {
28
+ /** The model the reasoner asks to decide — any transport (local, cloud, fake) behind the port. */
29
+ model: Model;
30
+ /** Read the CURRENT live manifest. The composition root supplies this (browser: domManifest(document);
31
+ * server: the built manifest) so grain stays DOM-free + transport-agnostic. Called per turn, so the
32
+ * model always reasons over what's on screen RIGHT NOW — including inView.readable state. */
33
+ manifest: () => Manifest;
34
+ /** Per-character cadence (ms) for the visible reply stream. 0 (default) streams instantly — used in
35
+ * tests; a UI passes a small value so the reply types out like the stub's. */
36
+ thinkMs?: number;
37
+ }
38
+
39
+ const TYPE_MS = 24; // per-character while typing the reply out (only applied when thinkMs > 0)
40
+
41
+ /** Build a Reasoner that decides via a `Model`. A natural-language turn (chat.send / say.set with text)
42
+ * goes to the model; any other verb is a control the human already chose, so it's executed directly
43
+ * (still validated against the contract). Reply-shaped verbs the model can't structurally act on
44
+ * (demo.run, say.stream) fall through to a spoken reply. */
45
+ export function makeModelReasoner(opts: ModelReasonerOptions): Reasoner {
46
+ const { model, manifest } = opts;
47
+ const thinkMs = opts.thinkMs ?? 0;
48
+ let seq = 0; // unique id per streamed AI chat bubble
49
+
50
+ /** Stream text into a surface one code point at a time (kit ops), then settle it clean. */
51
+ async function stream(surface: string, text: string, tools: ReasonTools): Promise<void> {
52
+ for (const ch of [...text]) {
53
+ if (tools.cancelled()) break;
54
+ if (thinkMs > 0) await tools.delay(TYPE_MS);
55
+ tools.emit(typeToken(surface, ch));
56
+ }
57
+ tools.emit(settleOp(surface));
58
+ }
59
+
60
+ /** Execute a VALIDATED move: perform its structural effect (if any) through the kit, then stream the
61
+ * human-facing reply into `replyTarget` (a chat bubble body, or the reflection line). `navigate` is
62
+ * emitted LAST — it's terminal for the page, so the reply is seen first. */
63
+ async function execute(move: ValidatedMove, tools: ReasonTools, replyTarget: string | null): Promise<Decision> {
64
+ const structural: RenderOp[] = [];
65
+ let terminal: RenderOp | null = null;
66
+
67
+ switch (move.action) {
68
+ case "note.append": structural.push(noteAppendOp(String(move.payload.text), "ai")); break;
69
+ case "note.replace": structural.push(noteReplaceOp(String(move.payload.text), "ai")); break;
70
+ case "navigate": terminal = navigateOp(move.target, String(move.payload.href)); break;
71
+ case "item.archive": {
72
+ await tools.archiveItem(surfaceId(move.target));
73
+ structural.push({ target: move.target, op: "replace", html: await tools.renderSurface(move.target),
74
+ provenance: "ai", commit: "committed" });
75
+ break;
76
+ }
77
+ // action null (reply-only) or a reply-shaped verb: the effect IS the reply, streamed below.
78
+ default: break;
79
+ }
80
+
81
+ for (const op of structural) tools.emit(op);
82
+ if (replyTarget) {
83
+ if (move.reply) await stream(replyTarget, move.reply, tools);
84
+ else tools.emit(settleOp(replyTarget)); // never leave an opened bubble blank
85
+ }
86
+ if (terminal) tools.emit(terminal);
87
+
88
+ return { ok: true, ops: [], reply: move.reply }; // ops all emitted inline (streaming pattern)
89
+ }
90
+
91
+ /** The agentic entry: a human message → the model picks + we execute one move. */
92
+ async function decideFromMessage(intent: Intent, tools: ReasonTools, message: string): Promise<Decision> {
93
+ const m = manifest();
94
+
95
+ // chat.send shows the human's message, then opens an AI bubble to stream the reply into. say.set
96
+ // writes straight back into the reflection surface it targeted (no chat bubble).
97
+ let replyTarget: string;
98
+ let bubble = false;
99
+ if (intent.action === "chat.send") {
100
+ tools.emit(userMessageOp(intent.surface, message));
101
+ replyTarget = `chat-msg:${++seq}`;
102
+ tools.emit(aiBubbleOp(intent.surface, replyTarget));
103
+ bubble = true;
104
+ } else {
105
+ replyTarget = intent.surface;
106
+ }
107
+
108
+ const fail = (human: string, reason: string): Decision => {
109
+ // don't leave an opened bubble blank — replace its body with the message; else flash the surface.
110
+ const op: RenderOp = bubble
111
+ ? replaceBodyOp(replyTarget, esc(human), "committed")
112
+ : { target: intent.surface, op: "flash", message: human, provenance: "system", commit: "committed" };
113
+ return { ok: false, reason, ops: [op] };
114
+ };
115
+
116
+ let raw: string;
117
+ try { raw = await model.complete(buildReasonerPrompt(manifestToText(m), message)); }
118
+ catch (e) { return fail("The model didn't respond — try again.", `model.complete threw: ${String(e)}`); }
119
+
120
+ const parsed = parseModelMove(raw);
121
+ if (!parsed.ok) return fail("I couldn't read that decision.", parsed.reason);
122
+ const valid = validateMove(parsed.move, m);
123
+ if (!valid.ok) return fail("I couldn't do that here.", valid.reason);
124
+
125
+ return execute(valid.move, tools, replyTarget);
126
+ }
127
+
128
+ return {
129
+ async decide(intent: Intent, tools: ReasonTools): Promise<Decision> {
130
+ const message = String(intent.payload?.text ?? "").trim();
131
+
132
+ if ((intent.action === "chat.send" || intent.action === "say.set") && message)
133
+ return decideFromMessage(intent, tools, message);
134
+
135
+ // A direct verb the human already chose (a control click). No model judgment needed — validate
136
+ // the intent as a move against the live manifest, then execute it. (The door already checked the
137
+ // verb exists + the surface KIND accepts it; validateMove adds target + payload checks.)
138
+ const m = manifest();
139
+ const valid = validateMove({ action: intent.action, target: intent.surface, payload: intent.payload }, m);
140
+ if (!valid.ok)
141
+ return { ok: false, reason: valid.reason,
142
+ ops: [{ target: intent.surface, op: "flash", message: "Can't do that here.", provenance: "system", commit: "committed" }] };
143
+ return execute(valid.move, tools, null);
144
+ },
145
+ };
146
+ }
@@ -0,0 +1,148 @@
1
+ // grain/ai/model.test.ts — UNIT: the transport-agnostic reasoning core (the M★ seam).
2
+ // Every piece is a pure function, so the whole brain is exercised with no browser + no network: a
3
+ // fake `Model` (canned completion) proves the prompt→parse→validate pipeline turns a model's raw
4
+ // output into a safe, contract-legal move — and REJECTS anything the vocabulary doesn't allow.
5
+ import { test, expect } from "bun:test";
6
+ import { buildReasonerPrompt, parseModelMove, validateMove, validTargetsFor, type Model } from "./model.ts";
7
+ import { buildManifest, type Manifest } from "./manifest.ts";
8
+ import type { ManifestTarget } from "./manifest.ts";
9
+
10
+ const targets: ManifestTarget[] = [
11
+ { id: "notepad", kind: "notepad", accepts: ["note.append", "note.replace"] },
12
+ { id: "chat-log", kind: "chat-log", accepts: ["chat.send"] },
13
+ { id: "item:ITM-1", kind: "item", accepts: ["item.archive"] },
14
+ ];
15
+ const manifest: Manifest = buildManifest("loop", targets, { surfaces: targets.map((t) => t.id), readable: [] });
16
+
17
+ // ── the Model port is satisfiable by a trivial fake — no SDK, no network ──────────────────────────
18
+ test("Model port: a fake completion satisfies the boundary", async () => {
19
+ const fake: Model = { complete: async () => '{"action":null,"reply":"hi"}' };
20
+ expect(await fake.complete("anything")).toContain("reply");
21
+ });
22
+
23
+ // ── buildReasonerPrompt ───────────────────────────────────────────────────────────────────────
24
+ test("buildReasonerPrompt: deterministic, embeds the manifest + message + output contract", () => {
25
+ const p1 = buildReasonerPrompt("MANIFEST-TEXT", "plan my thursday");
26
+ const p2 = buildReasonerPrompt("MANIFEST-TEXT", "plan my thursday");
27
+ expect(p1).toBe(p2); // deterministic
28
+ expect(p1).toContain("MANIFEST-TEXT");
29
+ expect(p1).toContain("plan my thursday");
30
+ expect(p1).toContain("ONLY a JSON object"); // the output contract
31
+ expect(p1).toContain("ONE move"); // the one-door rule
32
+ });
33
+
34
+ test("buildReasonerPrompt: blank message falls back to 'decide from what's in view'", () => {
35
+ expect(buildReasonerPrompt("M", " ")).toContain("decide from what's in view");
36
+ });
37
+
38
+ // ── parseModelMove ──────────────────────────────────────────────────────────────────────────────
39
+ test("parseModelMove: clean JSON parses", () => {
40
+ const r = parseModelMove('{"action":"note.append","target":"notepad","payload":{"text":"hi"}}');
41
+ expect(r).toEqual({ ok: true, move: { action: "note.append", target: "notepad", payload: { text: "hi" } } });
42
+ });
43
+
44
+ test("parseModelMove: pulls JSON out of prose + code fences", () => {
45
+ const raw = 'Sure! Here is my move:\n```json\n{"action":"chat.send","target":"chat-log","payload":{"text":"yo"}}\n```\nHope that helps.';
46
+ const r = parseModelMove(raw);
47
+ expect(r.ok).toBe(true);
48
+ if (r.ok) expect(r.move.action).toBe("chat.send");
49
+ });
50
+
51
+ test("parseModelMove: a brace inside a string doesn't break balance matching", () => {
52
+ const r = parseModelMove('{"action":null,"reply":"use {curly} braces"}');
53
+ expect(r.ok).toBe(true);
54
+ if (r.ok) expect(r.move.reply).toBe("use {curly} braces");
55
+ });
56
+
57
+ test("parseModelMove: no JSON / malformed JSON → informative failure", () => {
58
+ expect(parseModelMove("I refuse to answer")).toEqual({ ok: false, reason: "model returned no JSON object" });
59
+ expect(parseModelMove('{"action": oops}')).toMatchObject({ ok: false });
60
+ });
61
+
62
+ test("parseModelMove: a JSON array is rejected (must be an object)", () => {
63
+ expect(parseModelMove('[1,2,3]')).toMatchObject({ ok: false });
64
+ });
65
+
66
+ // ── validateMove: the safety boundary ─────────────────────────────────────────────────────────
67
+ test("validateMove: a legal act move passes, payload kept", () => {
68
+ const r = validateMove({ action: "note.append", target: "notepad", payload: { text: "buy milk" } }, manifest);
69
+ expect(r).toEqual({ ok: true, move: { action: "note.append", target: "notepad", payload: { text: "buy milk" }, reply: undefined } });
70
+ });
71
+
72
+ test("validateMove: a reply-only move (action null) with text passes", () => {
73
+ const r = validateMove({ action: null, reply: "I'm here — what next?" }, manifest);
74
+ expect(r).toEqual({ ok: true, move: { action: null, target: "", payload: {}, reply: "I'm here — what next?" } });
75
+ });
76
+
77
+ test("validateMove: reply-only with no reply is rejected", () => {
78
+ expect(validateMove({ action: null }, manifest)).toMatchObject({ ok: false });
79
+ });
80
+
81
+ test("validateMove: a hallucinated verb is rejected as unknown", () => {
82
+ const r = validateMove({ action: "task.nuke", target: "notepad" }, manifest);
83
+ expect(r).toMatchObject({ ok: false });
84
+ if (!r.ok) expect(r.reason).toContain("unknown verb");
85
+ });
86
+
87
+ test("validateMove: an unafforded verb on a real surface echoes the valid targets", () => {
88
+ const r = validateMove({ action: "chat.send", target: "notepad", payload: { text: "x" } }, manifest);
89
+ expect(r).toMatchObject({ ok: false });
90
+ if (!r.ok) {
91
+ expect(r.reason).toContain("does not accept chat.send");
92
+ expect(r.reason).toContain("chat-log"); // the surface that DOES accept it, echoed back
93
+ }
94
+ });
95
+
96
+ test("validateMove: an unknown target is rejected", () => {
97
+ const r = validateMove({ action: "note.append", target: "ghost", payload: { text: "x" } }, manifest);
98
+ expect(r).toMatchObject({ ok: false });
99
+ if (!r.ok) expect(r.reason).toContain("no surface");
100
+ });
101
+
102
+ test("validateMove: an acting verb with no target is rejected", () => {
103
+ expect(validateMove({ action: "note.append", payload: { text: "x" } }, manifest)).toMatchObject({ ok: false });
104
+ });
105
+
106
+ test("validateMove: a missing required payload field is rejected", () => {
107
+ const r = validateMove({ action: "note.append", target: "notepad", payload: {} }, manifest);
108
+ expect(r).toMatchObject({ ok: false });
109
+ if (!r.ok) expect(r.reason).toContain("missing required field");
110
+ });
111
+
112
+ test("validateMove: a wrong-typed payload field is rejected", () => {
113
+ const r = validateMove({ action: "note.append", target: "notepad", payload: { text: 42 } }, manifest);
114
+ expect(r).toMatchObject({ ok: false });
115
+ if (!r.ok) expect(r.reason).toContain("must be string");
116
+ });
117
+
118
+ test("validateMove: extra payload fields are dropped, not fatal", () => {
119
+ const r = validateMove({ action: "note.append", target: "notepad", payload: { text: "ok", evil: "drop me" } }, manifest);
120
+ expect(r.ok).toBe(true);
121
+ if (r.ok) expect(r.move.payload).toEqual({ text: "ok" }); // only the schema-declared field survives
122
+ });
123
+
124
+ test("validateMove: a no-arg verb needs no payload", () => {
125
+ const r = validateMove({ action: "item.archive", target: "item:ITM-1" }, manifest);
126
+ expect(r).toEqual({ ok: true, move: { action: "item.archive", target: "item:ITM-1", payload: {}, reply: undefined } });
127
+ });
128
+
129
+ test("validTargetsFor: lists every surface that accepts the verb", () => {
130
+ expect(validTargetsFor("note.append", manifest)).toEqual(["notepad"]);
131
+ expect(validTargetsFor("item.archive", manifest)).toEqual(["item:ITM-1"]);
132
+ });
133
+
134
+ // ── the pipeline end-to-end with a fake model ─────────────────────────────────────────────────
135
+ test("pipeline: fake model → parse → validate yields a safe move", async () => {
136
+ const model: Model = {
137
+ complete: async (prompt) => {
138
+ expect(prompt).toContain("What's operable right now"); // the prompt carried the manifest
139
+ return 'Thinking… {"action":"note.append","target":"notepad","payload":{"text":"remember the milk"}}';
140
+ },
141
+ };
142
+ const raw = await model.complete(buildReasonerPrompt("MANIFEST", "note the milk"));
143
+ const parsed = parseModelMove(raw);
144
+ expect(parsed.ok).toBe(true);
145
+ if (!parsed.ok) return;
146
+ const valid = validateMove(parsed.move, manifest);
147
+ expect(valid).toEqual({ ok: true, move: { action: "note.append", target: "notepad", payload: { text: "remember the milk" }, reply: undefined } });
148
+ });
package/ai/model.ts ADDED
@@ -0,0 +1,200 @@
1
+ // grain/ai/model.ts — the MODEL PORT + the transport-agnostic reasoning CORE (the M★ seam).
2
+ //
3
+ // The stub (reasoner.ts) is choreography over hardcoded surfaces. A REAL reasoner instead READS the
4
+ // manifest a page advertises (manifest-dom.ts / manifestForReasoner — now including inView.readable),
5
+ // asks a model to pick ONE move in the vocabulary, and VALIDATES that move against the contract before
6
+ // it ever becomes an Intent. This module is that brain — and it is deliberately TRANSPORT-AGNOSTIC:
7
+ // it depends on a `Model` PORT, never a concrete SDK. A local in-browser model (WebLLM/WebGPU), a
8
+ // cloud API (Claude), or a test fake all satisfy the port; selecting WHICH is the composition root's
9
+ // choice, exactly like the OpChannel transport (contract.ts §"the substrate PORT"). That's what keeps
10
+ // grain flexible: one reasoning core, many models.
11
+ //
12
+ // CLIENT-SAFE (ARCHITECTURE §19.2): pure, relative imports only, no DOM, no secrets. The pieces here
13
+ // (prompt build, parse, validate) are all pure functions so the whole core is unit-testable with a
14
+ // fake `Model` — no browser, no network. Turning a validated move into RenderOps (the side-effecting
15
+ // half) lives in the reasoner that composes this core, not here.
16
+
17
+ import { ACTIONS, isAction, type ActionName, type PayloadField } from "./contract.ts";
18
+ import type { Manifest } from "./manifest.ts";
19
+
20
+ // ── the model boundary ─────────────────────────────────────────────────────────────────────────
21
+ /** The model PORT — grain depends on this, never a concrete SDK. `complete` turns a prompt into raw
22
+ * completion text; the core parses + validates it (a model can't be trusted to emit only legal moves,
23
+ * so trust is established HERE, not assumed of the model). A streaming model can still satisfy this
24
+ * by resolving once its final text is assembled — token-level streaming of the human-facing reply is
25
+ * the composing reasoner's concern, not the port's. */
26
+ export interface Model {
27
+ complete(prompt: string): Promise<string>;
28
+ }
29
+
30
+ // ── the structured move a model must return ─────────────────────────────────────────────────────
31
+ /** ONE move in the vocabulary, as the model returns it (JSON). `action:null` (or absent) with a
32
+ * `reply` is a legal "just talk, don't act" move — the model isn't forced to touch the UI to answer.
33
+ * Everything here is UNTRUSTED until `validateMove` checks it against the contract + live manifest. */
34
+ export interface ModelMove {
35
+ action?: string | null; // an ActionName, or null/absent for a reply-only move
36
+ target?: string; // a surface address (required when action acts)
37
+ payload?: Record<string, unknown>; // the verb's args
38
+ reply?: string; // conversational text streamed back to the human (optional)
39
+ }
40
+
41
+ /** A move that has passed validation: `action` is a real ActionName targeting a real, accepting
42
+ * surface with a schema-valid payload — ready to become an Intent — OR a reply-only move
43
+ * (`action:null`). Either way it's safe for the reasoner to act on without re-checking. */
44
+ export interface ValidatedMove {
45
+ action: ActionName | null;
46
+ target: string;
47
+ payload: Record<string, unknown>;
48
+ reply?: string;
49
+ }
50
+
51
+ // ── the prompt ──────────────────────────────────────────────────────────────────────────────────
52
+ // EXPORTED so a chat-engine adapter (model-chat.ts) can lift the preamble into a `system` message —
53
+ // the prompt is built as `SYSTEM_PREAMBLE + "\n\n" + <manifest/message/contract>`, so a `startsWith`
54
+ // split recovers the two halves exactly.
55
+ export const SYSTEM_PREAMBLE =
56
+ "You operate a UI through ONE door: you may only choose from the vocabulary below. Every surface " +
57
+ "is addressed by a stable id; every verb lists the payload it needs and behaviour hints (read-only " +
58
+ "/ destructive / idempotent). Read `in view` for the current state before deciding. Choose EXACTLY " +
59
+ "ONE move: either act (pick an action + a target that accepts it + its payload), or reply without " +
60
+ "acting (action: null). Never invent a verb, a target, or a field that isn't listed.";
61
+
62
+ const OUTPUT_CONTRACT =
63
+ 'Respond with ONLY a JSON object, no prose, no code fence:\n' +
64
+ '{"action": "<verb or null>", "target": "<surface id or omit>", ' +
65
+ '"payload": { /* the verb\'s fields, or omit */ }, "reply": "<optional message to the human>"}';
66
+
67
+ /** Compose the reasoner prompt: the contract preamble, the live manifest (the exact text
68
+ * `manifestForReasoner()` emits — the move set + targets + `in view` readable state), the human's
69
+ * message, and the required JSON output shape. Pure + deterministic: same inputs → same string, so
70
+ * it's testable and cache-friendly. The manifest is passed IN (not harvested here) so this stays
71
+ * DOM-free and the caller controls which projection (server or live-DOM) the model sees. */
72
+ export function buildReasonerPrompt(manifestText: string, message: string): string {
73
+ return [
74
+ SYSTEM_PREAMBLE,
75
+ "",
76
+ "# What's operable right now",
77
+ manifestText,
78
+ "",
79
+ "# The human's message",
80
+ message.trim() || "(no message — decide from what's in view)",
81
+ "",
82
+ "# Your response",
83
+ OUTPUT_CONTRACT,
84
+ ].join("\n");
85
+ }
86
+
87
+ // ── parsing the model's output ──────────────────────────────────────────────────────────────────
88
+ /** Pull the first balanced JSON object out of raw model text and parse it. Models wrap JSON in prose
89
+ * or ```json fences despite instructions, so we scan for the first `{` and match to its closing `}`
90
+ * (bracket-depth, string-aware) rather than trusting the whole string to be clean JSON. Returns a
91
+ * ModelMove on success or an informative reason on failure — the reason feeds the same
92
+ * informative-rejection path a bad human intent takes (interaction-layer.ts), so a model can be told
93
+ * WHY its output was unusable and retry. */
94
+ export function parseModelMove(raw: string): { ok: true; move: ModelMove } | { ok: false; reason: string } {
95
+ const json = extractJsonObject(raw);
96
+ if (json === null) return { ok: false, reason: "model returned no JSON object" };
97
+ let parsed: unknown;
98
+ try { parsed = JSON.parse(json); }
99
+ catch { return { ok: false, reason: "model returned malformed JSON" }; }
100
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
101
+ return { ok: false, reason: "model output is not a JSON object" };
102
+ return { ok: true, move: parsed as ModelMove };
103
+ }
104
+
105
+ /** Scan for the first `{` and return the substring through its matching `}`, respecting string
106
+ * literals + escapes so a brace inside a JSON string doesn't throw off the depth count. null if
107
+ * there's no balanced object. */
108
+ function extractJsonObject(raw: string): string | null {
109
+ const start = raw.indexOf("{");
110
+ if (start === -1) return null;
111
+ let depth = 0, inStr = false, escaped = false;
112
+ for (let i = start; i < raw.length; i++) {
113
+ const ch = raw[i];
114
+ if (inStr) {
115
+ if (escaped) escaped = false;
116
+ else if (ch === "\\") escaped = true;
117
+ else if (ch === '"') inStr = false;
118
+ continue;
119
+ }
120
+ if (ch === '"') inStr = true;
121
+ else if (ch === "{") depth++;
122
+ else if (ch === "}" && --depth === 0) return raw.slice(start, i + 1);
123
+ }
124
+ return null;
125
+ }
126
+
127
+ // ── validating the move against the contract + the live manifest ─────────────────────────────────
128
+ /** Turn an UNTRUSTED ModelMove into a ValidatedMove or an informative rejection. This is the safety
129
+ * boundary: the model can PROPOSE anything, but only moves that are legal in the vocabulary AND
130
+ * legal on THIS page's surfaces survive. Checks, in order:
131
+ * - a reply-only move (action null/absent) is legal iff it carries a non-empty reply;
132
+ * - the action must be a real ActionName (registry), else "unknown verb";
133
+ * - the target must be a surface the manifest lists AND that accepts this verb, else the valid
134
+ * targets are named back (so the model can self-correct — the same echo a human rejection gets);
135
+ * - the payload must satisfy the verb's schema: every required field present + every provided field
136
+ * the right primitive type. Unknown extra fields are dropped, not fatal.
137
+ * The registry (ACTIONS) is the SSOT for verbs + payload shape; the live manifest is the SSOT for
138
+ * which targets accept a verb RIGHT NOW — so this never drifts from what's on screen. */
139
+ export function validateMove(
140
+ move: ModelMove,
141
+ manifest: Manifest,
142
+ ): { ok: true; move: ValidatedMove } | { ok: false; reason: string } {
143
+ const action = move.action ?? null;
144
+
145
+ // reply-only: the model chose to talk, not act.
146
+ if (action === null) {
147
+ const reply = (move.reply ?? "").trim();
148
+ if (!reply) return { ok: false, reason: "reply-only move carries no reply text" };
149
+ return { ok: true, move: { action: null, target: "", payload: {}, reply } };
150
+ }
151
+
152
+ if (typeof action !== "string" || !isAction(action))
153
+ return { ok: false, reason: `unknown verb ${JSON.stringify(action)} — not in the vocabulary` };
154
+
155
+ const target = typeof move.target === "string" ? move.target : "";
156
+ if (!target) return { ok: false, reason: `verb ${action} needs a target surface` };
157
+
158
+ const surface = manifest.targets.find((t) => t.id === target);
159
+ if (!surface)
160
+ return { ok: false, reason: `no surface ${JSON.stringify(target)} on this screen` };
161
+ if (!surface.accepts.includes(action)) {
162
+ const valid = validTargetsFor(action, manifest);
163
+ const echo = valid.length ? ` — ${action} applies to: ${valid.join(", ")}` : ` — nothing here accepts ${action}`;
164
+ return { ok: false, reason: `surface ${target} does not accept ${action}${echo}` };
165
+ }
166
+
167
+ const rawPayload = (move.payload && typeof move.payload === "object" && !Array.isArray(move.payload))
168
+ ? move.payload as Record<string, unknown> : {};
169
+ const checked = checkPayload(ACTIONS[action].payload, rawPayload);
170
+ if (!checked.ok) return checked;
171
+
172
+ return { ok: true, move: { action, target, payload: checked.payload, reply: (move.reply ?? "").trim() || undefined } };
173
+ }
174
+
175
+ /** Every target on the current screen that accepts `action` — named back on a rejection so the model
176
+ * can retry against a real surface (the manifest is the SSOT, so this can't drift). */
177
+ export function validTargetsFor(action: ActionName, manifest: Manifest): string[] {
178
+ return manifest.targets.filter((t) => t.accepts.includes(action)).map((t) => t.id);
179
+ }
180
+
181
+ /** Validate a payload against a verb's schema: required fields present, provided fields the right
182
+ * primitive type. Returns only the SCHEMA-DECLARED fields (extras dropped — a model padding the bag
183
+ * can't smuggle anything past the door). */
184
+ function checkPayload(
185
+ schema: Record<string, PayloadField>,
186
+ raw: Record<string, unknown>,
187
+ ): { ok: true; payload: Record<string, unknown> } | { ok: false; reason: string } {
188
+ const out: Record<string, unknown> = {};
189
+ for (const [name, field] of Object.entries(schema)) {
190
+ const has = Object.hasOwn(raw, name) && raw[name] !== null && raw[name] !== undefined;
191
+ if (!has) {
192
+ if (field.required) return { ok: false, reason: `payload missing required field ${JSON.stringify(name)} (${field.type})` };
193
+ continue;
194
+ }
195
+ if (typeof raw[name] !== field.type)
196
+ return { ok: false, reason: `payload field ${JSON.stringify(name)} must be ${field.type}, got ${typeof raw[name]}` };
197
+ out[name] = raw[name];
198
+ }
199
+ return { ok: true, payload: out };
200
+ }
@@ -0,0 +1,142 @@
1
+ // grain/ai/reasoner-kit.test.ts — the exported reasoner primitives. These are the shapes a
2
+ // consumer's real model composes with (and the stub dogfoods), so pin their contract.
3
+ import { test, expect, describe } from "bun:test";
4
+ import {
5
+ esc, chatBubble, chatBody, narrationLine, thinkingDots, choiceGroup,
6
+ userMessageOp, aiBubbleOp, typeToken, settleOp, replaceBodyOp, narrateOp, spotlightOp, navigateOp, fillOp,
7
+ thinkingOp, choicesOp,
8
+ notepadEntry, notepadBody, noteAppendOp, noteReplaceOp,
9
+ renderMarkdown,
10
+ } from "./reasoner-kit.ts";
11
+
12
+ describe("markup", () => {
13
+ test("esc neutralizes HTML metacharacters", () => {
14
+ expect(esc(`<b>"x"&`)).toBe("&lt;b&gt;&quot;x&quot;&amp;");
15
+ });
16
+ test("chatBubble carries role + grade + who", () => {
17
+ expect(chatBubble("ai", "grain", "<i>hi</i>", "Desk"))
18
+ .toBe('<div class="chat-message" data-role="ai" data-grade="grain"><span class="chat-message__who">Desk</span><i>hi</i></div>');
19
+ expect(chatBubble("you", "", "x")).toContain('data-role="you"');
20
+ expect(chatBubble("you", "", "x")).not.toContain("data-grade");
21
+ });
22
+ test("chatBody adds data-surface only when streaming", () => {
23
+ expect(chatBody("hi")).toBe('<span class="chat-message__body">hi</span>');
24
+ expect(chatBody("", "chat-msg:1")).toBe('<span class="chat-message__body" data-surface="chat-msg:1"></span>');
25
+ });
26
+ test("narrationLine renders an action badge + escaped desc", () => {
27
+ expect(narrationLine("reads", "a <note>")).toContain('<span class="action-badge">reads</span>');
28
+ expect(narrationLine("reads", "a <note>")).toContain("a &lt;note&gt;");
29
+ });
30
+ });
31
+
32
+ describe("op-builders", () => {
33
+ test("userMessageOp: committed human bubble on the log (escapes input)", () => {
34
+ const op = userMessageOp("chat-log", `<script>`);
35
+ expect(op).toMatchObject({ target: "chat-log", op: "append", provenance: "user", commit: "committed" });
36
+ expect(op.html).toContain('data-role="you"');
37
+ expect(op.html).toContain("&lt;script&gt;");
38
+ });
39
+ test("aiBubbleOp: pending grain bubble with a streamable surface", () => {
40
+ const op = aiBubbleOp("chat-log", "chat-msg:1", "Desk");
41
+ expect(op).toMatchObject({ provenance: "ai", commit: "pending" });
42
+ expect(op.html).toContain('data-surface="chat-msg:1"');
43
+ expect(op.html).toContain("Desk");
44
+ });
45
+ test("typeToken → pending, settleOp → committed done", () => {
46
+ expect(typeToken("chat-msg:1", "hel")).toMatchObject({ op: "type", text: "hel", commit: "pending" });
47
+ expect(settleOp("chat-msg:1")).toMatchObject({ op: "type", done: true, commit: "committed" });
48
+ });
49
+ test("replaceBodyOp keeps the surface so later ops still land", () => {
50
+ expect(replaceBodyOp("chat-msg:1", "done", "committed").html).toContain('data-surface="chat-msg:1"');
51
+ });
52
+ test("narrateOp defaults to the console push-surface", () => {
53
+ expect(narrateOp("reads", "x")).toMatchObject({ target: "console", op: "append" });
54
+ });
55
+ test("spotlightOp: active pends, release commits", () => {
56
+ expect(spotlightOp("screen", { active: true, click: true })).toMatchObject({ op: "spotlight", active: true, click: true, commit: "pending" });
57
+ expect(spotlightOp("screen", { active: false })).toMatchObject({ op: "spotlight", active: false, commit: "committed" });
58
+ });
59
+ test("navigateOp: a same-origin path becomes a committed navigate op", () => {
60
+ expect(navigateOp("screen", "/notes")).toMatchObject({ target: "screen", op: "navigate", href: "/notes", commit: "committed" });
61
+ });
62
+ test("navigateOp: an unsafe href throws here, at compose time — not later, silently, at the dispatcher", () => {
63
+ expect(() => navigateOp("screen", "javascript:alert(1)")).toThrow();
64
+ expect(() => navigateOp("screen", "https://evil.example")).toThrow();
65
+ });
66
+ test("fillOp: a safe value becomes a committed ai fill op — the value persists for human review", () => {
67
+ expect(fillOp("field:contact-message", "Hi TJ — about grain."))
68
+ .toMatchObject({ target: "field:contact-message", op: "fill", text: "Hi TJ — about grain.", provenance: "ai", commit: "committed" });
69
+ });
70
+ test("fillOp: an unsafe value throws here, at compose time — not later, silently, at the dispatcher", () => {
71
+ expect(() => fillOp("field:contact-message", "x".repeat(2001))).toThrow();
72
+ expect(() => fillOp("field:contact-message", "null\x00byte")).toThrow();
73
+ });
74
+ test("renderMarkdown is re-exported from the kit (same module ai/markdown.ts exports)", () => {
75
+ expect(renderMarkdown("**hi**")).toContain("<strong>hi</strong>");
76
+ });
77
+
78
+ test("thinkingDots is a labelled, animatable indicator", () => {
79
+ const d = thinkingDots();
80
+ expect(d).toContain('class="chat-thinking"');
81
+ expect(d).toContain('aria-label="Thinking"');
82
+ expect((d.match(/<span><\/span>/g) ?? []).length).toBe(3); // three dots
83
+ });
84
+ test("thinkingOp replaces the bubble body pending, keeping the surface for later ops", () => {
85
+ const op = thinkingOp("chat-msg:1");
86
+ expect(op).toMatchObject({ op: "replace", commit: "pending", target: "chat-msg:1" });
87
+ expect(op.html).toContain("chat-thinking");
88
+ expect(op.html).toContain('data-surface="chat-msg:1"');
89
+ });
90
+
91
+ test("choiceGroup: each option is a chat.send trigger carrying its own value; reuses the actionable-dialog row", () => {
92
+ const html = choiceGroup("chat-log", [{ label: "GRAIN", value: "take me to grain" }, { label: "Notes" }]);
93
+ expect(html).toContain('class="chat-message__actions" data-choices'); // reuses the existing dialog idiom
94
+ expect(html).toContain('data-action="chat.send"');
95
+ expect(html).toContain('data-target="chat-log"');
96
+ expect(html).toContain('data-payload-text="take me to grain"');
97
+ expect(html).toContain('data-payload-text="Notes"'); // value defaults to label
98
+ expect(html).toContain(">GRAIN</button>");
99
+ });
100
+ test("choiceGroup escapes both label and value at the single writer", () => {
101
+ const html = choiceGroup("chat-log", [{ label: `<b>x</b>`, value: `"&<` }]);
102
+ expect(html).not.toContain("<b>x</b>");
103
+ expect(html).toContain("&lt;b&gt;x&lt;/b&gt;");
104
+ expect(html).toContain("&quot;&amp;&lt;");
105
+ });
106
+ test("choicesOp: a committed AI bubble (the ask is the AI's finished turn) carrying the prompt + choices", () => {
107
+ const op = choicesOp("chat-log", "Where to?", [{ label: "Home", value: "go home" }]);
108
+ expect(op).toMatchObject({ op: "choices", target: "chat-log", commit: "committed", provenance: "ai" });
109
+ expect(op.choices).toEqual([{ label: "Home", value: "go home" }]);
110
+ expect(op.html).toContain('data-grade="grain"'); // the ask is AI speech → grain
111
+ expect(op.html).toContain("Where to?");
112
+ expect(op.html).toContain('data-payload-text="go home"');
113
+ });
114
+ });
115
+
116
+ describe("notepad markup + ops (DEMO-PLAN piece 2)", () => {
117
+ test("notepadEntry (ai): grain grade, markdown source in data-md, rendered body", () => {
118
+ const h = notepadEntry("**hi** there", "ai");
119
+ expect(h).toContain('data-grade="grain"'); // AI provenance persists as grain
120
+ expect(h).toContain('data-md="**hi** there"'); // the SOURCE, for round-trip to localStorage
121
+ expect(h).toContain("<strong>hi</strong>"); // the rendered projection for the eye
122
+ });
123
+ test("notepadEntry (human commit): clean ink, no grade", () => {
124
+ expect(notepadEntry("mine", "user")).not.toContain("data-grade");
125
+ });
126
+ test("notepadEntry escapes source + render so a note can never inject markup", () => {
127
+ const h = notepadEntry("<script>x</script>", "ai");
128
+ expect(h).not.toContain("<script>"); // neither in data-md nor the body
129
+ });
130
+ test("notepadBody carries the notepad-body surface so a replace stays addressable", () => {
131
+ expect(notepadBody("x")).toContain('data-surface="notepad-body"');
132
+ });
133
+ test("noteAppendOp: committed append to notepad-body, grade follows provenance", () => {
134
+ expect(noteAppendOp("a", "ai")).toMatchObject({ target: "notepad-body", op: "append", provenance: "ai", commit: "committed" });
135
+ expect(noteAppendOp("a", "user").html).not.toContain("data-grade");
136
+ });
137
+ test("noteReplaceOp: rebuilds the body wrapper via a replace op", () => {
138
+ const op = noteReplaceOp("a", "user");
139
+ expect(op).toMatchObject({ target: "notepad-body", op: "replace", provenance: "user", commit: "committed" });
140
+ expect(op.html).toContain('data-surface="notepad-body"');
141
+ });
142
+ });