baodan/.agents/skills/impeccable/scripts/critique-storage.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

214 lines
7.9 KiB
JavaScript

#!/usr/bin/env node
/**
* Critique persistence helper.
*
* Each critique run writes a per-target snapshot to
* .impeccable/critique/<timestamp>__<slug>.md
* with a small YAML frontmatter carrying the score + P0/P1 counts.
*
* The polish workflow reads the latest matching snapshot at start as its
* fix backlog. No other skill auto-reads critique output.
*
* The slug is derived mechanically from the *resolved* primary artifact
* (file path or URL), never from the user's natural-language phrasing.
* Slug stability across runs is what lets the trend display work.
*
* CLI entry points (called from skill instructions):
* node critique-storage.mjs slug <resolved-target>
* node critique-storage.mjs write <slug> <snapshot-body-file>
* node critique-storage.mjs latest <slug>
* node critique-storage.mjs trend <slug> [limit]
*
* Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
* markdown file; the model reads it directly with its file-read tool. This
* helper only exists for operations the model can't trivially do inline
* (normalizing paths, generating filenames, globbing + parsing frontmatter).
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { getCritiqueDir } from './lib/impeccable-paths.mjs';
import { slugFromTarget } from './lib/target-slug.mjs';
export { slugFromTarget } from './lib/target-slug.mjs';
/**
* Mechanically derive a slug from a resolved target. Returns null if the
* input doesn't look like a stable identifier (empty, project root, etc).
*
* Accepts file paths and URLs. The model resolves "the homepage" to a
* concrete artifact before calling this — we never slug a natural-language
* phrase.
*/
/**
* Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
* Plain colons aren't allowed on Windows filesystems.
*/
export function nowFilenameStamp(date = new Date()) {
const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
}
/**
* Write a snapshot for `slug`. `meta` carries the small structured frontmatter
* keys read back by readTrend(). `body` is the human-readable critique
* report (everything below the frontmatter).
*
* Returns the absolute path written.
*/
export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
if (!slug) throw new Error('writeSnapshot requires a slug');
const dir = getCritiqueDir(cwd);
fs.mkdirSync(dir, { recursive: true });
const timestamp = nowFilenameStamp(now);
const filePath = path.join(dir, `${timestamp}__${slug}.md`);
// Spread `meta` first so internally computed `timestamp` and `slug`
// always win. Otherwise a caller-supplied meta blob (parsed from the
// IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
// filename in disagreement with its frontmatter and corrupting trends.
const front = serializeFrontmatter({ ...meta, timestamp, slug });
fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
return filePath;
}
function serializeFrontmatter(obj) {
const lines = ['---'];
for (const [key, value] of Object.entries(obj)) {
if (value === undefined || value === null) continue;
const str = typeof value === 'string' ? value : String(value);
// Quote strings that contain : or # to keep parsing simple.
const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
}
lines.push('---');
return lines.join('\n');
}
function parseFrontmatter(text) {
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
if (!match) return {};
const out = {};
for (const line of match[1].split(/\r?\n/)) {
const colon = line.indexOf(':');
if (colon < 0) continue;
const key = line.slice(0, colon).trim();
let value = line.slice(colon + 1).trim();
if (/^".*"$/.test(value)) {
try { value = JSON.parse(value); } catch { /* leave as-is */ }
} else if (/^-?\d+$/.test(value)) {
value = Number(value);
}
out[key] = value;
}
return out;
}
/**
* Return all snapshot files for `slug`, sorted oldest → newest.
*/
function listSnapshotsForSlug(slug, cwd) {
const dir = getCritiqueDir(cwd);
if (!fs.existsSync(dir)) return [];
const suffix = `__${slug}.md`;
return fs.readdirSync(dir)
.filter((f) => f.endsWith(suffix))
.sort()
.map((f) => path.join(dir, f));
}
/**
* Return the most recent snapshot for `slug`, or null. Polish reads this
* to find its fix backlog when the slug matches.
*/
export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
const all = listSnapshotsForSlug(slug, cwd);
if (!all.length) return null;
const latest = all[all.length - 1];
const body = fs.readFileSync(latest, 'utf-8');
return { path: latest, body, meta: parseFrontmatter(body) };
}
/**
* Return the last `limit` snapshots' frontmatter, oldest → newest.
* Critique appends a one-line trend to its output using this.
*/
export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
const all = listSnapshotsForSlug(slug, cwd);
const slice = all.slice(-limit);
return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
}
// ---- CLI ---------------------------------------------------------------
// Accept either a ready slug or a concrete target (path/URL) everywhere, so
// callers never have to run the slug step separately. Anything containing a
// path or URL marker is resolved through slugFromTarget.
function coerceSlug(value) {
if (!value) return null;
if (/^[a-z0-9-]+$/.test(value) && !value.includes('/')) return value;
return slugFromTarget(value);
}
function main(argv) {
const [cmd, ...args] = argv;
switch (cmd) {
case 'slug': {
const slug = slugFromTarget(args[0]);
if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
process.stdout.write(`${slug}\n`);
return;
}
case 'write': {
const [slugArg, bodyFile] = args;
const slug = coerceSlug(slugArg);
if (!slug || !bodyFile) { process.stderr.write('usage: write <slug-or-target> <body-file>\n'); process.exit(1); }
const raw = fs.readFileSync(bodyFile, 'utf-8');
// The body file may be a full report. The caller passes the meta as
// a JSON object on stdin if it wants structured frontmatter; otherwise
// we write with minimal metadata.
let meta = {};
const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
if (metaArg) {
try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
}
const out = writeSnapshot({ slug, meta, body: raw });
process.stdout.write(`${out}\n`);
return;
}
case 'latest': {
const latest = readLatestSnapshot(coerceSlug(args[0]));
if (!latest) { process.exit(2); }
process.stdout.write(latest.body);
return;
}
case 'trend': {
const rows = readTrend(coerceSlug(args[0]), { limit: args[1] ? Number(args[1]) : 5 });
process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
return;
}
default:
process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
process.exit(1);
}
}
function isMainModule() {
if (!process.argv[1]) return false;
try {
return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
} catch {
// pathToFileURL normalizes Windows paths; keep it as a fallback for any
// environment where realpath is unavailable.
return import.meta.url === pathToFileURL(process.argv[1]).href;
}
}
// Why the realpath check: generated skills are often reached through symlinked
// harness directories (for example a demo repo's `.agents` -> source `.agents`).
// Node resolves import.meta.url to the real file, while process.argv[1] keeps
// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
if (isMainModule()) {
main(process.argv.slice(2));
}