baodan/.agents/skills/impeccable/scripts/lib/surface-briefs.mjs
wsb1224 e3479f0546 上线阻断问题全部修复
#	问题	修复	文件
1	前端构建失败(引号错误)	size="small type=" → size="small" type="	PosterHistoryPage.vue
2	migrate_014 ORM vs 缺失列	全部改为原始 SQL,不再引用 ORM 模型	migrate_014.py
3	cleanup 字段名错误	output_path → ppt_path	cleanup.py
4	文案生成 case 越权	添加 case.user_id != user_id 校验	poster/service.py
5	存储路径未接通持久化卷	全部改用 get_storage_root()(默认 /app/api/storage/insurance)	config.py, ppt/routes.py, poster/service.py, poster/tasks.py
高风险问题修复
#	问题	修复	文件
6	migrate_019 rollback 撤销成功字段	每个 ALTER 后立即 commit,失败只回滚当前语句	migrate_019.py
7	迁移锁 Windows 不兼容 + 句柄未持久化	全局变量保存锁句柄,支持 Windows msvcrt	api/insurance/db/__init__.py
8	PDF 校验异常时放行	异常返回 False(文件损坏)	security.py
9	健康检查始终返回成功	缺少关键资源时返回 503 + missing 列表	poster/routes.py
10	短密钥掩码泄露原值	≤4 字符返回 ****	ppt_admin_service.py
11	设置无键名白名单	添加 _ALLOWED_SETTING_KEYS 白名单	ppt_admin_service.py
12	容器重启任务永久 stuck	添加 recover_stale_tasks() 启动恢复函数	poster/tasks.py, ppt/parse_worker.py
2026-07-27 13:52:09 +08:00

