gongxiangp2/apps/detail-agent-pi/src/enterprise-rules.mjs

127 lines
8.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { digest } from './store.mjs';
import { FONT_FALLBACKS } from './rules.mjs';
const sha = text => createHash('sha256').update(text).digest('hex');
const chunks = text => Array.from({ length: Math.ceil(text.length / 1500) }, (_, i) => text.slice(i * 1500, (i + 1) * 1500));
// Heading boundaries are structural, not substring offsets. Only explicitly
// relevant sections and their safe descendants are copied to model rules.
function markdownSections(text) {
const lines = text.replace(/\r\n?/g, '\n').split('\n');
const sections = [];
let section = null, fence = null;
for (const line of lines) {
const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
if (marker && !fence) fence = { character: marker[1][0], length: marker[1].length };
else if (marker && marker[1][0] === fence?.character && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
if (marker || fence) continue;
const heading = line.match(/^ {0,3}(#{1,6})\s+(.+?)\s*#*\s*$/);
if (heading) {
section = { level: heading[1].length, title: heading[2].trim(), lines: [line] };
sections.push(section);
} else if (section) section.lines.push(line);
}
return sections;
}
const excludedSection = title => /人物|模特|素材索引|资源索引|主图|图库|头像/i.test(title);
const brandRule = /品牌风格|品牌调性|视觉风格|视觉规范|色彩|排版|提示词|验收/;
function selectSections(text, include) {
const levels = [];
const selected = [];
for (const section of markdownSections(text)) {
levels.length = section.level;
const parent = levels.slice(0, section.level).reverse().find(Boolean);
const excluded = Boolean(parent?.excluded) || excludedSection(section.title);
const allowed = !excluded && (include(section.title) || Boolean(parent?.allowed));
levels[section.level] = { allowed, excluded };
if (allowed) selected.push(section);
}
return selected;
}
const sectionText = sections => sections.map(section => section.lines.join('\n').trim()).join('\n\n');
function brandSection(text, name) {
const sections = markdownSections(text);
const start = sections.findIndex(section => section.title === name);
if (start < 0) return '';
const level = sections[start].level;
const result = [];
// An exact shop heading can carry a directly labelled tone before any
// subheading. Only explicitly identified rule lines are admitted here.
const intro = sections[start].lines.slice(1).filter(line =>
brandRule.test(line) && !excludedSection(line));
if (intro.length) result.push(`#### 品牌视觉规范\n${intro.join('\n')}`);
for (const section of sections.slice(start + 1)) {
if (section.level <= level) break;
result.push(section.lines.join('\n').trim());
}
return result.join('\n\n');
}
/** Offline import of the colleague-maintained source. Runtime never reads the shared drive. */
export async function importEnterpriseRules(platform, sourceRoot) {
if (!platform.shops?.length || !platform.categories?.length || !platform.capturedAt) throw Error('缺少真实素材库目录快照');
const root = await fs.realpath(sourceRoot), files = new Map();
async function read(relative) {
const resolved = await fs.realpath(path.resolve(root, relative));
if (!resolved.toLowerCase().startsWith((root + path.sep).toLowerCase())) throw Error('知识来源超出授权目录');
const text = await fs.readFile(resolved, 'utf8');
if (Buffer.byteLength(text) > 2 * 1024 * 1024) throw Error('规则源文件超过2MB导入上限');
files.set(relative, { path: relative.replaceAll('\\', '/'), sha256: sha(text) });
return text;
}
const styles = await read('references/brand-style-prompts.md');
const templateCatalog = JSON.parse(await read('template-adapter/references/template-catalog.json'));
const catalog = { schemaVersion: 1, source: 'enterprise-knowledge-offline-import', platformCapturedAt: platform.capturedAt,
brands: [], shops: [], categories: platform.categories.map(c => ({ ...c, revision: digest(c), source: `material-platform:product_categories:${c.id}`, rules: [`当前品类为「${c.name}」;只使用精确登记的模板和本款产品资料。`] })), bindings: [] };
for (const shop of platform.shops) {
const name = shop.name;
const dedicatedSource = platform.brandRuleSources?.[shop.id];
if (!dedicatedSource && !markdownSections(styles).some(section => section.title === name)) continue;
const sourceFile = dedicatedSource ?? 'references/brand-style-prompts.md';
const source = dedicatedSource ? await read(sourceFile) : brandSection(styles, name);
const sections = selectSections(source, title => brandRule.test(title));
if (!sections.some(({ title, lines }) =>
(brandRule.test(title) && /[::]\s*\S/.test(title)) || lines.slice(1).some(line => line.trim())
)) {
throw Object.assign(Error(`品牌「${name}」的规则来源 ${sourceFile} 缺少可导入的规范内容`), { code: 'RULE_BRAND_SOURCE' });
}
const text = sectionText(sections);
const tone = text.match(/品牌(?:风格|调性)[::]([^\n]+)/)?.[1]?.trim() || '';
const brandId = `enterprise:${shop.id}`;
catalog.brands.push({ id: brandId, name, revision: sha(text), source: `enterprise-knowledge:${sourceFile}`,
profile: { name, tone, fontFallbacks: [...FONT_FALLBACKS], visualRules: Object.fromEntries(chunks(text).map((part, i) => [`sourcePart${i + 1}`, part])),
adaptation: '原文规范离线迁入;字体按候选顺序回退,实际可用性取决于运行环境,不宣称已移植源PS模板字体。' } });
catalog.shops.push({ ...shop, brandId, revision: digest(shop), source: `material-platform:categories:${shop.id}`, platform: 'material-library', rules: [`当前素材库店铺为「${shop.name}」,店铺ID为${shop.id}。只使用此店铺的规范;渠道与售后政策未提供,不得自行补造。`] });
}
for (const template of templateCatalog.templates.filter(t => t.status === 'ready')) {
if (![template.template_id, template.brand, template.category, template.usage_guide, template.mapping_asset_path].every(value => typeof value === 'string' && value.trim())) {
throw Object.assign(Error('模板登记缺少身份或来源路径,未建立绑定'), { code: 'RULE_MAPPING_IDENTITY' });
}
const shop = catalog.shops.find(s => s.name === template.brand), category = catalog.categories.find(c => c.name === template.category);
if (!shop || !category) continue;
const guide = await read('template-adapter/' + template.usage_guide);
const mapping = JSON.parse(await read('template-adapter/' + template.mapping_asset_path));
if (!template.template_id || !template.brand || !template.category || mapping.brand !== template.brand || mapping.category !== template.category || mapping.template_id !== template.template_id) throw Object.assign(Error('模板登记与映射范围不一致,未建立绑定'), { code: 'RULE_MAPPING_IDENTITY' });
const relevant = sectionText(selectSections(guide, title => /屏号.*固定|固定.*元素|详情.*结构|页面.*结构/.test(title)));
if (!Array.isArray(mapping.screens) || !mapping.screens.length || mapping.screens.some(s => !s.screen_id)) throw Object.assign(Error('模板缺少真实屏幕映射,未建立绑定'), { code: 'RULE_MAPPING_IDENTITY' });
const screens = mapping.screens.map(s => ({ id: s.screen_id, title: s.title, purpose: s.purpose, role: s.page_role }));
const rules = [`当前品类模板:${template.template_name}(${template.template_id},映射版本${template.mapping_version})。`,
'以下为源模板约束,不是新产品事实。源模板固定参数与本款资料冲突时先记录问题,不自动采用示例参数、销量、认证、质保或售后承诺。',
`原稿画布为${template.canvas_px.join('×')}px;保持原稿尺寸、屏序、字体及排版,仅处理当前指定字段。`,
...chunks(relevant), ...chunks('登记模块:' + JSON.stringify(screens))];
catalog.bindings.push({ id: template.template_id, shopId: shop.id, categoryId: category.id, revision: digest({ template: template.mapping_version, relevant, screens }),
source: `enterprise-knowledge:template-adapter/${template.usage_guide}`, state: 'ready', rules,
template: { id: template.template_id, sourceVersion: template.mapping_version, sourceCanvas: template.canvas_px, screens } });
}
if (!catalog.bindings.length) throw Error('未找到真实店铺与品类的精确规则绑定;未生成测试替代数据');
catalog.sourceFiles = [...files.values()];
catalog.revision = digest({ brands: catalog.brands, shops: catalog.shops, categories: catalog.categories, bindings: catalog.bindings, files: catalog.sourceFiles });
return catalog;
}