@lemonriver/core 0.4.0 → 0.6.0

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 (115) hide show
  1. package/README.md +14 -4
  2. package/dist/{build-Nl7EeJ6x.js → build-RlcGG-Ve.js} +1 -1
  3. package/dist/cli/bin.js +4 -4
  4. package/dist/{config-CpC0nM3r.js → config-BJT87wE9.js} +4756 -2012
  5. package/dist/{dev-BB3THd5I.js → dev-DR-j_xda.js} +2 -2
  6. package/dist/{preview-BGjgTg7H.js → preview-BTAhTb5B.js} +1 -1
  7. package/dist/{update-DsxZBtwv.js → update-CMRxtTc9.js} +18 -8
  8. package/dist/vite/index.js +1 -1
  9. package/package.json +2 -2
  10. package/src/agent/types.ts +14 -2
  11. package/src/app/components/agent/agent-panel.tsx +17 -5
  12. package/src/app/components/agent/connect-view.tsx +1 -1
  13. package/src/app/components/agent/provider-logo.tsx +10 -1
  14. package/src/app/lemonriver/agent/provider-marks.tsx +53 -0
  15. package/src/app/lemonriver/agent-providers/section.tsx +75 -0
  16. package/src/app/lemonriver/agent-providers/use-providers.ts +61 -0
  17. package/src/app/lemonriver/board/blocks/block-panel.tsx +666 -0
  18. package/src/app/lemonriver/board/blocks/cache.ts +28 -0
  19. package/src/app/lemonriver/board/blocks/change-list.tsx +189 -0
  20. package/src/app/lemonriver/board/blocks/classify.test.ts +209 -0
  21. package/src/app/lemonriver/board/blocks/classify.ts +152 -0
  22. package/src/app/lemonriver/board/blocks/snapshot.ts +116 -0
  23. package/src/app/lemonriver/board/board-canvas.tsx +627 -104
  24. package/src/app/lemonriver/board/board-page.tsx +1702 -91
  25. package/src/app/lemonriver/board/board.css +58 -7
  26. package/src/app/lemonriver/board/layout.test.ts +84 -0
  27. package/src/app/lemonriver/board/layout.ts +112 -11
  28. package/src/app/lemonriver/board/model/agent-tasks.test.ts +200 -0
  29. package/src/app/lemonriver/board/model/agent-tasks.ts +223 -0
  30. package/src/app/lemonriver/board/model/apply-prompt.test.ts +121 -0
  31. package/src/app/lemonriver/board/model/apply-prompt.ts +115 -0
  32. package/src/app/lemonriver/board/model/apply.ts +71 -0
  33. package/src/app/lemonriver/board/model/cards.test.ts +95 -2
  34. package/src/app/lemonriver/board/model/cards.ts +88 -20
  35. package/src/app/lemonriver/board/model/changes.test.ts +244 -0
  36. package/src/app/lemonriver/board/model/changes.ts +268 -0
  37. package/src/app/lemonriver/board/model/filter.test.ts +50 -0
  38. package/src/app/lemonriver/board/model/filter.ts +42 -0
  39. package/src/app/lemonriver/board/model/history.test.ts +71 -0
  40. package/src/app/lemonriver/board/model/history.ts +51 -0
  41. package/src/app/lemonriver/board/model/restructure.test.ts +205 -0
  42. package/src/app/lemonriver/board/model/restructure.ts +169 -0
  43. package/src/app/lemonriver/board/model/self-check.test.ts +329 -0
  44. package/src/app/lemonriver/board/model/self-check.ts +489 -0
  45. package/src/app/lemonriver/board/model/structure.test.ts +249 -0
  46. package/src/app/lemonriver/board/model/structure.ts +209 -0
  47. package/src/app/lemonriver/board/model/timing.test.ts +113 -0
  48. package/src/app/lemonriver/board/model/timing.ts +117 -0
  49. package/src/app/lemonriver/board/page-node.tsx +258 -55
  50. package/src/app/lemonriver/board/self-check-jump.ts +23 -0
  51. package/src/app/lemonriver/board/self-check-panel.tsx +272 -0
  52. package/src/app/lemonriver/board/self-check-runner.tsx +150 -0
  53. package/src/app/lemonriver/board/status-style.ts +25 -0
  54. package/src/app/lemonriver/board/use-board-apply.ts +206 -0
  55. package/src/app/lemonriver/board/use-board-cards.ts +108 -5
  56. package/src/app/lemonriver/board/use-board-changes.ts +108 -0
  57. package/src/app/lemonriver/board/use-board-columns.ts +37 -56
  58. package/src/app/lemonriver/board/use-board-comments.ts +36 -0
  59. package/src/app/lemonriver/board/use-board-restructures.ts +107 -0
  60. package/src/app/lemonriver/board/use-history.ts +86 -0
  61. package/src/app/lemonriver/board/use-page-order.ts +65 -38
  62. package/src/app/lemonriver/board/use-self-check.ts +117 -0
  63. package/src/app/lemonriver/board/use-target-minutes.ts +47 -0
  64. package/src/app/lemonriver/board/views/block-readings.tsx +46 -0
  65. package/src/app/lemonriver/board/views/list-view.tsx +356 -0
  66. package/src/app/lemonriver/board/views/progress.tsx +32 -0
  67. package/src/app/lemonriver/board/views/timeline-view.tsx +341 -0
  68. package/src/app/lemonriver/chrome/filter-pill.tsx +30 -0
  69. package/src/app/lemonriver/chrome/sidebar-extras.tsx +12 -1
  70. package/src/app/lemonriver/features.test.ts +5 -0
  71. package/src/app/lemonriver/features.ts +2 -1
  72. package/src/app/lemonriver/home/deck-card.tsx +10 -0
  73. package/src/app/lemonriver/home/home-page.tsx +55 -6
  74. package/src/app/lemonriver/home/use-deck-times.ts +4 -1
  75. package/src/app/lemonriver/outline/build-team.tsx +42 -0
  76. package/src/app/lemonriver/outline/describe-page.tsx +128 -27
  77. package/src/app/lemonriver/outline/draft.ts +38 -0
  78. package/src/app/lemonriver/outline/model.test.ts +118 -0
  79. package/src/app/lemonriver/outline/model.ts +92 -7
  80. package/src/app/lemonriver/outline/outline-page.tsx +90 -7
  81. package/src/app/lemonriver/outline/pick-style.tsx +282 -0
  82. package/src/app/lemonriver/routes.test.tsx +17 -5
  83. package/src/app/lemonriver/routes.tsx +28 -0
  84. package/src/app/lemonriver/settings/settings-page.tsx +3 -0
  85. package/src/app/lemonriver/slide-extensions.tsx +14 -2
  86. package/src/app/lemonriver/templates/client.ts +60 -0
  87. package/src/app/lemonriver/templates/demo-page.tsx +79 -0
  88. package/src/app/lemonriver/templates/knobs.test.ts +62 -0
  89. package/src/app/lemonriver/templates/knobs.ts +62 -0
  90. package/src/app/lemonriver/templates/library-page.tsx +292 -0
  91. package/src/app/lemonriver/templates/model.test.ts +175 -0
  92. package/src/app/lemonriver/templates/model.ts +339 -0
  93. package/src/app/lemonriver/templates/preview-content.test.ts +117 -0
  94. package/src/app/lemonriver/templates/preview-content.ts +149 -0
  95. package/src/app/lemonriver/templates/recommend.test.ts +71 -0
  96. package/src/app/lemonriver/templates/recommend.ts +72 -0
  97. package/src/app/lemonriver/templates/use-library.ts +58 -0
  98. package/src/app/lemonriver/templates/virtual.d.ts +28 -0
  99. package/src/app/lemonriver/text/en.ts +228 -0
  100. package/src/app/lemonriver/text/es.ts +220 -0
  101. package/src/app/lemonriver/text/ja.ts +220 -0
  102. package/src/app/lemonriver/text/types.ts +243 -0
  103. package/src/app/lemonriver/text/zh-cn.ts +218 -0
  104. package/src/app/lemonriver/text/zh-tw.ts +218 -0
  105. package/src/app/lemonriver/theme/lemon-icon.tsx +6 -0
  106. package/src/app/lemonriver/theme/pages.test.ts +4 -0
  107. package/src/app/lemonriver/theme/pages.ts +6 -1
  108. package/src/app/lemonriver/theme/theme-menu.tsx +3 -2
  109. package/src/app/lemonriver/theme/use-theme.tsx +2 -2
  110. package/src/app/lemonriver/update/prompt.ts +1 -1
  111. package/src/app/lib/agent/use-agent.ts +4 -3
  112. package/src/app/routes/slide.tsx +1 -1
  113. package/src/app/assets/open-slide.svg +0 -39
  114. package/src/app/favicon.ico +0 -0
  115. package/src/app/favicon.svg +0 -39
