import { randomBytes } from "node:crypto"; import { lstatSync, readFileSync } from "node:fs"; import path from "node:path"; import type { ExtensionAPI, ExtensionCommandContext, RegisteredCommand, } from "@earendil-works/pi-coding-agent"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { runDoctor } from "./doctor.ts"; import { type DocumentType, directoryForType, discoverDocumentBundles, discoverProjectRoot, indexBundleDocuments, parseSystemConfig, } from "./documents.ts"; import { applyInitialization, inspectInitialization } from "./init.ts"; import { openHtmlFile } from "./open-browser.ts"; import { openEditableFile } from "./open-editor.ts"; import { systemPromptFor } from "./system-prompts.ts"; import { renderSystemBookSite, renderSystemViewSite, } from "./system-renderer.ts"; const LIFECYCLE = new Set([ "research", "spec", "spec-verify", "phase", "plan", "issue", "exec", ]); const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book", "edit"]); const SUBCOMMANDS = [ "init", "doctor", "view", "book", "edit", "research", "spec", "spec-verify", "phase", "plan", "issue", "exec", ] as const; type CommandOptions = Omit; export function createSystemCommand(pi: ExtensionAPI): CommandOptions { return { description: "The System project governance", getArgumentCompletions(prefix: string): AutocompleteItem[] | null { if (prefix.includes(" ")) return null; if (SUBCOMMANDS.some((item) => item === prefix)) return null; const items = SUBCOMMANDS.filter((item) => item.startsWith(prefix)).map( (item) => ({ value: item, label: item }), ); return items.length ? items : null; }, handler: async (args: string, ctx: ExtensionCommandContext) => { const parsed = parseSystemArgs(args); if (!parsed.subcommand) { ctx.ui.notify(systemHelp(), "info"); return; } if (parsed.subcommand === "init") { await runSystemInit(parsed.rest, ctx); return; } if (parsed.subcommand === "view") { const selectors = parsed.rest.trim().split(/\s+/).filter(Boolean); if (selectors.length !== 1) { ctx.ui.notify("Usage: /system view ", "error"); return; } const output = renderSystemView(ctx.cwd, selectors[0] as string); ctx.ui.notify(await openNotice("System view", output), "info"); return; } if (parsed.subcommand === "edit") { const selectors = parsed.rest.trim().split(/\s+/).filter(Boolean); if (selectors.length !== 1) { ctx.ui.notify("Usage: /system edit ", "error"); return; } const output = await editSystemDocument( ctx.cwd, selectors[0] as string, ); ctx.ui.notify(output, output.includes("opened:") ? "info" : "error"); return; } if (parsed.subcommand === "book") { if (parsed.rest.trim()) { ctx.ui.notify("Usage: /system book", "error"); return; } const output = renderSystemBook(ctx.cwd); ctx.ui.notify(await openNotice("System book", output), "info"); return; } if (parsed.subcommand === "doctor") { const result = runDoctor(ctx.cwd); await showCommandResult( ctx, formatDoctor(result), result.exitCode === 0 ? "info" : "warning", ); return; } await ctx.waitForIdle(); pi.sendUserMessage( systemPromptFor( parsed.subcommand, parsed.rest, generatedArtifactSlot(ctx.cwd, parsed.subcommand, parsed.rest), ), ); }, }; } function parseSystemArgs(args: string): { subcommand?: string; rest: string } { const trimmed = args.trim(); if (!trimmed) return { rest: "" }; const [raw = "", ...rest] = trimmed.split(/\s+/); const subcommand = raw.toLowerCase(); if (!LIFECYCLE.has(subcommand) && !NON_LIFECYCLE.has(subcommand)) return { rest: "" }; return { subcommand, rest: rest.join(" ") }; } function systemHelp(): string { return [ "/system ", "init [PROJECT-PREFIX]", "doctor", "view ", "edit ", "book", "research [instructions]", "spec [instructions]", "spec-verify [instructions]", "phase [instructions]", "plan [instructions]", "issue [instructions]", "exec [instructions]", ].join("\n"); } async function showCommandResult( ctx: ExtensionCommandContext, message: string, severity: "info" | "warning" | "error", ): Promise { await new Promise((resolve) => setTimeout(resolve, 0)); if (ctx.hasUI) await ctx.ui.confirm("System doctor", message); else ctx.ui.notify(message, severity); ctx.ui.setWidget?.("the-system", message.split("\n")); } async function runSystemInit( args: string, ctx: ExtensionCommandContext, ): Promise { let requested = args.trim() || undefined; let inspection = inspectInitialization(ctx.cwd, requested); requested ??= inspection.prefix; if (!requested) { requested = await ctx.ui.input("Project prefix", "SYS"); if (!requested) { ctx.ui.notify("/system init cancelled", "info"); return; } inspection = inspectInitialization(ctx.cwd, requested); } const summary = [ `Root: ${inspection.root}`, `Prefix: ${inspection.prefix}`, ...inspection.creates.map((item) => `Create: ${item}`), ...inspection.cores .filter((item) => item.state === "missing") .map((item) => `Create: ${item.path}`), ...inspection.upgrades.map((item) => `Upgrade: ${item}`), ].join("\n"); if (!(await ctx.ui.confirm("Initialize The System?", summary))) { ctx.ui.notify("/system init cancelled", "info"); return; } const result = applyInitialization(ctx.cwd, requested, true); ctx.ui.notify( [ `Initialized The System at ${result.root}`, `Prefix: ${result.prefix}`, ...result.changed.map((item) => `Wrote: ${item}`), ...result.removed.map((item) => `Removed: ${item}`), ].join("\n"), "info", ); } function formatDoctor(result: ReturnType): string { if (result.exitCode === 0) return `System doctor OK\nRoot: ${result.root}`; return [ `System doctor found ${result.diagnostics.length} issue(s)`, `Root: ${result.root}`, ...result.references.map((item) => `Ref: ${item.path} -> ${item.spec}`), ...result.diagnostics.map( (item) => `${item.code} ${item.path}: ${item.message}`, ), ].join("\n"); } function projectIndex(cwd: string) { const root = discoverProjectRoot(cwd); const config = parseSystemConfig( readFileSync(path.join(root, ".system/config.json"), "utf8"), ); const discovery = discoverDocumentBundles(root); const indexed = indexBundleDocuments(discovery.sources, config.prefix); return { root, documents: indexed.documents.map((document) => ({ ...document, markdown: discovery.sources.find((source) => source.path === document.path) ?.markdown ?? "", })), diagnostics: [...discovery.diagnostics, ...indexed.diagnostics], }; } function renderSystemView(cwd: string, selector: string): string { const index = projectIndex(cwd); const document = resolveDocument(index.root, index.documents, selector); return renderSystemViewSite(index, document).file; } function renderSystemBook(cwd: string): string { return renderSystemBookSite(projectIndex(cwd)).file; } async function editSystemDocument( cwd: string, selector: string, ): Promise { const index = projectIndex(cwd); const file = editableSystemPath(index.root, index.documents, selector); const opened = await openEditableFile(file); if (opened.ok) return `System document opened: ${file}\nEditor: ${opened.command}`; return `System document not opened: ${file}\nEditor: ${opened.error}`; } function editableSystemPath( root: string, documents: ReturnType["documents"], selector: string, ): string { const normalized = selector.split(path.sep).join("/"); if (normalized.includes("/") || normalized.endsWith(".md")) { const target = path.resolve(root, selector); const relative = path.relative(root, target).split(path.sep).join("/"); if ( relative.startsWith("../") || relative === ".." || !relative.startsWith(".system/") ) throw new Error(`System edit path must be inside .system: ${selector}`); const stats = lstatSync(target, { throwIfNoEntry: false }); if (!stats?.isFile() || stats.isSymbolicLink()) throw new Error(`No editable System file: ${selector}`); return target; } return path.join(root, resolveDocument(root, documents, selector).path); } function resolveDocument( root: string, documents: ReturnType["documents"], selector: string, ) { const normalized = selector.split(path.sep).join("/"); if (normalized.includes("/") || normalized.endsWith(".md")) { const relative = path .relative(root, path.resolve(root, selector)) .split(path.sep) .join("/"); const found = documents.find((document) => document.path === relative); if (!found) throw new Error(`No System document path: ${selector}`); return found; } const byId = documents.find((document) => document.metadata.id === selector); if (byId) return byId; const bySlug = documents.filter((document) => { const bundle = document.path.split("/")[2] ?? ""; return bundle.endsWith(`-${selector}`); }); if (bySlug.length === 1 && bySlug[0]) return bySlug[0]; if (bySlug.length > 1) throw new Error(`Ambiguous System slug: ${selector}`); throw new Error(`No System document: ${selector}`); } function generatedArtifactSlot( cwd: string, subcommand: string, instructions: string, ): string | undefined { const type = stageDocumentType(subcommand); if (!type) return undefined; let index: ReturnType; try { index = projectIndex(cwd); } catch { return undefined; } const id = generateDocumentId( parseSystemConfig( readFileSync(path.join(index.root, ".system/config.json"), "utf8"), ).prefix, type, new Set(index.documents.map((document) => document.metadata.id)), ); const slug = slugFor(instructions || type); return [ `For a new ${type} artifact, use this extension-generated ID and path exactly:`, `ID: ${id}`, `Path: .system/${directoryForType(type)}/${id}-${slug}/index.md`, "If amending an existing artifact, do not create this path.", ].join("\n"); } function stageDocumentType(subcommand: string): DocumentType | undefined { if (["research", "spec", "phase", "plan", "issue"].includes(subcommand)) return subcommand as DocumentType; return undefined; } function generateDocumentId( prefix: string, type: DocumentType, existing: ReadonlySet, ): string { while (true) { const token = randomBytes(6) .toString("base64url") .toUpperCase() .replaceAll("-", "_"); const id = `${prefix}-${type.toUpperCase()}-${token}`; if (!existing.has(id)) return id; } } function slugFor(source: string): string { const slug = source .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-|-$/g, "") .slice(0, 48) .replace(/-$/g, ""); return slug || "artifact"; } async function openNotice(label: string, output: string): Promise { const opened = await openHtmlFile(output); if (opened.ok) return `${label} opened: ${opened.url}\nFile: ${output}\nBrowser: ${opened.command}`; return `${label} written: ${output}\nOpen: ${opened.url}\nBrowser: ${opened.error}`; }