docs: 共有技能收归 meta 单一份并加工作区级笔记校验入口

- write-notes-like-deepseek 从三个子仓库的重复副本改为 meta 唯一副本
- 新增 .agents/scripts/verify-notes.ts,从 meta 视角一次校验四个笔记根
- workspace-layout 补「共有技能单一来源」的落位与理由
- .rgignore 排除 archived 历史快照
This commit is contained in:
cat-shark
2026-11-18 14:59:45 +08:00
parent a194477b65
commit f99e1e156d
27 changed files with 3767 additions and 11 deletions
@@ -0,0 +1,75 @@
/**
* Shared structural source of truth for the Agent Note tree.
* Portable: resolves .agents/notes from cwd (or AGENT_NOTE_ROOT env).
*/
import { readdirSync, existsSync } from 'node:fs'
import { resolve } from 'node:path'
/** Recurse `dir` and return posix-relative `.md` paths prefixed with `prefix`. Node 18 compatible (no fs.globSync). */
function listMd(dir: string, prefix: string): string[] {
if (!existsSync(dir)) return []
const out: string[] = []
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith('.')) continue
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
if (entry.isDirectory()) out.push(...listMd(resolve(dir, entry.name), rel))
else if (entry.isFile() && entry.name.endsWith('.md')) out.push(rel)
}
return out
}
function resolveAgentNoteRoot(): string {
if (process.env.AGENT_NOTE_ROOT) return resolve(process.env.AGENT_NOTE_ROOT)
return resolve(process.cwd(), '.agents/notes')
}
export const agentNoteRoot = resolveAgentNoteRoot()
const AGENT_NOTE_LIFECYCLES = ['proposed', 'implemented', 'rejected'] as const
export const AGENT_NOTE_CLASSES = ['feature', 'bug-fix', 'simplification', 'architecture', 'process', 'testing'] as const
const AGENT_NOTE_ARCHIVE = 'archived'
const ROOT_ALLOWLIST = new Set(['AGENTS.md', 'CLAUDE.md'])
export interface AgentNote {
lifecycle: string
rel: string
date: string
}
export function walkAgentNoteTree(): { notes: AgentNote[]; errors: string[] } {
const notes: AgentNote[] = []
const errors: string[] = []
if (!existsSync(agentNoteRoot)) return { notes, errors }
for (const entry of readdirSync(agentNoteRoot, { withFileTypes: true })) {
if (entry.name === 'INDEX.md') {
errors.push('structure: INDEX.md — centralized Agent Note indexes are forbidden; browse the lifecycle/class tree or search the repository')
continue
}
if (entry.isDirectory() && entry.name !== AGENT_NOTE_ARCHIVE && !(AGENT_NOTE_LIFECYCLES as readonly string[]).includes(entry.name)) {
errors.push(`structure: ${entry.name}/ — unknown lifecycle folder (allowed: ${AGENT_NOTE_LIFECYCLES.join(', ')}, plus ${AGENT_NOTE_ARCHIVE}/)`)
}
}
for (const lifecycle of AGENT_NOTE_LIFECYCLES) {
for (const match of listMd(resolve(agentNoteRoot, lifecycle), lifecycle).sort()) {
const segs = match.split('/')
if (segs.length === 2 && ROOT_ALLOWLIST.has(segs[1] ?? '')) continue
if (match.endsWith('.zh.md')) continue
const cls = segs[1]
const base = segs[2]
if (segs.length !== 3 || cls === undefined || base === undefined) {
errors.push(`structure: ${match} — expected {lifecycle}/{class}/file.md (got depth ${segs.length})`)
continue
}
if (!(AGENT_NOTE_CLASSES as readonly string[]).includes(cls)) {
errors.push(`structure: ${match} — unknown class folder "${cls}" (allowed: ${AGENT_NOTE_CLASSES.join(', ')})`)
continue
}
if (!/^\d{4}-\d{2}-\d{2}-.+\.md$/.test(base)) {
errors.push(`structure: ${match} — filename must be yyyy-mm-dd-topic.md`)
continue
}
notes.push({ lifecycle, rel: match, date: base.slice(0, 10) })
}
}
return { notes, errors }
}
@@ -0,0 +1,167 @@
/**
* CLI tool to archive an implemented Agent Note with frozen manifest sealing.
* Usage: node <skill-dir>/scripts/archive-agent-note.ts .agents/notes/implemented/<class>/<filename>.md [--superseded-by <new-note-path>]
* --superseded-by writes a relative link into the NEW note, never into the archived file.
*/
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 args = process.argv.slice(2);
const targetArg = args[0];
const supersededByArgIdx = args.indexOf("--superseded-by");
const supersededByArg = supersededByArgIdx !== -1 ? args[supersededByArgIdx + 1] : undefined;
if (supersededByArgIdx !== -1 && !supersededByArg) {
console.error("Error: --superseded-by requires a note path");
process.exit(1);
}
if (!targetArg) {
console.error("Usage: node <skill-dir>/scripts/archive-agent-note.ts <path-to-note> [--superseded-by <new-note-path>]");
process.exit(1);
}
let successorPath: string | undefined;
let successorRel: string | undefined;
if (supersededByArg) {
successorPath = resolve(process.cwd(), supersededByArg);
if (!existsSync(successorPath)) {
console.error(`Error: --superseded-by target not found at ${successorPath}`);
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);
}
// Local calendar date, not UTC — toISOString() would roll the archived stamp
// back one day for evening runs east of the prime meridian.
const nowLocal = new Date();
const pad2 = (n: number) => String(n).padStart(2, "0");
const today = `${nowLocal.getFullYear()}-${pad2(nowLocal.getMonth() + 1)}-${pad2(nowLocal.getDate())}`;
// DSH contract: `Archived:` sits immediately below `Status:` (L3/L4).
if (!lines.some((l) => l.startsWith("Archived:"))) {
lines.splice(statusIdx + 1, 0, `Archived: ${today}`);
}
if (successorPath) {
const rel = relative(agentNoteRoot, successorPath).replace(/\\/g, "/");
successorRel = rel;
const successorSegs = rel.split("/");
if (successorSegs.length !== 3 || !["proposed", "implemented", "rejected"].includes(successorSegs[0] ?? "")) {
console.error(`Error: --superseded-by target must be an active note in {lifecycle}/{class}/ (got: ${rel})`);
process.exit(1);
}
}
const oldTitle = (lines[0] ?? "").replace(/^# Agent Note[::] ?/, "").trim() || basename(filename, ".md");
const updatedContent = lines.join("\n");
// 2. Determine archived destination
const archivedDir = join(agentNoteRoot, "archived", cls);
mkdirSync(archivedDir, { recursive: true });
const archivedPath = join(archivedDir, filename);
if (existsSync(archivedPath)) {
console.error(`Error: target archived note already exists at ${archivedPath}`);
console.error("Refusing to overwrite existing archived note. Please inspect and resolve name collision manually.");
process.exit(1);
}
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 (precise markdown-link resolution)
const { notes } = walkAgentNoteTree();
const inboundFound: string[] = [];
const LINK_REGEX = /\[([^\]]+)\]\(([^)]+)\)/g;
for (const note of notes) {
const noteFullPath = resolve(agentNoteRoot, note.rel);
const content = readFileSync(noteFullPath, "utf8");
let match: RegExpExecArray | null;
LINK_REGEX.lastIndex = 0;
while ((match = LINK_REGEX.exec(content)) !== null) {
const rawTarget = match[2]?.trim();
if (!rawTarget || rawTarget.startsWith("http://") || rawTarget.startsWith("https://") || rawTarget.startsWith("#") || rawTarget.startsWith("mailto:")) continue;
const fileTarget = rawTarget.split("#")[0];
if (!fileTarget) continue;
// resolve the link relative to the linking note, then compare with the archived note's original location
const resolvedTarget = resolve(dirname(noteFullPath), fileTarget);
if (resolvedTarget === targetPath) {
inboundFound.push(note.rel);
break;
}
}
}
if (inboundFound.length > 0) {
console.log("\n[Notice] The following active notes link to 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 link to this archived note.");
}
if (successorPath && successorRel) {
const relLink = relative(dirname(successorPath), archivedPath).replace(/\\/g, "/");
const newRaw = readFileSync(successorPath, "utf8");
if (!newRaw.includes(`archived/${cls}/${filename}`) && !newRaw.includes(relLink)) {
writeFileSync(successorPath, `${newRaw.replace(/\s*$/, "")}\n\n[历史快照:${oldTitle}](${relLink})\n`, "utf8");
console.log(`Linked from ${successorRel}: [历史快照:${oldTitle}](${relLink})`);
}
}
@@ -0,0 +1,235 @@
#!/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);
}
// 检查参数
const isInitMode = args.includes('--init');
const isForce = args.includes('--force') || args.includes('-f');
const isMetadataOnly = args.includes('--metadata-only');
const cleanArgs = args.filter((a: string) => !a.startsWith('--') && !a.startsWith('-'));
function checkTargetSafety(targetPath: string) {
if (existsSync(targetPath) && !isForce) {
try {
const existing = readFileSync(targetPath, 'utf8');
const isBoard = existing.includes('generator" content="agent-notes-board"') || existing.includes('id="brand-project-title"');
if (!isBoard) {
console.error(`❌ 错误:目标文件已存在 (${targetPath}) 且并非看板生成文件!`);
console.error(`💡 为防止意外覆盖已有项目页面(如 Vite/React/Vue 项目的 index.html),请指定其他输出路径或传入 --force 确认覆盖。`);
process.exit(1);
}
} catch {}
}
}
if (isInitMode) {
const targetPath = cleanArgs[0] ? resolve(cleanArgs[0]) : resolve(process.cwd(), 'board.html');
const projectName = cleanArgs[1] || '工程决策看板';
checkTargetSafety(targetPath);
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] || '工程决策看板';
checkTargetSafety(outputPath);
const LIFECYCLES = ['implemented', 'proposed', 'rejected', 'archived'];
if (!existsSync(notesDir)) {
console.error(`❌ Notes directory not found at: ${notesDir}`);
process.exit(1);
}
/** Blank out fenced code-block lines so `## ` headings and [](.md) links inside them are never parsed as note structure. */
function stripFencedBlocks(raw: string): string {
let inFence = false;
return raw
.replace(/\r\n?/g, "\n")
.split("\n")
.map((l) => {
if (/^\s{0,3}```/.test(l)) {
inFence = !inFence;
return "";
}
return inFence ? "" : l;
})
.join("\n");
}
function parseNoteContent(raw: string, relPath: string, slugToId: Map<string, string>) {
const parseable = stripFencedBlocks(raw);
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(parseable);
if (h1Match) title = h1Match[1].trim();
function extractSection(secNamePattern: string) {
const re = new RegExp(`^## (?:${secNamePattern})\\s*\\n+([\\s\\S]*?)(?=^## |(?![\\s\\S]))`, 'm');
const m = re.exec(parseable);
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 parseable.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。`);
if (isMetadataOnly) {
console.log('🔒 [安全脱敏] 启用 --metadata-only 模式,已剥离所有笔记的具体正文和详细论证,仅保留决策元数据与关联拓扑。');
for (const n of notes) {
n.problem = '[正文已脱敏]';
n.decision = '[正文已脱敏]';
n.alternatives = '';
n.consequences = '';
n.rawBody = `# Agent Note: ${n.title}\n\nStatus: ${n.status}\n\n<!-- content redacted for public demo -->`;
}
} else {
console.log('⚠️ [安全提示] 正在生成包含完整正文的数据包。如需对外公开发布且避免泄露内部决策细节,请添加 --metadata-only 参数。');
}
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。`);
@@ -0,0 +1,103 @@
/**
* Soft report: physical reverse anchors (`// Note: ... 见 .agents/notes/...`).
* A. anchors in source code pointing at notes that do not exist (dangling)
* B. implemented notes with zero inbound code anchors (suspected missing anchor)
* Exit code is always 0 — this is an advisory report, not a gate.
* Env: AGENT_NOTE_CODE_ROOT (default: cwd) — source root to scan.
* Run: node <skill-dir>/scripts/check-note-anchors.ts
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const codeRoot = resolve(process.env.AGENT_NOTE_CODE_ROOT || process.cwd());
const CODE_EXT = new Set([
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
".py", ".go", ".rs", ".java", ".kt", ".c", ".cc", ".cpp", ".h", ".hpp",
".cs", ".rb", ".swift", ".vue", ".svelte", ".php",
]);
const SKIP_DIR = new Set([
"node_modules", ".git", "dist", "build", "out", "coverage", ".next",
".cache", ".agents", "vendor", "target",
]);
const ANCHOR_RE = /(?:\/\/|#|\/\*|\*\s*|<!--\s*)\s*Note[::]/;
const PATH_RE = /\.agents\/notes\/([^\s'"`)>]+?\.md)/;
const anchorHits = new Map<string, string[]>(); // note rel (from notes root, lowercased basename fallback) -> [code rel:line]
const dangling: string[] = [];
const notePathRefs: string[] = [];
function walk(dir: string, depth: number) {
if (depth > 12) return;
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (entry.name.startsWith(".") && entry.name !== ".agents") continue;
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (!SKIP_DIR.has(entry.name)) walk(full, depth + 1);
continue;
}
const dot = entry.name.lastIndexOf(".");
if (dot === -1 || !CODE_EXT.has(entry.name.slice(dot))) continue;
const rel = full.slice(codeRoot.length + 1);
const lines = readFileSync(full, "utf8").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n");
for (let i = 0; i < lines.length; i++) {
const l = lines[i];
if (!ANCHOR_RE.test(l)) continue;
const m = PATH_RE.exec(l);
if (!m) {
notePathRefs.push(`${rel}:${i + 1} — Note anchor without a .agents/notes path`);
continue;
}
const noteRel = m[1].split("#")[0].replace(/^\.\//, "");
const key = noteRel.replace(/\\/g, "/");
const list = anchorHits.get(key) ?? [];
list.push(`${rel}:${i + 1}`);
anchorHits.set(key, list);
if (!existsSync(join(agentNoteRoot, key))) {
dangling.push(`${rel}:${i + 1} — .agents/notes/${key} does not exist`);
}
}
}
}
walk(codeRoot, 0);
// implemented notes with zero inbound anchors
const { notes } = walkAgentNoteTree();
const implemented = notes.filter((n) => n.lifecycle === "implemented");
// basename -> note count: a slug shared by several notes is ambiguous and
// must not let one note's anchor count for another.
const slugCount = new Map<string, number>();
for (const n of notes) {
const slug = n.rel.split("/").pop()!;
slugCount.set(slug, (slugCount.get(slug) ?? 0) + 1);
}
const unanchored: string[] = [];
for (const n of implemented) {
const slug = n.rel.split("/").pop()!;
const direct = anchorHits.get(n.rel) ?? anchorHits.get(n.rel.replace(/\\/g, "/"));
const bySlug = [...anchorHits.keys()].filter((k) => k === slug || k.endsWith("/" + slug));
if (!direct && (bySlug.length === 0 || (slugCount.get(slug) ?? 0) > 1)) unanchored.push(n.rel);
}
console.log(`scanned: ${codeRoot}`);
console.log(`anchors found: ${[...anchorHits.values()].reduce((a, b) => a + b.length, 0)} across ${anchorHits.size} note(s)`);
if (notePathRefs.length) {
console.log(`\n[anchors without note path] ${notePathRefs.length}`);
for (const r of notePathRefs.slice(0, 20)) console.log(` - ${r}`);
}
if (dangling.length) {
console.log(`\n[dangling anchors] ${dangling.length}`);
for (const d of dangling.slice(0, 20)) console.log(` - ${d}`);
} else {
console.log("\n[dangling anchors] none");
}
console.log(`\n[implemented notes without any code anchor] ${unanchored.length} of ${implemented.length}`);
for (const u of unanchored.slice(0, 20)) console.log(` - ${u}`);
if (unanchored.length > 20) console.log(` ... and ${unanchored.length - 20} more`);
@@ -0,0 +1,158 @@
/**
* Enforce Agent Note headers, lifecycle-specific sections, alternatives.
* Implemented notes may not carry proposal-era H2s; present tense in the
* body is a prose rule, not a lexical scan.
* Run: node <skill-dir>/scripts/verify-agent-note-format.ts
*/
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const STATUS: Record<string, RegExp> = {
proposed: /^Status: proposed$|^状态[::] ?(?:proposed|已提议)$/,
implemented: /^Status: implemented$|^状态[::] ?(?:implemented|已实现)$/,
rejected: /^Status: rejected — .+$|^状态[::] ?(?:rejected|已否决) — .+$/,
};
const PROBLEM_FIRST = ["## Problem", "## 问题"];
const REQUIRED: Record<string, string[][]> = {
proposed: [
["## Proposal", "## 提议", "## 方案", "## 提案"],
["## Acceptance criteria", "## 验收标准", "## 验收条件", "## 接受标准"],
["## Risks", "## 风险"],
],
implemented: [
["## Decision", "## 决定", "## 决策"],
["## Consequences", "## 后果", "## 影响", "## 结果", "## 结果与代价", "## 影响与验证", "## 后果与边界"],
],
rejected: [
["## Proposal", "## 提议", "## 方案", "## 提案"],
],
};
const BANNED_IMPLEMENTED = new Set([
"## proposal", "## plan", "## migration plan", "## acceptance criteria",
"## 提议", "## 方案", "## 提案",
"## 计划", "## 规划", "## 迁移计划",
"## 验收标准", "## 验收条件", "## 接受标准",
]);
const ALTERNATIVES_RE = /^## (?:Alternatives considered|.{0,8}?(?:替代方案|备选(?:方案)?|其他做法))$/;
const FORMAT_ADOPTED = "2026-07-05";
const GRANDFATHER = "<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) -->";
/** Strip trailing parenthetical: `## Decision(说明)` → `## Decision`. */
function headingBase(h: string): string {
return h.replace(/[((].*$/, "").trimEnd();
}
interface MaskedSource {
lines: string[];
/** line indexes inside fenced code blocks */
fenced: boolean[];
/** line indexes inside HTML comments */
commented: boolean[];
}
/** Normalize BOM/CRLF, then mask fenced code and HTML comment regions. */
function maskSource(raw: string): MaskedSource {
const normalized = raw.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
const lines = normalized.split("\n");
const fenced = new Array<boolean>(lines.length).fill(false);
const commented = new Array<boolean>(lines.length).fill(false);
let inFence = false;
let inComment = false;
for (let i = 0; i < lines.length; i++) {
const l = lines[i];
fenced[i] = inFence;
commented[i] = inComment;
// A fence opens/closes only on its own line (≤3 leading spaces); fence
// mentions inside inline code or prose never toggle state.
if (!inComment && /^\s{0,3}```/.test(l)) {
fenced[i] = true;
inFence = !inFence;
} else if (inFence) {
fenced[i] = true;
}
// Fence interiors are opaque: a `<!--` in a HTML/JSX sample must not
// leak the comment mask past the closing fence.
if (inFence) continue;
const openIdx = inComment ? -1 : l.indexOf("<!--");
const closeIdx = l.indexOf("-->");
if (inComment) {
commented[i] = true;
if (closeIdx !== -1) inComment = false;
} else if (openIdx !== -1) {
commented[i] = true;
if (closeIdx === -1 || closeIdx < openIdx) inComment = true;
}
}
return { lines, fenced, commented };
}
function isProseLine(src: MaskedSource, i: number): boolean {
if (src.fenced[i] || src.commented[i]) return false;
return !/^\s*>/.test(src.lines[i]);
}
const { notes, errors } = walkAgentNoteTree();
for (const note of notes) {
const fail = (msg: string) => { errors.push(`format: ${note.rel} — ${msg}`); };
const src = maskSource(readFileSync(resolve(agentNoteRoot, note.rel), "utf8"));
const { lines } = src;
const proseIdx: number[] = [];
for (let i = 0; i < lines.length; i++) if (isProseLine(src, i)) proseIdx.push(i);
const prose = proseIdx.map((i) => lines[i]);
// Halfwidth or fullwidth colon (IME often inserts :)
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 (fences, quotes and comments immune). Match strict
// status-shaped lines only — body prose like "Status: 200 means OK" must
// not be miscounted as a duplicate status header.
const looksLikeStatusLine = (l: string) => {
const t = l.trim();
return Object.values(STATUS).some((re) => re.test(t));
};
const statusCount = prose.filter(looksLikeStatusLine).length;
if (statusCount !== 1) fail("Status: line must appear exactly once");
const h2s = prose.filter((l: string) => l.startsWith("## ")).map((l: string) => l.trimEnd());
const bases = h2s.map(headingBase);
if (!PROBLEM_FIRST.includes(headingBase(h2s[0] ?? ""))) {
fail(`first section must be ## Problem or ## 问题 (got ${JSON.stringify(h2s[0] ?? "<none>")})`);
}
for (const group of REQUIRED[note.lifecycle] ?? []) {
if (!group.some((h: string) => bases.includes(h))) fail(`missing one of ${JSON.stringify(group)}`);
}
if (note.lifecycle === "implemented") {
for (const h of bases.filter((x: string) => BANNED_IMPLEMENTED.has(x.toLowerCase()))) {
fail(`banned in implemented: ${h}`);
}
}
const hasSection = bases.some((h: string) => ALTERNATIVES_RE.test(h));
const rawText = readFileSync(resolve(agentNoteRoot, note.rel), "utf8");
const hasGrandfather = rawText.includes(GRANDFATHER);
if (hasSection && hasGrandfather) fail("carries both ## Alternatives considered and grandfather comment — drop the comment");
if (!hasSection && !hasGrandfather) {
fail("missing ## Alternatives considered / ## 备选方案");
}
if (hasGrandfather && note.date >= FORMAT_ADOPTED) fail(`grandfather comment only valid before ${FORMAT_ADOPTED}`);
}
if (errors.length) {
for (const e of errors) console.error(e);
process.exit(1);
}
console.log(`ok: ${notes.length} note(s) verified`);
@@ -0,0 +1,56 @@
/**
* Verify tree: lifecycle/class/filename/INDEX and internal relative markdown links.
* Run: node <skill-dir>/scripts/verify-agent-note-tree.ts
*/
import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve, sep } from "node:path";
import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const { notes, errors } = walkAgentNoteTree();
// 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) {
let rawTarget = match[2]?.trim();
if (!rawTarget) continue;
// Support CommonMark angle bracket destinations: [text](<path>)
if (rawTarget.startsWith("<") && rawTarget.endsWith(">")) {
rawTarget = rawTarget.slice(1, -1).trim();
}
// 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 (boundary-aware: a
// sibling like .agents/notes-backup/ must not prefix-match)
if (!resolvedTarget.startsWith(agentNoteRoot + sep)) {
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`);
@@ -0,0 +1,127 @@
/**
* Verify frozen archived Agent Notes: exact head layout, manifest.json seals,
* append-only extension vs a git baseline (skipped gracefully without git).
* Usage:
* node <skill-dir>/scripts/verify-archived-agent-notes.ts # verify only
* node <skill-dir>/scripts/verify-archived-agent-notes.ts --write # verify, then seal unsealed files
* Env: AGENT_NOTE_ARCHIVE_BASE_REF (default HEAD) — git ref the manifest is compared against.
*/
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
import { agentNoteRoot } from "./agent-note-tree.ts";
const isWrite = process.argv.includes("--write");
const errors: string[] = [];
const warnings: string[] = [];
const fail = (msg: string) => { errors.push(msg); };
// --- collect archived files (skip accidental .zh.md)
const archivedDir = join(agentNoteRoot, "archived");
const files: string[] = [];
function scan(dir: string) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (entry.isDirectory()) scan(full);
else if (entry.isFile() && entry.name.endsWith(".md") && !entry.name.endsWith(".zh.md")) {
const rel = relative(archivedDir, full).split("\\").join("/");
if (rel === "AGENTS.md" || rel === "manifest.json") continue;
files.push(rel);
}
}
}
if (existsSync(archivedDir)) scan(archivedDir);
// --- head layout: L1 title / L2 blank / L3 Status / L4 Archived / L5 blank
const TITLE_RE = /^# Agent Note[::] ?\S/;
const ARCHIVED_RE = /^Archived: \d{4}-\d{2}-\d{2}$/;
for (const rel of files) {
const lines = readFileSync(join(archivedDir, rel), "utf8").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n");
if (!TITLE_RE.test(lines[0] ?? "")) fail(`${rel} — line 1 must be \`# Agent Note: <title>\``);
if (lines[1] !== "") fail(`${rel} — line 2 must be blank`);
if (lines[2] !== "Status: implemented") fail(`${rel} — line 3 must be \`Status: implemented\``);
if (!ARCHIVED_RE.test(lines[3] ?? "")) fail(`${rel} — line 4 must be \`Archived: YYYY-MM-DD\` immediately below Status`);
if (lines[4] !== "") fail(`${rel} — line 5 must be blank after Archived`);
}
// --- manifest seals
const manifestPath = join(archivedDir, "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 {
fail("archived/manifest.json exists but is not valid JSON");
}
} else if (files.length > 0 && !isWrite) {
fail("archived/manifest.json missing — run with --write to seal existing archived notes");
}
const sealOf = (relFromRoot: string) =>
`sha256:${createHash("sha256").update(readFileSync(join(agentNoteRoot, relFromRoot))).digest("hex")}`;
for (const rel of files) {
const key = `archived/${rel}`;
const entry = manifest.files[key];
if (!entry) {
if (isWrite) {
manifest.files[key] = sealOf(key);
} else {
fail(`${key} — missing seal in manifest.json (run with --write)`);
}
} else if (entry !== sealOf(key)) {
fail(`${key} — seal mismatch: archived note was modified after sealing (frozen notes must never change)`);
}
}
for (const key of Object.keys(manifest.files)) {
if (!existsSync(join(agentNoteRoot, key))) fail(`${key} — sealed entry has no file on disk`);
}
// --- append-only vs git baseline (skipped without git)
const repoRoot = (() => {
try {
return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: agentNoteRoot, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
} catch {
return null;
}
})();
if (repoRoot) {
const baseRef = process.env.AGENT_NOTE_ARCHIVE_BASE_REF || "HEAD";
const manifestRel = relative(repoRoot, manifestPath).split("\\").join("/");
let baselineRaw: string | null = null;
try {
baselineRaw = execFileSync("git", ["show", `${baseRef}:${manifestRel}`], { cwd: repoRoot, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
} catch {
// manifest absent at baseline — nothing to compare
}
if (baselineRaw !== null) {
try {
const baseline = JSON.parse(baselineRaw) as Manifest;
for (const [key, seal] of Object.entries(baseline.files ?? {})) {
if (manifest.files[key] !== seal) {
fail(`${key} — seal added/changed/removed relative to ${baseRef}; archived seals are append-only`);
}
}
} catch {
fail(`archived/manifest.json at ${baseRef} was not valid JSON`);
}
}
} else {
warnings.push("not a git repository — append-only check skipped (seal hashes still verified against disk)");
}
if (errors.length) {
for (const e of errors) console.error(`archived: ${e}`);
process.exit(1);
}
if (isWrite) {
const sorted = Object.fromEntries(Object.entries(manifest.files).sort(([a], [b]) => a.localeCompare(b)));
writeFileSync(manifestPath, JSON.stringify({ version: 1, files: sorted }, null, 2) + "\n", "utf8");
}
for (const w of warnings) console.warn(`warning: ${w}`);
console.log(`ok: ${files.length} archived note(s) verified, ${Object.keys(manifest.files).length} seal(s) in manifest`);