@@ -0,0 +1,223 @@
1
+ import { type OutlinePage, sanitizeItems } from '../../outline/model.ts';
2
+ import { type Finding, sanitizeFindings } from './self-check.ts';
3
+
4
+ export const PAGE_ACTIONS = ['rewrite', 'chart', 'memo', 'expand'] as const;
5
+ export type PageAction = (typeof PAGE_ACTIONS)[number];
6
+
7
+ export const MAX_PLAN_ITEMS = 8;
8
+ export const MAX_CHAPTER_BRIEF = 500;
9
+ export const MAX_CHAPTER_TITLE = 120;
10
+ export const MAX_FINDINGS = 40;
11
+
12
+ /** One thing the board asks the agent to do. `changes` is the hand-over list. */
13
+ export type BoardTask =
14
+ | { kind: 'changes' }
15
+ | { kind: 'page'; page: string; action: PageAction }
16
+ | { kind: 'chapter-plan'; chapter: number; title: string; brief: string; count: number }
17
+ | { kind: 'chapter-write'; chapter: number; title: string }
18
+ | { kind: 'self-check'; findings: Finding[] };
19
+
20
+ export function isPageAction(value: unknown): value is PageAction {
21
+ return typeof value === 'string' && (PAGE_ACTIONS as readonly string[]).includes(value);
22
+ }
23
+
24
+ function wholeNumber(value: unknown, min: number, max: number): number | null {
25
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
26
+ return null;
27
+ }
28
+ return value;
29
+ }
30
+
31
+ export function sanitizeTask(raw: unknown): BoardTask | null {
32
+ if (!raw || typeof raw !== 'object') return null;
33
+ const task = raw as Record<string, unknown>;
34
+ switch (task.kind) {
35
+ case 'changes':
36
+ return { kind: 'changes' };
37
+ case 'page': {
38
+ if (!isPageAction(task.action)) return null;
39
+ if (typeof task.page !== 'string' || task.page === '') return null;
40
+ return { kind: 'page', page: task.page, action: task.action };
41
+ }
42
+ case 'chapter-plan': {
43
+ const chapter = wholeNumber(task.chapter, 0, 999);
44
+ const count = wholeNumber(task.count, 1, MAX_PLAN_ITEMS);
45
+ if (chapter === null || count === null) return null;
46
+ return {
47
+ kind: 'chapter-plan',
48
+ chapter,
49
+ title: typeof task.title === 'string' ? task.title.slice(0, MAX_CHAPTER_TITLE) : '',
50
+ brief: typeof task.brief === 'string' ? task.brief.slice(0, MAX_CHAPTER_BRIEF).trim() : '',
51
+ count,
52
+ };
53
+ }
54
+ case 'chapter-write': {
55
+ const chapter = wholeNumber(task.chapter, 0, 999);
56
+ if (chapter === null) return null;
57
+ return {
58
+ kind: 'chapter-write',
59
+ chapter,
60
+ title: typeof task.title === 'string' ? task.title.slice(0, MAX_CHAPTER_TITLE) : '',
61
+ };
62
+ }
63
+ case 'self-check': {
64
+ const findings = sanitizeFindings(task.findings).slice(0, MAX_FINDINGS);
65
+ return findings.length > 0 ? { kind: 'self-check', findings } : null;
66
+ }
67
+ default:
68
+ return null;
69
+ }
70
+ }
71
+
72
+ const QUOTED = (title: string) => (title ? ` "${title}"` : '');
73
+
74
+ const LANGUAGE = (lang: string) => `Write in the language "${lang}".`;
75
+
76
+ const DONE = 'When you are done, reply with one short sentence saying what changed.';
77
+
78
+ const ACTION_LINE: Record<Exclude<PageAction, 'memo'>, string> = {
79
+ rewrite: 'Rewrite this page: keep what it says, make it clearer and better laid out.',
80
+ chart: 'Turn the main numbers on this page into a chart. Keep the title and the point it makes.',
81
+ expand:
82
+ 'Expand this page into two pages: keep this one, and add one more right after it that goes deeper. Add a speaker note for the new page.',
83
+ };
84
+
85
+ /** The problems a finished deck's self-check found, one line each. */
86
+ export function selfCheckPrompt({
87
+ slideId,
88
+ findings,
89
+ lang,
90
+ }: {
91
+ slideId: string;
92
+ findings: readonly Finding[];
93
+ lang: string;
94
+ }): string {
95
+ const lines = findings.map((finding) => {
96
+ const box = finding.boxes[0];
97
+ const at = box ? ` at (${Math.round(box.x)}, ${Math.round(box.y)})` : '';
98
+ const times = finding.count > 1 ? ` (${finding.count} places)` : '';
99
+ return `- page ${finding.page}: ${finding.detail}${times}${at}`;
100
+ });
101
+ return [
102
+ `A finished deck at slides/${slideId}/index.tsx was checked automatically and these problems were found:`,
103
+ ...lines,
104
+ 'Fix only what is listed above, and only on those pages. Change nothing else, and do not add or remove pages.',
105
+ LANGUAGE(lang),
106
+ DONE,
107
+ ].join('\n');
108
+ }
109
+
110
+ /** The message for one page. A note action without a note has nothing to say. */
111
+ export function pageTaskPrompt({
112
+ slideId,
113
+ page,
114
+ action,
115
+ lang,
116
+ }: {
117
+ slideId: string;
118
+ page: { n: number; title: string; memo?: string };
119
+ action: PageAction;
120
+ lang: string;
121
+ }): string | null {
122
+ const memo = page.memo?.trim() ?? '';
123
+ if (action === 'memo' && !memo) return null;
124
+ const work =
125
+ action === 'memo'
126
+ ? `Change this page as the note says: ${JSON.stringify(memo)}`
127
+ : ACTION_LINE[action];
128
+ return [
129
+ `Work on page ${page.n}${QUOTED(page.title)} of slides/${slideId}/index.tsx only. Leave every other page, the theme and the speaker notes of other pages as they are.`,
130
+ work,
131
+ `${LANGUAGE(lang)} ${DONE}`,
132
+ ].join('\n');
133
+ }
134
+
135
+ /** Planning only: the agent answers with the titles, and touches no file. */
136
+ export function chapterPlanPrompt({
137
+ slideId,
138
+ chapter,
139
+ title,
140
+ brief,
141
+ count,
142
+ pages,
143
+ lang,
144
+ }: {
145
+ slideId: string;
146
+ chapter: number;
147
+ title: string;
148
+ brief: string;
149
+ count: number;
150
+ pages: { n: number; title: string }[];
151
+ lang: string;
152
+ }): string {
153
+ const now =
154
+ pages.length > 0
155
+ ? `It has these pages now: ${pages
156
+ .map((page) => `page ${page.n}${QUOTED(page.title)}`)
157
+ .join(', ')}.`
158
+ : 'It has no pages yet.';
159
+ return [
160
+ `Plan new pages for chapter ${chapter + 1}${QUOTED(title)} of slides/${slideId}/index.tsx. This turn is planning only: do not write, edit or create any file.`,
161
+ `The chapter should cover: ${brief}`,
162
+ now,
163
+ `Plan ${count} new pages that come after them.`,
164
+ LANGUAGE(lang),
165
+ 'Finish with one line of its own holding a JSON array between the tags <lemonriver-chapter> and </lemonriver-chapter>,',
166
+ 'each entry shaped like {"title": "…", "kind": "page"}.',
167
+ '"kind" is one of: cover, kpi, chart, list, page, end.',
168
+ `Give 1 to ${MAX_PLAN_ITEMS} entries.`,
169
+ ].join('\n');
170
+ }
171
+
172
+ /** Writing the titles the user settled on, right where the chapter sits. */
173
+ export function chapterWritePrompt({
174
+ slideId,
175
+ chapter,
176
+ title,
177
+ items,
178
+ anchor,
179
+ lang,
180
+ }: {
181
+ slideId: string;
182
+ chapter: number;
183
+ title: string;
184
+ items: OutlinePage[];
185
+ /** The page the new ones go after, or null for the start of the deck. */
186
+ anchor: { n: number; title: string } | null;
187
+ lang: string;
188
+ }): string {
189
+ const where = anchor
190
+ ? `, right after page ${anchor.n}${QUOTED(anchor.title)}`
191
+ : ', at the start of the deck';
192
+ const lines = items.map((item, i) => `${i + 1}. "${item.title}" (${item.kind})`);
193
+ return [
194
+ `Add these pages to chapter ${chapter + 1}${QUOTED(title)} of slides/${slideId}/index.tsx${where}.`,
195
+ ...lines,
196
+ "Follow the deck's existing theme and layout. Add a speaker note for each new page. Do not change any other page.",
197
+ `${LANGUAGE(lang)} ${DONE}`,
198
+ ].join('\n');
199
+ }
200
+
201
+ const CHAPTER_BLOCK_RE = /<lemonriver-chapter>([\s\S]*?)<\/lemonriver-chapter>/gi;
202
+
203
+ /** The last block wins, and a block still streaming in is not read at all. */
204
+ export function parseChapterBlock(text: string): OutlinePage[] | null {
205
+ let last: string | null = null;
206
+ for (const match of text.matchAll(CHAPTER_BLOCK_RE)) last = match[1] ?? '';
207
+ if (last === null) return null;
208
+ let parsed: unknown;
209
+ try {
210
+ parsed = JSON.parse(last.trim());
211
+ } catch {
212
+ return null;
213
+ }
214
+ const items = sanitizeItems(parsed).slice(0, MAX_PLAN_ITEMS);
215
+ return items.length >= 1 ? items : null;
216
+ }
217
+
218
+ export function stripChapterBlock(text: string): string {
219
+ return text
220
+ .replace(CHAPTER_BLOCK_RE, '')
221
+ .replace(/<lemonriver-chapter>[\s\S]*$/i, '')
222
+ .trim();
223
+ }
@@ -0,0 +1,121 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { applyPrompt, type PromptPage } from './apply-prompt.ts';
3
+ import type { Placement, Spot } from './changes.ts';
4
+ import type { Restructure } from './restructure.ts';
5
+
6
+ const PAGES: PromptPage[] = [
7
+ { key: 'a', n: 1, title: 'Cover' },
8
+ { key: 'b', n: 2, title: 'Ask' },
9
+ { key: 'c', n: 3, title: '' },
10
+ ];
11
+
12
+ const spot = (page: string, before: string | null = null, beforeInfo?: Spot['beforeInfo']): Spot =>
13
+ beforeInfo ? { page, before, beforeInfo } : { page, before };
14
+
15
+ const move = (to: Spot | 'parked', extra: Partial<Placement> = {}): Placement => ({
16
+ origin: { page: 'a', before: null, block: 'x' },
17
+ block: { kind: 'chart', text: 'Revenue by quarter', loc: null },
18
+ to,
19
+ ...extra,
20
+ });
21
+
22
+ function prompt(changes: Placement[], restructures: Restructure[] = []): string {
23
+ return applyPrompt({ slideId: 'deck', pages: PAGES, changes, restructures });
24
+ }
25
+
26
+ const lines = (changes: Placement[], restructures: Restructure[] = []): string[] =>
27
+ prompt(changes, restructures).split('\n');
28
+
29
+ describe('applyPrompt', () => {
30
+ it('opens with the file and the one rule, and closes with the speaker notes', () => {
31
+ const text = prompt([]);
32
+ expect(text.startsWith('Rearrange the deck slides/deck/index.tsx as listed below.')).toBe(true);
33
+ expect(text).toContain('keep every other page, the wording, the styles and the speaker notes');
34
+ expect(text.endsWith('reply with one short sentence saying what changed.')).toBe(true);
35
+ });
36
+
37
+ it('names the block, both pages and the block it goes before', () => {
38
+ const [line] = lines([
39
+ move(spot('c', 'y', { kind: 'point', text: 'Margins held', loc: null })),
40
+ ]).slice(1);
41
+ expect(line).toBe(
42
+ 'Move the chart "Revenue by quarter" from page 1 "Cover" to page 3, before the point "Margins held".',
43
+ );
44
+ });
45
+
46
+ it('says where a block at the end goes', () => {
47
+ const [line] = lines([move(spot('b'))]).slice(1);
48
+ expect(line).toBe(
49
+ 'Move the chart "Revenue by quarter" from page 1 "Cover" to page 2 "Ask", at the end.',
50
+ );
51
+ });
52
+
53
+ it('removes a block the user set aside', () => {
54
+ const [line] = lines([move('parked')]).slice(1);
55
+ expect(line).toBe('Remove the chart "Revenue by quarter" from page 1 "Cover".');
56
+ });
57
+
58
+ it('hands back the code of a block coming out of the holding area', () => {
59
+ const text = prompt([
60
+ move(spot('b', 'y', { kind: 'point', text: 'Ask first', loc: null }), {
61
+ fromParking: true,
62
+ code: '<p>Saved</p>',
63
+ }),
64
+ ]);
65
+ expect(text).toContain(
66
+ 'Add this block to page 2 "Ask", before the point "Ask first". Its code, taken from the deck before it was set aside:',
67
+ );
68
+ expect(text).toContain('```tsx\n<p>Saved</p>\n```');
69
+ });
70
+
71
+ it('splits a page by the blocks that leave it', () => {
72
+ const [line] = lines(
73
+ [],
74
+ [
75
+ {
76
+ kind: 'split',
77
+ page: 'c',
78
+ blocks: ['t', 'p'],
79
+ blockInfo: [
80
+ { id: 't', kind: 'title', text: 'Plan' },
81
+ { id: 'p', kind: 'point', text: 'Costs' },
82
+ ],
83
+ },
84
+ ],
85
+ ).slice(1);
86
+ expect(line).toBe(
87
+ 'Split page 3: move the title "Plan" and the point "Costs" onto a new page right after it.',
88
+ );
89
+ });
90
+
91
+ it('merges a page into the one before it', () => {
92
+ const [line] = lines([], [{ kind: 'merge', pages: ['b', 'c'] }]).slice(1);
93
+ expect(line).toBe(
94
+ 'Merge page 3 into page 2 "Ask": put the content of page 3 at the end of page 2 and remove page 3.',
95
+ );
96
+ });
97
+
98
+ it('names a block that has no words of its own by its kind', () => {
99
+ const [line] = lines([
100
+ move(spot('b'), { block: { kind: 'image', text: '', loc: '9:4' } }),
101
+ ]).slice(1);
102
+ expect(line).toBe('Move the image from page 1 "Cover" to page 2 "Ask", at the end.');
103
+ });
104
+
105
+ it('skips a change whose page is no longer in the deck', () => {
106
+ const text = prompt([
107
+ {
108
+ origin: { page: 'gone', before: null, block: 'x' },
109
+ block: { kind: 'text', text: 'Old', loc: null },
110
+ to: spot('b'),
111
+ },
112
+ {
113
+ origin: { page: 'a', before: null, block: 'z' },
114
+ block: { kind: 'text', text: 'Still here', loc: null },
115
+ to: 'parked',
116
+ },
117
+ ]);
118
+ expect(text).not.toContain('Old');
119
+ expect(text).toContain('Still here');
120
+ });
121
+ });
@@ -0,0 +1,115 @@
1
+ import type { BlockKind } from '../blocks/classify.ts';
2
+ import type { Placement } from './changes.ts';
3
+ import type { Restructure } from './restructure.ts';
4
+
5
+ /** A page as the prompt names it: where it sits now, and what the card calls it. */
6
+ export type PromptPage = { key: string; n: number; title: string };
7
+
8
+ export type ApplyPromptInput = {
9
+ slideId: string;
10
+ pages: PromptPage[];
11
+ changes: Placement[];
12
+ restructures: Restructure[];
13
+ };
14
+
15
+ const KIND_WORD: Record<BlockKind, string> = {
16
+ title: 'title',
17
+ point: 'point',
18
+ text: 'paragraph',
19
+ image: 'image',
20
+ chart: 'chart',
21
+ quote: 'quote',
22
+ number: 'number',
23
+ };
24
+
25
+ const OPENING = (slideId: string) =>
26
+ `Rearrange the deck slides/${slideId}/index.tsx as listed below. Change only what is listed: keep every other page, the wording, the styles and the speaker notes as they are.`;
27
+
28
+ const CLOSING =
29
+ "Keep the deck's speaker notes array aligned with the pages after any split or merge. When you are done, reply with one short sentence saying what changed.";
30
+
31
+ /** `the chart "Revenue by quarter"`, or just the kind when it has no words. */
32
+ function blockRef(kind: BlockKind, text: string): string {
33
+ return text ? `the ${KIND_WORD[kind]} "${text}"` : `the ${KIND_WORD[kind]}`;
34
+ }
35
+
36
+ function joined(refs: string[]): string {
37
+ if (refs.length <= 1) return refs[0] ?? '';
38
+ return `${refs.slice(0, -1).join(', ')} and ${refs[refs.length - 1]}`;
39
+ }
40
+
41
+ /**
42
+ * The whole change list as one message to the agent. Every line names the page
43
+ * and the block it is about, so nothing depends on where the user was looking.
44
+ */
45
+ export function applyPrompt({ slideId, pages, changes, restructures }: ApplyPromptInput): string {
46
+ const byKey = new Map(pages.map((page) => [page.key, page]));
47
+ const pageRef = (key: string): string | null => {
48
+ const page = byKey.get(key);
49
+ if (!page) return null;
50
+ return page.title ? `page ${page.n} "${page.title}"` : `page ${page.n}`;
51
+ };
52
+
53
+ const lines: string[] = [OPENING(slideId)];
54
+
55
+ for (const item of changes) {
56
+ const from = pageRef(item.origin.page);
57
+ if (!from) continue;
58
+ const block = blockRef(item.block.kind, item.block.text);
59
+
60
+ if (item.to === 'parked') {
61
+ lines.push(`Remove ${block} from ${from}.`);
62
+ continue;
63
+ }
64
+
65
+ const to = pageRef(item.to.page);
66
+ if (!to) continue;
67
+
68
+ if (item.fromParking) {
69
+ const before = item.to.beforeInfo;
70
+ const where =
71
+ item.to.before && before ? `before ${blockRef(before.kind, before.text)}` : 'at the end';
72
+ lines.push(
73
+ `Add this block to ${to}, ${where}. Its code, taken from the deck before it was set aside:`,
74
+ );
75
+ if (item.code) lines.push('', '```tsx', item.code, '```');
76
+ continue;
77
+ }
78
+
79
+ const before = item.to.beforeInfo;
80
+ // A record saved before the board kept the target block has no words for
81
+ // it; the agent then only learns the page and appends.
82
+ const tail =
83
+ item.to.before === null
84
+ ? ', at the end'
85
+ : before
86
+ ? `, before ${blockRef(before.kind, before.text)}`
87
+ : '';
88
+ lines.push(`Move ${block} from ${from} to ${to}${tail}.`);
89
+ }
90
+
91
+ for (const entry of restructures) {
92
+ if (entry.kind === 'split') {
93
+ const page = pageRef(entry.page);
94
+ if (!page) continue;
95
+ const refs = entry.blocks.map((_, at) => {
96
+ const info = entry.blockInfo?.[at];
97
+ return blockRef(info?.kind ?? 'text', info?.text ?? '');
98
+ });
99
+ if (refs.length === 0) continue;
100
+ lines.push(`Split ${page}: move ${joined(refs)} onto a new page right after it.`);
101
+ continue;
102
+ }
103
+
104
+ const [first, second] = entry.pages;
105
+ const keep = byKey.get(first);
106
+ const fold = byKey.get(second);
107
+ if (!keep || !fold) continue;
108
+ lines.push(
109
+ `Merge page ${fold.n}${fold.title ? ` "${fold.title}"` : ''} into page ${keep.n}${keep.title ? ` "${keep.title}"` : ''}: put the content of page ${fold.n} at the end of page ${keep.n} and remove page ${fold.n}.`,
110
+ );
111
+ }
112
+
113
+ lines.push(CLOSING);
114
+ return lines.join('\n');
115
+ }
@@ -0,0 +1,71 @@
1
+ import type { OutlinePage } from '../../outline/model.ts';
2
+ import { sanitizeItems } from '../../outline/model.ts';
3
+ import {
4
+ type BoardTask,
5
+ MAX_CHAPTER_BRIEF,
6
+ MAX_CHAPTER_TITLE,
7
+ MAX_PLAN_ITEMS,
8
+ sanitizeTask,
9
+ } from './agent-tasks.ts';
10
+
11
+ /** A task handed to the agent, waiting for its turn to end. */
12
+ export type BoardApplying = {
13
+ startedAt: number;
14
+ sessionId: string | null;
15
+ userItemId: string | null;
16
+ task: BoardTask;
17
+ };
18
+
19
+ /** How the last hand-over went. Written for the cards to light up. */
20
+ export type BoardLastApply = { ok: boolean; at: number; error?: string; pages: string[] };
21
+
22
+ /** The titles an agent planned for a chapter, before the user says to write them. */
23
+ export type ChapterPlan = {
24
+ chapter: number;
25
+ title: string;
26
+ brief: string;
27
+ items: OutlinePage[];
28
+ state: 'ready' | 'failed';
29
+ error?: string;
30
+ };
31
+
32
+ export function sanitizeApplying(raw: unknown): BoardApplying | null {
33
+ if (!raw || typeof raw !== 'object') return null;
34
+ const { startedAt, sessionId, userItemId, task } = raw as Record<string, unknown>;
35
+ if (typeof startedAt !== 'number' || !Number.isFinite(startedAt)) return null;
36
+ return {
37
+ startedAt,
38
+ sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,
39
+ userItemId: typeof userItemId === 'string' && userItemId ? userItemId : null,
40
+ task: sanitizeTask(task) ?? { kind: 'changes' },
41
+ };
42
+ }
43
+
44
+ export function sanitizeLastApply(raw: unknown): BoardLastApply | null {
45
+ if (!raw || typeof raw !== 'object') return null;
46
+ const { ok, at, error, pages } = raw as Record<string, unknown>;
47
+ if (typeof ok !== 'boolean' || typeof at !== 'number' || !Number.isFinite(at)) return null;
48
+ return {
49
+ ok,
50
+ at,
51
+ ...(typeof error === 'string' && error ? { error: error.slice(0, 200) } : {}),
52
+ pages: Array.isArray(pages)
53
+ ? pages.filter((page): page is string => typeof page === 'string')
54
+ : [],
55
+ };
56
+ }
57
+
58
+ export function sanitizeChapterPlan(raw: unknown): ChapterPlan | null {
59
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
60
+ const { chapter, title, brief, items, state, error } = raw as Record<string, unknown>;
61
+ if (typeof chapter !== 'number' || !Number.isInteger(chapter) || chapter < 0) return null;
62
+ if (state !== 'ready' && state !== 'failed') return null;
63
+ return {
64
+ chapter,
65
+ title: typeof title === 'string' ? title.slice(0, MAX_CHAPTER_TITLE) : '',
66
+ brief: typeof brief === 'string' ? brief.slice(0, MAX_CHAPTER_BRIEF) : '',
67
+ items: sanitizeItems(items).slice(0, MAX_PLAN_ITEMS),
68
+ state,
69
+ ...(typeof error === 'string' && error ? { error: error.slice(0, 200) } : {}),
70
+ };
71
+ }
@@ -13,6 +13,7 @@ import {
13
13
  patchCard,
14
14
  sanitizeCards,
15
15
  sanitizeLinks,
16
+ setLinkKind,
16
17
  unlinkCards,
17
18
  } from './cards.ts';
