Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 41 additions & 12 deletions src/core/planner.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
// Planner: brief -> structured spec + plan artifacts.
import fs from 'node:fs/promises';
import path from 'node:path';
import { renderProductDesign, validateProductDesign } from './productDesign.js';
import { referenceContentPart } from './referenceImages.js';

export const PLANNER_SYSTEM = `You are the planner of a bounded app-replication pipeline.
Given a product brief, output STRICT JSON with keys:
summary: string
visualDesign: { layout: string, palette: [string], typography: string, spacing: string, components: [string], responsive: string }
productDesign: {
productType: string
targetUsers: [string]
tone: string
density: string
navigation: string
contentStrategy: string
tokens: { colors: object, typography: object, spacing: [string], radii: [string] }
componentLanguage: [string]
requiredStates: [{ name, trigger }]
responsiveRules: [string]
}
pages: [{ name, route, purpose, mustContain: [string], referenceImage: string|null }]
// mustContain: 2-4 short visible text fragments that MUST appear on that page (labels, headings, seeded values)
// referenceImage: exact uploaded reference file name mapped to this page, or null when no image applies
Expand All @@ -19,6 +32,10 @@ Given a product brief, output STRICT JSON with keys:
// value is required for fill; expectText is a visible string that must appear AFTER the steps run.
// Encode each testable interaction from the brief as one scenario (e.g. add item -> new row visible, search -> filtered).
Keep the app small: mock data only, no backend, no auth. Do not invent features beyond the brief.
Make productDesign values executable and product-specific, not generic phrases such as modern or clean.
Provide at least 6 color tokens, 4 typography tokens, 5 spacing values, and 3 radii.
requiredStates must contain at least 2 distinct states named loading, empty, error, or success; each trigger must be concrete and at least 4 characters.
Core productDesign text must be concrete; density may be compact, otherwise describe it with at least 8 characters.
Every mustContain fragment and every scenario.expectText must be something a correct implementation of THIS brief will actually render.`;

export function createPlannerUserContent(config) {
Expand Down Expand Up @@ -46,11 +63,15 @@ export async function plan(ctx, provider, config) {
});
ctx.addUsage(usage);
validateVisualPlan(spec, config.references ?? []);
spec.productDesign = validateProductDesign(spec?.productDesign);

const specMd = renderSpec(spec);
const planMd = renderPlan(spec, config);
await fs.writeFile(path.join(ctx.runDir, 'SPEC.generated.md'), specMd, 'utf8');
await fs.writeFile(path.join(ctx.runDir, 'PLAN.generated.md'), planMd, 'utf8');
await ctx.logEvent('design:done', {
summary: String(spec.pages?.length ?? 0) + ' pages with executable product design',
});
await ctx.logEvent('plan:done', {
summary: `${spec.pages?.length ?? 0} pages, ${spec.scenarios?.length ?? 0} scenarios planned`,
});
Expand Down Expand Up @@ -97,52 +118,60 @@ function coded(code, message) {

function renderSpec(spec) {
const lines = [
'# Generated Spec', '',
`## Summary`, '', spec.summary ?? '(none)', '',
'## Visual Design', '',
'# 生成规格 / Generated Spec', '',
'## 概要 / Summary', '', spec.summary ?? '(none)', '',
'## 视觉设计 / Visual Design', '',
`- Layout: ${spec.visualDesign?.layout ?? '(not specified)'}`,
`- Palette: ${(spec.visualDesign?.palette ?? []).join(', ') || '(not specified)'}`,
`- Typography: ${spec.visualDesign?.typography ?? '(not specified)'}`,
`- Spacing: ${spec.visualDesign?.spacing ?? '(not specified)'}`,
`- Components: ${(spec.visualDesign?.components ?? []).join(', ') || '(not specified)'}`,
`- Responsive: ${spec.visualDesign?.responsive ?? '(not specified)'}`, '',
'## Pages', '',
renderProductDesign(spec.productDesign), '',
'## 页面 / Pages', '',
...(spec.pages ?? []).flatMap((p) => [
`- **${p.name}** \`${p.route}\` - ${p.purpose}`,
` - reference image: ${p.referenceImage ? `\`${p.referenceImage}\`` : '(none)'}`,
...(p.mustContain ?? []).map((t) => ` - must contain: \`${t}\``),
]), '',
'## Components', '',
'## 组件 / Components', '',
...(spec.components ?? []).map((c) => `- **${c.name}** (used by: ${c.usedBy})`), '',
'## Data Model', '',
'## 数据模型 / Data Model', '',
...(spec.dataModel ?? []).map((d) => `- **${d.entity}**: ${(d.fields ?? []).join(', ')}`), '',
'## Interactions', '',
'## 交互 / Interactions', '',
...(spec.interactions ?? []).map((i) => `- ${i}`), '',
'## Interaction Scenarios (verified)', '',
'## 交互场景(已验证) / Interaction Scenarios (verified)', '',
...(spec.scenarios ?? []).map(
(s) => `- **${s.name}** (\`${s.route}\`): ${(s.steps ?? []).map((st) => `${st.action} "${st.target}"${st.value ? `="${st.value}"` : ''}`).join(' -> ')} => expect \`${s.expectText}\``,
), '',
'## Acceptance Criteria', '',
'## 验收标准 / Acceptance Criteria', '',
...(spec.acceptance ?? []).map((a) => `- [ ] ${a}`), '',
];
return lines.join('\n');
}

