repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/dynamic-validator-worker.ts

Raw
File outline
import { once } from "node:events";
import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { getModels } from "@earendil-works/pi-ai/compat";
import {
	createAgentSession,
	DefaultResourceLoader,
	SessionManager,
} from "@earendil-works/pi-coding-agent";
import {
	artifactFiles,
	hashArtifacts as hashArtifactTree,
} from "./dynamic-artifacts.ts";
import {
	BUILTIN_TOOL_NAMES,
	type DynamicManifest,
	MARGINAL_LOAD_BUDGET_MS,
	ULTRA_RESERVED_TOOL_NAMES,
	VALIDATOR_CONTRACT_VERSION,
	VALIDATOR_WARNING_TARGET_MS,
	type ValidationAttestation,
	type ValidationDiagnostic,
	type WorkerValidationResult,
} from "./dynamic-contract.ts";
import { DYNAMIC_DEBUG_TEMPLATE } from "./dynamic-debug-template.ts";

export type {
	DynamicManifest,
	ValidationAttestation,
	ValidationDiagnostic,
	WorkerValidationResult,
} from "./dynamic-contract.ts";
export {
	MARGINAL_LOAD_BUDGET_MS,
	VALIDATOR_CONTRACT_VERSION,
	VALIDATOR_WARNING_TARGET_MS,
} from "./dynamic-contract.ts";

const REQUIRED_FILES = [
	"manifest.json",
	"package.json",
	"README.md",
	"index.ts",
	"index.test.ts",
	"benchmark.ts",
	"debug.ts",
] as const;
const README_SECTIONS = [
	"Purpose",
	"Scope",
	"Non-goals",
	"Alternatives considered",
	"Decision rationale",
	"Usage",
	"Architecture",
	"Test matrix",
	"Promotion notes",
] as const;
const HOST_PACKAGES = new Set([
	"@earendil-works/pi-ai",
	"@earendil-works/pi-agent-core",
	"@earendil-works/pi-coding-agent",
	"@earendil-works/pi-tui",
	"typebox",
]);
const FORBIDDEN_NAME_TERMS = new Set([
	"darwin",
	"helper",
	"helpers",
	"linux",
	"macos",
	"model",
	"models",
	"session",
	"sessions",
	"util",
	"utils",
	"utility",
	"version",
	"windows",
	"win32",
]);

interface ValidationState {
	draftPath: string;
	diagnostics: ValidationDiagnostic[];
	manifest?: DynamicManifest;
}

function boundedDiagnosticValue(value: unknown): unknown {
	if (value === undefined) return undefined;
	let encoded: string;
	try {
		encoded = JSON.stringify(value);
	} catch {
		encoded = String(value);
	}
	return encoded.length <= 8_000
		? value
		: { truncated: true, preview: encoded.slice(0, 8_000) };
}

function diagnostic(
	state: ValidationState,
	value: Omit<ValidationDiagnostic, "draftPath">,
): void {
	state.diagnostics.push({
		...value,
		...(value.expected === undefined
			? {}
			: { expected: boundedDiagnosticValue(value.expected) }),
		...(value.actual === undefined
			? {}
			: { actual: boundedDiagnosticValue(value.actual) }),
		...(value.output === undefined
			? {}
			: { output: boundedOutput(value.output) }),
		draftPath: state.draftPath,
	});
}

function parseJson(path: string): unknown {
	return JSON.parse(readFileSync(path, "utf8"));
}

function strings(value: unknown): value is string[] {
	return (
		Array.isArray(value) &&
		value.every((item) => typeof item === "string" && item.length > 0)
	);
}

