@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
package/ai/ai.css ADDED
@@ -0,0 +1,127 @@
1
+ /* grain/ai/ai.css — the AI-interaction MODULE's styling: the "AI is acting" spotlight.
2
+ Optional: include this ONLY when you use GRAIN's AI interface. The design system
3
+ (grain/styles/grain.css + the b-* atoms) works without it. (AI-INTERFACE §5c) */
4
+
5
+ /* When the AI (not the user) drives a surface, the page dims and a LAMP — one traveling
6
+ frame — glides onto the touched surface. Calm, monochrome, no shadows on content. */
7
+ /* THE LAMP MODEL (the root design): the spotlight is ONE fixed-position element whose rect
8
+ glides between surfaces; the dim is the lamp's own cutout shadow, so hole and veil travel
9
+ together. The lit element is NEVER restyled — a rect is a rect, so every surface kind
10
+ (card, list, row, input) gets the same treatment by construction (this designed out the
11
+ old per-kind lit CSS, grain lesson 8). The veil color is ONE theme token, --ai-veil, set
12
+ once in the theme (variables.css) so every page fades the same; the default below (a
13
+ gentle ink dim) applies if a theme doesn't set it. */
14
+ .ai-lamp {
15
+ position: fixed; top: 0; left: 0; z-index: var(--z-ai-veil, 9000);
16
+ border-radius: var(--radius-md); /* no border — the lamp is just the lit hole in the veil */
17
+ /* the dim IS the lamp's shadow: everything outside the frame recedes, and it MOVES with it */
18
+ box-shadow: 0 0 0 200vmax var(--ai-veil, color-mix(in srgb, var(--ink) 22%, transparent));
19
+ opacity: 0; pointer-events: none;
20
+ /* the focus-switch glide — the lamp EASES onto the new surface, soft start and landing,
21
+ like a page transition (keep the duration ≤ the reasoner's SETTLE so it lands before
22
+ the AI acts). Travel rides `transform` (composited — GPU, never janked by layout);
23
+ only the box's size interpolates in layout, and it's one element. */
24
+ transform: translate3d(50vw, 50vh, 0);
25
+ will-change: transform; /* transform only — promoting width/height forces extra invalidations */
26
+ transition: opacity 0.35s ease,
27
+ transform var(--ai-focus-move, 0.4s) var(--ai-focus-ease, ease),
28
+ width var(--ai-focus-move, 0.4s) var(--ai-focus-ease, ease),
29
+ height var(--ai-focus-move, 0.4s) var(--ai-focus-ease, ease);
30
+ }
31
+ .ai-lamp.is-on { opacity: 1; }
32
+ /* The click-catcher: invisible (the lamp's shadow carries the dim) but it still owns the
33
+ interrupt gesture — clicking anywhere while the AI acts asks it to stop. AI surfaces that
34
+ stay live during a run (chat, console, the acting label) sit above it at --z-ai-surface. */
35
+ .ai-backdrop {
36
+ position: fixed; inset: 0; z-index: var(--z-ai-veil, 9000);
37
+ background: transparent; pointer-events: none;
38
+ }
39
+ .ai-backdrop.is-on { pointer-events: auto; }
40
+ /* .ai-spotlit stays as the SEMANTIC marker for the surface under the lamp (tests, per-kind
41
+ data-attr logic in the dispatcher) — it carries no visual of its own in the lamp model. */
42
+ /* scroll-margin gives the lit surface breathing room from the scroll region's top/bottom edges
43
+ when the dispatcher scrolls it into view (block:"start") — so it never butts the top bar. */
44
+ .ai-spotlit { position: relative; scroll-margin-top: var(--space-4); scroll-margin-bottom: var(--space-4); }
45
+ /* the "AI clicked here" pulse. Self-sufficient: .is-click alone renders it (position:relative
46
+ anchors its own ::before), so pulsing never silently no-ops for want of a sibling .ai-spotlit.
47
+ (.ai-spotlit already establishes a positioned context, so spotlit elements are unaffected.) */
48
+ .is-click { position: relative; }
49
+ .is-click::before { /* ::before so it never collides with a button's ::after caret */
50
+ content: ""; position: absolute; inset: -4px;
51
+ border: 1px solid var(--ink); border-radius: inherit;
52
+ animation: ai-click 0.5s ease-out;
53
+ pointer-events: none;
54
+ }
55
+ @keyframes ai-click { from { transform: scale(1); opacity: 0.7; } to { transform: scale(1.12); opacity: 0; } }
56
+ .ai-acting-label {
57
+ position: fixed; top: var(--space-4); left: 50%; transform: translateX(-50%); z-index: var(--z-ai-surface, 9002);
58
+ font-family: var(--font-grain); font-size: var(--text-sm); color: var(--ink);
59
+ background: var(--paper); border: var(--border); border-radius: var(--radius-sm);
60
+ padding: var(--space-1) var(--space-3);
61
+ }
62
+
63
+ /* interrupt confirm — "ask the AI to stop?" (mediated, never a force-kill).
64
+ A native modal <dialog>: top-layer, focus-trap, Escape-to-close come free. The bare
65
+ element is transparent (the spotlight backdrop already dims); only the card shows. */
66
+ .ai-confirm { border: 0; padding: 0; background: transparent; opacity: 0; transition: opacity 0.18s ease; }
67
+ .ai-confirm[open] { opacity: 1; }
68
+ @starting-style { .ai-confirm[open] { opacity: 0; } } /* fade in from display:none */
69
+ .ai-confirm::backdrop { background: transparent; } /* the .ai-backdrop beneath already provides the dim */
70
+ .ai-confirm__card {
71
+ background: var(--paper); border: 1px solid var(--ink); border-radius: var(--radius-md);
72
+ padding: var(--space-5); max-width: 24rem; text-align: center;
73
+ }
74
+ .ai-confirm__msg { margin: 0 0 var(--space-4); }
75
+ .ai-confirm__actions { display: flex; gap: var(--space-3); justify-content: center; }
76
+
77
+ @media (prefers-reduced-motion: reduce) {
78
+ .ai-lamp { transition: none; }
79
+ .ai-confirm { transition: none; }
80
+ .is-click::before { animation: none; display: none; }
81
+ }
82
+
83
+ /* ---- X-RAY: see the page as the AI sees it (grain/scripts/xray.js) --------------------
84
+ A dev-mode overlay: outline every operable surface and label it with kind + accepted
85
+ verbs. Purely presentational — xray.js sets `data-xray` on <html> and stamps each
86
+ [data-surface] with a `data-xray-label`; this draws them. Tokens only, so it re-skins
87
+ with the theme. It's the visual twin of the terminal's `context` command. */
88
+ html[data-xray] [data-surface] {
89
+ outline: 1px dashed var(--color-accent, var(--ink));
90
+ outline-offset: 2px;
91
+ position: relative; /* anchor the label; dev-mode only (may shift abs-positioned children) */
92
+ }
93
+ html[data-xray] [data-surface]::after {
94
+ content: attr(data-xray-label);
95
+ position: absolute; top: 0; right: 0; z-index: var(--z-ai-surface, 9002);
96
+ font-family: var(--font-grain); font-size: var(--text-xs); line-height: 1;
97
+ padding: var(--space-1) var(--space-2);
98
+ color: var(--color-accent, var(--ink));
99
+ background: var(--color-bg, var(--paper));
100
+ border: 1px solid var(--color-line, var(--ink));
101
+ border-radius: var(--radius-sm);
102
+ pointer-events: none; white-space: nowrap;
103
+ }
104
+
105
+ /* ---- honest presence (the AI-online indicator) ---------------------------------------
106
+ The dispatcher stamps <body data-ai-online="true|false"> by OUTCOME (server `ready`
107
+ handshake received / client door actually loaded — ai-dispatch.js). A consumer's presence
108
+ indicator shows three states: waking (default, nothing reported yet), online, offline.
109
+ The wording inside the spans is the consumer's. */
110
+ .presence__on, .presence__off { display: none; }
111
+ body[data-ai-online] .presence__wait { display: none; }
112
+ body[data-ai-online="true"] .presence__on { display: inline; }
113
+ body[data-ai-online="false"] .presence__off { display: inline; }
114
+ /* the presence STAR is its own element (so its color tracks transport health, apart from the
115
+ wording): muted while waking, the accent hue when online, faint when offline. */
116
+ .presence__star { color: var(--color-muted); }
117
+ body[data-ai-online="true"] .presence__star { color: var(--color-accent); }
118
+ body[data-ai-online="false"] .presence__star { color: var(--ink-faint); }
119
+
120
+ /* ---- presence GATING: when the door's reply channel is down, AI controls are visibly
121
+ disabled (not silently dead). Consumers mark AI-only controls [data-ai-run] (a trigger that
122
+ drives the AI) or [data-ai-gate] (a composer/region gated on the AI). The dispatcher also
123
+ no-ops submit() when offline (belt-and-braces) — this is the honest visual half. */
124
+ body[data-ai-online="false"] [data-ai-run],
125
+ body[data-ai-online="false"] [data-ai-gate] {
126
+ pointer-events: none; opacity: 0.5; cursor: not-allowed;
127
+ }
@@ -0,0 +1,70 @@
1
+ // grain/ai/client-door.test.ts — UNIT: the browser-composed door (§19.3). Same layer, loopback
2
+ // channel: ops must reach applyOp directly, the /grain demo must run service-free, and provenance
3
+ // must be the AI's — the client transport changes the wire, never the contract.
4
+ import { test, expect, describe } from "bun:test";
5
+ import { createClientDoor } from "./client-door.ts";
6
+ import type { Intent, RenderOp } from "./contract.ts";
7
+
8
+ const intent = (over: Partial<Intent> = {}): Intent => ({
9
+ source: "user", session: "s1", screen: "grain", surface: "screen",
10
+ action: "demo.run", payload: {}, ...over,
11
+ });
12
+
13
+ describe("createClientDoor", () => {
14
+ test("demo.run on the grain screen loops ops straight into applyOp — no service, no wire", async () => {
15
+ const ops: RenderOp[] = [];
16
+ const door = createClientDoor((op) => ops.push(op), { thinkMs: 0 });
17
+ const decision = await door.handleIntent(intent());
18
+ expect(decision.ok).toBe(true);
19
+ expect(ops.length).toBeGreaterThan(0);
20
+ // every AI-authored op keeps AI provenance (grade doctrine: AI text stays grain)
21
+ expect(ops.some((o) => o.provenance === "ai")).toBe(true);
22
+ // the run releases: the last spotlight op must switch OFF (lesson 7 — always release)
23
+ const spots = ops.filter((o) => o.op === "spotlight");
24
+ expect(spots.length).toBeGreaterThan(0);
25
+ expect(spots[spots.length - 1]?.active).toBe(false);
26
+ });
27
+
28
+ test("validation still guards the door: unknown action is rejected with a system flash", async () => {
29
+ const ops: RenderOp[] = [];
30
+ const door = createClientDoor((op) => ops.push(op), { thinkMs: 0 });
31
+ const decision = await door.handleIntent(intent({ action: "not.a.verb" as Intent["action"] }));
32
+ expect(decision.ok).toBe(false);
33
+ expect(ops.every((o) => o.provenance !== "ai")).toBe(true);
34
+ });
35
+
36
+ test("field.set works on the client transport: a fill op loops back, committed, ai-provenance", async () => {
37
+ const ops: RenderOp[] = [];
38
+ const door = createClientDoor((op) => ops.push(op), { thinkMs: 0 });
39
+ const decision = await door.handleIntent(intent({ source: "ai", surface: "field:contact-message",
40
+ action: "field.set", payload: { value: "Hi TJ — about grain." } }));
41
+ expect(decision.ok).toBe(true);
42
+ const fill = ops.find((o) => o.op === "fill");
43
+ expect(fill).toMatchObject({ target: "field:contact-message", text: "Hi TJ — about grain.",
44
+ provenance: "ai", commit: "committed" });
45
+ });
46
+
47
+ test("a registered field surface shows up in observe() with field.set as its legal move", () => {
48
+ const door = createClientDoor(() => {}, { thinkMs: 0 });
49
+ const el = (attrs: Record<string, string>) => ({ getAttribute: (n: string) => attrs[n] ?? null, textContent: null });
50
+ const doc = {
51
+ body: el({ "data-screen": "contact" }),
52
+ querySelectorAll: () => [el({ "data-surface": "field:contact-message" })],
53
+ };
54
+ expect(door.observe(doc)).toContain("- field:contact-message [field] -> field.set");
55
+ });
56
+
57
+ test("observe(doc) re-harvests the live-DOM manifest — the 'read the result' half of the loop", () => {
58
+ const door = createClientDoor(() => {}, { thinkMs: 0 });
59
+ // a structural DomDoc fake (the same shape manifest-dom takes) — no browser needed
60
+ const el = (attrs: Record<string, string>) => ({ getAttribute: (n: string) => attrs[n] ?? null, textContent: null });
61
+ const doc = {
62
+ body: el({ "data-screen": "grain" }),
63
+ querySelectorAll: () => [el({ "data-surface": "chat-log" })],
64
+ };
65
+ const text = door.observe(doc);
66
+ expect(text).toContain("screen: grain");
67
+ expect(text).toContain("actions: ("); // the move set is listed
68
+ expect(text).toContain("- chat-log [chat-log] -> chat.send"); // and the live target
69
+ });
70
+ });
@@ -0,0 +1,56 @@
1
+ // grain/ai/client-door.ts — THE DOOR, IN THE BROWSER (ARCHITECTURE §19.3, opt-in). The same
2
+ // createInteractionLayer the server wires, composed for a client with no backend: the SSE OpChannel
3
+ // becomes a LOOPBACK (ops hand straight to the dispatcher's applyOp), POST /intent becomes a direct
4
+ // call. Same vocabulary, same validation, same single writer — a static host runs the full loop.
5
+ //
6
+ // CLIENT-SAFE (§19.2): this module and everything it imports must stay pure — relative imports only
7
+ // (the module server refuses bare imports), no secrets, no server-required behavior. Its reasoner is
8
+ // the stub; its write capabilities are inert, so only the service-free demo scenarios (e.g. the
9
+ // /grain screen's demo.run + chat.send) are honest here. Anything needing real state keeps the
10
+ // server door — selecting the transport is the page/composition root's choice, not grain's.
11
+
12
+ import { createInteractionLayer, type InteractionLayer } from "./interaction-layer.ts";
13
+ import { makeStubReasoner, type StubOptions, type Reasoner } from "./reasoner.ts";
14
+ import { createStreamLogSink } from "./timeline-log.ts";
15
+ import { manifestForReasoner, type DomDoc } from "./manifest-dom.ts";
16
+ import { OP_EVENT, type OpChannel, type RenderOp } from "./contract.ts";
17
+
18
+ export interface ClientDoorOptions extends StubOptions {
19
+ /** Swap the reasoner (e.g. a consumer's scripted scenario, or later a local model). It must be
20
+ * client-safe like everything else here. Default: GRAIN's stub. This is the same seam the
21
+ * server door has — the model arrives into a contract, on either transport. */
22
+ reasoner?: Reasoner;
23
+ }
24
+
25
+ /** The client door is a plain InteractionLayer PLUS an observe() step — the "read the result" half
26
+ * of an in-browser act → observe → decide loop. Because ops loop back synchronously into the DOM,
27
+ * by the time handleIntent resolves the page reflects the change; observe() re-harvests the LIVE
28
+ * DOM manifest so a driving reasoner sees the new state without a server round-trip. */
29
+ export interface ClientDoor extends InteractionLayer {
30
+ /** Re-harvest the live-DOM manifest as prompt-ready text (the same shape `manifestForReasoner`
31
+ * emits). The document is a PARAMETER, not the global — so this module needs no DOM lib and
32
+ * stays client-safe on the shared build (like `manifest-dom.ts`). In the browser, pass
33
+ * `document`; in a test, a structural `DomDoc` fake. */
34
+ observe(doc: DomDoc): string;
35
+ }
36
+
37
+ /** Wire the door for the browser: ops loop back synchronously into the given renderer (the
38
+ * dispatcher's applyOp). Returns a ClientDoor — the same InteractionLayer the server exposes (so
39
+ * the dispatcher treats both transports identically) plus observe() for an agentic driver. */
40
+ export function createClientDoor(applyOp: (op: RenderOp) => void, opts: ClientDoorOptions = {}): ClientDoor {
41
+ const { reasoner, ...reasonerOpts } = opts;
42
+ const loopback: OpChannel = {
43
+ push: (_session, event, data) => { if (event === OP_EVENT) applyOp(data as RenderOp); },
44
+ };
45
+ const layer = createInteractionLayer({
46
+ reasoner: reasoner ?? makeStubReasoner(reasonerOpts),
47
+ stream: loopback,
48
+ logSink: createStreamLogSink(loopback), // the timeline works on the client transport too (§5g)
49
+ // Inert capabilities: no storage exists client-side. The service-free scenarios never call
50
+ // these; if a future scenario does, renderSurface's empty string renders nothing rather than
51
+ // faking committed state — the honest failure mode for a demo transport.
52
+ archiveItem: async () => {},
53
+ renderSurface: async () => "",
54
+ });
55
+ return { ...layer, observe: (doc) => manifestForReasoner(doc) };
56
+ }
@@ -0,0 +1,158 @@
1
+ // grain/ai/contract.test.ts — CONFORMANCE: the `navigate` verb (CLAUDE.md lesson #5 — "if you
2
+ // keep getting something wrong, the contract is unclear... add a conformance test that catches
3
+ // misuse"). Pins three things a real consumer reasoner depends on: the verb is registered in the
4
+ // closed ACTIONS vocabulary (so it shows up in the manifest, see manifest-dom.test.ts), an
5
+ // unsafe/external href is rejected, and a same-origin root-relative one is accepted.
6
+ import { test, expect, describe } from "bun:test";
7
+ import { ACTIONS, isAction, actionsForKind, isSafeNavigateHref, isValidChoiceList, isSafeFieldValue, FIELD_VALUE_CAP } from "./contract.ts";
8
+
9
+ describe("navigate: registered in the closed ACTIONS vocabulary", () => {
10
+ test("is a real action, light depth, accepts the screen kind", () => {
11
+ expect(isAction("navigate")).toBe(true);
12
+ expect(ACTIONS.navigate).toMatchObject({ name: "navigate", depth: "light", accepts: ["screen"] });
13
+ });
14
+ test("actionsForKind('screen') includes it — so the manifest surfaces it as legal", () => {
15
+ expect(actionsForKind("screen")).toContain("navigate");
16
+ });
17
+ });
18
+
19
+ describe("note.append / note.replace: the notepad verbs", () => {
20
+ test("both are real actions, light depth, accept the notepad kind", () => {
21
+ expect(isAction("note.append")).toBe(true);
22
+ expect(isAction("note.replace")).toBe(true);
23
+ expect(ACTIONS["note.append"]).toMatchObject({ name: "note.append", depth: "light", accepts: ["notepad"] });
24
+ expect(ACTIONS["note.replace"]).toMatchObject({ name: "note.replace", depth: "light", accepts: ["notepad"] });
25
+ });
26
+ test("actionsForKind('notepad') surfaces both — the manifest advertises them on the pad", () => {
27
+ const acts = actionsForKind("notepad");
28
+ expect(acts).toContain("note.append");
29
+ expect(acts).toContain("note.replace");
30
+ });
31
+ });
32
+
33
+ describe("payload schema + description: every verb advertises how to call it", () => {
34
+ test("each ACTIONS entry declares a non-empty description and a payload object", () => {
35
+ for (const def of Object.values(ACTIONS)) {
36
+ expect(typeof def.description).toBe("string");
37
+ expect(def.description.trim().length).toBeGreaterThan(0);
38
+ expect(typeof def.payload).toBe("object");
39
+ for (const field of Object.values(def.payload)) {
40
+ expect(["string", "number", "boolean"]).toContain(field.type);
41
+ expect(typeof field.required).toBe("boolean");
42
+ }
43
+ }
44
+ });
45
+ test("text verbs require a text field; navigate requires an href; no-arg verbs are empty", () => {
46
+ expect(ACTIONS["chat.send"].payload.text).toMatchObject({ type: "string", required: true });
47
+ expect(ACTIONS["note.append"].payload.text).toMatchObject({ type: "string", required: true });
48
+ expect(ACTIONS.navigate.payload.href).toMatchObject({ type: "string", required: true });
49
+ expect(ACTIONS["item.archive"].payload).toEqual({});
50
+ expect(ACTIONS["say.stream"].payload).toEqual({});
51
+ });
52
+ });
53
+
54
+ describe("hints: MCP-style behaviour annotations for safe choice + retry", () => {
55
+ test("every verb declares a hints object", () => {
56
+ for (const def of Object.values(ACTIONS)) expect(typeof def.hints).toBe("object");
57
+ });
58
+ test("note.replace is destructive + idempotent; note.append is neither (additive)", () => {
59
+ expect(ACTIONS["note.replace"].hints).toMatchObject({ destructive: true, idempotent: true });
60
+ expect(ACTIONS["note.append"].hints.destructive).toBeUndefined();
61
+ expect(ACTIONS["note.append"].hints.idempotent).toBeUndefined();
62
+ });
63
+ test("navigate + desk.stop are read-only (no persisted-state mutation)", () => {
64
+ expect(ACTIONS.navigate.hints.readOnly).toBe(true);
65
+ expect(ACTIONS["desk.stop"].hints.readOnly).toBe(true);
66
+ });
67
+ test("item.archive is idempotent — a replay is a harmless no-op", () => {
68
+ expect(ACTIONS["item.archive"].hints.idempotent).toBe(true);
69
+ });
70
+ });
71
+
72
+ describe("isSafeNavigateHref: same-origin, root-relative only", () => {
73
+ test.each([
74
+ ["/", true],
75
+ ["/notes", true],
76
+ ["/notes/some-slug", true],
77
+ ["/notes?x=1#y", true],
78
+ ])("%s -> %s (valid, same-origin root-relative)", (href, expected) => {
79
+ expect(isSafeNavigateHref(href)).toBe(expected);
80
+ });
81
+
82
+ test.each([
83
+ ["https://evil.example", false],
84
+ ["http://evil.example", false],
85
+ ["//evil.example", false], // protocol-relative
86
+ ["javascript:alert(1)", false], // no leading "/" — never executable
87
+ ["data:text/html,<script>", false],
88
+ ["mailto:a@b.com", false],
89
+ ["/\\evil.example", false], // backslash-as-slash browser quirk
90
+ ["", false],
91
+ ["not-a-path", false],
92
+ ["/has space", false],
93
+ ])("%s -> %s (rejected)", (href, expected) => {
94
+ expect(isSafeNavigateHref(href)).toBe(expected);
95
+ });
96
+
97
+ test("rejects non-string values without throwing", () => {
98
+ expect(isSafeNavigateHref(undefined as unknown as string)).toBe(false);
99
+ expect(isSafeNavigateHref(null as unknown as string)).toBe(false);
100
+ expect(isSafeNavigateHref(42 as unknown as string)).toBe(false);
101
+ });
102
+ });
103
+
104
+ describe("field.set: registered in the closed ACTIONS vocabulary (plans/field-set-op.md)", () => {
105
+ test("is a real action, light depth, accepts the field kind, requires value:string", () => {
106
+ expect(isAction("field.set")).toBe(true);
107
+ expect(ACTIONS["field.set"]).toMatchObject({ name: "field.set", depth: "light", accepts: ["field"] });
108
+ expect(ACTIONS["field.set"].payload.value).toMatchObject({ type: "string", required: true });
109
+ });
110
+ test("actionsForKind('field') surfaces it — the manifest advertises it on registered fields", () => {
111
+ expect(actionsForKind("field")).toContain("field.set");
112
+ });
113
+ test("destructive + idempotent — it REPLACES a field's value; same value → same end state", () => {
114
+ expect(ACTIONS["field.set"].hints).toMatchObject({ destructive: true, idempotent: true });
115
+ });
116
+ test("no submit verb exists — the AI-never-submits guarantee is structural", () => {
117
+ for (const name of Object.keys(ACTIONS)) expect(name).not.toMatch(/submit/i);
118
+ });
119
+ });
120
+
121
+ describe("isSafeFieldValue: plain text, capped, no control chars", () => {
122
+ test("accepts plain text, newlines + tabs (a textarea needs both), and exactly the cap", () => {
123
+ expect(isSafeFieldValue("Hi TJ — I want to talk about grain.")).toBe(true);
124
+ expect(isSafeFieldValue("line one\nline two\tindented")).toBe(true);
125
+ expect(isSafeFieldValue("x".repeat(FIELD_VALUE_CAP))).toBe(true);
126
+ expect(isSafeFieldValue("")).toBe(true); // shape-safe; an EMPTY prefill is the reasoner's call to reject
127
+ });
128
+ test("rejects over-cap and control characters", () => {
129
+ expect(isSafeFieldValue("x".repeat(FIELD_VALUE_CAP + 1))).toBe(false);
130
+ expect(isSafeFieldValue("null\x00byte")).toBe(false);
131
+ expect(isSafeFieldValue("bell\x07")).toBe(false);
132
+ expect(isSafeFieldValue("esc\x1b[31m")).toBe(false);
133
+ expect(isSafeFieldValue("vt\x0b")).toBe(false);
134
+ });
135
+ test("rejects non-string values without throwing", () => {
136
+ expect(isSafeFieldValue(undefined)).toBe(false);
137
+ expect(isSafeFieldValue(null)).toBe(false);
138
+ expect(isSafeFieldValue(42)).toBe(false);
139
+ expect(isSafeFieldValue(["a"])).toBe(false);
140
+ });
141
+ });
142
+
143
+ describe("isValidChoiceList: 1–6 options, each a non-empty label", () => {
144
+ test("accepts well-formed lists (value optional)", () => {
145
+ expect(isValidChoiceList([{ label: "A" }])).toBe(true);
146
+ expect(isValidChoiceList([{ label: "A", value: "go a" }, { label: "B" }])).toBe(true);
147
+ expect(isValidChoiceList([1, 2, 3, 4, 5, 6].map((n) => ({ label: `opt${n}` })))).toBe(true);
148
+ });
149
+ test("rejects empty, oversized, and malformed lists without throwing", () => {
150
+ expect(isValidChoiceList([])).toBe(false); // must offer at least one
151
+ expect(isValidChoiceList([1, 2, 3, 4, 5, 6, 7].map((n) => ({ label: `o${n}` })))).toBe(false); // capped at 6
152
+ expect(isValidChoiceList([{ label: " " }])).toBe(false); // blank label
153
+ expect(isValidChoiceList([{ value: "x" } as unknown])).toBe(false); // missing label
154
+ expect(isValidChoiceList([{ label: "A", value: 3 as unknown }])).toBe(false);// non-string value
155
+ expect(isValidChoiceList("nope" as unknown)).toBe(false);
156
+ expect(isValidChoiceList(null)).toBe(false);
157
+ });
158
+ });