18
19
 
@@ -20,7 +21,14 @@ import {
20
21
  function run(state: CardState, entries: string[], op: PageOp) {
21
22
  const count = entries.length;
22
23
  const next = entriesAfter(op, entries, count);
23
- const nextCount = op.kind === 'move' ? count : op.kind === 'delete' ? count - 1 : count + 1;
24
+ const nextCount =
25
+ op.kind === 'delete'
26
+ ? count - 1
27
+ : op.kind === 'deleteMany'
28
+ ? count - op.indices.length
29
+ : op.kind === 'move' || op.kind === 'moveMany' || op.kind === 'reorder'
30
+ ? count
31
+ : count + 1;
24
32
  const carried = carryCards(
25
33
  state,
26
34
  pageKeys(entries, count),
@@ -199,12 +207,34 @@ describe('links', () => {
199
207
 
200
208
  it('follows both pages when the deck is reordered', () => {
201
209
  const keys = ['Close', 'Cover', 'Q3', 'Agenda'];
202
- expect(linkedPairs(keys, [{ a: 'Cover', b: 'Close' }])).toEqual([[1, 0]]);
210
+ expect(linkedPairs(keys, [{ a: 'Cover', b: 'Close' }])).toEqual([{ a: 1, b: 0 }]);
203
211
  });
204
212
 
205
213
  it('hides a link whose page is not in the deck', () => {
206
214
  expect(linkedPairs(deck, [{ a: 'Cover', b: 'Gone' }])).toEqual([]);
207
215
  });
216
+
217
+ it('carries what two pages have to do with each other', () => {
218
+ const keys = ['Close', 'Cover'];
219
+ expect(linkedPairs(keys, [{ a: 'Cover', b: 'Close', kind: 'cause' }])).toEqual([
220
+ { a: 1, b: 0, kind: 'cause' },
221
+ ]);
222
+ });
223
+
224
+ it('names a link without making a second one', () => {
225
+ const links = setLinkKind([{ a: 'A', b: 'B' }], 'B', 'A', 'cause');
226
+ expect(links).toEqual([{ a: 'A', b: 'B', kind: 'cause' }]);
227
+ expect(setLinkKind(links, 'A', 'B', null)).toEqual([{ a: 'A', b: 'B' }]);
228
+ });
229
+
230
+ it('keeps the kind when a page it points at moves', () => {
231
+ const after = run(
232
+ { cards: {}, links: [{ a: 'Cover', b: 'Q3', kind: 'contrast' }] },
233
+ ['Cover', 'Q3', 'Close'],
234
+ { kind: 'move', from: 1, to: 0 },
235
+ );
236
+ expect(after.state.links).toEqual([{ a: 'Cover', b: 'Q3', kind: 'contrast' }]);
237
+ });
208
238
  });
209
239
 
210
240
  describe('patchCard', () => {
@@ -236,4 +266,67 @@ describe('sanitize', () => {
236
266
  { a: 'A', b: 'B' },
237
267
  ]);
238
268
  });
269
+
270
+ it('keeps a kind it knows and drops one it does not', () => {
271
+ expect(
272
+ sanitizeLinks([
273
+ { a: 'A', b: 'B', kind: 'echo' },
274
+ { a: 'B', b: 'C', kind: 'because' },
275
+ { a: 'C', b: 'D' },
276
+ ]),
277
+ ).toEqual([
278
+ { a: 'A', b: 'B', kind: 'echo' },
279
+ { a: 'B', b: 'C' },
280
+ { a: 'C', b: 'D' },
281
+ ]);
282
+ });
283
+ });
284
+
285
+ describe('batch and structural operations', () => {
286
+ const state: CardState = {
287
+ cards: { Cover: { memo: 'one' }, Q3: { memo: 'two' }, Close: { memo: 'three' } },
288
+ links: [{ a: 'Q3', b: 'Close' }],
289
+ };
290
+
291
+ it('carries every card through a whole-deck reorder', () => {
292
+ const order = [3, 1, 0, 2];
293
+ const { state: next, entries } = run(state, deck, { kind: 'reorder', order });
294
+ expect(entries).toEqual(['Close', 'Agenda', 'Cover', 'Q3']);
295
+ expect(memos(next, entries, 4)).toEqual(['three', null, 'one', 'two']);
296
+ expect(next.links).toEqual([{ a: 'Q3', b: 'Close' }]);
297
+ });
298
+
299
+ it('keeps the relative order of several pages moved at once', () => {
300
+ const { state: next, entries } = run(state, deck, { kind: 'moveMany', moving: [0, 2], to: 3 });
301
+ expect(entries).toEqual(['Agenda', 'Close', 'Cover', 'Q3']);
302
+ expect(memos(next, entries, 4)).toEqual([null, 'three', 'one', 'two']);
303
+ });
304
+
305
+ it('drops the cards of every page removed at once', () => {
306
+ const { state: next, entries } = run(state, deck, { kind: 'deleteMany', indices: [0, 2] });
307
+ expect(entries).toEqual(['Agenda', 'Close']);
308
+ expect(memos(next, entries, 2)).toEqual([null, 'three']);
309
+ });
310
+ });
311
+
312
+ describe('restore', () => {
313
+ it('puts the page back under its own name, not a blank the deck must explain', () => {
314
+ const { entries } = run({ cards: {}, links: [] }, ['Cover', 'Q3', 'Close'], {
315
+ kind: 'restore',
316
+ index: 1,
317
+ entry: 'Agenda',
318
+ });
319
+ expect(entries).toEqual(deck);
320
+ expect(pageKeys(entries, 4).every(isSettledKey)).toBe(true);
321
+ });
322
+
323
+ it('lets a card written back under that name show up again', () => {
324
+ const { entries } = run({ cards: {}, links: [] }, ['Cover', 'Q3', 'Close'], {
325
+ kind: 'restore',
326
+ index: 1,
327
+ entry: 'Agenda',
328
+ });
329
+ const state = { cards: { Agenda: { memo: 'back' } }, links: [] };
330
+ expect(memos(state, entries, 4)).toEqual([null, 'back', null, null]);
331
+ });
239
332
  });