Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/startup-state.ts

Raw
import { inspectInitialization } from "./init.ts";
import { loadSystem } from "./loaders.js";
import { discoverProjectRoot } from "./project-root.ts";
import { SCHEMA_VERSION } from "./system-config.ts";

export type StartupRuntimeState = Readonly<{
	active: boolean;
	prefix?: string;
	phaseLabel?: string;
	notice?: string;
}>;

const INCOMPLETE_NOTICE =
	"The System is incomplete or invalid; run /system init before governed work.";
const SCHEMA_NOTICE = `The System schema does not match ${SCHEMA_VERSION}; run /system init to update it.`;

/** Keep routine startup on config and board JSON only.
 * Current phases require full Markdown validation and deliberately cross the
 * heavier System implementation boundary. */
export async function readStartupRuntimeState(
	cwd: string,
): Promise<StartupRuntimeState> {
	const root = discoverProjectRoot(cwd);
	if (!root) return { active: false };
	try {
		const inspection = inspectInitialization(root);
		if (inspection.rewrites.length > 0)
			return { active: true, notice: SCHEMA_NOTICE };
		if (inspection.currentPhase) {
			const { runtimeState } = await loadSystem();
			return runtimeState(cwd);
		}
		const incomplete =
			inspection.creates.length > 0 ||
			inspection.cores.some(({ state }) => state === "missing");
		return {
			active: true,
			...(inspection.prefix ? { prefix: inspection.prefix } : {}),
			...(incomplete ? { notice: INCOMPLETE_NOTICE } : {}),
		};
	} catch {
		return { active: true, notice: INCOMPLETE_NOTICE };
	}
}