docs: 对齐 DSH 全面优化

This commit is contained in:
czm
2026-09-14 09:18:49 +08:00
parent a24df6bb04
commit 9c90759aec
66 changed files with 2157 additions and 1634 deletions
-9
View File
@@ -7,15 +7,6 @@ import { resolve, sep } from 'node:path'
function resolveAgentNoteRoot(): string {
if (process.env.AGENT_NOTE_ROOT) return resolve(process.env.AGENT_NOTE_ROOT)
// walk up from cwd to find .agents/notes, fallback to cwd/.agents/notes
let cur = process.cwd()
for (let i = 0; i < 6; i++) {
const cand = resolve(cur, '.agents/notes')
if (existsSync(cand)) return cand
const parent = resolve(cur, '..')
if (parent === cur) break
cur = parent
}
return resolve(process.cwd(), '.agents/notes')
}
+67 -12
View File
@@ -1,17 +1,35 @@
/**
* 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
* Usage: npx tsx 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 targetArg = process.argv[2];
if (!targetArg) {
console.error("Usage: npx tsx scripts/archive-agent-note.ts <path-to-note>");
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: npx tsx 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)) {
@@ -42,11 +60,27 @@ if (statusIdx === -1) {
process.exit(1);
}
const today = new Date().toISOString().slice(0, 10);
// Insert Archived line after Status line if not present
// 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}`);
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
@@ -90,23 +124,44 @@ const sortedFiles = Object.fromEntries(
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
// 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");
if (content.includes(filename)) {
inboundFound.push(note.rel);
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 reference the archived note:");
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 reference this archived note.");
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})`);
}
}
+20 -3
View File
@@ -64,7 +64,24 @@ if (!existsSync(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];
@@ -77,12 +94,12 @@ function parseNoteContent(raw: string, relPath: string, slugToId: Map<string, st
const dMatch = /^(\d{4}-\d{2}-\d{2})/.exec(slug);
if (dMatch) date = dMatch[1];
const h1Match = /^# Agent Note[^::]*[::]\s*(.*)$/m.exec(raw);
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*$)`, 'm');
const m = re.exec(raw);
const m = re.exec(parseable);
return m ? m[1].trim() : '';
}
@@ -92,7 +109,7 @@ function parseNoteContent(raw: string, relPath: string, slugToId: Map<string, st
const consequences = extractSection('Consequences|后果');
const links: string[] = [];
for (const m of raw.matchAll(/\]\(([^)]+\.md)\)/g)) {
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');
+103
View File
@@ -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: npx tsx 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`);
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Export every assets/*.svg to a @2x PNG next to it (SVG is the source of truth).
# Usage: bash scripts/export-assets.sh # all SVGs
# bash scripts/export-assets.sh hero # just hero.svg
set -euo pipefail
cd "$(dirname "$0")/.."
EXPORTER=""
if command -v rsvg-convert >/dev/null 2>&1; then
EXPORTER="rsvg-convert"
elif command -v inkscape >/dev/null 2>&1; then
EXPORTER="inkscape"
else
echo "error: need rsvg-convert (brew install librsvg) or inkscape to export PNGs" >&2
exit 1
fi
filter="${1:-}"
failed=0
for svg in assets/*.svg; do
base="$(basename "$svg" .svg)"
if [ -n "$filter" ] && [ "$base" != "$filter" ]; then
continue
fi
png="assets/${base}.png"
case "$EXPORTER" in
rsvg-convert)
rsvg-convert -w 2800 -o "$png" "$svg" ;;
inkscape)
inkscape "$svg" -w 2800 -o "$png" >/dev/null ;;
esac
if [ -s "$png" ]; then
echo "ok: $svg -> $png"
else
echo "FAILED: $svg" >&2
failed=1
fi
done
exit "$failed"
+87 -32
View File
@@ -1,21 +1,21 @@
/**
* 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: npx tsx 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 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 PROBLEM_FIRST = ["## Problem", "## 问题"];
const REQUIRED: Record<string, string[][]> = {
proposed: [
["## Proposal", "## 提议", "## 方案", "## 提案"],
@@ -31,60 +31,115 @@ const REQUIRED: Record<string, string[][]> = {
],
};
const BANNED_IMPLEMENTED = /^## (?:Proposal\b|Plan\b|Migration plan\b|Acceptance criteria\b|计划\b|规划\b)/i;
const BANNED_IMPLEMENTED = new Set([
"## proposal", "## plan", "## migration plan", "## acceptance criteria",
"## 提议", "## 方案", "## 提案",
"## 计划", "## 规划", "## 迁移计划",
"## 验收标准", "## 验收条件", "## 接受标准",
]);
const ALTERNATIVES_RE = /^## (?:Alternatives considered|.{0,8}?(?:替代方案|备选方案))$/;
/** 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 raw = readFileSync(resolve(agentNoteRoot, note.rel), "utf8");
const lines = raw.split("\n");
let inFence = false;
const prose = lines.filter((l: string) => {
if (l.startsWith("```")) { inFence = !inFence; return false; }
return !inFence;
});
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]);
if (!/^# Agent Note: \S/.test(lines[0] ?? "")) fail("line 1 must be `# Agent Note: <title>`");
// 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
const statusCount = prose.filter((l: string) => l.startsWith("Status:")).length;
// 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 t === "Status: proposed" || t === "Status: implemented" || /^Status: rejected — .+$/.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());
if (h2s[0] !== "## Problem" && h2s[0] !== "## 问题") {
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] ?? []) {
const matched = group.some((h: string) => h2s.some((item: string) => item.startsWith(h)));
if (!matched) fail(`missing one of ${JSON.stringify(group)}`);
if (!group.some((h: string) => bases.includes(h))) fail(`missing one of ${JSON.stringify(group)}`);
}
if (note.lifecycle === "implemented") {
for (const h of h2s.filter((x: string) => BANNED_IMPLEMENTED.test(x))) {
for (const h of bases.filter((x: string) => BANNED_IMPLEMENTED.has(x.toLowerCase()))) {
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 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 (!bases.some((h: string) => ALTERNATIVES_RE.test(h))) {
fail("missing ## Alternatives considered / ## 备选方案");
}
}
+4 -3
View File
@@ -3,7 +3,7 @@
* Run: npx tsx scripts/verify-agent-note-tree.ts
*/
import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { dirname, resolve, sep } from "node:path";
import { agentNoteRoot, walkAgentNoteTree } from "./agent-note-tree.ts";
const { notes, errors } = walkAgentNoteTree();
@@ -31,8 +31,9 @@ for (const note of notes) {
const resolvedTarget = resolve(dirname(noteFullPath), fileTarget);
// Only verify internal links within agentNoteRoot
if (!resolvedTarget.startsWith(agentNoteRoot)) {
// Only verify internal links within agentNoteRoot (boundary-aware: a
// sibling like .agents/notes-backup/ must not prefix-match)
if (!resolvedTarget.startsWith(agentNoteRoot + sep)) {
continue;
}
+125
View File
@@ -0,0 +1,125 @@
/**
* Verify frozen archived Agent Notes: exact head layout, manifest.json seals,
* append-only extension vs a git baseline (skipped gracefully without git).
* Usage:
* npx tsx scripts/verify-archived-agent-notes.ts # verify only
* npx tsx 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")) {
files.push(relative(archivedDir, full).split("\\").join("/"));
}
}
}
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`);