@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.
- package/LICENSE +202 -0
- package/PLAN.md +27 -0
- package/README.md +243 -0
- package/ai/accepts.test.ts +69 -0
- package/ai/accepts.ts +57 -0
- package/ai/ai.css +127 -0
- package/ai/client-door.test.ts +70 -0
- package/ai/client-door.ts +56 -0
- package/ai/contract.test.ts +158 -0
- package/ai/contract.ts +285 -0
- package/ai/interaction-layer.test.ts +270 -0
- package/ai/interaction-layer.ts +138 -0
- package/ai/manifest-dom.test.ts +176 -0
- package/ai/manifest-dom.ts +187 -0
- package/ai/manifest.test.ts +71 -0
- package/ai/manifest.ts +57 -0
- package/ai/markdown.test.ts +68 -0
- package/ai/markdown.ts +74 -0
- package/ai/model-chat.test.ts +131 -0
- package/ai/model-chat.ts +151 -0
- package/ai/model-reasoner.test.ts +152 -0
- package/ai/model-reasoner.ts +146 -0
- package/ai/model.test.ts +148 -0
- package/ai/model.ts +200 -0
- package/ai/reasoner-kit.test.ts +142 -0
- package/ai/reasoner-kit.ts +159 -0
- package/ai/reasoner.test.ts +227 -0
- package/ai/reasoner.ts +446 -0
- package/ai/timeline-log.test.ts +55 -0
- package/ai/timeline-log.ts +50 -0
- package/ai/vocab-reference.test.ts +43 -0
- package/ai/vocab-reference.ts +107 -0
- package/ai/webllm.test.ts +79 -0
- package/ai/webllm.ts +125 -0
- package/assets/figure-sample.svg +14 -0
- package/assets/sprite.svg +22 -0
- package/catalog/catalog.test.ts +37 -0
- package/catalog/catalog.ts +424 -0
- package/components/atoms/action-badge/action-badge.css +17 -0
- package/components/atoms/action-badge/action-badge.html +6 -0
- package/components/atoms/action-badge/action-badge.md +23 -0
- package/components/atoms/b-badge/b-badge.css +15 -0
- package/components/atoms/b-badge/b-badge.html +2 -0
- package/components/atoms/b-badge/b-badge.md +16 -0
- package/components/atoms/b-button/b-button.ai.md +22 -0
- package/components/atoms/b-button/b-button.css +87 -0
- package/components/atoms/b-button/b-button.html +5 -0
- package/components/atoms/b-button/b-button.md +77 -0
- package/components/atoms/b-icon/b-icon.css +10 -0
- package/components/atoms/b-icon/b-icon.html +5 -0
- package/components/atoms/b-icon/b-icon.md +36 -0
- package/components/atoms/b-icon-button/b-icon-button.ai.md +11 -0
- package/components/atoms/b-icon-button/b-icon-button.css +43 -0
- package/components/atoms/b-icon-button/b-icon-button.html +8 -0
- package/components/atoms/b-icon-button/b-icon-button.md +33 -0
- package/components/atoms/b-input/b-input.css +36 -0
- package/components/atoms/b-input/b-input.html +8 -0
- package/components/atoms/b-input/b-input.md +59 -0
- package/components/atoms/b-kbd/b-kbd.css +11 -0
- package/components/atoms/b-kbd/b-kbd.html +3 -0
- package/components/atoms/b-kbd/b-kbd.md +13 -0
- package/components/atoms/b-list/b-list.css +21 -0
- package/components/atoms/b-list/b-list.html +6 -0
- package/components/atoms/b-list/b-list.md +24 -0
- package/components/atoms/b-meter/b-meter.css +39 -0
- package/components/atoms/b-meter/b-meter.md +44 -0
- package/components/atoms/b-select/b-select.css +35 -0
- package/components/atoms/b-select/b-select.md +75 -0
- package/components/atoms/b-switch/b-switch.css +61 -0
- package/components/atoms/b-switch/b-switch.html +6 -0
- package/components/atoms/b-switch/b-switch.md +40 -0
- package/components/atoms/b-text/b-text.ai.md +29 -0
- package/components/atoms/b-text/b-text.css +2 -0
- package/components/atoms/b-text/b-text.html +3 -0
- package/components/atoms/b-text/b-text.md +23 -0
- package/components/atoms/code-block/code-block.css +42 -0
- package/components/atoms/code-block/code-block.md +23 -0
- package/components/examples.test.ts +23 -0
- package/components/molecules/callout/callout.css +19 -0
- package/components/molecules/callout/callout.md +15 -0
- package/components/molecules/card/card.css +28 -0
- package/components/molecules/card/card.md +30 -0
- package/components/molecules/chat-message/chat-message.css +83 -0
- package/components/molecules/chat-message/chat-message.md +52 -0
- package/components/molecules/chip-group/chip-group.css +35 -0
- package/components/molecules/chip-group/chip-group.md +42 -0
- package/components/molecules/content-index/content-index.css +87 -0
- package/components/molecules/content-index/content-index.md +27 -0
- package/components/molecules/content-source/content-source.css +6 -0
- package/components/molecules/content-source/content-source.md +13 -0
- package/components/molecules/figure/figure.css +19 -0
- package/components/molecules/figure/figure.md +20 -0
- package/components/molecules/lede/lede.css +17 -0
- package/components/molecules/lede/lede.md +17 -0
- package/components/molecules/made-with/made-with.css +25 -0
- package/components/molecules/made-with/made-with.md +35 -0
- package/components/molecules/nav-item/nav-item.css +19 -0
- package/components/molecules/nav-item/nav-item.md +21 -0
- package/components/molecules/stat-tile/stat-tile.css +34 -0
- package/components/molecules/stat-tile/stat-tile.md +50 -0
- package/components/molecules/status-list/status-list.css +47 -0
- package/components/molecules/status-list/status-list.md +62 -0
- package/components/molecules/tab/tab.css +32 -0
- package/components/molecules/tab/tab.md +27 -0
- package/components/molecules/table/table.css +23 -0
- package/components/molecules/table/table.md +18 -0
- package/components/organisms/activity-bar/activity-bar.css +36 -0
- package/components/organisms/activity-bar/activity-bar.md +43 -0
- package/components/organisms/app-shell/app-shell.css +193 -0
- package/components/organisms/app-shell/app-shell.md +58 -0
- package/components/organisms/app-shell/app-shell.test.ts +74 -0
- package/components/organisms/app-window/app-window.css +111 -0
- package/components/organisms/app-window/app-window.md +53 -0
- package/components/organisms/chat-log/chat-log.css +5 -0
- package/components/organisms/chat-log/chat-log.md +14 -0
- package/components/organisms/code-editor/code-editor.ai.md +31 -0
- package/components/organisms/code-editor/code-editor.css +111 -0
- package/components/organisms/code-editor/code-editor.md +122 -0
- package/components/organisms/console/console.css +112 -0
- package/components/organisms/console/console.md +66 -0
- package/components/organisms/file-tree/file-tree.css +85 -0
- package/components/organisms/file-tree/file-tree.md +49 -0
- package/components/organisms/note/note.css +19 -0
- package/components/organisms/note/note.md +20 -0
- package/components/organisms/notepad/notepad.css +60 -0
- package/components/organisms/notepad/notepad.md +40 -0
- package/components/organisms/side-rail/side-rail.css +55 -0
- package/components/organisms/side-rail/side-rail.md +24 -0
- package/components/organisms/sidebar-panel/sidebar-panel.css +69 -0
- package/components/organisms/sidebar-panel/sidebar-panel.md +47 -0
- package/components/organisms/status-bar/status-bar.css +33 -0
- package/components/organisms/status-bar/status-bar.md +28 -0
- package/components/organisms/tab-bar/tab-bar.css +48 -0
- package/components/organisms/tab-bar/tab-bar.md +26 -0
- package/components/organisms/timeline/timeline.css +51 -0
- package/components/organisms/timeline/timeline.md +42 -0
- package/components/organisms/topbar/topbar.css +8 -0
- package/components/organisms/topbar/topbar.md +26 -0
- package/components/responsive-polish.test.ts +43 -0
- package/components/tokens.test.ts +39 -0
- package/fonts/redaction-35-400.woff2 +0 -0
- package/fonts/redaction-400.woff2 +0 -0
- package/fonts/redaction-50-400.woff2 +0 -0
- package/fonts/redaction-70-400.woff2 +0 -0
- package/package.json +46 -0
- package/scripts/ai-dispatch.js +583 -0
- package/scripts/ai-dispatch.test.ts +85 -0
- package/scripts/ai-spotlight.d.ts +23 -0
- package/scripts/ai-spotlight.js +139 -0
- package/scripts/ai-spotlight.test.ts +31 -0
- package/scripts/catalog-peek.js +156 -0
- package/scripts/catalog-peek.test.ts +31 -0
- package/scripts/cmdk.js +159 -0
- package/scripts/demo-box.js +53 -0
- package/scripts/handoff.js +64 -0
- package/scripts/handoff.test.ts +36 -0
- package/scripts/lightbox.js +144 -0
- package/scripts/lightbox.test.ts +23 -0
- package/scripts/made-with.d.ts +2 -0
- package/scripts/made-with.js +22 -0
- package/scripts/made-with.test.ts +25 -0
- package/scripts/notepad.js +100 -0
- package/scripts/shell.js +204 -0
- package/scripts/shell.test.ts +50 -0
- package/scripts/tabs.js +127 -0
- package/scripts/tabs.test.ts +40 -0
- package/scripts/terminal.js +271 -0
- package/scripts/terminal.test.ts +36 -0
- package/scripts/theme-boot.js +15 -0
- package/scripts/theme.js +87 -0
- package/scripts/type-effect.js +25 -0
- package/scripts/xray.js +79 -0
- package/scripts/xray.test.ts +43 -0
- package/styles/cmdk.css +65 -0
- package/styles/global.css +80 -0
- package/styles/grain.css +47 -0
- package/styles/lightbox.css +78 -0
- package/styles/themes/_template.css +48 -0
- package/styles/themes/baguette.css +30 -0
- package/styles/themes/brioche.css +30 -0
- package/styles/variables.css +217 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// grain/ai/reasoner-kit.ts — reusable building blocks for ANY reasoner (the built-in stub OR a
|
|
2
|
+
// consumer's real cloud/local model). Before this, the chat markup + op shapes lived as closures
|
|
3
|
+
// INSIDE makeStubReasoner, so a consumer writing its own reasoner had to COPY them — a silent-drift
|
|
4
|
+
// trap (grain's own hard-won lessons #3/#5: a contract that fails silently). The kit makes those
|
|
5
|
+
// primitives first-class and EXPORTED; the stub dogfoods them (reasoner.ts), so the kit and the
|
|
6
|
+
// shipped behaviour can never diverge. CLIENT-SAFE (§19.2): pure, no DOM, relative import only.
|
|
7
|
+
|
|
8
|
+
import type { RenderOp, Surface } from "./contract.ts";
|
|
9
|
+
import { PUSH_SURFACES, isSafeNavigateHref, isSafeFieldValue, FIELD_VALUE_CAP } from "./contract.ts";
|
|
10
|
+
// Imported for the notepad markup helpers below (they render markdown source to sanitized HTML) AND
|
|
11
|
+
// re-exported so a consumer building on the kit finds settle-time markdown rendering right next to
|
|
12
|
+
// the op-builders it pairs with, without a second import path to remember. Canonical home + tests:
|
|
13
|
+
// ./markdown.ts (kept separate so this file stays about OP shapes, not text rendering).
|
|
14
|
+
import { renderMarkdown } from "./markdown.ts";
|
|
15
|
+
export { renderMarkdown };
|
|
16
|
+
|
|
17
|
+
// ---- markup: the exact fragments the dispatcher's applyOp expects (chat bubbles, console lines) ----
|
|
18
|
+
|
|
19
|
+
/** Escape untrusted text before it enters an emitted HTML fragment — chat carries USER input, so it
|
|
20
|
+
* must be escaped at the single writer. */
|
|
21
|
+
export const esc = (s: string): string =>
|
|
22
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
23
|
+
|
|
24
|
+
/** One chat bubble — a human's message (clean) or the AI's (grain; provenance persists). `who`
|
|
25
|
+
* defaults from the role ("You"/"AI"); pass it to override (the /grain showcase signs "GRAIN"). */
|
|
26
|
+
export const chatBubble = (role: string, grade: string, inner: string, who?: string): string =>
|
|
27
|
+
`<div class="chat-message" data-role="${role}"${grade ? ` data-grade="${grade}"` : ""}>` +
|
|
28
|
+
`<span class="chat-message__who">${who ?? (role === "you" ? "You" : "AI")}</span>${inner}</div>`;
|
|
29
|
+
|
|
30
|
+
/** The message body span. Pass a `surface` for an AI bubble that will be STREAMED into (later `type`
|
|
31
|
+
* ops address it by data-surface); omit it for a static human message. */
|
|
32
|
+
export const chatBody = (inner = "", surface?: Surface): string =>
|
|
33
|
+
`<span class="chat-message__body"${surface ? ` data-surface="${surface}"` : ""}>${inner}</span>`;
|
|
34
|
+
|
|
35
|
+
/** One console narration line — the AI's verb vocabulary (contract.ts) made visible in the takeover
|
|
36
|
+
* feed, so a multi-second run never reads as stuck (lesson #7). */
|
|
37
|
+
export const narrationLine = (verb: string, desc: string): string =>
|
|
38
|
+
`<div class="console__line"><span class="action-badge">${verb}</span><span class="console__desc">${esc(desc)}</span></div>`;
|
|
39
|
+
|
|
40
|
+
/** An animated "typing" indicator for a chat bubble that's thinking but hasn't streamed a token yet
|
|
41
|
+
* (model load, retrieval) — so a pending bubble is NEVER a blank rectangle. Three pulsing dots,
|
|
42
|
+
* announced to assistive tech as "Thinking". Pair with a `pending` grade (thinkingOp below). */
|
|
43
|
+
export const thinkingDots = (): string =>
|
|
44
|
+
`<span class="chat-thinking" role="status" aria-label="Thinking"><span></span><span></span><span></span></span>`;
|
|
45
|
+
|
|
46
|
+
/** A row of choice buttons the human picks from. It IS an actionable chat dialog (`chat-message__
|
|
47
|
+
* actions` + `.btn` — reused, not reinvented: same clean-affordance grade treatment + online-gating
|
|
48
|
+
* the chat-message component already ships), marked `data-choices` so the dispatcher resolves it
|
|
49
|
+
* pick-once. Each button is a normal chat.send trigger through the ONE door (data-action/-target),
|
|
50
|
+
* carrying its own answer as data-payload-text (the static-payload primitive fireTrigger reads).
|
|
51
|
+
* Values default to the label; text is escaped at this single writer. */
|
|
52
|
+
export const choiceGroup = (log: Surface, choices: { label: string; value?: string }[]): string =>
|
|
53
|
+
`<div class="chat-message__actions" data-choices>` +
|
|
54
|
+
choices.map((c) =>
|
|
55
|
+
`<button type="button" class="btn chat-choice" data-action="chat.send" data-target="${esc(log)}"` +
|
|
56
|
+
` data-payload-text="${esc(c.value ?? c.label)}">${esc(c.label)}</button>`).join("") +
|
|
57
|
+
`</div>`;
|
|
58
|
+
|
|
59
|
+
// ---- notepad markup: the AI's memory as a visible, editable surface (DEMO-PLAN piece 2) ----------
|
|
60
|
+
// Canonical state is the markdown SOURCE, not this rendered HTML: each entry carries its own source
|
|
61
|
+
// in `data-md` so the client island can reconstitute the whole notepad's markdown (join the entries)
|
|
62
|
+
// and mirror it to localStorage — the DOM is a projection, the source is the truth. renderMarkdown is
|
|
63
|
+
// the SAME sanitizing allowlist the chat uses at settle-time, so an AI (or human) note can never
|
|
64
|
+
// inject markup. An AI entry grades `grain` (provenance persists — DESIGN-SYSTEM §3); a human commit
|
|
65
|
+
// omits the grade (clean ink). These are the SSOT the organism's SSR template and the note ops share.
|
|
66
|
+
|
|
67
|
+
/** One notepad entry: rendered markdown for the eye, `data-md` (the escaped source) for round-trip. */
|
|
68
|
+
export const notepadEntry = (text: string, provenance: "user" | "ai"): string =>
|
|
69
|
+
`<div class="notepad__entry"${provenance === "ai" ? ' data-grade="grain"' : ""} data-md="${esc(text)}">` +
|
|
70
|
+
`${renderMarkdown(text)}</div>`;
|
|
71
|
+
|
|
72
|
+
/** The notepad's inner content surface — the `note.*` ops' target. Reproduced verbatim by a
|
|
73
|
+
* `replace` op (which swaps the element's outerHTML), so its `data-surface` stays addressable. */
|
|
74
|
+
export const notepadBody = (inner = ""): string =>
|
|
75
|
+
`<div class="notepad__body" data-surface="${PUSH_SURFACES.notepadBody}">${inner}</div>`;
|
|
76
|
+
|
|
77
|
+
// ---- op-builders: the exact RenderOps a reasoner emits, so no consumer hand-rolls provenance/commit ----
|
|
78
|
+
|
|
79
|
+
/** A human's message, committed (clean). Committed on the chat-log target also releases the composer
|
|
80
|
+
* trigger + stands the op-silence watchdog down (dispatcher), so a long turn that follows is safe. */
|
|
81
|
+
export const userMessageOp = (log: Surface, text: string): RenderOp =>
|
|
82
|
+
({ target: log, op: "append", provenance: "user", commit: "committed",
|
|
83
|
+
html: chatBubble("you", "", chatBody(esc(text || "…"))) });
|
|
84
|
+
|
|
85
|
+
/** An empty AI bubble to stream into — grain (AI), pending until it settles. `who` overrides the label. */
|
|
86
|
+
export const aiBubbleOp = (log: Surface, surface: Surface, who?: string): RenderOp =>
|
|
87
|
+
({ target: log, op: "append", provenance: "ai", commit: "pending",
|
|
88
|
+
html: chatBubble("ai", "grain", chatBody("", surface), who) });
|
|
89
|
+
|
|
90
|
+
/** Stream a token (or a whole chunk) into a bubble body; grain persists (AI speech). */
|
|
91
|
+
export const typeToken = (surface: Surface, text: string): RenderOp =>
|
|
92
|
+
({ target: surface, op: "type", text, provenance: "ai", commit: "pending" });
|
|
93
|
+
|
|
94
|
+
/** Settle a streamed bubble — caret off, committed (stays grain: AI provenance persists). */
|
|
95
|
+
export const settleOp = (surface: Surface): RenderOp =>
|
|
96
|
+
({ target: surface, op: "type", done: true, provenance: "ai", commit: "committed" });
|
|
97
|
+
|
|
98
|
+
/** Replace a bubble body (status / progress / a final non-streamed line). Keep the same `surface` so
|
|
99
|
+
* later ops still land. `trusted` markup (e.g. a progress bar) may be passed as-is; text must be esc'd. */
|
|
100
|
+
export const replaceBodyOp = (surface: Surface, inner: string, commit: "pending" | "committed"): RenderOp =>
|
|
101
|
+
({ target: surface, op: "replace", provenance: "ai", commit, html: chatBody(inner, surface) });
|
|
102
|
+
|
|
103
|
+
/** Narrate a step to the console takeover feed (the `console` push-surface by default). */
|
|
104
|
+
export const narrateOp = (verb: string, desc: string, surface: Surface = PUSH_SURFACES.console): RenderOp =>
|
|
105
|
+
({ target: surface, op: "append", provenance: "ai", commit: "committed", html: narrationLine(verb, desc) });
|
|
106
|
+
|
|
107
|
+
/** Show the AI AS ACTOR on a surface: dim the page, light the target, optionally pulse it like a
|
|
108
|
+
* click. `active:false` releases. Driven by AI provenance (AI-INTERFACE §5c). */
|
|
109
|
+
export const spotlightOp = (target: Surface, opts: { active: boolean; click?: boolean } = { active: true }): RenderOp =>
|
|
110
|
+
({ target, op: "spotlight", active: opts.active, click: opts.click, provenance: "ai", commit: opts.active ? "pending" : "committed" });
|
|
111
|
+
|
|
112
|
+
/** Navigate the browser to `href` — a same-origin, root-relative path only (contract.ts's
|
|
113
|
+
* `isSafeNavigateHref`). Throws on an unsafe href RIGHT HERE, at the point a reasoner composes
|
|
114
|
+
* the op, rather than letting a bad value travel all the way to the dispatcher and fail silently
|
|
115
|
+
* there (CLAUDE.md lesson #3/#5: a contract must not fail silently) — the dispatcher's own guard
|
|
116
|
+
* is defense-in-depth against a tampered wire payload, not the first line of defense. `commit` is
|
|
117
|
+
* "committed": navigation is terminal for this page, there's nothing left to settle. */
|
|
118
|
+
export const navigateOp = (target: Surface, href: string): RenderOp => {
|
|
119
|
+
if (!isSafeNavigateHref(href))
|
|
120
|
+
throw new Error(`navigateOp: unsafe href ${JSON.stringify(href)} — must be a same-origin, root-relative path`);
|
|
121
|
+
return { target, op: "navigate", href, provenance: "ai", commit: "committed" };
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/** Prefill a registered form field (`field:` surface) with drafted text — the `fill` op. The value
|
|
125
|
+
* PERSISTS for human review; the AI never submits (no submit verb exists to call). Throws on an
|
|
126
|
+
* unsafe value RIGHT HERE, at the compose point, like navigateOp above (lesson #3/#5 — the
|
|
127
|
+
* dispatcher's own guard is defense-in-depth, not the first line). `committed`: the write is
|
|
128
|
+
* complete in one op; provenance `ai` drives the spotlight + the grain grade the dispatcher sets. */
|
|
129
|
+
export const fillOp = (target: Surface, value: string): RenderOp => {
|
|
130
|
+
if (!isSafeFieldValue(value))
|
|
131
|
+
throw new Error(`fillOp: unsafe value — must be a string ≤ ${FIELD_VALUE_CAP} chars with no control characters`);
|
|
132
|
+
return { target, op: "fill", text: value, provenance: "ai", commit: "committed" };
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** Replace a bubble body with the animated "thinking" dots, pending — the AI is working but hasn't a
|
|
136
|
+
* token to show yet. Reuses replaceBodyOp so the caret/settle lifecycle is identical to any stream. */
|
|
137
|
+
export const thinkingOp = (surface: Surface): RenderOp => replaceBodyOp(surface, thinkingDots(), "pending");
|
|
138
|
+
|
|
139
|
+
/** The AI asks the human to pick: an AI (grain) chat bubble with an optional prompt + a row of choice
|
|
140
|
+
* buttons appended to the chat `log`. `commit: "committed"` — the AI's TURN is done (it asked); the
|
|
141
|
+
* buttons are the human's control now, and each raises a fresh chat.send with its value when clicked
|
|
142
|
+
* (the dispatcher resolves the group on pick). `who` overrides the bubble label. */
|
|
143
|
+
export const choicesOp = (log: Surface, prompt: string, choices: { label: string; value?: string }[], who?: string): RenderOp =>
|
|
144
|
+
({ target: log, op: "choices", provenance: "ai", commit: "committed", prompt, choices,
|
|
145
|
+
// omit the body span entirely when there's no prompt (e.g. the model already spoke the question
|
|
146
|
+
// in its own bubble) — an empty body would render as a stray blank line above the buttons.
|
|
147
|
+
html: chatBubble("ai", "grain", (prompt ? chatBody(esc(prompt)) : "") + choiceGroup(log, choices), who) });
|
|
148
|
+
|
|
149
|
+
/** Append one markdown entry to the notepad. A note is a settled fact once made, so `committed`; the
|
|
150
|
+
* grade follows provenance (AI → grain, human commit → clean). Lands on the `notepad-body` surface. */
|
|
151
|
+
export const noteAppendOp = (text: string, provenance: "user" | "ai"): RenderOp =>
|
|
152
|
+
({ target: PUSH_SURFACES.notepadBody, op: "append", provenance, commit: "committed",
|
|
153
|
+
html: notepadEntry(text, provenance) });
|
|
154
|
+
|
|
155
|
+
/** Rewrite the whole notepad from one markdown body. Emits a `replace` (swaps the notepad-body node's
|
|
156
|
+
* outerHTML), rebuilding the surface wrapper so it stays addressable for the next note op. */
|
|
157
|
+
export const noteReplaceOp = (text: string, provenance: "user" | "ai"): RenderOp =>
|
|
158
|
+
({ target: PUSH_SURFACES.notepadBody, op: "replace", provenance, commit: "committed",
|
|
159
|
+
html: notepadBody(notepadEntry(text, provenance)) });
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// grain/ai/reasoner.test.ts — UNIT: the stub reasoner (the single writer) in isolation.
|
|
2
|
+
// We hand it a fake ReasonTools that records every emitted RenderOp + write, with zero
|
|
3
|
+
// delays, and assert the decision logic + the op stream it produces. No HTTP, no DOM.
|
|
4
|
+
import { test, expect } from "bun:test";
|
|
5
|
+
import { makeStubReasoner } from "./reasoner.ts";
|
|
6
|
+
import type { ReasonTools } from "./reasoner.ts";
|
|
7
|
+
import type { Intent, RenderOp } from "./contract.ts";
|
|
8
|
+
|
|
9
|
+
function fakeTools(over: Partial<ReasonTools> = {}) {
|
|
10
|
+
const emitted: RenderOp[] = [];
|
|
11
|
+
const archived: string[] = [];
|
|
12
|
+
const tools: ReasonTools = {
|
|
13
|
+
archiveItem: async (id) => { archived.push(id); },
|
|
14
|
+
renderSurface: async (s) => `<x data-surface="${s}" data-commit="committed">ok</x>`,
|
|
15
|
+
emit: (op) => { emitted.push(op); },
|
|
16
|
+
cancelled: () => false,
|
|
17
|
+
delay: async () => {},
|
|
18
|
+
...over,
|
|
19
|
+
};
|
|
20
|
+
return { tools, emitted, archived };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const intent = (over: Partial<Intent> = {}): Intent => ({
|
|
24
|
+
source: "user", session: "s1", screen: "loop",
|
|
25
|
+
surface: "item:ITM-1", action: "item.archive", payload: {}, ...over,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const reasoner = makeStubReasoner({ thinkMs: 0 });
|
|
29
|
+
const spots = (ops: RenderOp[]) => ops.filter((o) => o.op === "spotlight");
|
|
30
|
+
|
|
31
|
+
test("item.archive: writes through the scoped tool, returns a committed replace", async () => {
|
|
32
|
+
const { tools, archived } = fakeTools();
|
|
33
|
+
const d = await reasoner.decide(intent(), tools);
|
|
34
|
+
expect(d.ok).toBe(true);
|
|
35
|
+
expect(archived).toEqual(["ITM-1"]); // the write happened via the injected capability
|
|
36
|
+
expect(d.ops[0]?.op).toBe("replace");
|
|
37
|
+
expect(d.ops[0]?.commit).toBe("committed");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("item.archive failure rolls back: ok:false + a flash op", async () => {
|
|
41
|
+
const failing = makeStubReasoner({ thinkMs: 0, failRate: 1 });
|
|
42
|
+
const { tools, archived } = fakeTools();
|
|
43
|
+
const d = await failing.decide(intent(), tools);
|
|
44
|
+
expect(d.ok).toBe(false);
|
|
45
|
+
expect(archived).toEqual([]); // no write committed
|
|
46
|
+
expect(d.ops[0]?.op).toBe("flash");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("say.stream: brackets with spotlight on→off and streams type tokens that settle committed", async () => {
|
|
50
|
+
const { tools, emitted } = fakeTools();
|
|
51
|
+
await reasoner.decide(intent({ surface: "say-stream", action: "say.stream", payload: {} }), tools);
|
|
52
|
+
const types = emitted.filter((o) => o.op === "type");
|
|
53
|
+
expect(types.length).toBeGreaterThan(1);
|
|
54
|
+
expect(types.at(-1)?.commit).toBe("committed"); // grain settles committed
|
|
55
|
+
expect(spots(emitted)[0]?.active).toBe(true);
|
|
56
|
+
expect(spots(emitted).at(-1)?.active).toBe(false); // spotlight released when done
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("say.set: brackets with spotlight on→off and streams type tokens that settle committed", async () => {
|
|
60
|
+
const { tools, emitted } = fakeTools();
|
|
61
|
+
await reasoner.decide(intent({ surface: "reflection", action: "say.set", payload: { text: "hi" } }), tools);
|
|
62
|
+
const types = emitted.filter((o) => o.op === "type");
|
|
63
|
+
expect(types.length).toBeGreaterThan(1);
|
|
64
|
+
expect(types.at(-1)?.commit).toBe("committed"); // grain settles to clean
|
|
65
|
+
expect(spots(emitted)[0]?.active).toBe(true);
|
|
66
|
+
expect(spots(emitted).at(-1)?.active).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("demo.run: appends a 3-item list, erases (back), archives for real, commits clean, clicks, then releases", async () => {
|
|
70
|
+
const { tools, emitted, archived } = fakeTools();
|
|
71
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "demo.run" }), tools);
|
|
72
|
+
expect(d.ok).toBe(true);
|
|
73
|
+
expect(emitted.filter((o) => o.op === "append" && o.target === "plan")).toHaveLength(3); // 3 bullets
|
|
74
|
+
expect(emitted.some((o) => o.target === "console" && o.op === "append")).toBe(true); // narrated its steps to the console
|
|
75
|
+
expect(emitted.some((o) => o.op === "type" && (o.back ?? 0) > 0)).toBe(true); // backspaces (overwrite)
|
|
76
|
+
expect(archived).toContain("ITM-demo-1"); // the archive step WRITES for real through the service
|
|
77
|
+
expect(emitted.some((o) => o.op === "replace" && o.target === "item:ITM-demo-1" && o.commit === "committed")).toBe(true); // …then renders the committed card
|
|
78
|
+
expect(emitted.filter((o) => o.op === "replace" && o.commit === "committed").length) // list items + archived card + badge
|
|
79
|
+
.toBeGreaterThanOrEqual(4);
|
|
80
|
+
expect(spots(emitted).some((o) => o.click)).toBe(true); // clicks the commit button
|
|
81
|
+
expect(spots(emitted)[0]?.active).toBe(true);
|
|
82
|
+
expect(spots(emitted).at(-1)?.active).toBe(false); // hands back at the end
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("demo.run on the /grain screen: narrates to the terminal, drives the /grain surfaces, hands back", async () => {
|
|
86
|
+
const { tools, emitted } = fakeTools();
|
|
87
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "demo.run", screen: "grain" }), tools);
|
|
88
|
+
expect(d.ok).toBe(true);
|
|
89
|
+
// narrates each step to the console feed (the /grain terminal) so a run is legible, never "stuck"
|
|
90
|
+
expect(emitted.some((o) => o.target === "console" && o.op === "append")).toBe(true);
|
|
91
|
+
// drives the /grain surface addresses — NOT the /loop scenario's
|
|
92
|
+
const targets = new Set(emitted.map((o) => o.target));
|
|
93
|
+
expect(targets.has("grain-ask")).toBe(true);
|
|
94
|
+
expect(targets.has("chat-log:grain")).toBe(true); // the surface's OWN chat (distinct from the shell's)
|
|
95
|
+
expect(targets.has("grain-task-badge")).toBe(true);
|
|
96
|
+
expect(targets.has("plan")).toBe(false); // the loop scenario's surface — must not fire here
|
|
97
|
+
// the AI reply bubble is grain and stays grain (provenance persists)
|
|
98
|
+
expect(emitted.find((o) => o.op === "append" && o.target === "chat-log:grain")?.html).toContain('data-grade="grain"');
|
|
99
|
+
// hands back at the end: the LAST spotlight releases the screen (so the veil always drops)
|
|
100
|
+
const s = spots(emitted);
|
|
101
|
+
expect(s.at(-1)?.target).toBe("screen");
|
|
102
|
+
expect(s.at(-1)?.active).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("demo.run on the /notes screen: reads the newest notes, writes the notes-digest, releases", async () => {
|
|
106
|
+
const { tools, emitted } = fakeTools();
|
|
107
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "demo.run", screen: "notes" }), tools);
|
|
108
|
+
expect(d.ok).toBe(true);
|
|
109
|
+
// narrates each note read to the console feed (legible, never "stuck")
|
|
110
|
+
expect(emitted.filter((o) => o.target === "console" && o.op === "append").length).toBeGreaterThanOrEqual(3);
|
|
111
|
+
// travels the real note surfaces MILL addresses (mill/serve.ts itemSurfacePrefix)
|
|
112
|
+
const targets = new Set(emitted.map((o) => o.target));
|
|
113
|
+
expect(targets.has("note:feels-like-an-app")).toBe(true);
|
|
114
|
+
expect(targets.has("note:the-browser-grew-up")).toBe(true);
|
|
115
|
+
expect(targets.has("note:how-i-turned-github-into-a-classroom")).toBe(true);
|
|
116
|
+
// the digest streams into notes-digest and stays grain (AI-authored text stays grain)
|
|
117
|
+
const types = emitted.filter((o) => o.op === "type" && o.target === "notes-digest");
|
|
118
|
+
expect(types.length).toBeGreaterThan(1);
|
|
119
|
+
// natural completion also releases the spotlight — not just the stop path (grain CLAUDE.md lesson 7)
|
|
120
|
+
const s = spots(emitted);
|
|
121
|
+
expect(s.at(-1)?.target).toBe("screen");
|
|
122
|
+
expect(s.at(-1)?.active).toBe(false);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("demo.run on the /notes screen halts gracefully when cancelled: still releases, no throw", async () => {
|
|
126
|
+
const { tools, emitted } = fakeTools({ cancelled: () => true });
|
|
127
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "demo.run", screen: "notes" }), tools);
|
|
128
|
+
expect(d.ok).toBe(true);
|
|
129
|
+
expect(spots(emitted).at(-1)?.active).toBe(false);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("demo.run halts gracefully when cancelled: still releases the spotlight, no throw", async () => {
|
|
133
|
+
const { tools, emitted } = fakeTools({ cancelled: () => true });
|
|
134
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "demo.run" }), tools);
|
|
135
|
+
expect(d.ok).toBe(true);
|
|
136
|
+
expect(spots(emitted).at(-1)?.active).toBe(false); // graceful hand-back even on stop
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("chat.send: your message settles clean, the AI's reply streams into a grain bubble", async () => {
|
|
140
|
+
const { tools, emitted } = fakeTools();
|
|
141
|
+
const d = await reasoner.decide(intent({ surface: "chat-log", action: "chat.send", payload: { text: "plan my day" } }), tools);
|
|
142
|
+
expect(d.ok).toBe(true);
|
|
143
|
+
const appends = emitted.filter((o) => o.op === "append");
|
|
144
|
+
expect(appends).toHaveLength(2); // your bubble + the AI's (empty) bubble
|
|
145
|
+
expect(appends[0]?.provenance).toBe("user");
|
|
146
|
+
expect(appends[0]?.commit).toBe("committed"); // your words settle clean
|
|
147
|
+
expect(appends[0]?.html).toContain("plan my day");
|
|
148
|
+
expect(appends[1]?.provenance).toBe("ai");
|
|
149
|
+
expect(appends[1]?.html).toContain('data-grade="grain"'); // the AI's bubble is grain
|
|
150
|
+
const types = emitted.filter((o) => o.op === "type");
|
|
151
|
+
expect(types.length).toBeGreaterThan(1); // the reply streams char by char
|
|
152
|
+
expect(types.at(-1)?.done).toBe(true); // and finishes
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("chat.send escapes user input (no HTML injection at the single writer)", async () => {
|
|
156
|
+
const { tools, emitted } = fakeTools();
|
|
157
|
+
await reasoner.decide(intent({ surface: "chat-log", action: "chat.send", payload: { text: "<img src=x onerror=alert(1)>" } }), tools);
|
|
158
|
+
const you = emitted.find((o) => o.op === "append" && o.provenance === "user");
|
|
159
|
+
expect(you?.html).not.toContain("<img");
|
|
160
|
+
expect(you?.html).toContain("<img");
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("navigate: a safe href returns a single committed navigate op", async () => {
|
|
164
|
+
const { tools } = fakeTools();
|
|
165
|
+
const d = await reasoner.decide(intent({ surface: "screen", action: "navigate", payload: { href: "/notes" } }), tools);
|
|
166
|
+
expect(d.ok).toBe(true);
|
|
167
|
+
expect(d.ops).toHaveLength(1);
|
|
168
|
+
expect(d.ops[0]).toMatchObject({ op: "navigate", href: "/notes", target: "screen", commit: "committed" });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("navigate: an unsafe/missing href fails the REQUEST (not the dispatcher) — ok:false, a flash, no navigate op", async () => {
|
|
172
|
+
const { tools } = fakeTools();
|
|
173
|
+
const unsafe = await reasoner.decide(intent({ surface: "screen", action: "navigate", payload: { href: "javascript:alert(1)" } }), tools);
|
|
174
|
+
expect(unsafe.ok).toBe(false);
|
|
175
|
+
expect(unsafe.ops.some((o) => o.op === "navigate")).toBe(false);
|
|
176
|
+
expect(unsafe.ops[0]?.op).toBe("flash");
|
|
177
|
+
|
|
178
|
+
const missing = await reasoner.decide(intent({ surface: "screen", action: "navigate", payload: {} }), tools);
|
|
179
|
+
expect(missing.ok).toBe(false);
|
|
180
|
+
expect(missing.ops.some((o) => o.op === "navigate")).toBe(false);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// --- note.append / note.replace: the notepad (DEMO-PLAN piece 2) ---------------------------
|
|
184
|
+
test("note.append (ai): appends a grain entry to notepad-body carrying the markdown source", async () => {
|
|
185
|
+
const { tools } = fakeTools();
|
|
186
|
+
const d = await reasoner.decide(
|
|
187
|
+
intent({ source: "ai", screen: "notes", surface: "notepad", action: "note.append", payload: { text: "**Big** news" } }),
|
|
188
|
+
tools,
|
|
189
|
+
);
|
|
190
|
+
expect(d.ok).toBe(true);
|
|
191
|
+
const op = d.ops[0]!;
|
|
192
|
+
expect(op).toMatchObject({ target: "notepad-body", op: "append", provenance: "ai", commit: "committed" });
|
|
193
|
+
expect(op.html).toContain('data-grade="grain"'); // AI provenance persists
|
|
194
|
+
expect(op.html).toContain('data-md="**Big** news"'); // the source, for localStorage round-trip
|
|
195
|
+
expect(op.html).toContain("<strong>Big</strong>"); // rendered for the eye
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("note.append (user commit): a clean entry, no grade", async () => {
|
|
199
|
+
const { tools } = fakeTools();
|
|
200
|
+
const d = await reasoner.decide(
|
|
201
|
+
intent({ source: "user", surface: "notepad", action: "note.append", payload: { text: "mine" } }),
|
|
202
|
+
tools,
|
|
203
|
+
);
|
|
204
|
+
expect(d.ops[0]!.provenance).toBe("user");
|
|
205
|
+
expect(d.ops[0]!.html).not.toContain("data-grade");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("note.replace: rebuilds the notepad-body wrapper so the surface stays addressable", async () => {
|
|
209
|
+
const { tools } = fakeTools();
|
|
210
|
+
const d = await reasoner.decide(
|
|
211
|
+
intent({ source: "ai", surface: "notepad", action: "note.replace", payload: { text: "fresh" } }),
|
|
212
|
+
tools,
|
|
213
|
+
);
|
|
214
|
+
const op = d.ops[0]!;
|
|
215
|
+
expect(op).toMatchObject({ target: "notepad-body", op: "replace" });
|
|
216
|
+
expect(op.html).toContain('data-surface="notepad-body"');
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("note.append with empty text: rejected with a flash, nothing written (never a blank fact)", async () => {
|
|
220
|
+
const { tools } = fakeTools();
|
|
221
|
+
const d = await reasoner.decide(
|
|
222
|
+
intent({ source: "ai", surface: "notepad", action: "note.append", payload: { text: " " } }),
|
|
223
|
+
tools,
|
|
224
|
+
);
|
|
225
|
+
expect(d.ok).toBe(false);
|
|
226
|
+
expect(d.ops[0]!.op).toBe("flash");
|
|
227
|
+
});
|