repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/system.ts
RawFile outline
- CORE_BYTE_LIMIT line 23
- CORES line 24
- governanceError line 25
- coreBlock line 27
- composeSystemPrompt line 47
- runtimeNotice line 72
- MutationKind line 88
- MutationInput line 89
- GateResult line 90
- GovernanceUI line 91
- CORE_PATHS line 95
- posixRelative line 100
- blocked line 102
- diagnosticsReason line 103
- applyExactEdits line 111
- candidateContent line 134
- projectPrefix line 147
- GovernedDocumentPath line 152
- governedDocumentPath line 158
- ResolvedBundleMutation line 176
- resolveBundleMutation line 181
- symbolicLinkInPath line 233
- SHELL_MUTATOR line 244
- OWNED_SHELL_PATH line 246
- preflightShellMutation line 248
- preflightFileMutation line 257
- registerSystemGovernance line 358
- notifyOnce line 360
import { existsSync, lstatSync, readFileSync } from "node:fs";
import path from "node:path";
import type {
EditToolInput,
ExtensionAPI,
ExtensionContext,
WriteToolInput,
} from "@earendil-works/pi-coding-agent";
import { isToolCallEventType } from "@earendil-works/pi-coding-agent";
import {
type Diagnostic,
type DocumentMetadata,
discoverDocumentBundles,
discoverProjectRoot,
indexBundleDocuments,
parseAuthoredDocument,
parseSystemConfig,
resolveGovernedPath,
validateBundleCandidate,
} from "./documents.ts";
import { inspectInitialization } from "./init.ts";
export const CORE_BYTE_LIMIT = 32 * 1024;
const CORES = ["SYSTEM.md", "MISSION.md", "RULES.md"] as const;
const governanceError = (systemPrompt: string, message: string) =>
`${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until /system-doctor resolves this governance error.`;
const coreBlock = (root: string, name: (typeof CORES)[number]) => {
const relative = `.system/${name}`;
const target = path.join(root, relative);
try {
const stats = lstatSync(target, { throwIfNoEntry: false });
if (!stats) return undefined;
if (!stats.isFile())
throw new Error(
`Malformed core path ${relative}: expected a regular file.`,
);
if (stats.size > CORE_BYTE_LIMIT)
return `## ${name}\n\n[Not injected: ${name} exceeds the ${CORE_BYTE_LIMIT}-byte injection limit.]`;
return `## ${name}\n\n${readFileSync(target, "utf8")}`;
} catch (error) {
throw new Error(
`Unable to read core path ${relative}: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
export function composeSystemPrompt(cwd: string, systemPrompt: string): string {
let root: string;
try {
root = discoverProjectRoot(cwd);
} catch (error) {
return governanceError(
systemPrompt,
error instanceof Error ? error.message : String(error),
);
}
try {
const blocks = CORES.map((name) => coreBlock(root, name)).filter(
(block): block is string => block !== undefined,
);
return blocks.length === 0
? systemPrompt
: `${systemPrompt}\n\n# The System project law\n\n${blocks.join("\n\n")}`;
} catch (error) {
return governanceError(
systemPrompt,
error instanceof Error ? error.message : String(error),
);
}
}
export function runtimeNotice(cwd: string): string | undefined {
try {
const inspection = inspectInitialization(cwd);
if (
inspection.creates.length > 0 ||
inspection.cores.some(({ state }) => state === "missing")
)
return "The System is incomplete or invalid; run /system-init before governed work.";
if (inspection.upgrades.length > 0)
return "The System schema refresh is available; run /system-init to inspect and approve it.";
return undefined;
} catch {
return "The System is incomplete or invalid; run /system-init before governed work.";
}
}
type MutationKind = "write" | "edit";
type MutationInput = WriteToolInput | EditToolInput;
type GateResult = Readonly<{ block: true; reason: string }> | undefined;
export type GovernanceUI = Readonly<{
hasUI: boolean;
select(title: string, items: string[]): Promise<string | undefined>;
}>;
const CORE_PATHS = new Set([
".system/SYSTEM.md",
".system/MISSION.md",
".system/RULES.md",
]);
const posixRelative = (root: string, target: string) =>
path.relative(root, target).split(path.sep).join("/");
const blocked = (reason: string): GateResult => ({ block: true, reason });
const diagnosticsReason = (diagnostics: readonly Diagnostic[]) => {
const shown = diagnostics
.slice(0, 3)
.map((item) => `${item.path} ${item.code}: ${item.message}`);
if (diagnostics.length > shown.length)
shown.push(`+${diagnostics.length - shown.length} more finding(s)`);
return `The System candidate validation failed: ${shown.join("; ")}`;
};
const applyExactEdits = (source: string, edits: EditToolInput["edits"]) => {
const replacements = edits
.map((edit) => {
const start = source.indexOf(edit.oldText);
if (start < 0 || source.indexOf(edit.oldText, start + 1) >= 0)
throw new Error("each governed edit oldText must match exactly once");
return { start, end: start + edit.oldText.length, newText: edit.newText };
})
.sort((left, right) => left.start - right.start);
for (let index = 1; index < replacements.length; index++) {
const previous = replacements[index - 1];
const next = replacements[index];
if (previous && next && previous.end > next.start)
throw new Error("governed edits must not overlap");
}
let candidate = source;
for (const replacement of replacements.reverse())
candidate =
candidate.slice(0, replacement.start) +
replacement.newText +
candidate.slice(replacement.end);
return candidate;
};
const candidateContent = (
target: string,
kind: MutationKind,
input: MutationInput,
) => {
if (kind === "write") return (input as WriteToolInput).content;
if (!existsSync(target))
throw new Error("edit cannot create a governed file; use write");
return applyExactEdits(
readFileSync(target, "utf8"),
(input as EditToolInput).edits,
);
};
const projectPrefix = (root: string) =>
parseSystemConfig(
readFileSync(path.join(root, ".system/config.json"), "utf8"),
).prefix;
type GovernedDocumentPath = Readonly<{
directory: "specs" | "roadmaps" | "plans" | "issues" | "research";
bundle: string;
asset: string;
index: boolean;
}>;
const governedDocumentPath = (
relative: string,
): GovernedDocumentPath | undefined => {
const match =
/^\.system\/(specs|roadmaps|plans|issues|research)\/([^/]+)\/(.+)$/.exec(
relative,
);
if (!match) return undefined;
const [, directory, bundle, asset] = match;
if (!directory || !bundle || !asset || asset.endsWith("/index.md"))
return undefined;
return {
directory: directory as GovernedDocumentPath["directory"],
bundle,
asset,
index: asset === "index.md",
};
};
type ResolvedBundleMutation = Readonly<{
location: GovernedDocumentPath;
metadata?: DocumentMetadata;
findings: readonly Diagnostic[];
}>;
const resolveBundleMutation = (
root: string,
relative: string,
content: string | undefined,
): ResolvedBundleMutation => {
const location = governedDocumentPath(relative);
if (!location)
throw new Error(
`Authored paths require .system/<type>/<ID>-<slug>/<file>: ${relative}`,
);
const prefix = projectPrefix(root);
const discovery = discoverDocumentBundles(root);
const bundlePath = `.system/${location.directory}/${location.bundle}`;
const localDiscovery = discovery.diagnostics
.filter(
(item) =>
item.path === bundlePath || item.path.startsWith(`${bundlePath}/`),
)
.filter(
(item) =>
!(
location.index &&
item.path === bundlePath &&
item.code === "bundle.missing-index"
),
);
if (localDiscovery.length > 0) return { location, findings: localDiscovery };
if (location.index) {
if (content === undefined)
throw new Error("Missing index candidate content");
const findings = validateBundleCandidate(
discovery.sources,
{ path: relative, markdown: content },
prefix,
);
const parsed = parseAuthoredDocument(content, prefix);
return { location, metadata: parsed.metadata, findings };
}
const indexPath = `${bundlePath}/index.md`;
const owner = discovery.sources.find((source) => source.path === indexPath);
if (!owner)
throw new Error(
`Bundle requires a valid index.md before assets: ${bundlePath}`,
);
const indexed = indexBundleDocuments(discovery.sources, prefix);
const findings = indexed.diagnostics.filter(
(item) => item.path === indexPath,
);
const document = indexed.documents.find((item) => item.path === indexPath);
if (!document) throw new Error(`Bundle index is invalid: ${indexPath}`);
return { location, metadata: document.metadata, findings };
};
const symbolicLinkInPath = (root: string, target: string) => {
let current = root;
for (const part of path.relative(root, target).split(path.sep)) {
if (!part) continue;
current = path.join(current, part);
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())
return posixRelative(root, current);
}
return undefined;
};
const SHELL_MUTATOR =
/(?:^|[;&|]\s*)(?:rm|mv|cp|install|truncate|touch|tee|sed\s+-[^\n]*i|perl\s+-[^\n]*i)\b|(?:^|[^<])>>?/i;
const OWNED_SHELL_PATH =
/(?:^|[\s"'`])([^\s"'`;&|]*\.system\/(?:SYSTEM\.md|MISSION\.md|RULES\.md|specs\/[^/\s"'`;&|]+(?:\/[^\s"'`;&|]+)?))(?=$|[\s"'`;&|])/i;
export function preflightShellMutation(command: string): GateResult {
if (!SHELL_MUTATOR.test(command)) return undefined;
const owned = OWNED_SHELL_PATH.exec(command)?.[1];
if (!owned) return undefined;
return blocked(
`The System advisory shell guard blocked recognizable mutation of ${owned}; use write or edit for candidate validation and ownership approval. Shell recognition is not a sandbox or security boundary.`,
);
}
export async function preflightFileMutation(
cwd: string,
kind: MutationKind,
input: MutationInput,
ui: GovernanceUI,
): Promise<GateResult> {
let root: string;
try {
root = discoverProjectRoot(cwd);
} catch (error) {
return blocked(
`The System cannot resolve project ownership: ${error instanceof Error ? error.message : String(error)}`,
);
}
let target: string;
try {
target = resolveGovernedPath(root, path.resolve(cwd, input.path));
} catch (error) {
return blocked(
`The System rejected the governed path: ${error instanceof Error ? error.message : String(error)}`,
);
}
const relative = posixRelative(root, target);
if (
!CORE_PATHS.has(relative) &&
!/^\.system\/(specs|roadmaps|plans|issues|research)(?:\/|$)/.test(relative)
)
return undefined;
try {
const link = symbolicLinkInPath(root, target);
if (link)
return blocked(
`The System rejected symbolic link in governed path: ${link}.`,
);
} catch (error) {
return blocked(
`The System rejected unsafe governed path: ${error instanceof Error ? error.message : String(error)}`,
);
}
const targetStats = lstatSync(target, { throwIfNoEntry: false });
if (CORE_PATHS.has(relative)) {
if (targetStats)
return blocked(
`The System blocked mutation of human-owned core ${relative}.`,
);
if (kind === "edit")
return blocked(
`The System requires write, not edit, to create approved missing core ${relative}.`,
);
return undefined;
}
const location = governedDocumentPath(relative);
if (!location)
return blocked(
`The System requires document bundles at .system/<type>/<ID>-<slug>/<file>: ${relative}.`,
);
let content: string | undefined;
if (location.index)
try {
content = candidateContent(target, kind, input);
} catch (error) {
return blocked(
`The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
let resolved: ResolvedBundleMutation;
try {
resolved = resolveBundleMutation(root, relative, content);
} catch (error) {
return blocked(
`The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
if (resolved.findings.length > 0)
return blocked(diagnosticsReason(resolved.findings));
if (!resolved.metadata)
return blocked(
`The System could not determine bundle ownership: ${relative}.`,
);
if (!targetStats) return undefined;
if (!targetStats.isFile())
return blocked(`The System expected a regular owned file at ${relative}.`);
if (resolved.metadata.type !== "spec") return undefined;
if (!ui.hasUI)
return blocked(
`The System blocked existing human-owned ${relative}: interactive UI is unavailable.`,
);
const approve = `Approve once: ${kind} ${relative}`;
const deny = `Deny: keep ${relative} unchanged`;
const decision = await ui.select("The System ownership approval", [
approve,
deny,
]);
if (decision === approve) return undefined;
return blocked(
decision === deny
? `The System ownership approval was denied for ${relative}.`
: `The System ownership approval was cancelled for ${relative}.`,
);
}
export function registerSystemGovernance(pi: ExtensionAPI): void {
let notified = false;
const notifyOnce = (_event: unknown, ctx: ExtensionContext) => {
if (notified || !ctx.hasUI) return;
const message = runtimeNotice(ctx.cwd);
if (!message) return;
ctx.ui.notify(message, "warning");
notified = true;
};
pi.on("session_start", async (event, ctx) => {
notified = false;
notifyOnce(event, ctx);
});
pi.on("before_agent_start", async (event, ctx) => {
notifyOnce(event, ctx);
return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
});
pi.on("tool_call", async (event, ctx) => {
const ui: GovernanceUI = {
hasUI: ctx.hasUI,
select: (title, items) => ctx.ui.select(title, items),
};
if (isToolCallEventType("bash", event))
return preflightShellMutation(event.input.command);
if (isToolCallEventType("write", event))
return preflightFileMutation(ctx.cwd, "write", event.input, ui);
if (isToolCallEventType("edit", event))
return preflightFileMutation(ctx.cwd, "edit", event.input, ui);
});
}