152 lines
6.1 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { slugFromTarget } from './target-slug.mjs';
export const SURFACE_BRIEF_VERSION = 1;
export function getSurfaceBriefDir(projectRoot) {
return path.join(projectRoot, '.impeccable', 'surfaces');
}
export function normalizeSurfaceTarget(target, { projectRoot = process.cwd() } = {}) {
if (!target || typeof target !== 'string' || !target.trim()) return null;
const trimmed = target.trim();
if (/^https?:\/\//i.test(trimmed)) {
try {
const url = new URL(trimmed);
url.hash = '';
url.search = '';
return url.toString().replace(/\/$/, '') || url.origin;
} catch {
return null;
}
}
if (/^route:/i.test(trimmed)) {
const route = trimmed.slice(trimmed.indexOf(':') + 1).trim();
if (!route.startsWith('/') || route.includes('..')) return null;
const normalizedRoute = route.split(/[?#]/, 1)[0].replace(/\/{2,}/g, '/').replace(/\/$/, '') || '/';
return `route:${normalizedRoute}`;
}
if (trimmed === '/') return 'route:/';
if (trimmed.startsWith('/')) {
const absolute = path.resolve(trimmed);
const relativeToProject = path.relative(projectRoot, absolute);
const isProjectFile = relativeToProject && !relativeToProject.startsWith('..') && !path.isAbsolute(relativeToProject);
if (!isProjectFile && !fs.existsSync(absolute) && !trimmed.includes('..')) {
const normalizedRoute = trimmed.split(/[?#]/, 1)[0].replace(/\/{2,}/g, '/').replace(/\/$/, '') || '/';
return `route:${normalizedRoute}`;
}
}
const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(projectRoot, trimmed);
const rel = path.relative(projectRoot, abs);
if (!rel || rel === '.' || rel.startsWith('..') || path.isAbsolute(rel)) return null;
return rel.split(path.sep).join('/');
}
export function surfaceBriefPathForTarget(target, { projectRoot = process.cwd() } = {}) {
const normalized = normalizeSurfaceTarget(target, { projectRoot });
if (!normalized) return null;
const slugInput = normalized.startsWith('route:') ? `route${normalized.slice('route:'.length)}` : normalized;
const slug = slugFromTarget(slugInput, { cwd: projectRoot });
return slug ? path.join(getSurfaceBriefDir(projectRoot), `${slug}.md`) : null;
}
export function parseSurfaceBrief(text, filePath = null) {
const match = String(text || '').match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
const meta = {};
if (match) {
for (const line of match[1].split(/\r?\n/)) {
const colon = line.indexOf(':');
if (colon < 0) continue;
const key = line.slice(0, colon).trim();
const raw = line.slice(colon + 1).trim();
if (!key) continue;
if (/^(?:\[|\{|\")/.test(raw) || /^(?:true|false|null|-?\d+(?:\.\d+)?)$/.test(raw)) {
try { meta[key] = JSON.parse(raw); continue; } catch { /* keep string */ }
}
meta[key] = raw.replace(/^['"]|['"]$/g, '');
}
}
const primaryTarget = typeof meta.primary_target === 'string' ? meta.primary_target : null;
const relatedTargets = Array.isArray(meta.related_targets)
? meta.related_targets.filter((value) => typeof value === 'string')
: [];
return {
path: filePath,
text: String(text || ''),
body: match ? String(text || '').slice(match[0].length).trim() : String(text || '').trim(),
meta,
slug: typeof meta.slug === 'string' ? meta.slug : filePath ? path.basename(filePath, '.md') : null,
primaryTarget,
relatedTargets,
targets: [primaryTarget, ...relatedTargets].filter(Boolean),
};
}
export function listSurfaceBriefs(projectRoot = process.cwd()) {
const dir = getSurfaceBriefDir(projectRoot);
let names;
try {
names = fs.readdirSync(dir).filter((name) => name.endsWith('.md')).sort();
} catch {
return [];
}
return names.flatMap((name) => {
const filePath = path.join(dir, name);
try {
return [parseSurfaceBrief(fs.readFileSync(filePath, 'utf-8'), filePath)];
} catch {
return [];
}
});
}
export function resolveSurfaceBrief(projectRoot = process.cwd(), target = null) {
const briefs = listSurfaceBriefs(projectRoot);
if (!target) {
return {
brief: briefs.length === 1 ? briefs[0] : null,
candidates: briefs,
reason: briefs.length === 1 ? 'only-brief' : briefs.length > 1 ? 'ambiguous' : 'none',
};
}
const normalized = normalizeSurfaceTarget(target, { projectRoot });
if (!normalized) return { brief: null, candidates: briefs, reason: 'invalid-target' };
const exactPath = surfaceBriefPathForTarget(normalized, { projectRoot });
const exact = briefs.find((brief) => brief.path === exactPath && (!brief.targets.length || brief.targets.includes(normalized)));
if (exact) return { brief: exact, candidates: briefs, reason: 'slug' };
const mapped = briefs.filter((brief) => brief.targets.includes(normalized));
return {
brief: mapped.length === 1 ? mapped[0] : null,
candidates: mapped.length > 1 ? mapped : briefs,
reason: mapped.length === 1 ? 'mapping' : mapped.length > 1 ? 'ambiguous-target' : 'not-found',
};
}
export function writeSurfaceBrief({
projectRoot = process.cwd(),
primaryTarget,
relatedTargets = [],
body,
}) {
const normalizedPrimary = normalizeSurfaceTarget(primaryTarget, { projectRoot });
if (!normalizedPrimary) throw new Error('surface brief requires a concrete project-relative primary target or URL');
const normalizedRelated = [...new Set(relatedTargets
.map((target) => normalizeSurfaceTarget(target, { projectRoot }))
.filter((target) => target && target !== normalizedPrimary))];
const slug = slugFromTarget(normalizedPrimary, { cwd: projectRoot });
const filePath = surfaceBriefPathForTarget(normalizedPrimary, { projectRoot });
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const frontmatter = [
'---',
`version: ${SURFACE_BRIEF_VERSION}`,
`slug: ${JSON.stringify(slug)}`,
`primary_target: ${JSON.stringify(normalizedPrimary)}`,
`related_targets: ${JSON.stringify(normalizedRelated)}`,
'---',
].join('\n');
fs.writeFileSync(filePath, `${frontmatter}\n\n${String(body || '').trim()}\n`, 'utf-8');
return filePath;
}