repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/documents.ts
RawFile outline
- SCHEMA_VERSION line 9
- SystemDocumentError line 11
- code line 12
- constructor line 14
- nearestMarker line 21
- discoverProjectRoot line 35
- resolveGovernedPath line 50
- DOCUMENT_TYPES line 66
- DocumentType line 73
- SystemConfig line 74
- InspectedSystemConfig line 75
- ParsedDocumentId line 79
- SpecMetadata line 85
- RoadmapMetadata line 86
- PlanMetadata line 91
- IssueMetadata line 98
- ResearchMetadata line 104
- DocumentMetadata line 110
- Diagnostic line 116
- AuthoredDocument line 121
- BundleDocumentSource line 125
- BundleDocumentRecord line 126
- BundleDocumentIndex line 131
- BundleDiscovery line 135
- PREFIX line 140
- SLUG line 141
- TYPE_BY_TOKEN line 142
- DIRECTORY_BY_TYPE line 145
- objectValue line 153
- exactKeys line 164
- positiveInteger line 178
- duplicateTopLevelKeys line 180
- parseSystemConfig line 220
- inspectSystemConfig line 245
- parseDocumentId line 275
- validateDocumentPath line 303
- validDate line 326
- requiredStringField line 334
- optionalUniqueStrings line 340
- projectMetadata line 358
- reference line 370
- parseAuthoredDocument line 438
- diagnostic line 449
- compareDiagnostics line 454
- scanBundleAssets line 458
- discoverDocumentBundles line 484
- references line 574
- diagnosticIdentity line 591
- indexBundleDocuments line 594
- validateBundleCandidate line 704
import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import {
type FrontmatterMap,
type MarkdownDocumentError,
parseRichMarkdown,
} from "./markdown.ts";
export const SCHEMA_VERSION = 2;
export class SystemDocumentError extends Error {
readonly code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
this.name = "SystemDocumentError";
}
}
const nearestMarker = (
cwd: string,
marker: string,
markerExists: (candidate: string) => boolean,
) => {
let current = path.resolve(cwd);
while (true) {
if (markerExists(path.join(current, marker))) return current;
const parent = path.dirname(current);
if (parent === current) return undefined;
current = parent;
}
};
export function discoverProjectRoot(
cwd: string,
markerExists = existsSync,
): string {
const resolvedCwd = path.resolve(cwd);
const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
const git = nearestMarker(resolvedCwd, ".git", markerExists);
if (jj && git && jj !== git)
throw new SystemDocumentError(
"root.conflict",
`Conflicting project roots: Git ${git}; JJ ${jj}`,
);
return jj ?? git ?? resolvedCwd;
}
export function resolveGovernedPath(root: string, candidate: string): string {
const normalizedRoot = path.resolve(root);
const target = path.resolve(normalizedRoot, candidate);
const relative = path.relative(normalizedRoot, target);
if (
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
)
throw new SystemDocumentError(
"path.outside-root",
`Path is outside project root: ${candidate}`,
);
return target;
}
export const DOCUMENT_TYPES = [
"spec",
"roadmap",
"plan",
"issue",
"research",
] as const;
export type DocumentType = (typeof DOCUMENT_TYPES)[number];
export type SystemConfig = Readonly<{ prefix: string; schemaVersion: number }>;
export type InspectedSystemConfig = Readonly<{
config: SystemConfig;
legacyStyleVersion?: number;
}>;
export type ParsedDocumentId = Readonly<{
id: string;
prefix: string;
type: DocumentType;
sequence: number;
}>;
export type SpecMetadata = Readonly<{ id: string; type: "spec" }>;
export type RoadmapMetadata = Readonly<{
id: string;
type: "roadmap";
spec: string;
}>;
export type PlanMetadata = Readonly<{
id: string;
type: "plan";
spec: string;
roadmap?: string;
phase?: number;
}>;
export type IssueMetadata = Readonly<{
id: string;
type: "issue";
status: "open" | "fixed";
specs: readonly string[];
}>;
export type ResearchMetadata = Readonly<{
id: string;
type: "research";
capturedAt: string;
sources?: readonly string[];
}>;
export type DocumentMetadata =
| SpecMetadata
| RoadmapMetadata
| PlanMetadata
| IssueMetadata
| ResearchMetadata;
export type Diagnostic = Readonly<{
code: string;
path: string;
message: string;
}>;
export type AuthoredDocument = Readonly<{
metadata: DocumentMetadata;
frontmatter: FrontmatterMap;
}>;
export type BundleDocumentSource = Readonly<{ path: string; markdown: string }>;
export type BundleDocumentRecord = Readonly<{
path: string;
metadata: DocumentMetadata;
frontmatter: FrontmatterMap;
}>;
export type BundleDocumentIndex = Readonly<{
documents: readonly BundleDocumentRecord[];
diagnostics: readonly Diagnostic[];
}>;
export type BundleDiscovery = Readonly<{
sources: readonly BundleDocumentSource[];
diagnostics: readonly Diagnostic[];
}>;
const PREFIX = /^[A-Z][A-Z0-9]{1,7}$/;
const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
const TYPE_BY_TOKEN = new Map(
DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]),
);
const DIRECTORY_BY_TYPE: Readonly<Record<DocumentType, string>> = {
spec: "specs",
roadmap: "roadmaps",
plan: "plans",
issue: "issues",
research: "research",
};
const objectValue = (
value: unknown,
label: string,
): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new SystemDocumentError(
"json.shape",
`${label} must be a JSON object`,
);
return value as Record<string, unknown>;
};
const exactKeys = (
value: Record<string, unknown>,
required: readonly string[],
) => {
const actual = Object.keys(value).sort();
if (
required.some((key) => !(key in value)) ||
actual.some((key) => !required.includes(key))
)
throw new SystemDocumentError(
"json.keys",
`Expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`,
);
};
const positiveInteger = (value: unknown) =>
typeof value === "number" && Number.isInteger(value) && value > 0;
const duplicateTopLevelKeys = (source: string): string[] => {
const keys: string[] = [];
const duplicates = new Set<string>();
let depth = 0;
let index = 0;
while (index < source.length) {
const character = source[index];
if (character === "{") {
depth += 1;
index += 1;
continue;
}
if (character === "}") {
depth -= 1;
index += 1;
continue;
}
if (character !== '"') {
index += 1;
continue;
}
const start = index++;
let escaped = false;
while (index < source.length) {
const current = source[index++];
if (!escaped && current === '"') break;
escaped = !escaped && current === "\\";
if (current !== "\\") escaped = false;
}
if (depth !== 1) continue;
let cursor = index;
while (/\s/.test(source[cursor] ?? "")) cursor += 1;
if (source[cursor] !== ":") continue;
const key = JSON.parse(source.slice(start, index)) as string;
if (keys.includes(key)) duplicates.add(key);
keys.push(key);
}
return [...duplicates].sort();
};
export function parseSystemConfig(source: string): SystemConfig {
let parsed: unknown;
try {
parsed = JSON.parse(source);
} catch {
throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
}
const duplicates = duplicateTopLevelKeys(source);
if (duplicates.length)
throw new SystemDocumentError(
"config.duplicate-key",
`Duplicate config keys: ${duplicates.join(", ")}`,
);
const value = objectValue(parsed, "Config");
exactKeys(value, ["prefix", "schemaVersion"]);
if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix))
throw new SystemDocumentError("config.prefix", "Invalid project prefix");
if (!positiveInteger(value.schemaVersion))
throw new SystemDocumentError(
"config.version",
"Schema version must be a positive integer",
);
return { prefix: value.prefix, schemaVersion: value.schemaVersion as number };
}
export function inspectSystemConfig(source: string): InspectedSystemConfig {
try {
return { config: parseSystemConfig(source) };
} catch (currentError) {
let parsed: unknown;
try {
parsed = JSON.parse(source);
} catch {
throw currentError;
}
if (duplicateTopLevelKeys(source).length > 0) throw currentError;
let value: Record<string, unknown>;
try {
value = objectValue(parsed, "Legacy config");
exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
} catch {
throw currentError;
}
if (value.schemaVersion !== 1 || !positiveInteger(value.styleVersion))
throw currentError;
const config = parseSystemConfig(
JSON.stringify({
prefix: value.prefix,
schemaVersion: value.schemaVersion,
}),
);
return { config, legacyStyleVersion: value.styleVersion as number };
}
}
export function parseDocumentId(
source: string,
expectedPrefix?: string,
): ParsedDocumentId {
const match =
/^([A-Z][A-Z0-9]{1,7})-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-([0-9]{3,})$/.exec(
source,
);
const sequence = match ? Number(match[3]) : 0;
const canonical = sequence > 0 ? String(sequence).padStart(3, "0") : "";
if (!match || match[3] !== canonical)
throw new SystemDocumentError(
"id.invalid",
`Invalid document ID: ${source}`,
);
if (expectedPrefix && match[1] !== expectedPrefix)
throw new SystemDocumentError(
"id.prefix",
`Document ID must use prefix ${expectedPrefix}: ${source}`,
);
return {
id: source,
prefix: match[1],
type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
sequence,
};
}
export function validateDocumentPath(
documentPath: string,
metadata: DocumentMetadata,
prefix: string,
): void {
const parsed = parseDocumentId(metadata.id, prefix);
const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
const pattern = new RegExp(`^${metadata.id}-${SLUG}$`);
const parts = documentPath.split("/");
if (
parsed.type !== metadata.type ||
parts.length !== 4 ||
parts[0] !== ".system" ||
parts[1] !== expectedDirectory ||
!pattern.test(parts[2] ?? "") ||
parts[3] !== "index.md"
)
throw new SystemDocumentError(
"document.path",
`Bundle path mismatch for ${metadata.id}: ${documentPath}`,
);
}
const validDate = (value: unknown) => {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
return false;
const date = new Date(`${value}T00:00:00Z`);
return (
!Number.isNaN(date.valueOf()) && date.toISOString().slice(0, 10) === value
);
};
const requiredStringField = (fields: FrontmatterMap, key: string): string => {
const value = fields.get(key);
if (typeof value !== "string")
throw new SystemDocumentError("metadata.value", `${key} must be a string`);
return value;
};
const optionalUniqueStrings = (
fields: FrontmatterMap,
key: string,
): readonly string[] | undefined => {
const value = fields.get(key);
if (value === undefined) return undefined;
if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
throw new SystemDocumentError(
"metadata.value",
`${key} must be a string array`,
);
if (new Set(value).size !== value.length)
throw new SystemDocumentError(
"metadata.duplicate",
`${key} must contain unique values`,
);
return value as readonly string[];
};
const projectMetadata = (
fields: FrontmatterMap,
prefix: string,
): DocumentMetadata => {
const id = requiredStringField(fields, "id");
const type = requiredStringField(fields, "type");
const own = parseDocumentId(id, prefix);
if (own.type !== type)
throw new SystemDocumentError(
"metadata.identity",
`Metadata ID/type mismatch: ${id} / ${type}`,
);
const reference = (key: string) => {
const value = requiredStringField(fields, key);
parseDocumentId(value, prefix);
return value;
};
switch (type) {
case "spec":
return { id, type };
case "roadmap":
return { id, type, spec: reference("spec") };
case "plan": {
const roadmap = fields.get("roadmap");
const phase = fields.get("phase");
if (
(roadmap === undefined) !== (phase === undefined) ||
(roadmap !== undefined &&
(typeof roadmap !== "string" || !positiveInteger(phase)))
)
throw new SystemDocumentError(
"metadata.plan-phase",
"Plan roadmap and positive phase must appear together",
);
return roadmap === undefined
? { id, type, spec: reference("spec") }
: {
id,
type,
spec: reference("spec"),
roadmap,
phase: phase as number,
};
}
case "issue": {
const status = requiredStringField(fields, "status");
if (status !== "open" && status !== "fixed")
throw new SystemDocumentError(
"metadata.status",
"Issue status must be open or fixed",
);
const specs = optionalUniqueStrings(fields, "specs");
if (!specs)
throw new SystemDocumentError(
"metadata.value",
"specs must be a string array",
);
for (const spec of specs) parseDocumentId(spec, prefix);
return { id, type, status, specs };
}
case "research": {
const capturedAt = requiredStringField(fields, "capturedAt");
if (!validDate(capturedAt))
throw new SystemDocumentError(
"metadata.date",
"capturedAt must be a valid ISO date",
);
const sources = optionalUniqueStrings(fields, "sources");
return sources
? { id, type, capturedAt, sources }
: { id, type, capturedAt };
}
default:
throw new SystemDocumentError(
"metadata.type",
`Unsupported metadata type: ${type}`,
);
}
};
export function parseAuthoredDocument(
source: string,
prefix: string,
): AuthoredDocument {
const parsed = parseRichMarkdown(source);
return {
metadata: projectMetadata(parsed.frontmatter, prefix),
frontmatter: parsed.frontmatter,
};
}
const diagnostic = (
code: string,
diagnosticPath: string,
message: string,
): Diagnostic => ({ code, path: diagnosticPath, message });
const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =>
left.path.localeCompare(right.path) ||
left.code.localeCompare(right.code) ||
left.message.localeCompare(right.message);
const scanBundleAssets = (
absolute: string,
relative: string,
findings: Diagnostic[],
): void => {
for (const entry of readdirSync(absolute, { withFileTypes: true }).sort(
(left, right) => left.name.localeCompare(right.name),
)) {
if (relative.split("/").length === 3 && entry.name === "index.md") continue;
const childAbsolute = path.join(absolute, entry.name);
const childRelative = `${relative}/${entry.name}`;
const stats = lstatSync(childAbsolute, { throwIfNoEntry: false });
if (!stats) continue;
if (stats.isSymbolicLink())
findings.push(
diagnostic(
"bundle.symbolic-link",
childRelative,
`Bundle path is a symbolic link: ${childRelative}`,
),
);
else if (stats.isDirectory())
scanBundleAssets(childAbsolute, childRelative, findings);
}
};
export function discoverDocumentBundles(root: string): BundleDiscovery {
const sources: BundleDocumentSource[] = [];
const diagnostics: Diagnostic[] = [];
const systemRoot = path.join(root, ".system");
if (lstatSync(systemRoot, { throwIfNoEntry: false })?.isSymbolicLink())
return {
sources,
diagnostics: [
diagnostic(
"bundle.symbolic-link",
".system",
"Bundle path is a symbolic link: .system",
),
],
};
for (const directory of Object.values(DIRECTORY_BY_TYPE)) {
const relativeDirectory = `.system/${directory}`;
const absoluteDirectory = path.join(root, relativeDirectory);
const directoryStats = lstatSync(absoluteDirectory, {
throwIfNoEntry: false,
});
if (!directoryStats?.isDirectory() || directoryStats.isSymbolicLink())
continue;
for (const entry of readdirSync(absoluteDirectory, {
withFileTypes: true,
}).sort((left, right) => left.name.localeCompare(right.name))) {
const bundleRelative = `${relativeDirectory}/${entry.name}`;
const bundleAbsolute = path.join(absoluteDirectory, entry.name);
const bundleStats = lstatSync(bundleAbsolute, { throwIfNoEntry: false });
if (bundleStats?.isSymbolicLink()) {
diagnostics.push(
diagnostic(
"bundle.symbolic-link",
bundleRelative,
`Bundle path is a symbolic link: ${bundleRelative}`,
),
);
continue;
}
if (!bundleStats?.isDirectory()) {
diagnostics.push(
diagnostic(
"bundle.expected-directory",
bundleRelative,
`Expected a document bundle directory: ${bundleRelative}`,
),
);
continue;
}
const indexRelative = `${bundleRelative}/index.md`;
const indexAbsolute = path.join(bundleAbsolute, "index.md");
const indexStats = lstatSync(indexAbsolute, { throwIfNoEntry: false });
if (!indexStats)
diagnostics.push(
diagnostic(
"bundle.missing-index",
bundleRelative,
`Bundle is missing index.md: ${bundleRelative}`,
),
);
else if (indexStats.isSymbolicLink())
diagnostics.push(
diagnostic(
"bundle.symbolic-link",
indexRelative,
`Bundle path is a symbolic link: ${indexRelative}`,
),
);
else if (!indexStats.isFile())
diagnostics.push(
diagnostic(
"bundle.expected-file",
indexRelative,
`Expected a regular index.md: ${indexRelative}`,
),
);
else
sources.push({
path: indexRelative,
markdown: readFileSync(indexAbsolute, "utf8"),
});
scanBundleAssets(bundleAbsolute, bundleRelative, diagnostics);
}
}
return {
sources: sources.sort((left, right) => left.path.localeCompare(right.path)),
diagnostics: diagnostics.sort(compareDiagnostics),
};
}
const references = (
metadata: DocumentMetadata,
): readonly (readonly [string, DocumentType])[] => {
switch (metadata.type) {
case "roadmap":
return [[metadata.spec, "spec"]];
case "plan":
return [
[metadata.spec, "spec"],
...(metadata.roadmap ? ([[metadata.roadmap, "roadmap"]] as const) : []),
];
case "issue":
return metadata.specs.map((spec) => [spec, "spec"] as const);
default:
return [];
}
};
const diagnosticIdentity = (item: Diagnostic) =>
JSON.stringify([item.path, item.code, item.message]);
export function indexBundleDocuments(
sources: readonly BundleDocumentSource[],
prefix: string,
): BundleDocumentIndex {
const documents: BundleDocumentRecord[] = [];
const graphEligible: BundleDocumentRecord[] = [];
const diagnostics: Diagnostic[] = [];
for (const item of [...sources].sort((left, right) =>
left.path.localeCompare(right.path),
)) {
try {
const parsed = parseAuthoredDocument(item.markdown, prefix);
let pathValid = true;
try {
validateDocumentPath(item.path, parsed.metadata, prefix);
} catch (error) {
pathValid = false;
diagnostics.push(
diagnostic("document.path", item.path, (error as Error).message),
);
}
const record = {
path: item.path,
metadata: parsed.metadata,
frontmatter: parsed.frontmatter,
};
documents.push(record);
if (pathValid) graphEligible.push(record);
} catch (error) {
const value = error as SystemDocumentError | MarkdownDocumentError;
diagnostics.push(
diagnostic(
"document.metadata",
item.path,
`${value.code}: ${value.message}`,
),
);
}
}
const groups = new Map<string, BundleDocumentRecord[]>();
for (const document of graphEligible)
groups.set(document.metadata.id, [
...(groups.get(document.metadata.id) ?? []),
document,
]);
for (const [id, records] of groups) {
if (records.length < 2) continue;
const paths = records.map((record) => record.path).sort();
for (const record of records)
diagnostics.push(
diagnostic(
"graph.duplicate-id",
record.path,
`Duplicate ID ${id}: ${paths.join(", ")}`,
),
);
}
const unique = new Map(
[...groups].flatMap(([id, records]) => {
const [record] = records;
return records.length === 1 && record ? [[id, record] as const] : [];
}),
);
for (const document of graphEligible) {
for (const [targetId, expectedType] of references(document.metadata)) {
const referencedType = parseDocumentId(targetId, prefix).type;
const target = unique.get(targetId);
if (referencedType !== expectedType)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${referencedType}`,
),
);
else if (!target)
diagnostics.push(
diagnostic(
"graph.dangling-reference",
document.path,
`${document.metadata.id} references missing ${targetId}`,
),
);
else if (target.metadata.type !== expectedType)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${target.metadata.type}`,
),
);
}
if (document.metadata.type === "plan" && document.metadata.roadmap) {
const roadmap = unique.get(document.metadata.roadmap);
if (
roadmap?.metadata.type === "roadmap" &&
roadmap.metadata.spec !== document.metadata.spec
)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.roadmap} belongs to ${roadmap.metadata.spec}, not ${document.metadata.spec}`,
),
);
}
}
return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };
}
export function validateBundleCandidate(
current: readonly BundleDocumentSource[],
candidate: BundleDocumentSource,
prefix: string,
): readonly Diagnostic[] {
const baseline = new Set(
indexBundleDocuments(current, prefix).diagnostics.map(diagnosticIdentity),
);
const next = indexBundleDocuments(
[...current.filter((source) => source.path !== candidate.path), candidate],
prefix,
);
return next.diagnostics.filter(
(item) =>
item.path === candidate.path ||
(!baseline.has(diagnosticIdentity(item)) &&
item.code !== "graph.duplicate-id"),
);
}