function validManifest(value: unknown): value is DynamicManifest {
	if (!value || typeof value !== "object" || Array.isArray(value)) return false;
	const manifest = value as Record<string, unknown>;
	const fields = new Set([
		"schemaVersion",
		"name",
		"description",
		"topic",
		"scope",
		"nonGoals",
		"tags",
		"capabilities",
		"requiredExecutables",
		"optionalExecutables",
		"overrides",
		"benchmarkBudgets",
	]);
	const budgets = manifest.benchmarkBudgets;
	return (
		Object.keys(manifest).every((field) => fields.has(field)) &&
		manifest.schemaVersion === 1 &&
		typeof manifest.name === "string" &&
		typeof manifest.description === "string" &&
		typeof manifest.topic === "string" &&
		typeof manifest.scope === "string" &&
		strings(manifest.nonGoals) &&
		strings(manifest.tags) &&
		strings(manifest.capabilities) &&
		strings(manifest.requiredExecutables) &&
		Array.isArray(manifest.optionalExecutables) &&
		manifest.optionalExecutables.every((item) => typeof item === "string") &&
		Array.isArray(manifest.overrides) &&
		manifest.overrides.every((item) => typeof item === "string") &&
		!!budgets &&
		typeof budgets === "object" &&
		!Array.isArray(budgets) &&
		Object.values(budgets).every(
			(budget) =>
				!!budget &&
				typeof budget === "object" &&
				typeof (budget as { hotPathMs?: unknown }).hotPathMs === "number" &&
				(budget as { hotPathMs: number }).hotPathMs > 0,
		)
	);
}

function checkManifest(state: ValidationState): void {
	const path = join(state.draftPath, "manifest.json");
	let value: unknown;
	try {
		value = parseJson(path);
	} catch (error) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_json",
			status: "error",
			path,
			actual: error instanceof Error ? error.message : String(error),
			remediation:
				"Write valid manifest.json using the U008 manifest contract.",
		});
		return;
	}
	if (!validManifest(value)) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_schema",
			status: "error",
			path,
			expected:
				"schemaVersion 1 plus durable identity, capability, executable, override, and benchmark fields",
			actual: value,
			remediation:
				"Restore every required manifest field with the documented type.",
		});
		return;
	}
	state.manifest = value;
	const terms = value.name.split("-");
	if (
		terms.length < 2 ||
		terms.length > 4 ||
		!terms.every((term) => /^[a-z0-9]+$/u.test(term)) ||
		terms.some(
			(term) =>
				FORBIDDEN_NAME_TERMS.has(term) || /^v?\d+(?:[._]\d+)*$/u.test(term),
		)
	) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_name",
			status: "error",
			path,
			expected: "two-to-four-term kebab-case domain capability name",
			actual: value.name,
			remediation:
				"Rename the extension without platform, version, model, session, helper, or utils terms.",
		});
	}
	if (
		!/[.!?]$/u.test(value.description.trim()) ||
		/[\r\n]/u.test(value.description.trim())
	) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_description",
			status: "error",
			path,
			expected: "one concrete sentence ending in punctuation",
			actual: value.description,
			remediation:
				"Write one concrete capability sentence ending in punctuation.",
		});
	}
	for (const [field, content] of [
		["topic", value.topic],
		["scope", value.scope],
	] as const) {
		if (content.trim().length === 0)
			diagnostic(state, {
				gate: "manifest",
				code: `manifest_${field}`,
				status: "error",
				path,
				expected: `non-empty ${field}`,
				actual: content,
				remediation: `Describe the extension's single ${field}.`,
			});
	}
	for (const capability of value.capabilities) {
		if (!/^[a-z0-9]+(?:-[a-z0-9]+)+$/u.test(capability))
			diagnostic(state, {
				gate: "manifest",
				code: "manifest_capability",
				status: "error",
				path,
				expected: "stable kebab-case capability ID",
				actual: capability,
				remediation: "Use a stable multi-term kebab-case capability ID.",
			});
	}
	if (new Set(value.capabilities).size !== value.capabilities.length)
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_capabilities_duplicate",
			status: "error",
			path,
			actual: value.capabilities,
			remediation: "Remove duplicate capability IDs.",
		});
	const requiredExecutables = new Set(value.requiredExecutables);
	const optionalExecutables = new Set(value.optionalExecutables);
	if (
		requiredExecutables.size !== value.requiredExecutables.length ||
		optionalExecutables.size !== value.optionalExecutables.length ||
		[...requiredExecutables].some((name) => optionalExecutables.has(name))
	)
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_executables_duplicate",
			status: "error",
			path,
			actual: {
				required: value.requiredExecutables,
				optional: value.optionalExecutables,
			},
			remediation:
				"Declare each executable once as either required or optional.",
		});
	if (new Set(value.overrides).size !== value.overrides.length)
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_overrides_duplicate",
			status: "error",
			path,
			actual: value.overrides,
			remediation: "Remove duplicate qualified overrides.",
		});
	if (new Set(value.tags).size !== value.tags.length) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_tags_duplicate",
			status: "error",
			path,
			actual: value.tags,
			remediation: "Remove duplicate tags.",
		});
	}
	for (const override of value.overrides) {
		if (
			ULTRA_RESERVED_TOOL_NAMES.has(override.replace(/^tool:/u, "")) &&
			override.startsWith("tool:")
		)
			diagnostic(state, {
				gate: "manifest",
				code: "manifest_reserved_override",
				status: "error",
				path,
				actual: override,
				remediation:
					"Remove overrides reserved by Ultra's orchestration boundary.",
			});
		if (
			!/^(tool|command|flag|shortcut|renderer|entry-renderer|provider):[^:]+$/u.test(
				override,
			)
		) {
			diagnostic(state, {
				gate: "manifest",
				code: "manifest_override",
				status: "error",
				path,
				expected: "an exact qualified target such as tool:read",
				actual: override,
				remediation:
					"Qualify the override with its registration kind and exact name.",
			});
		}
	}
	if (!value.benchmarkBudgets[process.platform]) {
		diagnostic(state, {
			gate: "manifest",
			code: "manifest_platform_budget",
			status: "error",
			path,
			expected: process.platform,
			actual: Object.keys(value.benchmarkBudgets),
			remediation: "Declare a hotPathMs budget for the current platform.",
		});
	}
}

