feat: 支持工程决策看板与构建体系

This commit is contained in:
czm
2026-09-08 13:34:49 +08:00
parent 9420c100bc
commit bed64d8a3f
52 changed files with 126596 additions and 191 deletions
+106
View File
@@ -0,0 +1,106 @@
/**
* CLI tool to archive an implemented Agent Note with frozen manifest sealing.
* Usage: npx tsx scripts/archive-agent-note.ts .agents/notes/implemented/<class>/<filename>.md
*/
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { basename, dirname, join, relative, resolve } from "node:path";
import { agentNoteRoot, AGENT_NOTE_CLASSES, walkAgentNoteTree } from "./agent-note-tree.ts";
const targetArg = process.argv[2];
if (!targetArg) {
console.error("Usage: npx tsx scripts/archive-agent-note.ts <path-to-note>");
process.exit(1);
}
const targetPath = resolve(process.cwd(), targetArg);
if (!existsSync(targetPath)) {
console.error(`Error: target note not found at ${targetPath}`);
process.exit(1);
}
const relToRoot = relative(agentNoteRoot, targetPath).replace(/\\/g, "/");
const segs = relToRoot.split("/");
if (segs[0] !== "implemented" || segs.length !== 3) {
console.error(`Error: only notes in .agents/notes/implemented/<class>/ can be archived (got: ${relToRoot})`);
process.exit(1);
}
const [, cls, filename] = segs;
if (!AGENT_NOTE_CLASSES.includes(cls as any)) {
console.error(`Error: unknown class "${cls}"`);
process.exit(1);
}
// 1. Read and update content with Archived line
const raw = readFileSync(targetPath, "utf8");
const lines = raw.split("\n");
const statusIdx = lines.findIndex((l) => l === "Status: implemented");
if (statusIdx === -1) {
console.error("Error: note must contain `Status: implemented` to be archived");
process.exit(1);
}
const today = new Date().toISOString().slice(0, 10);
// Insert Archived line after Status line if not present
if (!lines.some((l) => l.startsWith("Archived:"))) {
lines.splice(statusIdx + 1, 0, "", `Archived: ${today}`);
}
const updatedContent = lines.join("\n");
// 2. Determine archived destination
const archivedDir = join(agentNoteRoot, "archived", cls);
mkdirSync(archivedDir, { recursive: true });
const archivedPath = join(archivedDir, filename);
writeFileSync(targetPath, updatedContent, "utf8");
renameSync(targetPath, archivedPath);
console.log(`Moved: ${relToRoot} -> archived/${cls}/${filename}`);
// 3. Update archived/manifest.json with SHA-256 seal
const manifestPath = join(agentNoteRoot, "archived", "manifest.json");
interface Manifest {
version: 1;
files: Record<string, string>;
}
let manifest: Manifest = { version: 1, files: {} };
if (existsSync(manifestPath)) {
try {
manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
} catch (e) {
console.warn("Warning: existing manifest.json was invalid, creating fresh");
}
}
const newArchivedRel = `archived/${cls}/${filename}`;
const sha256 = `sha256:${createHash("sha256").update(readFileSync(archivedPath)).digest("hex")}`;
manifest.files[newArchivedRel] = sha256;
// Deterministic sort keys
const sortedFiles = Object.fromEntries(
Object.entries(manifest.files).sort(([a], [b]) => a.localeCompare(b))
);
writeFileSync(manifestPath, JSON.stringify({ version: 1, files: sortedFiles }, null, 2) + "\n", "utf8");
console.log(`Sealed in archived/manifest.json with hash ${sha256.slice(0, 16)}...`);
// 4. Scan inbound links in active notes
const { notes } = walkAgentNoteTree();
const inboundFound: string[] = [];
for (const note of notes) {
const noteFullPath = resolve(agentNoteRoot, note.rel);
const content = readFileSync(noteFullPath, "utf8");
if (content.includes(filename)) {
inboundFound.push(note.rel);
}
}
if (inboundFound.length > 0) {
console.log("\n[Notice] The following active notes reference the archived note:");
for (const rel of inboundFound) {
console.log(` - ${rel}`);
}
console.log("Please review and update their relative markdown links if necessary.");
} else {
console.log("\nNo active notes reference this archived note.");
}
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
import { join, resolve, relative, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const templatePath = resolve(__dirname, '../assets/agent-notes-board.html');
const args = process.argv.slice(2);
if (!existsSync(templatePath)) {
console.error(`❌ Template not found at: ${templatePath}`);
process.exit(1);
}
// 检查是否为 --init 模式(日常开发:生成 69KB 轻量模板,不内联数据,直连本地目录)
const isInitMode = args.includes('--init');
const cleanArgs = args.filter((a: string) => a !== '--init' && a !== '--bundle');
if (isInitMode) {
const targetPath = cleanArgs[0] ? resolve(cleanArgs[0]) : resolve(process.cwd(), 'index.html');
const projectName = cleanArgs[1] || '工程决策看板';
let template = readFileSync(templatePath, 'utf8');
template = template.replace('id="brand-project-title">工程决策看板<', () => `id="brand-project-title">${projectName}<`);
writeFileSync(targetPath, template, 'utf8');
console.log(`✅ [日常开发模式] 轻量看板已生成 (仅 ~69KB): ${targetPath}`);
console.log(`💡 用浏览器打开后,点击右上角「连接本地目录」选择 .agents/notes,后续新建/修改笔记切回浏览器即可自动热刷新!`);
process.exit(0);
}
// 打包模式(生成内联完整数据的单文件,如 demo.html)
const notesDir = cleanArgs[0] ? resolve(cleanArgs[0]) : resolve(process.cwd(), '.agents/notes');
const outputPath = cleanArgs[1] ? resolve(cleanArgs[1]) : resolve(process.cwd(), 'demo.html');
const projectName = cleanArgs[2] || '工程决策看板';
const LIFECYCLES = ['implemented', 'proposed', 'rejected', 'archived'];
if (!existsSync(notesDir)) {
console.error(`❌ Notes directory not found at: ${notesDir}`);
process.exit(1);
}
function parseNoteContent(raw: string, relPath: string, slugToId: Map<string, string>) {
const slug = relPath.split('/').pop()!.replace(/\.md$/, '');
const parts = relPath.split('/');
const lifecycle = parts[0];
const cls = parts[1] || 'architecture';
let title = slug;
let status = lifecycle;
let date = '';
const dMatch = /^(\d{4}-\d{2}-\d{2})/.exec(slug);
if (dMatch) date = dMatch[1];
const h1Match = /^# Agent Note[^::]*[::]\s*(.*)$/m.exec(raw);
if (h1Match) title = h1Match[1].trim();
function extractSection(secNamePattern: string) {
const re = new RegExp(`^## (?:${secNamePattern})\\s*\\n+([\\s\\S]*?)(?=^## |\\s*$)`, 'm');
const m = re.exec(raw);
return m ? m[1].trim() : '';
}
const problem = extractSection('Problem|问题');
const decision = extractSection('Decision|Proposal|决策|提案');
const alternatives = extractSection('Alternatives considered|曾考虑的替代方案|曾考虑的备选');
const consequences = extractSection('Consequences|后果');
const links: string[] = [];
for (const m of raw.matchAll(/\]\(([^)]+\.md)\)/g)) {
let targetHref = m[1].split('#')[0].trim();
if (targetHref.includes('://')) continue;
targetHref = targetHref.replace(/\.zh\.md$/, '.md');
const segs = `${lifecycle}/${cls}/${targetHref}`.split('/');
const resolved: string[] = [];
for (const s of segs) {
if (!s || s === '.') continue;
if (s === '..') resolved.pop();
else resolved.push(s);
}
const cleanTarget = resolved.join('/');
let finalTarget = '';
if (slugToId.has(cleanTarget)) {
finalTarget = slugToId.get(cleanTarget)!;
} else {
const targetSlug = targetHref.split('/').pop()!.replace(/\.md$/, '');
if (slugToId.has(targetSlug)) {
finalTarget = slugToId.get(targetSlug)!;
}
}
if (finalTarget && finalTarget !== relPath) {
links.push(finalTarget);
}
}
return {
id: relPath,
slug,
lifecycle,
cls,
date,
title,
status,
problem,
decision,
alternatives,
consequences,
outLinks: [...new Set(links)],
rawBody: raw,
};
}
function walk(dir: string, baseDir: string = dir): any[] {
const noteFiles = new Map<string, string>(); // relPath -> fullPath
function scan(currentDir: string) {
const items = readdirSync(currentDir, { withFileTypes: true });
for (const entry of items) {
if (entry.name.startsWith('.')) continue;
const fullPath = join(currentDir, entry.name);
if (entry.isDirectory()) {
scan(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
const isZh = entry.name.endsWith('.zh.md');
const relPath = relative(baseDir, fullPath).replace(/\\/g, '/');
const cleanRel = isZh ? relPath.replace(/\.zh\.md$/, '.md') : relPath;
const parts = cleanRel.split('/');
if (parts.length >= 3 && LIFECYCLES.includes(parts[0])) {
if (!noteFiles.has(cleanRel) || isZh) {
noteFiles.set(cleanRel, fullPath);
}
}
}
}
}
scan(dir);
const slugToId = new Map<string, string>();
for (const relPath of noteFiles.keys()) {
const slug = relPath.split('/').pop()!.replace(/\.md$/, '');
slugToId.set(slug, relPath);
slugToId.set(relPath, relPath);
}
const results: any[] = [];
for (const [relPath, fullPath] of noteFiles.entries()) {
try {
const raw = readFileSync(fullPath, 'utf8');
results.push(parseNoteContent(raw, relPath, slugToId));
} catch (err) {
console.warn(`⚠️ Error reading ${relPath}:`, err);
}
}
return results;
}
console.log(`🔍 [打包模式] 正在扫描笔记目录: ${notesDir}`);
const notes = walk(notesDir);
console.log(`✅ 解析完成,共发现 ${notes.length} 篇有效 Agent Notes。`);
let template = readFileSync(templatePath, 'utf8');
// 注入项目名
template = template.replace('id="brand-project-title">工程决策看板<', () => `id="brand-project-title">${projectName}<`);
// 注入数据
const jsonSafe = JSON.stringify(notes).replace(/</g, '\\u003c');
template = template.replace(
'window.__INLINE_DATA__ = null;',
() => `window.__INLINE_DATA__ = ${jsonSafe};`
);
writeFileSync(outputPath, template, 'utf8');
console.log(`🎉 [打包完成] 自包含大单体看板已生成: ${outputPath}`);
console.log(`💡 该文件内置了全部 ${notes.length} 篇笔记数据,可脱机分发、离线演示或部署至 GitHub Pages。`);
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env node
import { readdirSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join, resolve, relative, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const args = process.argv.slice(2);
const dshNotesDir = args[0] ? resolve(args[0]) : resolve(process.cwd(), '../deepseek-harness/.agents/notes');
const targetNotesDir = args[1] ? resolve(args[1]) : resolve(__dirname, '../.agents/notes');
const LIFECYCLES = ['implemented', 'proposed', 'rejected', 'archived'];
if (!existsSync(dshNotesDir)) {
console.error(`❌ Source dsh notes not found at: ${dshNotesDir}`);
process.exit(1);
}
console.log(`📦 正在从 ${dshNotesDir} 提取并标准化中文 Note...`);
// 扫描所有文件并配对:优先取 .zh.md
const noteMap = new Map<string, string>(); // cleanRelPath -> sourceFilePath
function scan(currentDir: string) {
const entries = readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith('.')) continue;
const fullPath = join(currentDir, entry.name);
if (entry.isDirectory()) {
scan(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
const rel = relative(dshNotesDir, fullPath).replace(/\\/g, '/');
const isZh = entry.name.endsWith('.zh.md');
const cleanRel = isZh ? rel.replace(/\.zh\.md$/, '.md') : rel;
const parts = cleanRel.split('/');
if (parts.length >= 3 && LIFECYCLES.includes(parts[0])) {
if (!noteMap.has(cleanRel) || isZh) {
noteMap.set(cleanRel, fullPath);
}
}
}
}
}
scan(dshNotesDir);
console.log(`🔍 扫描完毕,发现 ${noteMap.size} 篇唯一 Note 待迁移。`);
let copied = 0;
for (const [cleanRel, sourcePath] of noteMap.entries()) {
const destPath = join(targetNotesDir, cleanRel);
mkdirSync(dirname(destPath), { recursive: true });
let content = readFileSync(sourcePath, 'utf8');
// 1. 去除多余的双语切换条目,例如 `[English](xxx.md) | 中文` 或 `English | [中文](xxx.zh.md)`
content = content.replace(/^\[English\]\([^)]+\)\s*\|\s*中文\s*\n+/m, '');
content = content.replace(/^English\s*\|\s*\[中文\]\([^)]+\)\s*\n+/m, '');
content = content.replace(/^\[English\]\([^)]+\)\s*\n+/m, '');
// 2. 将文内所有的 `.zh.md` 相对链接归一化为标准的 `.md`(包括带有 #anchor 的链接)
content = content.replace(/\]\(([^)#]+)\.zh\.md([#)])/g, ']($1.md$2');
writeFileSync(destPath, content, 'utf8');
copied++;
}
// 拷贝 README.md 和 AGENTS.md 到 .agents/notes 根目录供相对跳转
for (const topDoc of ['README.zh.md', 'README.md', 'AGENTS.md']) {
const p = join(dshNotesDir, topDoc);
if (existsSync(p)) {
let topContent = readFileSync(p, 'utf8').replace(/\]\(([^)#]+)\.zh\.md([#)])/g, ']($1.md$2');
writeFileSync(join(targetNotesDir, topDoc === 'README.zh.md' ? 'README.md' : topDoc), topContent, 'utf8');
}
}
console.log(`✅ 成功将 ${copied} 篇中文 Note 标准化写入到: ${targetNotesDir}`);
+62 -17
View File
@@ -9,43 +9,88 @@ import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const FORMAT_ADOPTED = "2026-07-05";
const GRANDFATHER = "<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) -->";
const LEGACY_MARKERS = ["XXX: legacy ADR/RFC body format", "XXX: legacy ADR/Agent Note body format"];
const STATUS: Record<string, RegExp> = {
proposed: /^Status: proposed$/,
implemented: /^Status: implemented$/,
rejected: /^Status: rejected — .+$/,
};
const REQUIRED: Record<string, string[]> = {
proposed: ["## Proposal", "## Acceptance criteria", "## Risks"],
implemented: ["## Decision", "## Consequences"],
rejected: ["## Proposal"],
const REQUIRED: Record<string, string[][]> = {
proposed: [
["## Proposal", "## 提议", "## 方案", "## 提案"],
["## Acceptance criteria", "## 验收标准", "## 验收条件", "## 接受标准"],
["## Risks", "## 风险"],
],
implemented: [
["## Decision", "## 决定", "## 决策"],
["## Consequences", "## 后果", "## 影响", "## 结果"],
],
rejected: [
["## Proposal", "## 提议", "## 方案", "## 提案"],
],
};
const BANNED_IMPLEMENTED = /^## (?:Proposal\b|Plan\b|Migration plan\b|Acceptance criteria\b)/i;
const BANNED_IMPLEMENTED = /^## (?:Proposal\b|Plan\b|Migration plan\b|Acceptance criteria\b|计划\b|规划\b)/i;
const { notes, errors } = walkAgentNoteTree();
for (const note of notes) {
const fail = (msg: string) => { errors.push(`format: ${note.rel} — ${msg}`); };
const raw = readFileSync(resolve(agentNoteRoot, note.rel), "utf8");
const lines = raw.split("\n");
let inFence = false;
const prose = lines.filter((l) => { if (l.startsWith("```")) { inFence = !inFence; return false; } return !inFence; });
const prose = lines.filter((l: string) => {
if (l.startsWith("```")) { inFence = !inFence; return false; }
return !inFence;
});
if (!/^# Agent Note: \S/.test(lines[0] ?? "")) fail("line 1 must be `# Agent Note: <title>`");
if (lines[1] !== "") fail("line 2 must be blank");
const re = STATUS[note.lifecycle];
if (re && !re.test(lines[2] ?? "")) fail(`line 3 must match ${note.lifecycle} status grammar (${String(re)})`);
if (lines[3] !== "") fail("line 4 must be blank");
// single Status line
const statusCount = prose.filter((l) => l.startsWith("Status:")).length;
const statusCount = prose.filter((l: string) => l.startsWith("Status:")).length;
if (statusCount !== 1) fail("Status: line must appear exactly once");
const h2s = prose.filter((l) => l.startsWith("## ")).map((l) => l.trimEnd());
if (h2s[0] !== "## Problem") fail(`first section must be ## Problem (got ${JSON.stringify(h2s[0] ?? "<none>")})`);
for (const h of REQUIRED[note.lifecycle] ?? []) if (!h2s.includes(h)) fail(`missing ${h}`);
if (note.lifecycle === "implemented") for (const h of h2s.filter((x) => BANNED_IMPLEMENTED.test(x))) fail(`banned in implemented: ${h}`);
const hasAlt = h2s.includes("## Alternatives considered");
const h2s = prose.filter((l: string) => l.startsWith("## ")).map((l: string) => l.trimEnd());
if (h2s[0] !== "## Problem" && h2s[0] !== "## 问题") {
fail(`first section must be ## Problem or ## 问题 (got ${JSON.stringify(h2s[0] ?? "<none>")})`);
}
for (const group of REQUIRED[note.lifecycle] ?? []) {
const matched = group.some((h: string) => h2s.some((item: string) => item.startsWith(h)));
if (!matched) fail(`missing one of ${JSON.stringify(group)}`);
}
if (note.lifecycle === "implemented") {
for (const h of h2s.filter((x: string) => BANNED_IMPLEMENTED.test(x))) {
fail(`banned in implemented: ${h}`);
}
}
const hasAlt = h2s.some((h: string) =>
h.includes("Alternatives") ||
h.includes("备选") ||
h.includes("替代") ||
h.includes("取舍")
);
const hasGrandfather = prose.includes(GRANDFATHER);
if (hasAlt && hasGrandfather) fail("has both ## Alternatives considered and grandfather comment — drop the comment");
if (!hasAlt && !hasGrandfather) fail("missing ## Alternatives considered");
if (hasGrandfather && note.date >= FORMAT_ADOPTED) fail("grandfather comment only valid before " + FORMAT_ADOPTED);
if (prose.some((l) => LEGACY_MARKERS.some((m) => l.includes(m)))) fail("retired legacy-format debt marker");
if (hasAlt && hasGrandfather) fail("has both Alternatives section and grandfather comment — drop the comment");
if (!hasAlt && !hasGrandfather && note.date >= FORMAT_ADOPTED) {
fail("missing ## Alternatives considered / ## 考虑过的备选方案");
}
if (prose.some((l: string) => LEGACY_MARKERS.some((m: string) => l.includes(m)))) {
fail("retired legacy-format debt marker");
}
}
if (errors.length) { for (const e of errors) console.error(e); process.exit(1); }
if (errors.length) {
for (const e of errors) console.error(e);
process.exit(1);
}
console.log(`ok: ${notes.length} note(s) verified`);
+49 -4
View File
@@ -1,5 +1,50 @@
/** Verify tree: lifecycle/class/filename/INDEX. Run: npx tsx scripts/verify-agent-note-tree.ts */
import { walkAgentNoteTree } from "./agent-note-tree.ts";
/**
* Verify tree: lifecycle/class/filename/INDEX and internal relative markdown links.
* Run: npx tsx scripts/verify-agent-note-tree.ts
*/
import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const { notes, errors } = walkAgentNoteTree();
if (errors.length) { for (const e of errors) console.error(e); process.exit(1); }
console.log(`ok: ${notes.length} note(s) tree verified`);
// Check relative markdown links inside active notes
const LINK_REGEX = /\[([^\]]+)\]\(([^)]+)\)/g;
for (const note of notes) {
const noteFullPath = resolve(agentNoteRoot, note.rel);
const content = readFileSync(noteFullPath, "utf8");
let match: RegExpExecArray | null;
while ((match = LINK_REGEX.exec(content)) !== null) {
const rawTarget = match[2]?.trim();
if (!rawTarget) continue;
// Ignore web links, intra-page anchors and ellipsis placeholders
if (rawTarget.startsWith("http://") || rawTarget.startsWith("https://") || rawTarget.startsWith("#") || rawTarget.startsWith("mailto:") || rawTarget.includes("…")) {
continue;
}
// Strip anchor fragment if present
const fileTarget = rawTarget.split("#")[0];
if (!fileTarget) continue;
const resolvedTarget = resolve(dirname(noteFullPath), fileTarget);
// Only verify internal links within agentNoteRoot
if (!resolvedTarget.startsWith(agentNoteRoot)) {
continue;
}
if (!existsSync(resolvedTarget)) {
errors.push(`link: ${note.rel} -> "${rawTarget}" target file does not exist`);
}
}
}
if (errors.length) {
for (const e of errors) console.error(e);
process.exit(1);
}
console.log(`ok: ${notes.length} note(s) tree and relative links verified`);