File size: 10,617 Bytes
a0ebf39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
 * Structural assertion tests for the orchestration prompt templates.
 *
 * These replace the byte-equal snapshot suite that was initially added — the
 * goal here is catching real regressions (missing variables, broken role
 * dispatch, broken scene-type stripping) without forcing a snapshot update
 * for every intentional prompt-content tweak.
 */

import { describe, test, expect } from 'vitest';
import { buildStructuredPrompt } from '@/lib/orchestration/prompt-builder';
import { buildDirectorPrompt } from '@/lib/orchestration/director-prompt';
import { buildPBLSystemPrompt } from '@/lib/pbl/pbl-system-prompt';
import type { AgentConfig } from '@/lib/orchestration/registry/types';
import type { StatelessChatRequest } from '@/lib/types/chat';

const baseAgent: AgentConfig = {
  id: 'a1',
  name: 'Mr. Chen',
  role: 'teacher',
  persona: 'Patient physics teacher.',
  avatar: '',
  color: '#000',
  allowedActions: [
    'spotlight',
    'laser',
    'wb_open',
    'wb_draw_text',
    'wb_draw_latex',
    'wb_draw_shape',
    'wb_close',
  ],
  priority: 100,
  createdAt: new Date(0),
  updatedAt: new Date(0),
  isDefault: true,
};

const slideState: StatelessChatRequest['storeState'] = {
  stage: {
    id: 's1',
    name: 'Test',
    createdAt: 0,
    updatedAt: 0,
    languageDirective: 'zh-CN',
  },
  scenes: [
    {
      id: 'sc1',
      stageId: 's1',
      type: 'slide',
      title: 'T',
      order: 0,
      content: {
        type: 'slide',
        canvas: {
          id: 'c1',
          viewportSize: 1000,
          viewportRatio: 0.5625,
          theme: {
            backgroundColor: '#fff',
            themeColors: [],
            fontColor: '#333',
            fontName: 'YaHei',
          },
          elements: [],
        },
      },
    },
  ],
  currentSceneId: 'sc1',
  mode: 'autonomous',
  whiteboardOpen: false,
};

const quizState: StatelessChatRequest['storeState'] = {
  ...slideState,
  scenes: [
    {
      ...slideState.scenes[0],
      type: 'quiz',
      content: { type: 'quiz', questions: [] },
    },
  ],
};

// Matches any surviving {{placeholder}} token in rendered output
const UNRESOLVED_PLACEHOLDER = /\{\{\w[\w-]*\}\}/;

describe('no surviving placeholders', () => {
  test('agent-system / teacher / slide', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    expect(out).not.toMatch(UNRESOLVED_PLACEHOLDER);
  });

  test('director prompt', () => {
    const out = buildDirectorPrompt([baseAgent], 'No history', [], 0);
    expect(out).not.toMatch(UNRESOLVED_PLACEHOLDER);
  });

  test('pbl-design prompt', () => {
    const out = buildPBLSystemPrompt({
      projectTopic: 'Smart Garden',
      projectDescription: 'IoT project',
      targetSkills: ['IoT', 'Python'],
      issueCount: 3,
      languageDirective: 'en',
    });
    expect(out).not.toMatch(UNRESOLVED_PLACEHOLDER);
  });
});

describe('role dispatch', () => {
  test('teacher prompt carries LEAD TEACHER guideline', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    expect(out).toContain('LEAD TEACHER');
  });

  test('student prompt does NOT carry LEAD TEACHER guideline', () => {
    const studentAgent: AgentConfig = { ...baseAgent, role: 'student' };
    const out = buildStructuredPrompt(studentAgent, slideState);
    expect(out).not.toContain('LEAD TEACHER');
    expect(out).toContain('STUDENT');
  });

  test('assistant prompt carries TEACHING ASSISTANT guideline', () => {
    const assistantAgent: AgentConfig = { ...baseAgent, role: 'assistant' };
    const out = buildStructuredPrompt(assistantAgent, slideState);
    expect(out).toContain('TEACHING ASSISTANT');
    expect(out).not.toContain('LEAD TEACHER');
  });

  test('teacher whiteboard prompt is sourced from agent-system-wb-teacher template', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    expect(out).toContain('Whiteboard — Teacher Role');
  });

  test('assistant whiteboard prompt is sourced from agent-system-wb-assistant template', () => {
    const assistantAgent: AgentConfig = { ...baseAgent, role: 'assistant' };
    const out = buildStructuredPrompt(assistantAgent, slideState);
    expect(out).toContain('Whiteboard — Teaching Assistant Role');
  });

  test('student whiteboard prompt is sourced from agent-system-wb-student template', () => {
    const studentAgent: AgentConfig = { ...baseAgent, role: 'student' };
    const out = buildStructuredPrompt(studentAgent, slideState);
    expect(out).toContain('Whiteboard — Student Role');
  });
});

describe('scene-type action stripping', () => {
  test('slide scene exposes spotlight action description', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    expect(out).toMatch(/^- spotlight:/m);
  });

  test('quiz scene strips spotlight + laser from action descriptions', () => {
    const out = buildStructuredPrompt(baseAgent, quizState);
    expect(out).not.toMatch(/^- spotlight:/m);
    expect(out).not.toMatch(/^- laser:/m);
  });
});