function lineOf(text: string, needle: string): number | undefined {
	const index = text.indexOf(needle);
	return index < 0 ? undefined : text.slice(0, index).split("\n").length;
}

function markdownSection(text: string, section: string): string | undefined {
	const heading = `## ${section}`;
	const start = text.indexOf(heading);
	if (start < 0) return undefined;
	const bodyStart = start + heading.length;
	const next = /^##\s+/gmu;
	next.lastIndex = bodyStart;
	const match = next.exec(text);
	return text.slice(bodyStart, match?.index ?? text.length).trim();
}

function checkReadme(state: ValidationState): void {
	const path = join(state.draftPath, "README.md");
	let text = "";
	try {
		text = readFileSync(path, "utf8");
	} catch {
		diagnostic(state, {
			gate: "readme",
			code: "readme_missing",
			status: "error",
			path,
			remediation: "Create README.md with every mandatory section.",
		});
		return;
	}
	for (const section of README_SECTIONS) {
		const heading = `## ${section}`;
		const content = markdownSection(text, section);
		if (content === undefined)
			diagnostic(state, {
				gate: "readme",
				code: "readme_section",
				status: "error",
				path,
				expected: heading,
				remediation: `Add and populate the ${section} section.`,
			});
		else if (content.length === 0)
			diagnostic(state, {
				gate: "readme",
				code: "readme_section_empty",
				status: "error",
				path,
				line: lineOf(text, heading),
				actual: heading,
				remediation: `Populate the ${section} section.`,
			});
	}
	const placeholder = /\b(?:TODO|TBD|PLACEHOLDER|FIXME)\b/u.exec(text);
	if (placeholder)
		diagnostic(state, {
			gate: "readme",
			code: "readme_placeholder",
			status: "error",
			path,
			line: lineOf(text, placeholder[0]),
			actual: placeholder[0],
			remediation:
				"Replace unresolved scaffold placeholders with durable documentation.",
		});
	const testMatrix = markdownSection(text, "Test matrix") ?? "";
	if (!state.manifest)
		diagnostic(state, {
			gate: "readme",
			code: "readme_capability_mapping_blocked",
			status: "blocked",
			path,
			remediation: "Fix manifest.json before checking capability mappings.",
		});
	for (const capability of state.manifest?.capabilities ?? []) {
		if (!testMatrix.includes(capability))
			diagnostic(state, {
				gate: "readme",
				code: "readme_capability_mapping",
				status: "error",
				path,
				actual: capability,
				remediation: "List this capability ID in the README Test matrix.",
			});
	}
}

