refactor: isolate runtime contracts and enforce import boundaries (#6166)
* test: enforce Python import ownership boundaries * test: protect client import boundaries and rehome shared UI contracts * refactor: remove gateway and client dependency inversions * fix: detect dynamic imports in conditional expressions * refactor(tools): keep configuration contracts with their owners * docs: keep design guidance focused on ownership and checks * fix: preserve default threaded turn delivery
This commit is contained in:
1 parent
cd2a863710
commit
328e933d36
162 files changed
+3449
-1888
No files matched your search
@@ -0,0 +1,315 @@
|
||||
/** Check client imports without loading application or channel modules. */
|
||||
import { Glob } from "bun";
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
const REPO_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const UI_PACKAGES = ["react", "react-dom", "react-i18next", "@radix-ui", "lucide-react", "@opentui"];
|
||||
const WEBUI_VIEWS = ["webui/src/components", "webui/src/hooks", "webui/src/providers"];
|
||||
const TUI_VIEWS = ["tui/src/app", "tui/src/views", "tui/src/rendering", "tui/src/composer", "tui/src/menus"];
|
||||
const CHANNEL_CONTRACTS = ["webui/src/channel-plugins/types.ts", "webui/src/channel-plugins/catalog.ts"];
|
||||
|
||||
function slash(value) {
|
||||
return value.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function within(value, prefix) {
|
||||
if (process.platform === "win32") {
|
||||
value = value.toLowerCase();
|
||||
prefix = prefix.toLowerCase();
|
||||
}
|
||||
return value === prefix || value.startsWith(`${prefix}/`);
|
||||
}
|
||||
|
||||
function channelUi(value) {
|
||||
return /^nanobot\/channels\/[^/]+\/webui\//.test(process.platform === "win32" ? value.toLowerCase() : value);
|
||||
}
|
||||
|
||||
function sourcePath(root, file) {
|
||||
return slash(path.relative(root, file));
|
||||
}
|
||||
|
||||
function uiPackage(specifier) {
|
||||
return UI_PACKAGES.some((prefix) => within(specifier, prefix));
|
||||
}
|
||||
|
||||
export function loadCompiler(project) {
|
||||
return createRequire(path.join(REPO_ROOT, project, "package.json"))("typescript");
|
||||
}
|
||||
|
||||
function projectOptions(compiler, root, project) {
|
||||
const configPath = path.join(root, project, "tsconfig.json");
|
||||
const config = compiler.readConfigFile(configPath, compiler.sys.readFile);
|
||||
if (config.error) throw new Error(compiler.flattenDiagnosticMessageText(config.error.messageText, "\n"));
|
||||
const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, path.dirname(configPath));
|
||||
if (parsed.errors.length) {
|
||||
throw new Error(parsed.errors.map((error) => compiler.flattenDiagnosticMessageText(error.messageText, "\n")).join("\n"));
|
||||
}
|
||||
return parsed.options;
|
||||
}
|
||||
|
||||
function targets(root, file, specifier, options, project) {
|
||||
if (specifier.startsWith(".")) return [path.resolve(path.dirname(file), specifier)];
|
||||
if (specifier.startsWith("/")) return [path.resolve(root, project, specifier.slice(1))];
|
||||
for (const [pattern, replacements] of Object.entries(options.paths ?? {})) {
|
||||
const wildcard = pattern.indexOf("*");
|
||||
const prefix = wildcard < 0 ? pattern : pattern.slice(0, wildcard);
|
||||
const suffix = wildcard < 0 ? "" : pattern.slice(wildcard + 1);
|
||||
if (wildcard < 0 ? specifier !== pattern : !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) continue;
|
||||
const capture = wildcard < 0 ? "" : specifier.slice(prefix.length, specifier.length - suffix.length);
|
||||
const base = options.baseUrl ?? path.join(root, project);
|
||||
return replacements.map((replacement) => path.resolve(base, replacement.replace("*", capture)));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function stringValue(compiler, node) {
|
||||
return node && (compiler.isStringLiteral(node) || compiler.isNoSubstitutionTemplateLiteral(node))
|
||||
? node.text
|
||||
: null;
|
||||
}
|
||||
|
||||
function globTargets(compiler, argument, root, file, options, project) {
|
||||
const nodes = compiler.isArrayLiteralExpression(argument) ? argument.elements : [argument];
|
||||
const patterns = nodes.map((node) => stringValue(compiler, node));
|
||||
if (patterns.some((pattern) => pattern === null)) return [];
|
||||
const positive = [];
|
||||
const negative = [];
|
||||
for (const pattern of patterns) {
|
||||
const excluded = pattern.startsWith("!");
|
||||
for (const target of targets(root, file, excluded ? pattern.slice(1) : pattern, options, project)) {
|
||||
const relative = sourcePath(root, target);
|
||||
if (relative.startsWith("../")) throw new Error(`${sourcePath(root, file)}: glob resolves outside the repository`);
|
||||
(excluded ? negative : positive).push(new Glob(relative));
|
||||
}
|
||||
}
|
||||
const matches = new Set();
|
||||
for (const pattern of positive) {
|
||||
for (const match of pattern.scanSync({ cwd: root, onlyFiles: true })) {
|
||||
const relative = slash(match);
|
||||
if (!negative.some((excluded) => excluded.match(relative))) matches.add(relative);
|
||||
}
|
||||
}
|
||||
return [...matches];
|
||||
}
|
||||
|
||||
export function findViolations(compiler, root, file, source, options, project) {
|
||||
const relative = sourcePath(root, file);
|
||||
const tree = compiler.createSourceFile(file, source, compiler.ScriptTarget.Latest, true);
|
||||
if (tree.parseDiagnostics.length) {
|
||||
const error = tree.parseDiagnostics[0];
|
||||
const line = tree.getLineAndCharacterOfPosition(error.start).line + 1;
|
||||
throw new Error(`${relative}:${line}: ${compiler.flattenDiagnosticMessageText(error.messageText, "\n")}`);
|
||||
}
|
||||
const violations = [];
|
||||
const reported = new Set();
|
||||
|
||||
function check(specifier, target, node) {
|
||||
const rules = [];
|
||||
const targetPath = target === null ? null : sourcePath(root, target);
|
||||
if (within(relative, "packages/client-events")) {
|
||||
if ((targetPath !== null && !within(targetPath, "packages/client-events")) || uiPackage(specifier)) {
|
||||
rules.push("shared-client-contracts");
|
||||
}
|
||||
}
|
||||
if (within(relative, "tui/src/client")) {
|
||||
if (TUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix)) || uiPackage(specifier)) {
|
||||
rules.push("tui-client");
|
||||
}
|
||||
}
|
||||
if (within(relative, "webui/src/lib") && WEBUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix))) {
|
||||
rules.push("webui-lib");
|
||||
}
|
||||
const comparableTarget = process.platform === "win32" ? targetPath?.toLowerCase() : targetPath;
|
||||
if (within(relative, "webui/src/lib")
|
||||
&& /^webui\/src\/i18n(?:\/index(?:\.[cm]?[jt]sx?)?)?$/.test(comparableTarget ?? "")) {
|
||||
rules.push("webui-lib-bootstrap");
|
||||
}
|
||||
if (within(relative, "webui/src/lib/format.ts") && ["i18next", "react-i18next"].includes(specifier)) {
|
||||
rules.push("pure-format-utils");
|
||||
}
|
||||
if (CHANNEL_CONTRACTS.includes(relative) && WEBUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix))) {
|
||||
rules.push("channel-ui-contracts");
|
||||
}
|
||||
if (targetPath !== null) {
|
||||
const webuiSource = within(relative, "webui/src") || channelUi(relative);
|
||||
const tuiSource = within(relative, "tui/src");
|
||||
if ((webuiSource && within(targetPath, "tui"))
|
||||
|| (tuiSource && (within(targetPath, "webui") || channelUi(targetPath)))) {
|
||||
rules.push("client-app-isolation");
|
||||
}
|
||||
}
|
||||
const line = tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1;
|
||||
for (const rule of rules) {
|
||||
const message = `${relative}:${line}: [${rule}] must not import ${targetPath ?? specifier}`;
|
||||
if (!reported.has(message)) {
|
||||
reported.add(message);
|
||||
violations.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function add(specifier, node) {
|
||||
if (specifier === null) return;
|
||||
const resolved = targets(root, file, specifier, options, project);
|
||||
if (resolved.length) {
|
||||
for (const target of resolved) check(specifier, target, node);
|
||||
} else {
|
||||
check(specifier, null, node);
|
||||
}
|
||||
}
|
||||
|
||||
function visit(node) {
|
||||
if (compiler.isImportDeclaration(node) || compiler.isExportDeclaration(node)) {
|
||||
add(stringValue(compiler, node.moduleSpecifier), node);
|
||||
} else if (compiler.isImportTypeNode(node) && compiler.isLiteralTypeNode(node.argument)) {
|
||||
add(stringValue(compiler, node.argument.literal), node);
|
||||
} else if (compiler.isImportEqualsDeclaration(node) && compiler.isExternalModuleReference(node.moduleReference)) {
|
||||
add(stringValue(compiler, node.moduleReference.expression), node);
|
||||
} else if (compiler.isCallExpression(node) && node.arguments.length) {
|
||||
if (node.expression.kind === compiler.SyntaxKind.ImportKeyword
|
||||
|| (compiler.isIdentifier(node.expression) && node.expression.text === "require")) {
|
||||
add(stringValue(compiler, node.arguments[0]), node);
|
||||
} else if (compiler.isPropertyAccessExpression(node.expression)
|
||||
&& node.expression.name.text === "glob"
|
||||
&& compiler.isMetaProperty(node.expression.expression)
|
||||
&& node.expression.expression.keywordToken === compiler.SyntaxKind.ImportKeyword) {
|
||||
for (const target of globTargets(compiler, node.arguments[0], root, file, options, project)) {
|
||||
check(target, path.join(root, target), node);
|
||||
}
|
||||
}
|
||||
}
|
||||
compiler.forEachChild(node, visit);
|
||||
}
|
||||
|
||||
visit(tree);
|
||||
return violations;
|
||||
}
|
||||
|
||||
function productionSources(directory) {
|
||||
const files = [];
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
if (entry.isDirectory() && !["tests", "__tests__"].includes(entry.name)) {
|
||||
files.push(...productionSources(path.join(directory, entry.name)));
|
||||
} else if (entry.isFile() && /\.(?:[cm]?[jt]s|[jt]sx)$/.test(entry.name) && !/\.(?:test|spec)\./.test(entry.name)) {
|
||||
files.push(path.join(directory, entry.name));
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
export function findRuntimeCycles(compiler, root, project, files, options) {
|
||||
files = files.filter((file) => !/\.d\.[cm]?ts$/.test(file));
|
||||
const key = (file) => process.platform === "win32" ? path.resolve(file).toLowerCase() : path.resolve(file);
|
||||
const sources = new Map(files.map((file) => [key(file), file]));
|
||||
const graph = new Map(files.map((file) => [key(file), new Set()]));
|
||||
|
||||
for (const file of files) {
|
||||
// TypeScript's emitter removes type-only dependencies, including value-spelled type imports.
|
||||
const { outputText } = compiler.transpileModule(readFileSync(file, "utf8"), {
|
||||
fileName: file,
|
||||
compilerOptions: { ...options, noEmit: false, module: compiler.ModuleKind.ESNext },
|
||||
});
|
||||
const tree = compiler.createSourceFile(file, outputText, compiler.ScriptTarget.Latest, true);
|
||||
const outgoing = graph.get(key(file));
|
||||
function add(specifier) {
|
||||
if (specifier === null) return;
|
||||
const resolved = compiler.resolveModuleName(specifier, file, options, compiler.sys).resolvedModule;
|
||||
if (resolved && sources.has(key(resolved.resolvedFileName))) outgoing.add(key(resolved.resolvedFileName));
|
||||
}
|
||||
function visit(node, deferred = false) {
|
||||
if (compiler.isImportDeclaration(node) || compiler.isExportDeclaration(node)) {
|
||||
add(stringValue(compiler, node.moduleSpecifier));
|
||||
} else if (!deferred && compiler.isCallExpression(node) && node.arguments.length
|
||||
&& compiler.isIdentifier(node.expression) && node.expression.text === "require") {
|
||||
add(stringValue(compiler, node.arguments[0]));
|
||||
} else if (compiler.isCallExpression(node) && node.arguments.length > 1
|
||||
&& compiler.isPropertyAccessExpression(node.expression) && node.expression.name.text === "glob"
|
||||
&& compiler.isMetaProperty(node.expression.expression)
|
||||
&& node.expression.expression.keywordToken === compiler.SyntaxKind.ImportKeyword) {
|
||||
const settings = node.arguments[1];
|
||||
const eager = compiler.isObjectLiteralExpression(settings) && settings.properties.some((property) =>
|
||||
compiler.isPropertyAssignment(property)
|
||||
&& (compiler.isIdentifier(property.name) ? property.name.text : stringValue(compiler, property.name)) === "eager"
|
||||
&& property.initializer.kind === compiler.SyntaxKind.TrueKeyword);
|
||||
if (eager) {
|
||||
for (const target of globTargets(compiler, node.arguments[0], root, file, options, project)) {
|
||||
const resolved = key(path.join(root, target));
|
||||
if (sources.has(resolved)) outgoing.add(resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
compiler.forEachChild(node, (child) => visit(child, deferred || compiler.isFunctionLike(node)));
|
||||
}
|
||||
visit(tree);
|
||||
}
|
||||
|
||||
const visited = new Set();
|
||||
const active = new Map();
|
||||
const stack = [];
|
||||
const violations = [];
|
||||
function visit(file) {
|
||||
if (active.has(file)) {
|
||||
const cycle = [...stack.slice(active.get(file)), file].map((node) => sourcePath(root, sources.get(node)));
|
||||
violations.push(`${cycle[0]}: [client-runtime-cycle] eager dependencies form a cycle: ${cycle.join(" -> ")}`);
|
||||
return;
|
||||
}
|
||||
if (visited.has(file)) return;
|
||||
active.set(file, stack.length);
|
||||
stack.push(file);
|
||||
for (const target of [...graph.get(file)].sort()) visit(target);
|
||||
stack.pop();
|
||||
active.delete(file);
|
||||
visited.add(file);
|
||||
}
|
||||
for (const file of [...graph.keys()].sort()) visit(file);
|
||||
return violations;
|
||||
}
|
||||
|
||||
export function checkRepository(compiler, root, project) {
|
||||
const options = projectOptions(compiler, root, project);
|
||||
const files = [
|
||||
...productionSources(path.join(root, project, "src")),
|
||||
...productionSources(path.join(root, "packages/client-events")),
|
||||
];
|
||||
if (project === "webui") {
|
||||
const channels = path.join(root, "nanobot/channels");
|
||||
for (const entry of readdirSync(channels, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const channelRoot = path.join(channels, entry.name);
|
||||
if (readdirSync(channelRoot).includes("webui")) files.push(...productionSources(path.join(channelRoot, "webui")));
|
||||
}
|
||||
}
|
||||
const violations = files.sort().flatMap((file) => findViolations(
|
||||
compiler, root, file, readFileSync(file, "utf8"), options, project,
|
||||
));
|
||||
violations.push(...findRuntimeCycles(compiler, root, project, files, options));
|
||||
return { checked: files.length, violations };
|
||||
}
|
||||
|
||||
export function main() {
|
||||
const { values } = parseArgs({
|
||||
options: { project: { type: "string" }, root: { type: "string", default: REPO_ROOT } },
|
||||
});
|
||||
if (!["webui", "tui"].includes(values.project)) throw new Error("--project must be webui or tui");
|
||||
const root = path.resolve(values.root);
|
||||
const result = checkRepository(loadCompiler(values.project), root, values.project);
|
||||
if (result.violations.length) {
|
||||
for (const violation of result.violations) console.error(violation);
|
||||
return 1;
|
||||
}
|
||||
console.log(`Client import boundaries passed (${values.project}, ${result.checked} files).`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
process.exitCode = main();
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { afterEach, beforeEach, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { findViolations, loadCompiler } from "./check_client_import_boundaries.mjs";
|
||||
|
||||
const project = path.basename(process.cwd());
|
||||
const compiler = loadCompiler(project);
|
||||
const script = fileURLToPath(new URL("./check_client_import_boundaries.mjs", import.meta.url));
|
||||
const temporaryPrefix = path.resolve(os.tmpdir(), "nanobot-client-imports-");
|
||||
let root;
|
||||
|
||||
function write(relative, source = "export {};\n") {
|
||||
const file = path.join(root, relative);
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
writeFileSync(file, source);
|
||||
return file;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
root = path.resolve(mkdtempSync(temporaryPrefix));
|
||||
for (const name of ["webui", "tui"]) {
|
||||
write(`${name}/tsconfig.json`, JSON.stringify({
|
||||
compilerOptions: { baseUrl: ".", paths: { "@/*": ["src/*"] } },
|
||||
include: ["src"],
|
||||
}));
|
||||
}
|
||||
for (const file of [
|
||||
"webui/src/lib/model.ts", "webui/src/components/View.tsx",
|
||||
"webui/src/channel-plugins/types.ts", "webui/src/channel-plugins/registry.ts",
|
||||
"tui/src/client/api.ts", "tui/src/app/app.ts",
|
||||
"packages/client-events/notifications.ts", "packages/client-events/delivery.ts",
|
||||
"nanobot/channels/example/webui/index.ts",
|
||||
]) write(file);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (!root.startsWith(temporaryPrefix)) throw new Error("Fixture root is outside the allocated temporary directory");
|
||||
rmSync(root, { recursive: true });
|
||||
});
|
||||
|
||||
function inspect(relative, source) {
|
||||
return findViolations(compiler, root, path.join(root, relative), source, {
|
||||
baseUrl: path.join(root, "webui"), paths: { "@/*": ["src/*"] },
|
||||
}, relative.startsWith("tui/") ? "tui" : "webui");
|
||||
}
|
||||
|
||||
test.each([
|
||||
'import { View } from "@/components/View";',
|
||||
'import type { View } from "../components/View";',
|
||||
'import "@/components/View";',
|
||||
'export { View } from "@/components/View";',
|
||||
'export type { View } from "@/components/View";',
|
||||
'export * from "@/components/View";',
|
||||
'type View = import("@/components/View").View;',
|
||||
'function load() { return import("@/components/View"); }',
|
||||
'const load = () => import(`@/components/View`);',
|
||||
'const view = require("@/components/View");',
|
||||
])("WebUI library rejects a view dependency: %s", (source) => {
|
||||
expect(inspect("webui/src/lib/model.ts", source)).toEqual([
|
||||
"webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/components/View",
|
||||
]);
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "win32")("checks Windows imports that differ in directory casing", () => {
|
||||
expect(existsSync(path.join(root, "webui/src/Components/View.tsx"))).toBe(true);
|
||||
expect(inspect("webui/src/lib/model.ts", 'import type { View } from "../Components/View";')).toEqual([
|
||||
"webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/Components/View",
|
||||
]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["packages/client-events/notifications.ts", 'import "../../webui/src/components/View";', "shared-client-contracts"],
|
||||
["packages/client-events/notifications.ts", 'import type { ReactNode } from "react";', "shared-client-contracts"],
|
||||
["tui/src/client/api.ts", 'export * from "../app/app";', "tui-client"],
|
||||
["tui/src/client/api.ts", 'import type { TextRenderable } from "@opentui/core";', "tui-client"],
|
||||
["webui/src/channel-plugins/types.ts", 'import type { View } from "@/components/View";', "channel-ui-contracts"],
|
||||
["webui/src/lib/model.ts", 'import "../../../tui/src/client/api";', "client-app-isolation"],
|
||||
["tui/src/client/api.ts", 'import "../../../webui/src/lib/model";', "client-app-isolation"],
|
||||
["webui/src/lib/model.ts", 'import "../i18n";', "webui-lib-bootstrap"],
|
||||
["webui/src/lib/model.ts", 'import "../i18n/index.ts";', "webui-lib-bootstrap"],
|
||||
["webui/src/lib/format.ts", 'import i18n from "i18next";', "pure-format-utils"],
|
||||
])("rejects the owning boundary in %s", (relative, source, rule) => {
|
||||
expect(inspect(relative, source)).toHaveLength(1);
|
||||
expect(inspect(relative, source)[0]).toContain(`[${rule}] must not import`);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["packages/client-events/notifications.ts", 'import "./delivery";'],
|
||||
["tui/src/client/api.ts", 'import "../../../packages/client-events/notifications";'],
|
||||
["webui/src/lib/model.ts", 'import "../../../packages/client-events/notifications";'],
|
||||
["webui/src/channel-plugins/types.ts", 'import type { ComponentType } from "react";'],
|
||||
])("permits the shared contract or contribution interface in %s", (relative, source) => {
|
||||
expect(inspect(relative, source)).toEqual([]);
|
||||
});
|
||||
|
||||
test("checks Vite glob dependencies using configured aliases and extension alternatives", () => {
|
||||
expect(inspect("webui/src/lib/model.ts", 'import.meta.glob("@/components/*.{ts,tsx}", { eager: true });')).toEqual([
|
||||
"webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/components/View.tsx",
|
||||
]);
|
||||
});
|
||||
|
||||
test("respects Vite glob exclusions", () => {
|
||||
expect(inspect("webui/src/lib/model.ts", 'import.meta.glob(["../components/*.{ts,tsx}", "!../components/**"]);')).toEqual([]);
|
||||
});
|
||||
|
||||
test("permits channel registry composition through a Vite glob", () => {
|
||||
expect(inspect("webui/src/channel-plugins/registry.ts", 'import.meta.glob("../../../nanobot/channels/*/webui/index.{ts,tsx}", { eager: true });')).toEqual([]);
|
||||
});
|
||||
|
||||
test("includes nested dynamic import locations in diagnostics", () => {
|
||||
expect(inspect("webui/src/lib/model.ts", 'export async function load() {\n return import("@/components/View");\n}')).toEqual([
|
||||
"webui/src/lib/model.ts:2: [webui-lib] must not import webui/src/components/View",
|
||||
]);
|
||||
});
|
||||
|
||||
function run() {
|
||||
return Bun.spawnSync([process.execPath, script, "--project", project, "--root", root], {
|
||||
cwd: process.cwd(), stdout: "pipe", stderr: "pipe",
|
||||
});
|
||||
}
|
||||
|
||||
test("CLI accepts a repository with valid client and shared dependencies", () => {
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(new TextDecoder().decode(result.stdout)).toContain(`Client import boundaries passed (${project},`);
|
||||
});
|
||||
|
||||
test("CLI rejects a client violation with its source location", () => {
|
||||
const relative = project === "webui" ? "webui/src/lib/model.ts" : "tui/src/client/api.ts";
|
||||
const target = project === "webui" ? "@/components/View" : "../app/app";
|
||||
write(relative, `export async function load() {\n return import("${target}");\n}\n`);
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(new TextDecoder().decode(result.stderr)).toContain(`${relative}:2:`);
|
||||
});
|
||||
|
||||
test("CLI rejects a shared contract that acquires a UI dependency", () => {
|
||||
write("packages/client-events/notifications.ts", 'import type { ReactNode } from "react";\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(new TextDecoder().decode(result.stderr)).toContain("packages/client-events/notifications.ts:1: [shared-client-contracts] must not import react");
|
||||
});
|
||||
|
||||
test("ignores test modules in production source scans", () => {
|
||||
const relative = project === "webui" ? "webui/src/lib/model.test.ts" : "tui/src/client/api.test.ts";
|
||||
write(relative, 'import "../../../webui/src/components/View";\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
test("checks the actual shared source directory rather than a fixture inventory", () => {
|
||||
write("packages/client-events/new-event.ts", 'export * from "../../tui/src/app/app";\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(new TextDecoder().decode(result.stderr)).toContain("new-event.ts:1: [shared-client-contracts]");
|
||||
});
|
||||
|
||||
test("CLI detects a runtime cycle through a barrel re-export", () => {
|
||||
const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;
|
||||
write(`${directory}/a.ts`, 'import { value } from "./barrel"; export const first = () => value;\n');
|
||||
write(`${directory}/barrel.ts`, 'export { value } from "./b";\n');
|
||||
write(`${directory}/b.ts`, 'import { first } from "./a"; export const value = () => first;\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
const diagnostic = new TextDecoder().decode(result.stderr);
|
||||
expect(diagnostic).toContain("[client-runtime-cycle]");
|
||||
for (const file of ["a.ts", "barrel.ts", "b.ts"]) expect(diagnostic).toContain(`${directory}/${file}`);
|
||||
});
|
||||
|
||||
test("CLI permits erased type imports and deferred dynamic imports", () => {
|
||||
const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;
|
||||
write(`${directory}/a.ts`, 'import { Item } from "./b"; export const first = (item: Item) => item;\n');
|
||||
write(`${directory}/b.ts`, 'import { first } from "./a"; export type Item = string; export const second = first;\n');
|
||||
write(`${directory}/lazy.ts`, 'export const load = () => import("./owner");\n');
|
||||
write(`${directory}/owner.ts`, 'import { load } from "./lazy"; export const owner = load;\n');
|
||||
write(`${project}/src/vite-env.d.ts`, 'declare module "virtual:example" { export const value: string; }\n');
|
||||
expect(run().exitCode).toBe(0);
|
||||
});
|
||||
|
||||
test("CLI detects eager literal require cycles and permits function-local require", () => {
|
||||
const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;
|
||||
write(`${directory}/a.ts`, 'export const first = require("./b");\n');
|
||||
write(`${directory}/b.ts`, 'export const second = require("./a");\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(new TextDecoder().decode(result.stderr)).toContain("[client-runtime-cycle]");
|
||||
write(`${directory}/a.ts`, 'export const first = () => require("./b");\n');
|
||||
expect(run().exitCode).toBe(0);
|
||||
});
|
||||
|
||||
test.skipIf(project !== "webui")("CLI detects an eager Vite registry cycle and permits its lazy form", () => {
|
||||
write("webui/src/channel-plugins/registry.ts", 'export const plugins = import.meta.glob("../../../nanobot/channels/*/webui/index.ts", { "eager": true });\n');
|
||||
write("nanobot/channels/example/webui/index.ts", 'import { plugins } from "../../../../webui/src/channel-plugins/registry"; export default plugins;\n');
|
||||
const result = run();
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(new TextDecoder().decode(result.stderr)).toContain("[client-runtime-cycle]");
|
||||
write("webui/src/channel-plugins/registry.ts", 'export const plugins = import.meta.glob("../../../nanobot/channels/*/webui/index.ts");\n');
|
||||
expect(run().exitCode).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Check direct Python imports against the gateway's ownership boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from importlib.util import resolve_name
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportEdge:
|
||||
target: str
|
||||
line: int
|
||||
type_only: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportRule:
|
||||
name: str
|
||||
sources: tuple[str, ...]
|
||||
forbidden: tuple[str, ...]
|
||||
type_only_allowed: tuple[str, ...] = ()
|
||||
allowed_targets: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Violation:
|
||||
rule: str
|
||||
target: str
|
||||
line: int
|
||||
|
||||
|
||||
_ADAPTERS = (
|
||||
"nanobot.api",
|
||||
"nanobot.channels",
|
||||
"nanobot.cli",
|
||||
"nanobot.gateway",
|
||||
"nanobot.webui",
|
||||
)
|
||||
|
||||
_TOOL_CONFIG_MODULES = (
|
||||
"nanobot.agent.tools.cli_apps_config",
|
||||
"nanobot.agent.tools.filesystem_config",
|
||||
"nanobot.agent.tools.image_generation_config",
|
||||
"nanobot.agent.tools.self_config",
|
||||
"nanobot.agent.tools.shell_config",
|
||||
"nanobot.agent.tools.web_config",
|
||||
)
|
||||
|
||||
IMPORT_RULES = (
|
||||
ImportRule(
|
||||
"core-execution",
|
||||
("nanobot.agent.loop", "nanobot.agent.runner", "nanobot.agent.turn_delivery"),
|
||||
_ADAPTERS,
|
||||
allowed_targets=("nanobot.channels.notification_routes",),
|
||||
),
|
||||
ImportRule(
|
||||
"channel-routing-contracts",
|
||||
("nanobot.channels.notification_routes",),
|
||||
("nanobot",),
|
||||
),
|
||||
ImportRule(
|
||||
"session-storage",
|
||||
("nanobot.session.manager", "nanobot.session.history", "nanobot.session.summary",
|
||||
"nanobot.session.recovery"),
|
||||
(*_ADAPTERS, "nanobot.agent"),
|
||||
),
|
||||
ImportRule(
|
||||
"security-primitives",
|
||||
("nanobot.security",),
|
||||
(*_ADAPTERS, "nanobot.agent", "nanobot.session"),
|
||||
),
|
||||
ImportRule(
|
||||
"websocket-transport",
|
||||
("nanobot.channels.websocket.runtime",),
|
||||
(
|
||||
"nanobot.bus.outbound_events",
|
||||
"nanobot.command",
|
||||
"nanobot.runtime_context",
|
||||
"nanobot.security.workspace_access",
|
||||
"nanobot.session.goal_state",
|
||||
"nanobot.webui.cli_apps_api",
|
||||
"nanobot.webui.forking",
|
||||
"nanobot.webui.mcp_presets_api",
|
||||
"nanobot.webui.sidebar_state",
|
||||
"nanobot.webui.transcription_ws",
|
||||
),
|
||||
type_only_allowed=("nanobot.bus.outbound_events.ProgressEvent",),
|
||||
),
|
||||
ImportRule(
|
||||
"tool-config-base",
|
||||
("nanobot.agent.tools", "nanobot.channels"),
|
||||
("nanobot.config.schema.Base",),
|
||||
),
|
||||
ImportRule(
|
||||
"configuration-contracts",
|
||||
("nanobot.config", "nanobot.config_base"),
|
||||
(*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session"),
|
||||
allowed_targets=_TOOL_CONFIG_MODULES,
|
||||
),
|
||||
ImportRule(
|
||||
"tool-configuration-contracts",
|
||||
_TOOL_CONFIG_MODULES,
|
||||
(*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session", "nanobot.config"),
|
||||
allowed_targets=_TOOL_CONFIG_MODULES,
|
||||
),
|
||||
ImportRule(
|
||||
"shared-primitives",
|
||||
("nanobot.utils.file_io", "nanobot.agent.skill_metadata", "nanobot.providers.generation",
|
||||
"nanobot.llm_usage.types", "nanobot.session.automation_spec"),
|
||||
(*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session", "nanobot.config"),
|
||||
),
|
||||
ImportRule(
|
||||
"oauth-catalog-cache",
|
||||
("nanobot.providers.oauth_catalog_cache",),
|
||||
("nanobot.providers.oauth_model_catalog", "nanobot.providers.openai_codex_provider",
|
||||
"nanobot.providers.github_copilot_provider", "nanobot.providers.xai_grok_provider"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _within(name: str, prefix: str) -> bool:
|
||||
return name == prefix or name.startswith(prefix + ".")
|
||||
|
||||
|
||||
def _qualified_name(node: ast.expr) -> str:
|
||||
if isinstance(node, ast.Name):
|
||||
return node.id
|
||||
if isinstance(node, ast.Attribute):
|
||||
return f"{_qualified_name(node.value)}.{node.attr}"
|
||||
return ""
|
||||
|
||||
|
||||
def _argument(call: ast.Call, position: int, name: str) -> ast.expr | None:
|
||||
if len(call.args) > position:
|
||||
return call.args[position]
|
||||
return next((keyword.value for keyword in call.keywords if keyword.arg == name), None)
|
||||
|
||||
|
||||
def _literal_string(node: ast.expr | None) -> str | None:
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
return node.value
|
||||
return None
|
||||
|
||||
|
||||
class ImportCollector(ast.NodeVisitor):
|
||||
"""Resolve static imports and literal dynamic imports without loading modules."""
|
||||
|
||||
def __init__(self, tree: ast.Module, module: str, *, is_package: bool = False) -> None:
|
||||
self.package = module if is_package else module.rpartition(".")[0]
|
||||
self.edges: list[ImportEdge] = []
|
||||
self.type_only = False
|
||||
self.type_guards: set[str] = set()
|
||||
self.import_module_calls: set[str] = set()
|
||||
self.builtin_import_calls = {"__import__"}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
binding = alias.asname or alias.name
|
||||
if alias.name == "importlib":
|
||||
self.import_module_calls.add(f"{binding}.import_module")
|
||||
elif alias.name == "typing":
|
||||
self.type_guards.add(f"{binding}.TYPE_CHECKING")
|
||||
elif alias.name == "builtins":
|
||||
self.builtin_import_calls.add(f"{binding}.__import__")
|
||||
elif isinstance(node, ast.ImportFrom) and not node.level:
|
||||
for alias in node.names:
|
||||
binding = alias.asname or alias.name
|
||||
if node.module == "importlib" and alias.name == "import_module":
|
||||
self.import_module_calls.add(binding)
|
||||
elif node.module == "typing" and alias.name == "TYPE_CHECKING":
|
||||
self.type_guards.add(binding)
|
||||
elif node.module == "builtins" and alias.name == "__import__":
|
||||
self.builtin_import_calls.add(binding)
|
||||
|
||||
def _add(self, target: str, line: int) -> None:
|
||||
if _within(target, "nanobot"):
|
||||
self.edges.append(ImportEdge(target, line, self.type_only))
|
||||
|
||||
def visit_Import(self, node: ast.Import) -> None:
|
||||
for alias in node.names:
|
||||
self._add(alias.name, node.lineno)
|
||||
|
||||
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
|
||||
module = node.module or ""
|
||||
if node.level:
|
||||
module = resolve_name("." * node.level + module, self.package)
|
||||
for alias in node.names:
|
||||
target = module if alias.name == "*" else f"{module}.{alias.name}"
|
||||
self._add(target, node.lineno)
|
||||
|
||||
def visit_If(self, node: ast.If) -> None:
|
||||
self.visit(node.test)
|
||||
previous = self.type_only
|
||||
self.type_only = previous or _qualified_name(node.test) in self.type_guards
|
||||
for statement in node.body:
|
||||
self.visit(statement)
|
||||
self.type_only = previous
|
||||
for statement in node.orelse:
|
||||
self.visit(statement)
|
||||
|
||||
def visit_Call(self, node: ast.Call) -> None:
|
||||
name = _qualified_name(node.func)
|
||||
target = _literal_string(_argument(node, 0, "name"))
|
||||
if target is not None and name in self.import_module_calls:
|
||||
if target.startswith("."):
|
||||
package_arg = _argument(node, 1, "package")
|
||||
package = _literal_string(package_arg)
|
||||
if isinstance(package_arg, ast.Name) and package_arg.id == "__package__":
|
||||
package = self.package
|
||||
if package is not None:
|
||||
self._add(resolve_name(target, package), node.lineno)
|
||||
else:
|
||||
self._add(target, node.lineno)
|
||||
elif target is not None and name in self.builtin_import_calls:
|
||||
level = _argument(node, 4, "level")
|
||||
if level is None or (isinstance(level, ast.Constant) and level.value == 0):
|
||||
self._add(target, node.lineno)
|
||||
self.generic_visit(node)
|
||||
|
||||
|
||||
def find_violations(
|
||||
source: str, module: str, *, is_package: bool = False,
|
||||
) -> list[Violation]:
|
||||
tree = ast.parse(source, filename=module)
|
||||
collector = ImportCollector(tree, module, is_package=is_package)
|
||||
collector.visit(tree)
|
||||
violations: list[Violation] = []
|
||||
for rule in IMPORT_RULES:
|
||||
if not any(_within(module, prefix) for prefix in rule.sources):
|
||||
continue
|
||||
for edge in collector.edges:
|
||||
if edge.type_only and edge.target in rule.type_only_allowed:
|
||||
continue
|
||||
if any(_within(edge.target, prefix) for prefix in rule.allowed_targets):
|
||||
continue
|
||||
if any(_within(edge.target, prefix) for prefix in rule.forbidden):
|
||||
violations.append(Violation(rule.name, edge.target, edge.line))
|
||||
return violations
|
||||
|
||||
|
||||
def check_repository(root: Path) -> tuple[int, list[str]]:
|
||||
checked = 0
|
||||
violations: list[str] = []
|
||||
for path in sorted((root / "nanobot").rglob("*.py")):
|
||||
relative = path.relative_to(root)
|
||||
if "tests" in relative.parts:
|
||||
continue
|
||||
parts = relative.with_suffix("").parts
|
||||
is_package = parts[-1] == "__init__"
|
||||
module = ".".join(parts[:-1] if is_package else parts)
|
||||
if not any(
|
||||
_within(module, prefix) for rule in IMPORT_RULES for prefix in rule.sources
|
||||
):
|
||||
continue
|
||||
checked += 1
|
||||
for violation in find_violations(
|
||||
path.read_text(encoding="utf-8"), module, is_package=is_package,
|
||||
):
|
||||
violations.append(
|
||||
f"{relative.as_posix()}:{violation.line}: [{violation.rule}] "
|
||||
f"must not import {violation.target}"
|
||||
)
|
||||
return checked, violations
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--root", type=Path, default=Path(__file__).resolve().parents[1],
|
||||
help="repository root containing nanobot/",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if not (args.root / "nanobot").is_dir():
|
||||
parser.error(f"{args.root} does not contain nanobot/")
|
||||
checked, violations = check_repository(args.root)
|
||||
if checked == 0:
|
||||
parser.error(f"{args.root} contains no protected Python modules")
|
||||
if violations:
|
||||
for violation in violations:
|
||||
print(violation, file=sys.stderr)
|
||||
return 1
|
||||
print(f"Import boundaries passed ({len(IMPORT_RULES)} rules, {checked} files).")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user