describe('optional sections toggle on / off correctly', () => {
  test('peer context appears when other agents have spoken this round', () => {
    const out = buildStructuredPrompt(baseAgent, slideState, undefined, undefined, undefined, [
      {
        agentId: 'other',
        agentName: 'Lily',
        contentPreview: 'quick thought',
        actionCount: 1,
        whiteboardActions: [],
      },
    ]);
    expect(out).toContain("This Round's Context");
    expect(out).toContain('Lily');
  });

  test('peer context is absent when agentResponses is empty/undefined', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    expect(out).not.toContain("This Round's Context");
  });

  test('language constraint is omitted when stage.languageDirective is absent', () => {
    const stateNoLang: StatelessChatRequest['storeState'] = {
      ...slideState,
      stage: { ...slideState.stage!, languageDirective: undefined },
    };
    const out = buildStructuredPrompt(baseAgent, stateNoLang);
    expect(out).not.toContain('# Language (CRITICAL)');
  });
});

describe('director routing contract', () => {
  test('output spec mentions next_agent JSON field', () => {
    const out = buildDirectorPrompt([baseAgent], 'No history', [], 0);
    expect(out).toContain('next_agent');
  });

  test('Q&A mode omits Discussion Mode block', () => {
    const out = buildDirectorPrompt([baseAgent], 'No history', [], 0);
    expect(out).not.toContain('Discussion Mode');
  });

  test('discussion mode inserts Discussion Mode block with topic', () => {
    const out = buildDirectorPrompt(
      [baseAgent],
      'No history',
      [],
      0,
      { topic: 'Force decomposition', prompt: 'Think of real examples' },
      'student_1',
    );
    expect(out).toContain('# Discussion Mode');
    expect(out).toContain('Force decomposition');
    expect(out).toContain('student_1');
  });
});

describe('pbl-design template fills all repeated placeholders', () => {
  test('issueCount is substituted at every occurrence (3x in template)', () => {
    const UNIQUE = 42;
    const out = buildPBLSystemPrompt({
      projectTopic: 'Smart Garden',
      projectDescription: 'IoT project',
      targetSkills: ['IoT'],
      issueCount: UNIQUE,
      languageDirective: 'en',
    });
    // Template references {{issueCount}} at 3 positions:
    // "Suggested Number of Issues: N", "Create N sequential issues", "Create exactly N issues"
    const occurrences = out.match(new RegExp(`\\b${UNIQUE}\\b`, 'g'))?.length ?? 0;
    expect(occurrences).toBeGreaterThanOrEqual(3);
  });
});

describe('placeholder naming convention lint', () => {
  // The `interpolateVariables` regex is /\{\{(\w+)\}\}/, which is
  // strictly [A-Za-z0-9_]. Kebab-case placeholders would silently pass
  // through. Convention (per README) is camelCase. This test scans every
  // template for non-conforming placeholders.
  //
  // slide-content/{system,user}.md predates the convention and still uses
  // snake_case ({{canvas_width}}, {{canvas_height}}). Grandfather it here;
  // new templates must be camelCase.
  test('templates (excluding grandfathered) use camelCase placeholders', async () => {
    const { readdirSync, readFileSync, statSync } = await import('fs');
    const { join } = await import('path');

    const templatesDir = join(process.cwd(), 'lib', 'prompts', 'templates');
    const GRANDFATHERED = new Set(['slide-content']);

    const offenders: string[] = [];
    for (const promptId of readdirSync(templatesDir)) {
      if (GRANDFATHERED.has(promptId)) continue;
      const promptDir = join(templatesDir, promptId);
      if (!statSync(promptDir).isDirectory()) continue;

      for (const file of ['system.md', 'user.md']) {
        const p = join(promptDir, file);
        try {
          const content = readFileSync(p, 'utf-8');
          // Match {{placeholder}} but NOT {{snippet:name}}, {{#if}}, or {{/if}}
          const matches = content.match(/\{\{(?!snippet:|#if |\/if)([^}]+)\}\}/g) || [];
          for (const m of matches) {
            const name = m.slice(2, -2);
            // camelCase: starts with lowercase, rest alphanumeric; reject _ and -
            if (!/^[a-z][a-zA-Z0-9]*$/.test(name)) {
              offenders.push(`${promptId}/${file}: ${m}`);
            }
          }
        } catch {
          // user.md is optional
        }
      }
    }

    expect(offenders).toEqual([]);
  });
});

describe('whiteboard-reference snippet is wired into every role', () => {
  const KEY_SECTIONS = [
    'Canvas Specifications',
    'Action Reference',
    'LaTeX JSON Escape (CRITICAL)',
    'Bounds & Overlap',
    'Font Size Table',
    'Pre-Output Checklist',
  ];

  test('teacher prompt contains every key whiteboard-reference section', () => {
    const out = buildStructuredPrompt(baseAgent, slideState);
    for (const section of KEY_SECTIONS) {
      expect(out).toContain(section);
    }
  });

  test('assistant prompt contains every key whiteboard-reference section', () => {
    const assistantAgent: AgentConfig = { ...baseAgent, role: 'assistant' };
    const out = buildStructuredPrompt(assistantAgent, slideState);
    for (const section of KEY_SECTIONS) {
      expect(out).toContain(section);
    }
  });

  test('student prompt contains every key whiteboard-reference section', () => {
    const studentAgent: AgentConfig = { ...baseAgent, role: 'student' };
    const out = buildStructuredPrompt(studentAgent, slideState);
    for (const section of KEY_SECTIONS) {
      expect(out).toContain(section);
    }
  });
});