function renderPlan(spec, config) {
return [
'# Generated Plan', '',
'# 生成计划 / Generated Plan', '',
'- 产品概要 / Product Summary: ' + (spec.summary ?? '(none)'),
`- Stack: ${config.stack}`,
`- Viewport: ${config.viewport.width}x${config.viewport.height}`,
`- Max repair rounds: ${config.maxRepairRounds}`,
`- Pages to build: ${(spec.pages ?? []).map((p) => p.name).join(', ')}`,
`- Reference images: ${(config.references ?? []).map((reference) => reference.name).join(', ') || '(none)'}`,
`- Visual direction: ${spec.visualDesign?.layout ?? '(not specified)'}; ${(spec.visualDesign?.palette ?? []).join(', ') || '(no palette)'}`,
'- 产品设计 / Product design: '
+ spec.productDesign.productType
+ '; '
+ spec.productDesign.tone
+ '; '
+ spec.productDesign.density,
'',
'## Reference mapping', '',
'## 参考图映射 / Reference Mapping', '',
...(spec.pages ?? []).map(
(page) => `- **${page.name}**: ${page.referenceImage ? `\`${page.referenceImage}\`` : '(none)'}`,
), '',
'## Verification plan', '',
'## 验证计划 / Verification Plan', '',
'1. `npm install --ignore-scripts`',
'2. `npm run build`',
'3. start preview server on a free port',
Expand Down
127 changes: 127 additions & 0 deletions test/core.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,102 @@ test('planner content includes reference images and visual schema instructions',
assert.match(PLANNER_SYSTEM, /referenceImage/);
});

test('planner validates product design and writes bilingual artifacts', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vibe-planner-product-design-'));
const events = [];
const ctx = {
runDir: root,
logEvent: async (type, data) => events.push({ type, ...data }),
addUsage: () => {},
};
const config = {
brief: '构建客服质检运营工作台',
references: [],
stack: 'react-vite',
viewport: { width: 1440, height: 900 },
maxRepairRounds: 1,
};

try {
const spec = productPlanFixture();
const result = await plan(ctx, {
chatJson: async () => ({
json: spec,
usage: { prompt_tokens: 12, completion_tokens: 34 },
}),
}, config);
const [specMd, planMd] = await Promise.all([
fs.readFile(path.join(root, 'SPEC.generated.md'), 'utf8'),
fs.readFile(path.join(root, 'PLAN.generated.md'), 'utf8'),
]);

assert.deepEqual(result.productDesign, PRODUCT_DESIGN);
assert.match(PLANNER_SYSTEM, /productDesign/);
assert.match(PLANNER_SYSTEM, /productType.*targetUsers.*tone.*density.*navigation.*contentStrategy/s);
assert.match(PLANNER_SYSTEM, /colors.*typography.*spacing.*radii/s);
assert.match(PLANNER_SYSTEM, /componentLanguage.*requiredStates.*responsiveRules/s);
assert.match(PLANNER_SYSTEM, /product-specific.*not generic.*modern.*clean/is);
assert.match(PLANNER_SYSTEM, /at least 6 color tokens.*4 typography tokens.*5 spacing values.*3 radii/is);
assert.match(PLANNER_SYSTEM, /at least 2 distinct states.*loading.*empty.*error.*success/is);
assert.match(PLANNER_SYSTEM, /trigger.*at least 4 characters/is);
assert.match(PLANNER_SYSTEM, /density.*compact.*8 characters/is);
assert.match(specMd, /产品设计 \/ Product Design/);
assert.match(specMd, /客服运营主管/);
assert.match(specMd, /#2457D6/);
assert.match(planMd, /验证计划 \/ Verification Plan/);
assert.match(planMd, /数据密集型 B2B SaaS/);
assert.match(planMd, /面向客服运营团队的会话质量与风险处置工作台/);
assert.ok(events.some((event) => event.type === 'design:done'));
assert.ok(events.some((event) => event.type === 'plan:done'));
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});

test('planner rejects missing or invalid product design before writing artifacts', async () => {
for (const productDesign of [
undefined,
{ ...PRODUCT_DESIGN, tone: '现代简洁' },
]) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vibe-planner-invalid-design-'));
const events = [];
const spec = productPlanFixture();
if (productDesign === undefined) delete spec.productDesign;
else spec.productDesign = productDesign;
const ctx = {
runDir: root,
logEvent: async (type, data) => events.push({ type, ...data }),
addUsage: () => {},
};
const config = {
brief: '构建客服质检运营工作台',
references: [],
stack: 'react-vite',
viewport: { width: 1440, height: 900 },
maxRepairRounds: 1,
};

try {
await assert.rejects(
plan(ctx, { chatJson: async () => ({ json: spec }) }, config),
(error) => error.code === 'PRODUCT_DESIGN_INVALID',
);
await assert.rejects(
fs.access(path.join(root, 'SPEC.generated.md')),
(error) => error.code === 'ENOENT',
);
await assert.rejects(
fs.access(path.join(root, 'PLAN.generated.md')),
(error) => error.code === 'ENOENT',
);
assert.equal(events.some((event) => event.type === 'design:done'), false);
assert.equal(events.some((event) => event.type === 'plan:done'), false);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
}
});

test('planner rejects incomplete or unsafe visual mappings for reference jobs', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vibe-planner-visual-contract-'));
const reference = {
Expand Down Expand Up @@ -403,6 +499,37 @@ function visualDesignFixture() {
};
}

function productPlanFixture() {
return {
summary: '面向客服运营团队的会话质量与风险处置工作台。',
visualDesign: visualDesignFixture(),
productDesign: PRODUCT_DESIGN,
pages: [{
name: '质量概览',
route: '/',
purpose: '定位风险趋势与待处理会话',
mustContain: ['质量概览', '待处理会话'],
referenceImage: null,
}],
components: [
{ name: '风险指标卡', usedBy: '质量概览' },
{ name: '会话数据表', usedBy: '质量概览' },
],
dataModel: [{
entity: 'QualityConversation',
fields: ['id', 'riskLevel', 'owner', 'status'],
}],
interactions: ['按风险等级筛选会话', '批量标记复核完成'],
acceptance: ['运营人员可以从异常指标下钻到风险会话'],
scenarios: [{
name: '筛选高风险会话',
route: '/',
steps: [{ action: 'click', target: '高风险' }],
expectText: '待处理会话',
}],
};
}

test('provider retries transient gateway failures', async (t) => {
const originalFetch = globalThis.fetch;
t.after(() => {
Expand Down
Loading