function sourceFiles(root: string): string[] {
	return artifactFiles(root);
}

function importedPackages(files: string[]): Set<string> {
	const packages = new Set<string>();
	const pattern = /(?:\bfrom\s+|\bimport\s*(?:\(\s*)?)["']([^"']+)["']/gu;
	for (const file of files.filter((path) => path.endsWith(".ts"))) {
		let text: string;
		try {
			if (lstatSync(file).isSymbolicLink()) continue;
			text = readFileSync(file, "utf8");
		} catch {
			continue;
		}
		for (const match of text.matchAll(pattern)) {
			const specifier = match[1];
			if (
				specifier.startsWith(".") ||
				specifier.startsWith("node:") ||
				specifier.startsWith("/")
			)
				continue;
			packages.add(
				specifier.startsWith("@")
					? specifier.split("/").slice(0, 2).join("/")
					: specifier.split("/")[0],
			);
		}
	}
	return packages;
}

function checkPackage(state: ValidationState): void {
	const path = join(state.draftPath, "package.json");
	let pkg: Record<string, unknown>;
	try {
		pkg = parseJson(path) as Record<string, unknown>;
	} catch (error) {
		diagnostic(state, {
			gate: "package",
			code: "package_json",
			status: "error",
			path,
			actual: error instanceof Error ? error.message : String(error),
			remediation: "Write valid package.json.",
		});
		return;
	}
	if (pkg.private !== true || pkg.type !== "module" || pkg.main !== "index.ts")
		diagnostic(state, {
			gate: "package",
			code: "package_metadata",
			status: "error",
			path,
			expected: { private: true, type: "module", main: "index.ts" },
			actual: { private: pkg.private, type: pkg.type, main: pkg.main },
			remediation:
				"Keep generated packages private ESM entries rooted at index.ts.",
		});
	const dependencies = {
		...((pkg.dependencies as Record<string, unknown> | undefined) ?? {}),
		...((pkg.optionalDependencies as Record<string, unknown> | undefined) ??
			{}),
	};
	if (Object.keys(dependencies).length > 0)
		diagnostic(state, {
			gate: "package",
			code: "package_runtime_dependency",
			status: "error",
			path,
			actual: Object.keys(dependencies),
			remediation:
				"Remove third-party runtime npm dependencies; use Node or Pi host APIs.",
		});
	const peers = (pkg.peerDependencies ?? {}) as Record<string, unknown>;
	const imports = importedPackages(sourceFiles(state.draftPath));
	for (const imported of imports) {
		if (!HOST_PACKAGES.has(imported)) {
			diagnostic(state, {
				gate: "package",
				code: "package_third_party_import",
				status: "error",
				path,
				actual: imported,
				remediation: "Remove the third-party runtime import.",
			});
			continue;
		}
		if (!(imported in peers))
			diagnostic(state, {
				gate: "package",
				code: "package_missing_peer",
				status: "error",
				path,
				actual: imported,
				remediation: `Declare ${imported} as a peer dependency because source imports it.`,
			});
	}
	for (const peer of Object.keys(peers)) {
		if (!HOST_PACKAGES.has(peer) || !imports.has(peer))
			diagnostic(state, {
				gate: "package",
				code: "package_unused_peer",
				status: "error",
				path,
				actual: peer,
				remediation:
					"Remove peer dependencies that are not imported Pi host packages.",
			});
	}
}

function checkDebugAndArtifacts(state: ValidationState): void {
	for (const file of REQUIRED_FILES) {
		const path = join(state.draftPath, file);
		if (!existsSync(path))
			diagnostic(state, {
				gate: "artifacts",
				code: "artifact_missing",
				status: "error",
				path,
				remediation: `Restore mandatory scaffold artifact ${file}.`,
			});
	}
	const debugPath = join(state.draftPath, "debug.ts");
	if (
		existsSync(debugPath) &&
		readFileSync(debugPath, "utf8") !== DYNAMIC_DEBUG_TEMPLATE
	)
		diagnostic(state, {
			gate: "debug-template",
			code: "debug_template_changed",
			status: "error",
			path: debugPath,
			remediation: "Restore debug.ts from create_dynamic_extension output.",
		});
	for (const file of sourceFiles(state.draftPath)) {
		if (lstatSync(file).isSymbolicLink()) {
			diagnostic(state, {
				gate: "artifacts",
				code: "artifact_symlink",
				status: "error",
				path: file,
				remediation: "Replace the symlink with a regular artifact file.",
			});
			continue;
		}
		if (!file.endsWith(".ts")) continue;
		const source = readFileSync(file, "utf8");
		const unsupported =
			/\b(?:const\s+)?enum\s+[A-Za-z_$]/u.exec(source) ??
			/\bnamespace\s+[A-Za-z_$]/u.exec(source) ??
			/constructor\s*\([^)]*\b(?:public|private|protected|readonly)\s+[A-Za-z_$]/u.exec(
				source,
			);
		if (unsupported)
			diagnostic(state, {
				gate: "artifacts",
				code: "typescript_not_erasable",
				status: "error",
				path: file,
				line: lineOf(source, unsupported[0]),
				actual: unsupported[0],
				remediation:
					"Replace transform-only TypeScript with directly erasable syntax.",
			});
	}
}

function executableOnPath(name: string): boolean {
	if (name.includes("/") || name.includes("\\")) return false;
	const extensions =
		process.platform === "win32"
			? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
					.split(";")
					.map((extension) => extension.toLowerCase())
			: [""];
	for (const dir of (process.env.PATH ?? "").split(sep === "\\" ? ";" : ":")) {
		for (const extension of extensions) {
			const candidate = join(dir, `${name}${extension}`);
			try {
				if (statSync(candidate).isFile()) return true;
			} catch {}
		}
	}
	return false;
}

function checkExecutables(state: ValidationState): void {
	if (!state.manifest) {
		diagnostic(state, {
			gate: "executables",
			code: "executables_blocked",
			status: "blocked",
			remediation: "Fix manifest.json before checking executable declarations.",
		});
		return;
	}
	for (const name of state.manifest.requiredExecutables) {
		if (!executableOnPath(name))
			diagnostic(state, {
				gate: "executables",
				code: "required_executable_missing",
				status: "error",
				actual: name,
				remediation: `Install ${name} or redesign the extension without it.`,
			});
	}
	for (const name of state.manifest.optionalExecutables) {
		if (!executableOnPath(name))
			diagnostic(state, {
				gate: "executables",
				code: "optional_executable_missing",
				status: "warning",
				actual: name,
				remediation: `Install ${name} to exercise its optional capability path.`,
			});
	}
}

function boundedOutput(value: string, limit = 8_000): string {
	return value.length <= limit
		? value
		: `${value.slice(0, limit)}\n[truncated]`;
}

async function checkTests(state: ValidationState): Promise<void> {
	const tests = sourceFiles(state.draftPath).filter((path) => {
		try {
			return path.endsWith(".test.ts") && !lstatSync(path).isSymbolicLink();
		} catch {
			return false;
		}
	});
	const testText = tests.map((path) => readFileSync(path, "utf8")).join("\n");
	if (!state.manifest)
		diagnostic(state, {
			gate: "tests",
			code: "test_capability_mapping_blocked",
			status: "blocked",
			remediation: "Fix manifest.json before checking capability mappings.",
		});
	for (const capability of state.manifest?.capabilities ?? []) {
		const escaped = capability.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
		if (
			!new RegExp("(?:test|it)\\s*\\(\\s*[\"'`]" + escaped, "u").test(testText)
		)
			diagnostic(state, {
				gate: "tests",
				code: "test_capability_mapping",
				status: "error",
				actual: capability,
				remediation:
					"Include the exact capability ID in at least one node:test case name.",
			});
	}
	if (tests.length === 0) {
		diagnostic(state, {
			gate: "tests",
			code: "tests_missing",
			status: "error",
			remediation: "Add at least one .test.ts node:test file.",
		});
		return;
	}
	const { run } = await import("node:test");
	const start = performance.now();
	const failures: unknown[] = [];
	let success = false;
	const stream = run({ files: tests, concurrency: false, isolation: "none" });
	stream.on("test:fail", (failure) => failures.push(failure));
	stream.on("test:summary", (summary) => {
		success = summary.success;
	});
	stream.resume();
	await once(stream, "end");
	const elapsedMs = performance.now() - start;
	if (!success)
		diagnostic(state, {
			gate: "tests",
			code: "tests_failed",
			status: "error",
			output: boundedOutput(JSON.stringify(failures)),
			elapsedMs,
			remediation: "Fix every node:test failure and rerun validation.",
		});
}

async function checkBenchmark(state: ValidationState): Promise<void> {
	const path = join(state.draftPath, "benchmark.ts");
	if (!existsSync(path)) {
		diagnostic(state, {
			gate: "benchmark",
			code: "benchmark_blocked",
			status: "blocked",
			path,
			remediation:
				"Restore benchmark.ts before checking its contract and budget.",
		});
		return;
	}
	const output: string[] = [];
	const originalLog = console.log;
	let benchmarkError: unknown;
	try {
		console.log = (...values: unknown[]) =>
			output.push(values.map((value) => String(value)).join(" "));
		await import(`${pathToFileURL(path).href}?validation=${Date.now()}`);
	} catch (error) {
		benchmarkError = error;
	} finally {
		console.log = originalLog;
	}
	let measured: unknown;
	try {
		measured = (JSON.parse(output.at(-1) ?? "") as { hotPathMs?: unknown })
			.hotPathMs;
	} catch {}
	if (benchmarkError || typeof measured !== "number" || measured < 0) {
		diagnostic(state, {
			gate: "benchmark",
			code: "benchmark_contract",
			status: "error",
			path,
			output: boundedOutput(
				`${output.join("\n")}\n${benchmarkError instanceof Error ? (benchmarkError.stack ?? benchmarkError.message) : (benchmarkError ?? "")}`,
			),
			expected: "final stdout line is JSON with non-negative hotPathMs",
			actual: measured,
			remediation:
				"Make benchmark.ts run the hot path and print its measured JSON result.",
		});
		return;
	}
	const budget = state.manifest?.benchmarkBudgets[process.platform]?.hotPathMs;
	if (budget === undefined)
		diagnostic(state, {
			gate: "benchmark",
			code: "benchmark_budget_blocked",
			status: "blocked",
			path,
			remediation:
				"Fix the current-platform manifest budget before comparing it.",
		});
	else if (measured > budget)
		diagnostic(state, {
			gate: "benchmark",
			code: "benchmark_budget",
			status: "warning",
			path,
			expected: budget,
			actual: measured,
			remediation:
				"Reproduce under controlled benchmark conditions, then optimize the hot path or deliberately revise its budget.",
		});
}

async function checkRealLoad(state: ValidationState): Promise<void> {
	const indexPath = join(state.draftPath, "index.ts");
	if (!existsSync(indexPath)) {
		diagnostic(state, {
			gate: "real-loader",
			code: "real_loader_blocked",
			status: "blocked",
			path: indexPath,
			remediation: "Restore index.ts before real-loader validation.",
		});
		return;
	}
	const agentDir = await mkdtemp(join(tmpdir(), "ultra-validator-agent-"));
	let session:
		| Awaited<ReturnType<typeof createAgentSession>>["session"]
		| undefined;
	const extensionErrors: unknown[] = [];
	try {
		const loaderOptions = {
			cwd: state.draftPath,
			agentDir,
			noExtensions: true,
			noSkills: true,
			noPromptTemplates: true,
			noThemes: true,
			noContextFiles: true,
		};
		const baselinePath = join(agentDir, "baseline-extension.ts");
		await writeFile(
			baselinePath,
			"export default function baselineExtension() {}\n",
			"utf8",
		);
		const baselineLoader = new DefaultResourceLoader({
			...loaderOptions,
			additionalExtensionPaths: [baselinePath],
		});
		const baselineStarted = performance.now();
		await baselineLoader.reload();
		const baselineMs = performance.now() - baselineStarted;
		const loader = new DefaultResourceLoader({
			...loaderOptions,
			additionalExtensionPaths: [indexPath],
		});
		const start = performance.now();
		await loader.reload();
		const loadMs = Math.max(0, performance.now() - start - baselineMs);
		const loaded = loader.getExtensions();
		if (loaded.errors.length > 0) {
			diagnostic(state, {
				gate: "real-loader",
				code: "extension_load",
				status: "error",
				path: indexPath,
				actual: loaded.errors,
				remediation:
					"Fix extension initialization so DefaultResourceLoader can load index.ts.",
			});
			return;
		}
		if (loadMs > MARGINAL_LOAD_BUDGET_MS)
			diagnostic(state, {
				gate: "load-timing",
				code: "marginal_load_budget",
				status: "warning",
				path: indexPath,
				limitMs: MARGINAL_LOAD_BUDGET_MS,
				elapsedMs: loadMs,
				remediation:
					"Reproduce under controlled benchmark conditions, then make index.ts thin and defer optional work until first use.",
			});
		const model = getModels("openai")[0] ?? getModels("anthropic")[0];
		if (!model)
			throw new Error(
				"Pi exposes no built-in model for an in-memory validation session.",
			);
		({ session } = await createAgentSession({
			cwd: state.draftPath,
			agentDir,
			model,
			resourceLoader: loader,
			sessionManager: SessionManager.inMemory(state.draftPath),
			noTools: "builtin",
		}));
		await session.bindExtensions({
			mode: "print",
			onError: (error) => extensionErrors.push(error),
		});
		const generatedTools = loaded.extensions.flatMap((extension) => [
			...extension.tools.keys(),
		]);
		for (const name of generatedTools) {
			if (ULTRA_RESERVED_TOOL_NAMES.has(name))
				diagnostic(state, {
					gate: "real-loader",
					code: "generated_tool_reserved",
					status: "error",
					path: indexPath,
					actual: name,
					remediation:
						"Rename tools reserved by Ultra's orchestration boundary.",
				});
			else if (
				BUILTIN_TOOL_NAMES.has(name) &&
				!state.manifest?.overrides.includes(`tool:${name}`)
			)
				diagnostic(state, {
					gate: "real-loader",
					code: "generated_tool_override_undeclared",
					status: "error",
					path: indexPath,
					actual: name,
					remediation: `Declare the exact qualified override tool:${name} or rename the tool.`,
				});
		}
		const active = new Set(session.getActiveToolNames());
		const inactive = generatedTools.filter((name) => !active.has(name));
		if (inactive.length > 0)
			diagnostic(state, {
				gate: "real-loader",
				code: "generated_tool_inactive",
				status: "error",
				path: indexPath,
				actual: {
					inactive,
					active: session.getActiveToolNames(),
					all: session.getAllTools().map((tool) => tool.name),
					extensionErrors,
				},
				remediation:
					"Activate every generated tool from the extension's session_start handler.",
			});
		await session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});
	} catch (error) {
		diagnostic(state, {
			gate: "real-loader",
			code: "real_loader_session",
			status: "error",
			path: indexPath,
			actual:
				error instanceof Error ? (error.stack ?? error.message) : String(error),
			remediation:
				"Fix print-mode loading, session_start, and session_shutdown behavior.",
		});
	} finally {
		session?.dispose();
		await rm(agentDir, { recursive: true, force: true });
	}
}

