@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/contract.ts ADDED
@@ -0,0 +1,285 @@
1
+ // /app/ai/contract.ts — the action vocabulary contract (see https://tjakoen.github.io/grain/docs/ai-interface).
2
+ //
3
+ // Two closed registries + three envelopes. Both a human interaction and an AI
4
+ // decision become the SAME Intent, flow through the SAME door, and come back as
5
+ // RenderOps addressed to semantic SURFACES. No privileged AI→DOM back channel.
6
+
7
+ // ---- Surfaces: "kind:id" for instances, a bare slug for singleton regions -------
8
+ // SurfaceKind is the CLOSED set of kinds (the "enum", erasable-style: a union, since
9
+ // `enum` is banned by erasableSyntaxOnly). Build addresses with surface(), never by
10
+ // hand-concatenating strings, so a typo is a compile error.
11
+ export type Surface = string; // e.g. "item:ITM-1", "reflection"
12
+ // SurfaceKind is exactly the set of kinds a VERB can accept (they drive `actionsForKind` +
13
+ // the manifest). Push-only DISPLAY surfaces the AI only ever WRITES to — never a verb
14
+ // target — are intentionally NOT kinds: `console` (the takeover narration feed), plus the
15
+ // demo-only render targets `plan` / `summary` / `ask-input`. They're addressed by their
16
+ // bare `data-surface` slug and need no entry here. Add a kind only when a verb accepts it.
17
+ // `notepad` is a verb target (note.append / note.replace) — a persisted markdown surface both
18
+ // the AI and the human write into through the one door; the ops land on its inner `notepad-body`
19
+ // push surface (below), the wrapper `notepad` is what gets spotlit when the AI is the actor.
20
+ // `field` is a registered FORM FIELD (field.set) — text-like only (INPUT of a text-ish type,
21
+ // TEXTAREA); a field is addressable ONLY if the page marked it `data-surface="field:…"`, so
22
+ // refusal on anything else is free (plans/field-set-op.md). The AI prefills; it never submits —
23
+ // structurally: no submit verb exists in the vocabulary.
24
+ export type SurfaceKind = "item" | "reflection" | "say-stream" | "screen" | "chat-log" | "notepad" | "field";
25
+ export const surface = (kind: SurfaceKind, id?: string): Surface => (id ? `${kind}:${id}` : kind);
26
+ export const surfaceKind = (s: Surface): SurfaceKind => (s.split(":")[0] ?? "") as SurfaceKind;
27
+ export const surfaceId = (s: Surface): string => s.split(":").slice(1).join(":");
28
+
29
+ // ---- Actions: the closed verb vocabulary (grows reluctantly) --------------------
30
+ // item.archive — stands in for task.complete (optimistic light path)
31
+ // say.set — input → AI writes back into a reflection line (grain → settles clean)
32
+ // say.stream — button → AI types a line out, token by token, over SSE
33
+ // chat.send — composer → your message (clean) + the AI's reply streamed (grain) into a chat log
34
+ // note.append — add a markdown entry to the notepad (AI writes grain; a human commit settles clean)
35
+ // note.replace — rewrite the whole notepad from one markdown body (same door, same grade rule)
36
+ // navigate — a control (or a reasoner's own decision) asks to change screens; see below
37
+ // field.set — prefill a registered form field with drafted text; the human reviews and
38
+ // submits (the AI never submits — no submit verb exists to call)
39
+ // The full product vocabulary lives at https://tjakoen.github.io/grain/docs/ai-interface.
40
+ export type ActionName =
41
+ | "item.archive" | "say.set" | "say.stream" | "demo.run" | "desk.stop" | "chat.send"
42
+ | "note.append" | "note.replace" | "navigate" | "field.set";
43
+ export type Depth = "light" | "heavy";
44
+
45
+ // ---- Payload schema: the machine-readable INPUT shape a verb expects -------------
46
+ // The registry declares not just WHICH verbs exist and WHERE they apply, but HOW to
47
+ // call each one — the field names, types, and which are required. This is what lets a
48
+ // reasoner (a real model reading the manifest) construct a valid Intent without guessing
49
+ // the payload from prose (the MCP `inputSchema` equivalent; AI-INTERFACE §1b). Kept a
50
+ // tiny closed shape on purpose — a verb's payload is a flat bag of primitives today, so a
51
+ // full JSON-Schema dependency would be more than the contract needs.
52
+ export type PayloadType = "string" | "number" | "boolean";
53
+ export interface PayloadField {
54
+ type: PayloadType;
55
+ required: boolean;
56
+ note?: string; // a short hint for the reasoner (e.g. "markdown", "root-relative path")
57
+ }
58
+ /** A verb's payload schema: field name → its shape. `{}` = a no-argument verb. */
59
+ export type PayloadSchema = Record<string, PayloadField>;
60
+
61
+ // ---- Action hints: the GRAIN analog of MCP's tool annotations ---------------------
62
+ // Safety/behaviour flags a reasoner reads to CHOOSE and RETRY safely — is a verb read-only
63
+ // (changes no persisted state), destructive (overwrites/discards existing content, as opposed
64
+ // to additive), idempotent (same payload → same end state, so a replay is harmless)? All default
65
+ // false/absent; only the flags that actually hold are set. "read-only" means it doesn't mutate
66
+ // persisted app state — navigation and the stop control signal qualify (they change view/run
67
+ // state, not data). These let a local model reason "can I retry this?" without guessing.
68
+ export interface ActionHints {
69
+ readOnly?: boolean;
70
+ destructive?: boolean;
71
+ idempotent?: boolean;
72
+ }
73
+
74
+ export interface ActionDef {
75
+ name: ActionName;
76
+ depth: Depth;
77
+ accepts: SurfaceKind[]; // surface KINDS this verb applies to (typed → no stray kinds)
78
+ description: string; // one line: what the verb does / when to reach for it — surfaced to the reasoner
79
+ payload: PayloadSchema; // the verb's input shape — advertised in the manifest so a model can call it
80
+ hints: ActionHints; // behaviour hints (MCP-style) — so a reasoner chooses + retries safely
81
+ }
82
+
83
+ const REQ = (type: PayloadType, note?: string): PayloadField => ({ type, required: true, note });
84
+
85
+ export const ACTIONS: Record<ActionName, ActionDef> = {
86
+ "item.archive": { name: "item.archive", depth: "light", accepts: ["item"],
87
+ description: "Archive an item (stands in for task.complete on the optimistic light path).",
88
+ payload: {}, hints: { idempotent: true } }, // re-archiving is a harmless no-op
89
+ "say.set": { name: "say.set", depth: "light", accepts: ["reflection"],
90
+ description: "Write a noted line back into a reflection surface.",
91
+ payload: { text: REQ("string") }, hints: { idempotent: true } }, // same text → same line
92
+ "say.stream": { name: "say.stream", depth: "light", accepts: ["say-stream"],
93
+ description: "Stream a reflection line out token by token.",
94
+ payload: {}, hints: { idempotent: true } },
95
+ "demo.run": { name: "demo.run", depth: "heavy", accepts: ["screen"],
96
+ description: "Play a scripted AI-acting demo on the current screen.",
97
+ payload: {}, hints: { idempotent: true } }, // re-runnable: drives demo surfaces, mutates no real state
98
+ "desk.stop": { name: "desk.stop", depth: "light", accepts: ["screen"],
99
+ description: "Ask the AI to halt the current run (mediated — never a force-kill).",
100
+ payload: {}, hints: { readOnly: true, idempotent: true } }, // a control signal, writes no state
101
+ "chat.send": { name: "chat.send", depth: "light", accepts: ["chat-log"],
102
+ description: "Send a chat message; the AI's reply streams back over SSE.",
103
+ payload: { text: REQ("string") }, hints: {} }, // additive — each send adds a new turn (not idempotent)
104
+ "note.append": { name: "note.append", depth: "light", accepts: ["notepad"],
105
+ description: "Append one markdown entry to the notepad.",
106
+ payload: { text: REQ("string", "markdown") }, hints: {} }, // additive — each append adds an entry
107
+ "note.replace": { name: "note.replace", depth: "light", accepts: ["notepad"],
108
+ description: "Rewrite the whole notepad from one markdown body.",
109
+ payload: { text: REQ("string", "markdown") }, hints: { destructive: true, idempotent: true } }, // discards prior pad
110
+ // ActionName AND a RenderOpKind, deliberately BOTH (see the `navigate` RenderOpKind below for why
111
+ // one alone doesn't cover it): registering it here as a "screen" verb is what makes it show up in
112
+ // `actionsForKind("screen")` — and so in the manifest (manifest.ts/manifest-dom.ts) — as something
113
+ // a control (or a reasoner reading the manifest) can see is legal to invoke on the current screen.
114
+ "navigate": { name: "navigate", depth: "light", accepts: ["screen"],
115
+ description: "Change screens — same-origin, root-relative href only (validated at the door).",
116
+ payload: { href: REQ("string", "root-relative path, e.g. /notes") },
117
+ hints: { readOnly: true, idempotent: true } }, // changes view, not persisted state
118
+ "field.set": { name: "field.set", depth: "light", accepts: ["field"],
119
+ description: "Prefill a registered form field with drafted text — the human reviews and submits; the AI never submits.",
120
+ payload: { value: REQ("string", "plain text; replaces the field's current value") },
121
+ hints: { destructive: true, idempotent: true } }, // REPLACES what the field holds (may be human-typed); same value → same end state
122
+ };
123
+
124
+ export const isAction = (s: string): s is ActionName => Object.hasOwn(ACTIONS, s);
125
+
126
+ // `desk.stop` is a CONTROL signal, not a reasoner verb — named once here so the door
127
+ // and the (browser-side) dispatcher agree on the wire string without a magic literal.
128
+ export const STOP_ACTION: ActionName = "desk.stop";
129
+
130
+ // Invert the registry: which verbs apply to a surface kind. Lets the manifest derive
131
+ // a region's accepts from the registry instead of hand-listing them (AI-INTERFACE §4).
132
+ export const actionsForKind = (kind: SurfaceKind): ActionName[] =>
133
+ Object.values(ACTIONS).filter((a) => a.accepts.includes(kind)).map((a) => a.name);
134
+
135
+ // ---- Envelope 1: Intent — every interaction (human OR ai) becomes this ----------
136
+ export interface Intent {
137
+ source: "user" | "ai"; // provenance, stamped at the entrance — never taken from the client.
138
+ // HTTP /intent always stamps "user"; only IN-PROCESS actors raise "ai".
139
+ session: string; // which SSE stream the result is pushed back on
140
+ screen: string; // "check what's in view"
141
+ surface: Surface; // what was touched / referred to
142
+ action: ActionName;
143
+ payload: Record<string, unknown>;
144
+ }
145
+
146
+ // ---- Envelope 2: RenderOp — what the single writer emits, addressed to a surface -
147
+ // replace/append/remove — structural; flash — transient note;
148
+ // type — stream a text token into the target (text), or finish it (done);
149
+ // spotlight — show the AI AS ACTOR: dim everything, light the target, pulse it like a
150
+ // click; `active:false` releases. Driven by AI provenance (AI-INTERFACE §5c).
151
+ // log — append one provenance-tagged entry to the interaction TIMELINE (§5g); the client
152
+ // caps the DOM + pins to newest. The unified human-and-AI log made visible.
153
+ // navigate — change the browser's location (href). The ONLY op that leaves the page, so it's
154
+ // the ONE op the dispatcher validates before acting on (isSafeNavigateHref, below) —
155
+ // every other op only ever touches the DOM the manifest already exposed as addressable.
156
+ // Why a RenderOpKind and not just the `navigate` ActionName above: an ActionName is a
157
+ // REQUEST vocabulary word (what a control may ask the door to do); a RenderOpKind is an
158
+ // EFFECT the single writer (the reasoner) hands back for the dispatcher to apply — and
159
+ // the dispatcher (scripts/ai-dispatch.js) only ever executes RenderOps, never ActionNames
160
+ // directly. So the reasoner handling ANY intent (not only a `navigate` one — e.g. a
161
+ // chat.send reply that decides to route the user somewhere) needs an op it can emit to
162
+ // actually move the browser. Both exist because they answer different questions: "is this
163
+ // verb legal here" (ActionName, surfaced in the manifest) vs "make it happen" (RenderOp,
164
+ // applied by the dispatcher).
165
+ // `choices` — the AI ASKS and the human ANSWERS through a control: an AI chat bubble carrying a
166
+ // short prompt + a row of buttons. It's the mirror of every other op (which is the AI acting on the
167
+ // human's behalf): here the AI hands the decision back. Kept a first-class RenderOpKind, not a bare
168
+ // `append` of button HTML, for the same reason `navigate` is (below): it names a distinct intent the
169
+ // dispatcher renders + wires uniformly (each button is a normal chat.send trigger through the ONE
170
+ // door — no parallel path), and it's conformance-testable as its own vocabulary word.
171
+ // `fill` — atomic whole-value assignment into a registered form field (field.set's effect), matching
172
+ // the verb's payload 1:1 and keeping the op idempotent. A NEW kind on purpose (plans/field-set-op.md):
173
+ // `type`'s INPUT/TEXTAREA branch appends tokens and CLEARS on `done` (composer-submit physics — a
174
+ // prefill must PERSIST for review), and `replace` swaps outerHTML (a field's value is state, not
175
+ // 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";
177
+ export type Provenance = "user" | "ai" | "system";
178
+ export type Commit = "pending" | "committed"; // grade = commit state (DESIGN-SYSTEM §3)
179
+
180
+ /** One option in a `choices` op. `label` is the button text; `value` is the text submitted as the
181
+ * next chat turn when it's picked (defaults to `label`) — so a choice is just a pre-filled ask. */
182
+ export interface Choice { label: string; value?: string }
183
+
184
+ export interface RenderOp {
185
+ target: Surface;
186
+ op: RenderOpKind;
187
+ html?: string; // server-rendered fragment (replace / append / flash)
188
+ text?: string; // a streamed token (type)
189
+ back?: number; // delete the last N chars (type) — the AI REVISING / overwriting
190
+ done?: boolean; // last token of a stream → settle grain to clean (type)
191
+ active?: boolean; // spotlight on (move to target) vs off (release)
192
+ click?: boolean; // spotlight: this is a "click" → pulse the target (else just lift it)
193
+ message?: string; // human-facing note (flash)
194
+ href?: string; // navigate: where to (validated — isSafeNavigateHref, below)
195
+ prompt?: string; // choices: the question shown above the buttons (optional)
196
+ choices?: Choice[]; // choices: the options the human picks from (validated — isValidChoiceList)
197
+ provenance: Provenance;
198
+ commit: Commit;
199
+ }
200
+
201
+ /** A well-formed choice list: 1–6 options, each with a non-empty string label (value optional). The
202
+ * cap keeps a chat dialog scannable; the shape guard is the SSOT the dispatcher's own check mirrors. */
203
+ export const isValidChoiceList = (x: unknown): x is Choice[] =>
204
+ Array.isArray(x) && x.length >= 1 && x.length <= 6 &&
205
+ x.every((c) => !!c && typeof (c as Choice).label === "string" && (c as Choice).label.trim().length > 0 &&
206
+ ((c as Choice).value === undefined || typeof (c as Choice).value === "string"));
207
+
208
+ // ---- navigate's href validator — the SSOT the dispatcher's own guard must never drift from ------
209
+ // Same-origin, ROOT-RELATIVE paths only. Rejects:
210
+ // - any absolute URL ("https://…", "http://…") — external navigation is never AI-directed
211
+ // - a scheme with no "//" ("javascript:…", "data:…", "mailto:…") — never starts with "/"
212
+ // - protocol-relative ("//evil.com") — a second leading "/" is rejected by the lookahead
213
+ // - a leading backslash right after the slash ("/\evil.com") — some browsers treat "\" as "/",
214
+ // which would otherwise smuggle a protocol-relative URL past the "//" check
215
+ // - any whitespace — blocks control-character / smuggling tricks, and no real route needs one
216
+ // A bare "/" (root) is valid. Query strings and hashes are valid ("/notes?x=1#y").
217
+ const SAFE_NAV_HREF = /^\/(?!\/)[^\s\\]*$/;
218
+ export const isSafeNavigateHref = (href: unknown): href is string =>
219
+ typeof href === "string" && SAFE_NAV_HREF.test(href);
220
+
221
+ // ---- field.set's value validator — the SSOT the dispatcher's own guard must never drift from ----
222
+ // A rejection echoes the constraint in Decision.reason (informative rejections, AI-INTERFACE §0),
223
+ // e.g. "field.set value rejected: over 2000 chars" — so a reasoner can shorten and retry.
224
+ /** Cap on a field.set value — a prefill is a message draft, not a document. */
225
+ export const FIELD_VALUE_CAP = 2000;
226
+ /** Plain text only: no C0 control chars except \n and \t (a textarea needs both). */
227
+ const FIELD_VALUE_BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
228
+ export const isSafeFieldValue = (v: unknown): v is string =>
229
+ typeof v === "string" && v.length <= FIELD_VALUE_CAP && !FIELD_VALUE_BAD_CHARS.test(v);
230
+
231
+ // ---- The reasoner's verdict ------------------------------------------------------
232
+ export interface Decision {
233
+ ok: boolean;
234
+ ops: RenderOp[];
235
+ reply?: string; // conversational feedback (chat) — optional
236
+ reason?: string; // trace / failure note
237
+ }
238
+
239
+ // Push-only display surfaces — the AI only ever WRITES to these; no verb accepts them
240
+ // as a kind target. Typed here so a typo is caught at the call site, not silently dropped.
241
+ export const PUSH_SURFACES = {
242
+ console: "console", // takeover narration feed (narrate/clearConsole)
243
+ plan: "plan", // demo plan bullet list
244
+ summary: "summary", // demo summary text
245
+ askInput: "ask-input", // demo ask-input field
246
+ demoTaskBadge: "demo-task-badge",// demo task badge
247
+ timeline: "timeline", // the interaction TIMELINE feed (unified log, §5g) — `log` ops land here
248
+ notepadBody: "notepad-body", // the notepad's inner content — note.append/replace ops land here (the `notepad` wrapper is the verb target + spotlight surface)
249
+ } as const;
250
+ export type PushSurface = typeof PUSH_SURFACES[keyof typeof PUSH_SURFACES];
251
+
252
+ // The SSE event name render ops are pushed under (the dispatcher listens for it).
253
+ export const OP_EVENT = "op";
254
+
255
+ // ---- The substrate PORT GRAIN needs: a way to push to a session ----------------
256
+ // GRAIN depends on this interface, never on a concrete substrate. BATCH's SSE hub
257
+ // satisfies it structurally; a WebSocket hub, a test double, or another substrate
258
+ // would too. This is what keeps GRAIN runnable on something other than BATCH.
259
+ export interface OpChannel {
260
+ push(session: string, event: string, data: unknown): void;
261
+ }
262
+
263
+ // ---- The interaction LOG — a uniform record of every door crossing --------------
264
+ // Every Intent — human OR AI — enters through handleIntent (the single writer, the natural
265
+ // choke point). Recording it THERE yields ONE uniform, source-tagged history of both operators
266
+ // for a few lines at one place — and because both cross the same door, they're recorded
267
+ // IDENTICALLY (uniform auditability; AI-INTERFACE §5g). The visual "interaction timeline" is
268
+ // just a LogSink impl that pushes `log` RenderOps to the `timeline` surface (timeline-log.ts).
269
+ export interface LogEntry {
270
+ session: string; // the SSE stream this crossing belongs to (where a `log` op is pushed)
271
+ source: Provenance; // WHO authored it — user | ai | system (drives the timeline colour + grade)
272
+ kind: "intent" | "response"; // the request that came IN, or the decision that went OUT
273
+ screen: string;
274
+ surface: Surface; // what was touched / referred to
275
+ action: ActionName;
276
+ ok: boolean; // request valid / write succeeded
277
+ ops: number; // how many RenderOps the decision emitted (0 for an intent record)
278
+ }
279
+
280
+ // The LOG PORT GRAIN needs — a place to record each crossing. Like OpChannel, GRAIN depends on
281
+ // this interface, never a concrete store: a console logger, an audit journal, or the timeline
282
+ // stream-sink all satisfy it. OPTIONAL at the door (observability, not core correctness).
283
+ export interface LogSink {
284
+ record(entry: LogEntry): void;
285
+ }
@@ -0,0 +1,270 @@
1
+ // /app/ai/interaction-layer.test.ts — the one door: validation, single-writer, push.
2
+ import { test, expect } from "bun:test";
3
+ import { createInteractionLayer } from "./interaction-layer.ts";
4
+ import { makeStubReasoner } from "./reasoner.ts";
5
+ import type { Reasoner, ReasonTools } from "./reasoner.ts";
6
+ import type { Intent, RenderOp, OpChannel, LogSink, LogEntry } from "./contract.ts";
7
+
8
+ // An OpChannel double that records what got pushed and to whom (GRAIN's only port).
9
+ function fakeStream() {
10
+ const pushed: Array<{ session: string; event: string; data: unknown }> = [];
11
+ const stream: OpChannel = {
12
+ push: (session, event, data) => { pushed.push({ session, event, data }); },
13
+ };
14
+ return { stream, pushed };
15
+ }
16
+
17
+ // A LogSink double: captures every recorded door crossing (the interaction timeline port).
18
+ function fakeLog() {
19
+ const entries: LogEntry[] = [];
20
+ const sink: LogSink = { record: (e) => { entries.push(e); } };
21
+ return { sink, entries };
22
+ }
23
+
24
+ function makeLayer(opts: { failRate?: number } = {}) {
25
+ const archived: string[] = [];
26
+ const { stream, pushed } = fakeStream();
27
+ const { sink, entries } = fakeLog();
28
+ const layer = createInteractionLayer({
29
+ reasoner: makeStubReasoner({ failRate: opts.failRate ?? 0, thinkMs: 0 }),
30
+ stream,
31
+ archiveItem: async (id) => { archived.push(id); },
32
+ renderSurface: async (s) => `<article data-surface="${s}" data-commit="committed">ok</article>`,
33
+ logSink: sink,
34
+ });
35
+ return { layer, archived, pushed, entries };
36
+ }
37
+
38
+ const intent = (over: Partial<Intent> = {}): Intent => ({
39
+ source: "user", session: "sess-1", screen: "loop",
40
+ surface: "item:ITM-1", action: "item.archive", payload: {}, ...over,
41
+ });
42
+
43
+ const ops = (pushed: Array<{ data: unknown }>) => pushed.map((p) => p.data as RenderOp);
44
+
45
+ test("valid intent: single writer commits, then pushes a committed replace op", async () => {
46
+ const { layer, archived, pushed } = makeLayer();
47
+ const decision = await layer.handleIntent(intent());
48
+
49
+ expect(decision.ok).toBe(true);
50
+ expect(archived).toEqual(["ITM-1"]); // the write happened, through the scoped tool
51
+ expect(pushed[0]?.session).toBe("sess-1"); // pushed to the originating session
52
+ const op = ops(pushed)[0]!;
53
+ expect(op.op).toBe("replace");
54
+ expect(op.provenance).toBe("ai");
55
+ expect(op.commit).toBe("committed"); // grade = commit state
56
+ });
57
+
58
+ test("unknown action is rejected at the door — no write, a flash op", async () => {
59
+ const { layer, archived, pushed } = makeLayer();
60
+ const decision = await layer.handleIntent(intent({ action: "bogus.verb" as Intent["action"] }));
61
+
62
+ expect(decision.ok).toBe(false);
63
+ expect(archived).toEqual([]);
64
+ expect(ops(pushed)[0]!.op).toBe("flash");
65
+ // the rejection ECHOES the vocabulary so a reasoner can pick a real verb next turn
66
+ expect(decision.reason).toContain("known verbs");
67
+ expect(decision.reason).toContain("item.archive");
68
+ });
69
+
70
+ test("surface kind that doesn't accept the action is rejected", async () => {
71
+ const { layer, archived, pushed } = makeLayer();
72
+ const decision = await layer.handleIntent(intent({ surface: "item-list" }));
73
+
74
+ expect(decision.ok).toBe(false);
75
+ expect(archived).toEqual([]);
76
+ expect(ops(pushed)[0]!.op).toBe("flash");
77
+ });
78
+
79
+ test("a wrong-surface rejection echoes the verbs that surface DOES accept — self-correction", async () => {
80
+ const { layer, pushed } = makeLayer();
81
+ // item.archive on a reflection surface: rejected, and the door tells the reasoner reflection takes say.set
82
+ const decision = await layer.handleIntent(intent({ surface: "reflection", action: "item.archive" }));
83
+
84
+ expect(decision.ok).toBe(false);
85
+ expect(decision.reason).toContain("say.set"); // the machine-facing trace names the valid move
86
+ expect(ops(pushed)[0]!.message).toContain("say.set"); // and so does the human-facing flash
87
+ });
88
+
89
+ test("failed write rolls back: a flash op, no committed replace", async () => {
90
+ const { layer, pushed } = makeLayer({ failRate: 1 });
91
+ const decision = await layer.handleIntent(intent());
92
+
93
+ expect(decision.ok).toBe(false);
94
+ expect(ops(pushed)[0]!.op).toBe("flash");
95
+ });
96
+
97
+ test("demo.run plays an AI-acting sequence: spotlight on … then off, with typed text between", async () => {
98
+ const { layer, pushed } = makeLayer();
99
+ const decision = await layer.handleIntent(intent({ surface: "screen", action: "demo.run" }));
100
+
101
+ expect(decision.ok).toBe(true);
102
+ const all = ops(pushed);
103
+ const spots = all.filter((o) => o.op === "spotlight");
104
+ expect(spots[0]!.active).toBe(true); // raises the backdrop
105
+ expect(spots[spots.length - 1]!.active).toBe(false); // and releases at the end
106
+ expect(all.some((o) => o.op === "type" && o.text)).toBe(true); // it writes while acting
107
+ });
108
+
109
+ test("say.stream emits type tokens over SSE and settles with a committed done op", async () => {
110
+ const { layer, pushed } = makeLayer();
111
+ const decision = await layer.handleIntent(intent({ surface: "say-stream", action: "say.stream" }));
112
+
113
+ expect(decision.ok).toBe(true);
114
+ const typeOps = ops(pushed).filter((o) => o.op === "type");
115
+ expect(typeOps.length).toBeGreaterThan(1); // streamed token by token
116
+ expect(typeOps.some((o) => typeof o.text === "string")).toBe(true);
117
+ const last = typeOps[typeOps.length - 1]!;
118
+ expect(last.done).toBe(true);
119
+ expect(last.commit).toBe("committed"); // grain settles to clean
120
+ });
121
+
122
+ // --- the interaction TIMELINE: every crossing recorded at the one door (§5g) -----
123
+ test("logs both halves of a valid crossing: the user's request, then the AI's response", async () => {
124
+ const { layer, entries } = makeLayer();
125
+ await layer.handleIntent(intent());
126
+
127
+ const req = entries.find((e) => e.kind === "intent")!;
128
+ const res = entries.find((e) => e.kind === "response")!;
129
+ expect(req.source).toBe("user"); // the human raised it
130
+ expect(req.action).toBe("item.archive");
131
+ expect(req.session).toBe("sess-1");
132
+ expect(res.source).toBe("ai"); // the AI authored the render
133
+ expect(res.ok).toBe(true);
134
+ expect(res.ops).toBeGreaterThan(0); // it emitted render ops
135
+ });
136
+
137
+ test("a rejected request is logged as a system response (failed, no ops from the AI)", async () => {
138
+ const { layer, entries } = makeLayer();
139
+ await layer.handleIntent(intent({ action: "bogus.verb" as Intent["action"] }));
140
+
141
+ const res = entries.find((e) => e.kind === "response")!;
142
+ expect(res.source).toBe("system"); // the door refused — not the AI
143
+ expect(res.ok).toBe(false);
144
+ });
145
+
146
+ test("an AI-sourced intent is recorded with ai provenance (both operators, one format)", async () => {
147
+ const { layer, entries } = makeLayer();
148
+ await layer.handleIntent(intent({ source: "ai" }));
149
+
150
+ expect(entries.find((e) => e.kind === "intent")!.source).toBe("ai");
151
+ });
152
+
153
+ test("the door runs fine with no logSink wired (observability is optional)", async () => {
154
+ const archived: string[] = [];
155
+ const layer = createInteractionLayer({
156
+ reasoner: makeStubReasoner({ thinkMs: 0 }), stream: fakeStream().stream,
157
+ archiveItem: async (id) => { archived.push(id); }, renderSurface: async () => "",
158
+ });
159
+ const decision = await layer.handleIntent(intent());
160
+ expect(decision.ok).toBe(true); // no throw, no requirement on the sink
161
+ });
162
+
163
+ // --- stop control is keyed PER TURN (not per session) ---------------------------
164
+ // A long turn that yields between steps and reports whether it saw the stop.
165
+ function longTurn(onEnd: (cancelled: boolean) => void): Reasoner {
166
+ return {
167
+ async decide(i, tools: ReasonTools) {
168
+ if (i.action === "demo.run") {
169
+ for (let n = 0; n < 12; n++) { await tools.delay(0); if (tools.cancelled()) { onEnd(true); return { ok: true, ops: [] }; } }
170
+ onEnd(false);
171
+ }
172
+ return { ok: true, ops: [] };
173
+ },
174
+ };
175
+ }
176
+ const layerWith = (reasoner: Reasoner) =>
177
+ createInteractionLayer({ reasoner, stream: fakeStream().stream, archiveItem: async () => {}, renderSurface: async () => "" });
178
+
179
+ test("desk.stop halts the running turn (it polls cancelled and hands back)", async () => {
180
+ let cancelled = false;
181
+ const layer = layerWith(longTurn((c) => { cancelled = c; }));
182
+ const running = layer.handleIntent(intent({ surface: "screen", action: "demo.run" }));
183
+ await layer.handleIntent(intent({ surface: "screen", action: "desk.stop" }));
184
+ await running;
185
+ expect(cancelled).toBe(true);
186
+ });
187
+
188
+ test("a concurrent chat mid-run does NOT clear the running turn's stop (per-turn keying)", async () => {
189
+ let cancelled = false;
190
+ const layer = layerWith(longTurn((c) => { cancelled = c; }));
191
+ const running = layer.handleIntent(intent({ surface: "screen", action: "demo.run" })); // the AI starts working
192
+ await layer.handleIntent(intent({ surface: "screen", action: "desk.stop" })); // user asks it to stop
193
+ await layer.handleIntent(intent({ surface: "chat-log", action: "chat.send", payload: { text: "hi" } })); // …then chats
194
+ await running;
195
+ expect(cancelled).toBe(true); // the run still saw the stop despite the concurrent chat
196
+ });
197
+
198
+ // --- note verbs at the door: kind validation + the AI-acting spotlight bracket ---------------
199
+ test("note.append on the notepad kind: validates, the reasoner writes an append to notepad-body", async () => {
200
+ const { layer, pushed } = makeLayer();
201
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "notepad", action: "note.append", payload: { text: "hi" } }));
202
+ expect(d.ok).toBe(true);
203
+ const appended = ops(pushed).find((o) => o.op === "append" && o.target === "notepad-body");
204
+ expect(appended).toBeTruthy();
205
+ });
206
+
207
+ test("note.append on a non-notepad surface: rejected by the closed vocabulary", async () => {
208
+ const { layer } = makeLayer();
209
+ const d = await layer.handleIntent(intent({ surface: "item:ITM-1", action: "note.append", payload: { text: "hi" } }));
210
+ expect(d.ok).toBe(false);
211
+ expect(d.ops[0]?.op).toBe("flash");
212
+ });
213
+
214
+ test("an AI note write is bracketed by a spotlight on the notepad surface (AI as actor)", async () => {
215
+ const { layer, pushed } = makeLayer();
216
+ await layer.handleIntent(intent({ source: "ai", surface: "notepad", action: "note.append", payload: { text: "hi" } }));
217
+ const spots = ops(pushed).filter((o) => o.op === "spotlight" && o.target === "notepad");
218
+ expect(spots.some((o) => o.active === true)).toBe(true);
219
+ expect(spots.some((o) => o.active === false)).toBe(true);
220
+ });
221
+
222
+ // --- field.set at the door: kind validation, value validation, the fill op (plans/field-set-op.md) ---
223
+ test("field.set on a field kind: validates, the reasoner emits a committed ai fill op", async () => {
224
+ const { layer, pushed } = makeLayer();
225
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "field:contact-message",
226
+ action: "field.set", payload: { value: "Hi TJ — I want to talk about grain." } }));
227
+ expect(d.ok).toBe(true);
228
+ const fill = ops(pushed).find((o) => o.op === "fill");
229
+ expect(fill).toMatchObject({ target: "field:contact-message",
230
+ text: "Hi TJ — I want to talk about grain.", provenance: "ai", commit: "committed" });
231
+ });
232
+
233
+ test("field.set on a non-field surface: rejected with the accepts echo (closed vocabulary)", async () => {
234
+ const { layer } = makeLayer();
235
+ const d = await layer.handleIntent(intent({ surface: "item:ITM-1", action: "field.set", payload: { value: "hi" } }));
236
+ expect(d.ok).toBe(false);
237
+ expect(d.ops[0]?.op).toBe("flash");
238
+ expect(d.reason).toContain("item:ITM-1 rejects field.set");
239
+ expect(d.reason).toContain("item.archive"); // the verbs that surface DOES accept, echoed back
240
+ });
241
+
242
+ test("field.set with an oversized value: rejected, the reason echoes the constraint so a reasoner can shorten", async () => {
243
+ const { layer, pushed } = makeLayer();
244
+ const d = await layer.handleIntent(intent({ source: "ai", surface: "field:contact-message",
245
+ action: "field.set", payload: { value: "x".repeat(2001) } }));
246
+ expect(d.ok).toBe(false);
247
+ expect(d.reason).toContain("field.set value rejected");
248
+ expect(d.reason).toContain("2000");
249
+ expect(ops(pushed).find((o) => o.op === "fill")).toBeUndefined(); // nothing reached the field
250
+ });
251
+
252
+ test("field.set with an empty or control-char value: rejected (never a silent blank fill)", async () => {
253
+ const { layer } = makeLayer();
254
+ const empty = await layer.handleIntent(intent({ source: "ai", surface: "field:contact-message",
255
+ action: "field.set", payload: { value: " " } }));
256
+ expect(empty.ok).toBe(false);
257
+ const ctrl = await layer.handleIntent(intent({ source: "ai", surface: "field:contact-message",
258
+ action: "field.set", payload: { value: "bad\x00byte" } }));
259
+ expect(ctrl.ok).toBe(false);
260
+ expect(ctrl.reason).toContain("control characters");
261
+ });
262
+
263
+ test("an AI field.set is bracketed by a spotlight on the field surface (AI as actor)", async () => {
264
+ const { layer, pushed } = makeLayer();
265
+ await layer.handleIntent(intent({ source: "ai", surface: "field:contact-message",
266
+ action: "field.set", payload: { value: "draft" } }));
267
+ const spots = ops(pushed).filter((o) => o.op === "spotlight" && o.target === "field:contact-message");
268
+ expect(spots.some((o) => o.active === true)).toBe(true);
269
+ expect(spots.some((o) => o.active === false)).toBe(true);
270
+ });