repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/init.ts

Raw
File outline
import {
	lstatSync,
	mkdirSync,
	readFileSync,
	unlinkSync,
	writeFileSync,
} from "node:fs";
import path from "node:path";
import {
	discoverProjectRoot,
	inspectSystemConfig,
	parseSystemConfig,
	resolveGovernedPath,
	SCHEMA_VERSION,
	SystemDocumentError,
} from "./documents.ts";

export type MachineState = Readonly<{ schemaVersion: number }>;
export type InitializationInspection = Readonly<{
	root: string;
	prefix?: string;
	cores: readonly Readonly<{ path: string; state: "missing" | "preserve" }>[];
	creates: readonly string[];
	upgrades: readonly string[];
}>;
export type InitializationResult = Readonly<{
	root: string;
	prefix: string;
	changed: readonly string[];
	removed: readonly string[];
	pending: readonly string[];
}>;

const DIRECTORIES = [
	".system",
	".system/specs",
	".system/phases",
	".system/plans",
	".system/issues",
	".system/research",
] as const;
const CORES = [
	".system/SYSTEM.md",
	".system/MISSION.md",
	".system/RULES.md",
] as const;
const CONFIG = ".system/config.json";
const CSS = ".system/system.css";
const CORE_CONTENT: Readonly<Record<(typeof CORES)[number], string>> = {
	".system/SYSTEM.md":
		"# SYSTEM\n\nStable project identity, domain truths, architecture invariants, and non-negotiable conventions.\nKeep durable; do not put current tasks here.\n",
	".system/MISSION.md":
		"# MISSION\n\nCurrent objective and why it matters now.\nUpdate when project direction changes.\n",
	".system/RULES.md":
		"# RULES\n\nConcrete operating constraints: commands, safety, style, boundaries, and do/don't rules.\nKeep executable; avoid goals and rationale unless needed.\n",
};
export const DEFAULT_MACHINE_STATE: MachineState = Object.freeze({
	schemaVersion: SCHEMA_VERSION,
});

const target = (root: string, relative: string) =>
	resolveGovernedPath(root, relative);
const kind = (file: string) => {
	const stats = lstatSync(file, { throwIfNoEntry: false });
	if (!stats) return "missing" as const;
	if (stats.isSymbolicLink()) return "link" as const;
	if (stats.isDirectory()) return "directory" as const;
	if (stats.isFile()) return "file" as const;
	return "other" as const;
};
const requireKind = (
	root: string,
	relative: string,
	expected: "directory" | "file",
) => {
	const actual = kind(target(root, relative));
	if (actual !== "missing" && actual !== expected)
		throw new SystemDocumentError(
			"init.unsafe-path",
			`${relative} must be a regular ${expected}; found ${actual}`,
		);
	return actual;
};
const projectTitle = (root: string) => path.basename(root) || "Project";
const validatePrefix = (prefix: string, state: MachineState) => {
	parseSystemConfig(
		JSON.stringify({
			prefix,
			schemaVersion: state.schemaVersion,
			title: "Project",
		}),
	);
	return prefix;
};
const configSource = (root: string, prefix: string, state: MachineState) =>
	`${JSON.stringify(
		{ prefix, schemaVersion: state.schemaVersion, title: projectTitle(root) },
		null,
		"\t",
	)}\n`;

export function inspectInitialization(
	cwd: string,
	requestedPrefix?: string,
	state: MachineState = DEFAULT_MACHINE_STATE,
): InitializationInspection {
	const root = discoverProjectRoot(cwd);
	for (const relative of DIRECTORIES) requireKind(root, relative, "directory");
	const configKind = requireKind(root, CONFIG, "file");
	const cssKind = requireKind(root, CSS, "file");
	const requested = requestedPrefix
		? validatePrefix(requestedPrefix, state)
		: undefined;
	const inspected =
		configKind === "file"
			? inspectSystemConfig(readFileSync(target(root, CONFIG), "utf8"))
			: undefined;
	const config = inspected?.config;
	if (config && requested && config.prefix !== requested)
		throw new SystemDocumentError(
			"init.prefix-conflict",
			`Existing prefix ${config.prefix} does not match requested ${requested}`,
		);
	if (config && config.schemaVersion > state.schemaVersion)
		throw new SystemDocumentError(
			"init.version-newer",
			`Project schema ${config.schemaVersion} is newer than installed schema ${state.schemaVersion}`,
		);
	const creates: string[] = [];
	for (const relative of DIRECTORIES)
		if (kind(target(root, relative)) === "missing") creates.push(relative);
	if (configKind === "missing") creates.push(CONFIG);
	const upgrades: string[] = [];
	if (config && config.schemaVersion !== state.schemaVersion)
		upgrades.push(
			`${CONFIG} schemaVersion ${config.schemaVersion} -> ${state.schemaVersion}${inspected?.legacyStyleVersion ? "; remove styleVersion" : ""}`,
		);
	if (config && !config.title)
		upgrades.push(`${CONFIG} add title "${projectTitle(root)}"`);
	if (cssKind === "file")
		upgrades.push(`${CSS} remove obsolete machine-owned asset`);
	return {
		root,
		prefix: config?.prefix ?? requested,
		cores: CORES.map((relative) => ({
			path: relative,
			state:
				kind(target(root, relative)) === "missing" ? "missing" : "preserve",
		})),
		creates,
		upgrades,
	};
}

export function applyInitialization(
	cwd: string,
	requestedPrefix?: string,
	approveUpgrades = false,
	state: MachineState = DEFAULT_MACHINE_STATE,
): InitializationResult {
	const inspection = inspectInitialization(cwd, requestedPrefix, state);
	if (!inspection.prefix)
		throw new SystemDocumentError(
			"init.prefix-required",
			"An approved project prefix is required before initialization",
		);
	const changed: string[] = [];
	const removed: string[] = [];
	for (const relative of DIRECTORIES) {
		if (kind(target(inspection.root, relative)) !== "missing") continue;
		mkdirSync(target(inspection.root, relative));
		changed.push(relative);
	}
	const configUpgrade = inspection.upgrades.some((item) =>
		item.startsWith(`${CONFIG} `),
	);
	if (
		kind(target(inspection.root, CONFIG)) === "missing" ||
		(approveUpgrades && configUpgrade)
	) {
		writeFileSync(
			target(inspection.root, CONFIG),
			configSource(inspection.root, inspection.prefix, state),
			kind(target(inspection.root, CONFIG)) === "missing"
				? { encoding: "utf8", flag: "wx" }
				: "utf8",
		);
		changed.push(CONFIG);
	}
	for (const core of inspection.cores) {
		if (core.state !== "missing") continue;
		writeFileSync(
			target(inspection.root, core.path),
			CORE_CONTENT[core.path as keyof typeof CORE_CONTENT],
			{
				encoding: "utf8",
				flag: "wx",
			},
		);
		changed.push(core.path);
	}
	if (
		approveUpgrades &&
		inspection.upgrades.includes(`${CSS} remove obsolete machine-owned asset`)
	) {
		unlinkSync(target(inspection.root, CSS));
		removed.push(CSS);
	}
	return {
		root: inspection.root,
		prefix: inspection.prefix,
		changed,
		removed,
		pending: approveUpgrades ? [] : inspection.upgrades,
	};
}