export function hashArtifacts(root: string): string {
	return hashArtifactTree(root);
}

export async function validateDraft(
	draftPath: string,
): Promise<WorkerValidationResult> {
	const started = performance.now();
	const state: ValidationState = {
		draftPath: resolve(draftPath),
		diagnostics: [],
	};
	checkManifest(state);
	checkReadme(state);
	checkPackage(state);
	checkDebugAndArtifacts(state);
	checkExecutables(state);
	await checkTests(state);
	await checkBenchmark(state);
	await checkRealLoad(state);
	let hash: string | undefined;
	try {
		hash = hashArtifacts(state.draftPath);
	} catch (error) {
		diagnostic(state, {
			gate: "hash",
			code: "artifact_hash",
			status: "error",
			actual: error instanceof Error ? error.message : String(error),
			remediation: "Remove symlinks and make every artifact readable.",
		});
	}
	const durationMs = performance.now() - started;
	if (durationMs > VALIDATOR_WARNING_TARGET_MS)
		diagnostic(state, {
			gate: "validator-runtime",
			code: "validator_warning_target",
			status: "warning",
			limitMs: VALIDATOR_WARNING_TARGET_MS,
			elapsedMs: durationMs,
			remediation:
				"Keep tests focused; this warning does not block publication.",
		});
	const ok =
		!!state.manifest &&
		!!hash &&
		!state.diagnostics.some((item) => item.status === "error");
	const gates = [
		"manifest",
		"readme",
		"package",
		"debug-template",
		"artifacts",
		"executables",
		"tests",
		"benchmark",
		"real-loader",
		"load-timing",
		"hash",
	];
	const attestation: ValidationAttestation | undefined =
		ok && hash
			? {
					schemaVersion: 1,
					validatorContractVersion: VALIDATOR_CONTRACT_VERSION,
					sourceHash: hash,
					validatedAt: new Date().toISOString(),
					platform: process.platform,
					testedPlatforms: [process.platform],
					nodeVersion: process.version,
					warningTargetMs: VALIDATOR_WARNING_TARGET_MS,
					gates,
				}
			: undefined;
	return {
		ok,
		diagnostics: state.diagnostics,
		...(state.manifest ? { manifest: state.manifest } : {}),
		...(hash ? { hash } : {}),
		...(attestation ? { attestation } : {}),
		durationMs,
	};
}

async function emitWorkerResult(result: WorkerValidationResult): Promise<void> {
	const resultPath = process.env.ULTRA_VALIDATOR_RESULT_PATH;
	if (resultPath) await writeFile(resultPath, JSON.stringify(result), "utf8");
	console.log(`ULTRA_VALIDATION_RESULT=${JSON.stringify(result)}`);
}

const invokedPath = process.argv[1] ? resolve(process.argv[1]) : undefined;
if (invokedPath === resolve(fileURLToPath(import.meta.url))) {
	const draftPath = process.argv[2];
	if (!draftPath) {
		console.error("usage: dynamic-validator-worker.ts <draft-path>");
		process.exitCode = 2;
	} else {
		validateDraft(draftPath).then(
			(result) => emitWorkerResult(result),
			async (error) => {
				await emitWorkerResult({
					ok: false,
					diagnostics: [
						{
							gate: "validator",
							code: "validator_crash",
							status: "error",
							actual:
								error instanceof Error
									? (error.stack ?? error.message)
									: String(error),
							remediation: "Repair the validator crash before retrying.",
							draftPath,
						},
					],
					durationMs: 0,
				});
				process.exitCode = 1;
			},
		);
	}
}