The Open Framework for Building Agents
#!/usr/bin/env node
/**
* Mechanical enforcement of framework code invariants.
*
* Several framework invariants can be checked mechanically. Each one gets a
* dedicated guard here. Every guard prints an error message that explains
* *why* the invariant exists and how to fix the violation, so contributors
* can self-correct without needing a reviewer to re-explain the rule.
*
* The numeric rule IDs below are stable identifiers for these lints, tied to
* the underlying invariant.
*
* rule 9 — No symlinks anywhere in the repo. (Rationale: symlinks are
* too unpredictable for a framework to rely on; replace with a
* real file or a small loader.)
* rule 13 — No spread-ternary object composition
* (`...(c ? {} : { k: v })`). (Rationale: hard to read, easy
* to mistype; declare the object then assign optional keys.)
* rule 19 — No `new AsyncLocalStorage()` outside the two allowlisted
* files. All ambient runtime state flows through a single
* `EveContext`.
* rule 21 — No authored `name:` (or `id:`) field on
* `defineMcpClientConnection`, `defineTool`, `defineSkill`,
* `defineSandbox`, `defineSchedule`, `defineAgent`, or
* `defineEval` calls inside authored
* agent trees (`apps/<name>/agent/**`,
* `apps/<category>/<name>/agent/**`,
* `apps/<name>/evals/**`,
* `apps/<category>/<name>/evals/**`, or a top-level `agent/**` /
* `evals/**` directory). Identity is derived from the file
* path (or, for the root agent, from the package name); an
* authored field creates a redundant source of truth that
* can drift. Evals also reject `id:` because eval
* identity comes from the path under `evals/`.
* rule 23 — No new `as unknown as T` double casts (ratcheted via
* baseline). Double casts hide real type errors.
* rule 25 — No new direct calls to `installBundledCompiledArtifacts`,
* `resetBundledCompiledArtifacts`, or
* `clearProcessDefaultRuntimeSession` from test bodies.
* Tests must scope runtime state through
* `createTestRuntime().run(fn)` / `withRuntimeSession(...)`.
* rule 26 — No `loadContext() as ContextContainer` casts. Thread a
* `ContextContainer` parameter through instead.
* rule 27 — No `state:` field on hook lifecycle result types in
* `packages/eve/src/public/definitions/hook.ts`. Hook
* return shapes must carry only what the harness consumes;
* durable state belongs on `ctx.eve`.
* rule 28 — Imports under `packages/eve/src/setup/scaffold/**` stay within
* their layer: node:* builtins, relative siblings, and eve's
* vendored integration catalog. The scaffold stays free of
* framework runtime, compiler, terminal UI, and provider SDK
* dependencies.
* rule 29 — Changeset package keys must match workspace package names.
* Release metadata is consumed before `pnpm release`, so bad
* changeset package names must fail in PR CI rather than in the
* post-merge release workflow.
* rule 30 — The compiled-vendor pipeline (`scripts/vendor-compiled/**`)
* must not write a per-package `package.json` into a vendored
* output directory. Such a file creates a package scope that
* shadows eve's `#compiled/*` imports map, so a cross-package
* `#compiled/<pkg>` reference inside one vendored `.d.ts`
* (e.g. `@workflow/core` → `@workflow/world` → `zod`) silently
* degrades to `any` under `skipLibCheck`. The bundled ESM
* inherits `"type": "module"` from eve's root package.json, so
* no per-package file is needed. See `prepareCompiledModule`.
* rule 31 — Active source and docs must not reference the removed
* `create-eve` package or `eve setup` command. Use `eve init`
* for project creation and the dedicated current commands
* (`eve link`, `eve channels add`, `eve deploy`) afterward.
* Changelogs and changesets are historical records and excluded.
* rule 32 — Every Markdown file under `research/` must have valid YAML
* frontmatter with non-empty `issue` and `status` fields plus an
* ISO `last_updated` date. Research documents are implementation
* plans attached to tracked GitHub work, not an unowned parallel
* backlog.
* rule 33 — Workflow runtime imports and queue-namespace environment writes
* must go through the `src/internal/workflow/runtime.ts` facade and
* `queue-namespace.ts`. The generated agent bootstrap installs the
* agent-scoped namespace before queue-producing APIs can run.
* rule 34 — `phase` stays a runtime-only dependency. No file under the Eve\n * logo renderer's GPU/runtime boundary (render/, shaders/, or the\n * offline render harness) may import the `phase` package. This keeps\n * the mechanical separation between the lifecycle layer and the GPU\n * renderer enforceable.
* rule 36 — Extension capability epochs have immutable hashed API metadata
* and explicit support history. The current hash must match the
* authoring roots, every historical epoch must be supported or
* dropped, every retained epoch needs a compiling fixture, and
* every public authoring value must belong to a capability.
* rule 37 — Instrumentation ownership stays provider-neutral and outside the
* harness. The lifecycle contract must not import from `ai`, harness
* code may import only runtime facade types, and execution may use
* only runtime entrypoints and cancellation-state preservation.
* rule 38 — Workspace build scripts must not launch a nested
* `pnpm --filter eve build`. Turbo owns workspace dependency
* ordering; nested builds race on eve's clean-and-publish dist
* directory and let consumers observe a partial package.
* rule 43 — Reusable session plumbing stays independent of the subagent
* executor. The generic inbox and state cursor must not
* import subagent modules; session/turn composition roots may
* compose built-in executors directly.
* rule 44 — Sandbox providers are built on the public provider contract.
* Files under `src/execution/sandbox/bindings/` and
* `src/sandbox/providers/` reach the contract only through
* `#public/sandbox/*` and never import core sandbox modules
* (session construction, ensure, prewarm, sandbox state, the
* shutdown registry, tool sessions, the runtime sandbox
* registry, or the shared provider and session internals).
* `sandbox/providers/default.ts` may import `#sandbox/state.js`
* for `DefaultSandbox`'s two internal state hooks. Engine
* helpers such as other binding modules,
* stream utilities, and the optional-package loader stay
* allowed. Every concrete built-in under `src/sandbox/providers/`
* is defined through `defineSandboxProvider()`.
* rule 45 — Provided tools under `packages/eve/src/tools/provided/**` and
* the body of every agent tool import only public eve entry
* points (the `#` specifiers of the package's `exports`), the
* vendored Workflow SDK that authored bodies import as
* `workflow`, and each other. eve is built on eve: a provided
* tool that needs a private hook means authors cannot build the
* same tool. Files that predate the rule are baselined and may
* only leave the baseline.
* rule 46 — Tasks own their records and their words. Only
* `execution/tasks/table*.ts` names the session's task table, so
* every record write goes through it, and the model-facing task
* markers appear only in `execution/tasks/render.ts`, which holds
* all of the tasks' model text.
* rule 47 — A caller hears from its session only at a turn's real end.
* Only `execution/session/program.ts` sends the caller's reply,
* after the turn loop returns, and `execution/session/finalization.ts`
* when the session ends. A held turn is still open, so nothing
* inside the turn loop or the harness may reply.
* rule 48 — Remote agent protocol 1 stays in
* `execution/legacy-remote-agent/`. Only the ingress files that
* route protocol-1 callers into it may import it, so deleting the
* directory removes protocol 1 without a search.
* rule 49 — Provided tool definitions carry a framework tool flag,
* so telemetry ownership survives renamed and namespaced tools.
* rule 50 — The human-in-the-loop lifecycle in `harness/hitl/` is
* reached only through its `index.ts`, its request vocabulary
* (`approval-prompt`, `budget-request`, `relays`, `sign-ins`) and
* read surface via index.ts or the Workflow-safe view.ts.
* Only commit.ts and checkpoint-migrations.ts import requests.ts
* for saving and legacy upgrades.
* rule 51 — Only the session machine (`harness/session-machine/`) and the
* human-in-the-loop lifecycle it delegates to
* (`harness/hitl/`) build lifecycle events and read the
* machine's private state. The guard checks only those imports;
* it does not prove every state change emits events (approval
* candidates are still written directly, and `matchSignIns`
* emits none). The model step's streamed content (its calls and
* their inline results) is built where it streams.
* rule 52 — The tracing library in `packages/tracing/src/` imports only
* itself and external packages. eve reaches it only through the
* vendored root, delegation, otel, and ai-sdk entrypoints under
* `#compiled/@vercel/agent-runs/`, never the workspace package itself.
* rule 53 — Legacy session snapshots are read only at ingress. Outside
* `execution/legacy-session/`, only the ingress files that import
* protocol-1 sessions may import it, so current execution
* consumes only normalized session state.
*
* Baselines for rules with pre-existing violations live in
* `guard-invariants-baseline.json`. Counts and allowlists in that file
* may only shrink (as offenders are removed) — they may never grow.
*/
import { glob, readFile, readdir, lstat } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { load as loadYaml } from "js-yaml";
import { checkExtensionCapabilityContracts } from "./extension-capability-contracts.mjs";
const require = createRequire(import.meta.url);
const extractorRequire = createRequire(require.resolve("@microsoft/api-extractor/package.json"));
const ts = extractorRequire("typescript");
const REPO_ROOT = resolve(fileURLToPath(import.meta.url), "../..");
const BASELINE_PATH = join(REPO_ROOT, "scripts/guard-invariants-baseline.json");
const FRONTMATTER_RE = /^\uFEFF?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m;
/**
* Parses a Markdown document's YAML frontmatter. Returns `undefined` when the
* document has no complete leading `---` block.
*
* @param {string} content
* @returns {unknown}
*/
function readFrontmatter(content) {
const match = FRONTMATTER_RE.exec(content);
if (match === null || match.index !== 0) return undefined;
return loadYaml(match[1] ?? "") ?? {};
}
/** @param {string} content */
function startsWithFrontmatter(content) {
return /^\uFEFF?---/.test(content);
}
const SKIP_DIRS = new Set([
"node_modules",
".git",
".turbo",
".eve",
".next",
".nitro",
".output",
"dist",
"build",
"coverage",
".vercel",
]);
/** @typedef {{ rule: number; file: string; line?: number; message: string }} Violation */
/**
* Recursively walk the workspace, yielding regular files.
* Skips well-known build/dependency directories.
*
* @param {string} root
* @returns {AsyncGenerator<{ absPath: string; relPath: string; stat: import("node:fs").Stats }>}
*/
async function* walkFiles(root) {
const entries = await readdir(root, { withFileTypes: true });
for (const entry of entries) {
if (SKIP_DIRS.has(entry.name)) continue;
const absPath = join(root, entry.name);
if (entry.isSymbolicLink()) {
const stat = await lstat(absPath);
yield { absPath, relPath: relative(REPO_ROOT, absPath), stat };
continue;
}
if (entry.isDirectory()) {
yield* walkFiles(absPath);
} else if (entry.isFile()) {
const stat = await lstat(absPath);
yield { absPath, relPath: relative(REPO_ROOT, absPath), stat };
}
}
}
/**
* Normalize a relative path to forward slashes so baselines stay
* portable across Windows and POSIX.
*
* @param {string} relPath
*/
function toPosix(relPath) {
return sep === "/" ? relPath : relPath.split(sep).join("/");
}
/**
* @param {string} relPath
*/
function isTsLike(relPath) {
return /\.(ts|tsx|mts|cts)$/.test(relPath) && !relPath.endsWith(".d.ts");
}
/**
* Walks the working copy once and feeds each TypeScript file through the
* per-file rule checks. Rule 9 (symlinks) and rule 23 (file-count baseline)
* also run during the walk.
*
* @param {{
* rule13: { baseline: Record<string, number>; current: Map<string, number> };
* rule19: { allowlist: Set<string>; current: Set<string>; lines: Map<string, number> };
* rule21: { allowlist: Set<string>; violations: Violation[] };
* rule23: { baseline: Record<string, number>; current: Map<string, number> };
* rule25: { allowlist: Set<string>; new: Map<string, number> };
* rule26: Violation[];
* rule27: Violation[];
* rule28: Violation[];
* rule33: Violation[];
* rule37: Violation[];
* rule43: Violation[];
* rule44: Violation[];
* rule45: { allowlist: Set<string>; violations: Violation[] };
* rule46: Violation[];
* rule47: Violation[];
* rule48: Violation[];
* rule50: Violation[];
* rule51: Violation[];
* rule52: Violation[];
* rule53: Violation[];
* symlinks: string[];
* }} state
*/
async function scanRepo(state) {
for await (const { absPath, relPath, stat } of walkFiles(REPO_ROOT)) {
const posix = toPosix(relPath);
if (stat.isSymbolicLink()) {
state.symlinks.push(posix);
continue;
}
if (!isTsLike(posix)) continue;
const content = await readFile(absPath, "utf8");
const lines = content.split(/\r?\n/);
checkRule13(posix, lines, state.rule13);
checkRule19(posix, lines, state.rule19);
checkRule21(posix, lines, state.rule21.allowlist, state.rule21.violations);
checkRule23(posix, lines, state.rule23);
checkRule25(posix, lines, state.rule25);
checkRule26(posix, lines, state.rule26);
checkRule27(posix, lines, state.rule27);
checkRule28(posix, lines, state.rule28);
checkRule33(posix, lines, state.rule33);
checkRule37(posix, content, state.rule37);
checkRule43(posix, lines, state.rule43);
checkRule44(posix, lines, state.rule44);
checkRule53(posix, lines, state.rule53);
checkRule45(posix, lines, state.rule45);
checkRule46(posix, lines, state.rule46);
checkRule47(posix, lines, state.rule47);
checkRule48(posix, lines, state.rule48);
checkRule50(posix, lines, state.rule50);
checkRule51(posix, lines, state.rule51);
if (posix.startsWith("packages/tracing/src/")) {
for (const [index, line] of lines.entries()) {
const imports = [...line.matchAll(/(?:from\s+|import\s*\()(["'])([^"']+)\1/g)];
for (const match of imports) {
const specifier = match[2];
const escapes =
specifier.startsWith("#") ||
(specifier.startsWith(".") &&
!toPosix(relative(REPO_ROOT, resolve(dirname(absPath), specifier))).startsWith(
"packages/tracing/src/",
));
if (escapes)
state.rule52.push({
rule: 52,
file: posix,
line: index + 1,
message:
"Tracing library imports must stay inside the library or use an external package. Host integration belongs in the host.",
});
}
}
}
if (posix.startsWith("packages/eve/")) {
lines.forEach((line, index) => {
const privateImport =
/['"]#compiled\/@vercel\/agent-runs\/(?!(?:index|delegation|otel|ai-sdk)\.js['"])/.test(
line,
) ||
/(?:from\s+|import\s*\()['"]@vercel\/agent-runs(?:\/[^'"]*)?['"]/.test(line) ||
[...line.matchAll(/(?:from\s+|import\s*\()(["'])([^"']+)\1/g)].some(
(match) =>
match[2].startsWith(".") &&
toPosix(relative(REPO_ROOT, resolve(dirname(absPath), match[2]))).startsWith(
"packages/tracing/",
),
);
if (privateImport)
state.rule52.push({
rule: 52,
file: posix,
line: index + 1,
message:
"Import the tracing library from #compiled/@vercel/agent-runs/{index,delegation,otel,ai-sdk}.js, not the workspace package or its private modules.",
});
});
}
}
}
// ---------- Rule 43: executor-neutral session plumbing ----------
// Matches both `#` alias specifiers and relative paths into the executor trees.
const SUBAGENT_IMPORT_RE = /from ["'](?:#|(?:\.\.?\/)+(?:[\w-]+\/)*)subagents(?:\/|\.js|["'])/;
const RULE43_GENERIC_SESSION_FILES = new Set([
"packages/eve/src/execution/session-hook-claims.ts",
"packages/eve/src/execution/session-inbox/inbox.ts",
"packages/eve/src/execution/session-input-ledger.ts",
"packages/eve/src/execution/session-input-queue.ts",
"packages/eve/src/execution/session-state-cursor.ts",
]);
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule43(posix, lines, violations) {
if (!RULE43_GENERIC_SESSION_FILES.has(posix)) return;
lines.forEach((line, idx) => {
if (!SUBAGENT_IMPORT_RE.test(line)) return;
violations.push({
rule: 43,
file: posix,
line: idx + 1,
message:
"generic session plumbing imports the subagent executor. Move executor-specific behavior to composition roots or subagent-owned modules.",
});
});
}
// Legacy import is reachable only from workflow discovery and ingress.
const LEGACY_INGRESS_FILES = new Set([
"packages/eve/src/execution/session-inbox/resume.ts",
"packages/eve/src/execution/connections/callback-route.ts",
"packages/eve/src/eve-channel/index.ts",
]);
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule53(posix, lines, violations) {
if (
posix.includes("/execution/legacy-session/") ||
posix.includes("/internal/testing/") ||
/\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix) ||
LEGACY_INGRESS_FILES.has(posix)
)
return;
lines.forEach((line, index) => {
if (
/from ["'][^"']*legacy-session\//.test(line) ||
/import\(["'][^"']*legacy-session\//.test(line)
)
violations.push({
rule: 53,
file: posix,
line: index + 1,
message:
"Legacy session import belongs at ingress; current execution must consume only normalized session state.",
});
});
}
// ---------- Rule 44: sandbox providers use the public provider contract ----------
const SANDBOX_PROVIDER_DIRS = [
"packages/eve/src/execution/sandbox/bindings/",
"packages/eve/src/sandbox/providers/",
];
const SANDBOX_CORE_IMPORT_RE =
/(?:from\s+|import\s*\()["']#(?:sandbox\/(?:provider|state)|execution\/sandbox\/(?:active-connections|ensure|prewarm|session|logging-session)|execution\/tool-session\/[^"']*|runtime\/sandbox\/[^"']*|shared\/sandbox-(?:provider|session|write-files))\.js["']/;
const SANDBOX_CORE_IMPORT_EXEMPTIONS = new Map([
["packages/eve/src/sandbox/providers/default.ts", /["']#sandbox\/state\.js["']/],
]);
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule44(posix, lines, violations) {
if (!SANDBOX_PROVIDER_DIRS.some((dir) => posix.startsWith(dir))) return;
if (posix.endsWith(".test.ts")) return;
const exemption = SANDBOX_CORE_IMPORT_EXEMPTIONS.get(posix);
lines.forEach((line, index) => {
if (!SANDBOX_CORE_IMPORT_RE.test(line) || exemption?.test(line)) return;
violations.push({
rule: 44,
file: posix,
line: index + 1,
message:
"Sandbox providers reach the provider contract only through #public/sandbox/* and may not import core sandbox modules. Use the public contract, or an engine helper such as another binding module.",
});
});
if (!posix.startsWith("packages/eve/src/sandbox/providers/")) return;
const source = lines.join("\n");
if (!/\bdefineSandboxProvider\(/.test(source)) {
violations.push({
rule: 44,
file: posix,
message: "Built-in sandbox providers must use defineSandboxProvider().",
});
}
if (source.includes("createSandboxEnvironment")) {
violations.push({
rule: 44,
file: posix,
message:
"Built-in sandbox providers must not bypass defineSandboxProvider() through createSandboxEnvironment().",
});
}
}
// ---------- Rule 45: provided tools use only public entry points ----------
const PROVIDED_TOOLS_DIR = "packages/eve/src/tools/provided/";
// Every agent tool is a `serve` workflow tool eve generates around this body.
const AGENT_TOOL_BODY_PATH = "packages/eve/src/runtime/subagents/workflow.ts";
const EVE_PACKAGE_EXPORTS = require(join(REPO_ROOT, "packages/eve/package.json")).exports;
const EXPORTED_TYPES_PATH_RE = /^\.\/dist\/src\/(.+)\.d\.ts$/;
/**
* The `#` specifier eve's own source uses for one exported module, such as
* `#public/tools/index.js` for `eve/tools`.
*
* @param {unknown} target
*/
function toSourceSpecifier(target) {
if (typeof target !== "object" || target === null) return undefined;
const types = Reflect.get(target, "types");
if (typeof types !== "string") return undefined;
const match = EXPORTED_TYPES_PATH_RE.exec(types);
return match === null ? undefined : `#${match[1]}.js`;
}
const EVE_PUBLIC_ENTRY_SPECIFIERS = new Set(
Object.values(EVE_PACKAGE_EXPORTS)
.map(toSourceSpecifier)
.filter((specifier) => specifier !== undefined),
);
const PROVIDED_TOOL_EXTRA_IMPORTS = new Set([
// What an authored body imports as `workflow`: eve vendors the Workflow SDK.
"#compiled/@workflow/core/index.js",
// `defineJsonSchema` is not public yet, and provided tools declare schemas without zod.
"#tools/schema.js",
]);
// `eve__task_wait` and `eve__task_cancel` belong to the session, not to authors: they
// take their model text from execution/tasks/render.ts directly.
const PROVIDED_TASK_TOOL_FILES = new Set([
"packages/eve/src/tools/provided/task-cancel.ts",
"packages/eve/src/tools/provided/task-wait.ts",
]);
const IMPORT_SPECIFIER_RE = /(?:\bfrom\s+|\bimport\s*\(\s*|^\s*import\s+)["']([^"']+)["']/;
/** @param {string} specifier */
function isProvidedToolImportAllowed(specifier) {
if (EVE_PUBLIC_ENTRY_SPECIFIERS.has(specifier)) return true;
if (PROVIDED_TOOL_EXTRA_IMPORTS.has(specifier)) return true;
return specifier.startsWith("#tools/provided/") || specifier.startsWith("./");
}
/**
* @param {string} posix
* @param {string[]} lines
* @param {{ allowlist: Set<string>; violations: Violation[] }} state
*/
function checkRule45(posix, lines, state) {
const provided = posix.startsWith(PROVIDED_TOOLS_DIR) && !posix.endsWith(".test.ts");
if (!provided && posix !== AGENT_TOOL_BODY_PATH) return;
if (state.allowlist.has(posix) || PROVIDED_TASK_TOOL_FILES.has(posix)) return;
lines.forEach((line, idx) => {
// Doc comments show authors how to import the tool from its public entry.
if (/^\s*(?:\*|\/\/)/.test(line)) return;
const specifier = IMPORT_SPECIFIER_RE.exec(line)?.[1];
if (specifier === undefined || isProvidedToolImportAllowed(specifier)) return;
state.violations.push({
rule: 45,
file: posix,
line: idx + 1,
message: `imports "${specifier}", which is not a public eve entry point. Provided tools use only the API authors have: import from the matching entry in packages/eve/package.json "exports" (for example "#public/tools/index.js" for eve/tools), or make the capability public first.`,
});
});
}
// ---------- Rule 46: tasks own their records and model text ----------
const TASKS_DIR = "packages/eve/src/execution/tasks/";
const TASK_TABLE_FILE_RE = /^packages\/eve\/src\/execution\/tasks\/table[\w-]*\.ts$/;
const TASK_RENDER_FILE = `${TASKS_DIR}render.ts`;
const TASK_TABLE_KEY = '"eve.taskTable"';
const TASK_MODEL_MARKERS = ["<task_result", "[Tasks]", "Started task ", "Sent to task "];
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule46(posix, lines, violations) {
if (!posix.startsWith("packages/eve/src/") || posix.endsWith(".test.ts")) return;
lines.forEach((line, idx) => {
if (line.includes(TASK_TABLE_KEY) && !TASK_TABLE_FILE_RE.test(posix)) {
violations.push({
rule: 46,
file: posix,
line: idx + 1,
message:
"names the session's task table outside execution/tasks/table*.ts. Read and write task records through the table module's helpers.",
});
}
if (posix === TASK_RENDER_FILE || /^\s*(?:\/?\*|\/\/)/.test(line)) return;
const marker = TASK_MODEL_MARKERS.find((candidate) => line.includes(candidate));
if (marker === undefined) return;
violations.push({
rule: 46,
file: posix,
line: idx + 1,
message: `writes the model-facing task text "${marker}" outside execution/tasks/render.ts. Keep every string the model reads about tasks in the renderer and import it from there.`,
});
});
}
// ---------- Rule 47: one caller-reply site ----------
const CALLER_REPLY_DEFINITION_FILE = "packages/eve/src/subagents/parent-notification.ts";
const CALLER_REPLY_FILES = new Set([
"packages/eve/src/execution/session/program.ts",
"packages/eve/src/execution/session/finalization.ts",
]);
const CALLER_REPLY_CALL_RE = /\b(?:notifyTurnCallerStep|notifyCancelledTaskCallerStep)\(/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule47(posix, lines, violations) {
if (!posix.startsWith("packages/eve/src/") || posix.endsWith(".test.ts")) return;
if (posix === CALLER_REPLY_DEFINITION_FILE || CALLER_REPLY_FILES.has(posix)) return;
lines.forEach((line, idx) => {
if (!CALLER_REPLY_CALL_RE.test(line)) return;
violations.push({
rule: 47,
file: posix,
line: idx + 1,
message:
"sends a caller's reply outside execution/session/program.ts and execution/session/finalization.ts. A turn replies to its caller only at its real end, which the session program owns; finalization replies when the session ends.",
});
});
}
// ---------- Rule 50: the human-in-the-loop lifecycle has one seam ----------
const HUMAN_INPUT_DIR = "packages/eve/src/harness/hitl/";
const HUMAN_INPUT_PRIVATE_IMPORT_RE =
/["'](?:#harness\/|(?:\.\.?\/)+)hitl\/(?!(?:index|view|approval-prompt|budget-request|relays|sign-ins)\.js["'])/;
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule50(posix, lines, violations) {
if (
!posix.startsWith("packages/eve/src/") ||
posix.startsWith(HUMAN_INPUT_DIR) ||
posix.startsWith("packages/eve/src/internal/testing/") ||
/\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix)
)
return;
lines.forEach((line, idx) => {
if (!HUMAN_INPUT_PRIVATE_IMPORT_RE.test(line)) return;
if (
/["']#harness\/hitl\/requests\.js["']/.test(line) &&
(posix === "packages/eve/src/harness/session-machine/commit.ts" ||
posix === "packages/eve/src/execution/session/checkpoint-migrations.ts")
)
return;
violations.push({
rule: 50,
file: posix,
line: idx + 1,
message:
"imports the human-in-the-loop lifecycle's internals. Reach it through `#harness/hitl/index.js`, or use the read-only `#harness/hitl/view.js` from workflow bodies.",
});
});
}
// ---------- Rule 51: the session machine owns lifecycle ----------
const SESSION_MACHINE_DIR = "packages/eve/src/harness/session-machine/";
const LIFECYCLE_EVENT_BUILDER_RE =
/\bcreate(?:Session(?:Started|Waiting|Failed|Completed)|Turn(?:Started|Completed|Failed|Cancelled|Waiting)|MessageReceived|Step(?:Started|Failed)|Input(?:Requested|Resolved)|Authorization(?:Required|Completed)|Approval(?:Candidate|Settled)|Task(?:Started|Settled)|ContextCleared|ResultCompleted)Event\b/;
const CALL_EVENT_BUILDER_RE = /\bcreateAction(?:Result|sRequested)Event\b/;
/** Where the model step streams its calls, their inline results, and the calls they made. */
const STREAM_CONTENT_FILES = new Set([
"packages/eve/src/harness/emission.ts",
"packages/eve/src/harness/nested-actions.ts",
"packages/eve/src/harness/step-hooks.ts",
"packages/eve/src/harness/stream-actions.ts",
]);
const MACHINE_PRIVATE_IMPORT_RE = /["']#harness\/session-machine\/(?:state|events)\.js["']/;
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule51(posix, lines, violations) {
if (
!posix.startsWith("packages/eve/src/") ||
posix.startsWith(SESSION_MACHINE_DIR) ||
posix.startsWith(HUMAN_INPUT_DIR) ||
posix.startsWith("packages/eve/src/protocol/") ||
posix.startsWith("packages/eve/src/internal/testing/") ||
posix.endsWith(".test.ts") ||
posix.includes("/test/")
)
return;
lines.forEach((line, idx) => {
const builder = LIFECYCLE_EVENT_BUILDER_RE.exec(line)?.[0];
const callBuilder = STREAM_CONTENT_FILES.has(posix)
? undefined
: CALL_EVENT_BUILDER_RE.exec(line)?.[0];
if (builder !== undefined || callBuilder !== undefined) {
violations.push({
rule: 51,
file: posix,
line: idx + 1,
message: `uses ${builder ?? callBuilder} outside harness/session-machine/. Only the session machine builds lifecycle events: return them from a transition and publish what it returns with \`applyTransition\`.`,
});
}
if (MACHINE_PRIVATE_IMPORT_RE.test(line)) {
violations.push({
rule: 51,
file: posix,
line: idx + 1,
message:
"imports the session machine's private state or event builders. Read execution state through `#harness/session-machine/view.js`; change it with a transition.",
});
}
});
}
// ---------- Rule 48: remote agent protocol 1 stays compartmentalized ----------
const LEGACY_REMOTE_AGENT_DIR = "packages/eve/src/execution/legacy-remote-agent/";
const LEGACY_REMOTE_AGENT_INGRESS_FILES = new Set([
"packages/eve/src/channel/types.ts",
"packages/eve/src/context/keys.ts",
"packages/eve/src/eve-channel/create-request.ts",
"packages/eve/src/eve-channel/index.ts",
"packages/eve/src/eve-channel/request.ts",
"packages/eve/src/execution/forward-session-input.ts",
"packages/eve/src/subagents/callback-route.ts",
]);
// `from "…"` covers imports and re-exports; `import "…"` and `import("…")` cover side effects and dynamic imports.
const LEGACY_REMOTE_AGENT_IMPORT_RE = /\b(?:from|import)\s*\(?\s*["'][^"']*legacy-remote-agent\//;
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule48(posix, lines, violations) {
if (
!posix.startsWith("packages/eve/src/") ||
posix.startsWith(LEGACY_REMOTE_AGENT_DIR) ||
/\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix) ||
LEGACY_REMOTE_AGENT_INGRESS_FILES.has(posix)
)
return;
lines.forEach((line, idx) => {
if (!LEGACY_REMOTE_AGENT_IMPORT_RE.test(line)) return;
violations.push({
rule: 48,
file: posix,
line: idx + 1,
message:
"imports remote agent protocol 1 outside its ingress files. Route protocol-1 behavior through execution/legacy-remote-agent/ from an existing ingress so the legacy path stays removable in one place.",
});
});
}
// ---------- Rule 13: spread-ternary object composition ----------
/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */
const SPREAD_TERNARY_RE = /\.\.\.\([^()\n]*\?[^()\n]*:\s*\{/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {{ baseline: Record<string, number>; current: Map<string, number> }} state
*/
function checkRule13(posix, lines, state) {
let count = 0;
for (const line of lines) {
if (SPREAD_TERNARY_RE.test(line)) count++;
}
if (count > 0) state.current.set(posix, count);
}
// ---------- Rule 33: namespaced Workflow runtime boundary ----------
const RAW_WORKFLOW_RUNTIME_SPECIFIER_RE =
/["'](?:#compiled\/@workflow\/core\/runtime(?:\.js|\/[^"']+\.js)|@workflow\/core\/runtime(?:\/[^"']+)?|workflow\/(?:api|runtime))["']/;
const WORKFLOW_QUEUE_NAMESPACE_WRITE_RE =
/process\.env(?:\.WORKFLOW_QUEUE_NAMESPACE|\[\s*(?:WORKFLOW_QUEUE_NAMESPACE_ENV|["']WORKFLOW_QUEUE_NAMESPACE["'])\s*\])\s*=/;
const WORKFLOW_RUNTIME_FACADES = new Set(["packages/eve/src/internal/workflow/runtime.ts"]);
const WORKFLOW_QUEUE_NAMESPACE_MODULE = "packages/eve/src/internal/workflow/queue-namespace.ts";
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule33(posix, lines, violations) {
// The single-runtime-identity boundary is eve's own source. Application code
// (fixtures, templates) legitimately imports the public `workflow/api`
// surface, which eve's bundler resolves to its own runtime.
if (!posix.startsWith("packages/eve/src/")) return;
lines.forEach((line, idx) => {
const isTypeOnlyImport = /^\s*(?:import|export)\s+type\b/.test(line);
const isRuntimeImport =
/^(?:import|export)\b|^}\s*from\b|\b(?:import|require)\s*\(/.test(line.trimStart()) &&
RAW_WORKFLOW_RUNTIME_SPECIFIER_RE.test(line);
if (!WORKFLOW_RUNTIME_FACADES.has(posix) && !isTypeOnlyImport && isRuntimeImport) {
violations.push({
rule: 33,
file: posix,
line: idx + 1,
message: `imports the raw Workflow runtime. Import from "#internal/workflow/runtime.js" to preserve eve's single Workflow runtime package identity.`,
});
}
if (posix !== WORKFLOW_QUEUE_NAMESPACE_MODULE && WORKFLOW_QUEUE_NAMESPACE_WRITE_RE.test(line)) {
violations.push({
rule: 33,
file: posix,
line: idx + 1,
message: `writes WORKFLOW_QUEUE_NAMESPACE outside the canonical namespace module. Use installEveWorkflowQueueNamespace() so every queue surface derives the same agent-scoped value.`,
});
}
});
}
// ---------- Rule 37: instrumentation lifecycle provider boundary ----------
const INSTRUMENTATION_LIFECYCLE_CONTRACT = "packages/eve/src/instrumentation/lifecycle.ts";
const HARNESS_RUNTIME_IMPORTS = new Map([
["InstrumentationAttempt", "type"],
["InstrumentationStepScope", "type"],
["SessionInstrumentation", "type"],
]);
const EXECUTION_INSTRUMENTATION_IMPORTS = new Map([
[
"#instrumentation/runtime.js",
new Map([
["bindSessionInstrumentation", "value"],
["ExecutionInstrumentation", "type"],
["initializeSessionInstrumentation", "value"],
]),
],
["#instrumentation/state.js", new Map([["preserveSerializedInstrumentationState", "value"]])],
]);
/**
* @param {string} posix
* @param {string} source
* @param {Violation[]} violations
*/
function checkRule37(posix, source, violations) {
const productionHarness =
posix.startsWith("packages/eve/src/harness/") &&
!/\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix);
const productionExecution =
posix.startsWith("packages/eve/src/execution/") &&
!/\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix);
if (posix !== INSTRUMENTATION_LIFECYCLE_CONTRACT && !productionHarness && !productionExecution) {
return;
}
const sourceFile = ts.createSourceFile(
posix,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS,
);
const visit = (node) => {
const specifier = importSpecifier(node);
if (
posix === INSTRUMENTATION_LIFECYCLE_CONTRACT &&
specifier !== undefined &&
(specifier.text === "ai" || specifier.text.startsWith("ai/"))
) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports from "ai". Lifecycle event payloads are eve's own shape, so an AI SDK type reaching them makes an SDK upgrade a breaking change for every provider. Add an eve type here and map to it in ai-sdk-hook-bridge.ts.`,
});
}
if (
productionHarness &&
specifier?.text.startsWith("#instrumentation/") === true &&
specifier.text !== "#instrumentation/runtime.js"
) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports "${specifier.text}" directly. Harness code may consume instrumentation only through the bound SessionInstrumentation facade from "#instrumentation/runtime.js".`,
});
}
if (productionHarness && specifier?.text.startsWith("#tracing/") === true) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports "${specifier.text}" directly. Tracing implementation belongs behind the bound instrumentation facade.`,
});
}
if (
productionHarness &&
specifier?.text === "#instrumentation/runtime.js" &&
!hasOnlyAllowedNamedImports(node, HARNESS_RUNTIME_IMPORTS)
) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports unsupported instrumentation runtime bindings. Harness code may use only the SessionInstrumentation, InstrumentationStepScope, and InstrumentationAttempt types.`,
});
}
if (productionHarness && specifier?.text.startsWith("#compiled/@opentelemetry/") === true) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports OpenTelemetry directly. OTel implementation belongs behind the bound instrumentation facade.`,
});
}
if (
productionExecution &&
specifier?.text.startsWith("#instrumentation/") === true &&
!hasOnlyAllowedNamedImports(
node,
EXECUTION_INSTRUMENTATION_IMPORTS.get(specifier.text) ?? new Map(),
)
) {
violations.push({
rule: 37,
file: posix,
line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
message: `imports unsupported instrumentation bindings from "${specifier.text}". Execution may use only session binding/initialization, the ExecutionInstrumentation type, and cancellation-state preservation.`,
});
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
}
function hasOnlyAllowedNamedImports(node, allowed) {
if (!ts.isImportDeclaration(node)) return false;
const clause = node.importClause;
if (
clause === undefined ||
clause.name !== undefined ||
clause.namedBindings === undefined ||
!ts.isNamedImports(clause.namedBindings) ||
clause.namedBindings.elements.length === 0
) {
return false;
}
return clause.namedBindings.elements.every((element) => {
const imported = element.propertyName?.text ?? element.name.text;
const expectedKind = allowed.get(imported);
const actualKind = clause.isTypeOnly || element.isTypeOnly ? "type" : "value";
return expectedKind === actualKind;
});
}
function importSpecifier(node) {
if (
(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
node.moduleSpecifier !== undefined &&
ts.isStringLiteralLike(node.moduleSpecifier)
) {
return node.moduleSpecifier;
}
if (
ts.isImportEqualsDeclaration(node) &&
ts.isExternalModuleReference(node.moduleReference) &&
node.moduleReference.expression !== undefined &&
ts.isStringLiteralLike(node.moduleReference.expression)
) {
return node.moduleReference.expression;
}
if (
ts.isImportTypeNode(node) &&
ts.isLiteralTypeNode(node.argument) &&
ts.isStringLiteralLike(node.argument.literal)
) {
return node.argument.literal;
}
if (
ts.isCallExpression(node) &&
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
(ts.isIdentifier(node.expression) && node.expression.text === "require")) &&
node.arguments[0] !== undefined &&
ts.isStringLiteralLike(node.arguments[0])
) {
return node.arguments[0];
}
return undefined;
}
// ---------- Rule 19: AsyncLocalStorage instances ----------
const NEW_ALS_RE = /new\s+AsyncLocalStorage\s*[<(]/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {{ allowlist: Set<string>; current: Set<string>; lines: Map<string, number> }} state
*/
function checkRule19(posix, lines, state) {
lines.forEach((line, idx) => {
if (NEW_ALS_RE.test(line)) {
state.current.add(posix);
if (!state.lines.has(posix)) state.lines.set(posix, idx + 1);
}
});
}
// ---------- Rule 21: authored `name:` (or `id:`) on define* calls ----------
const DEFINE_FNS = [
"defineAgent",
"defineEval",
"defineMcpClientConnection",
"defineSandbox",
"defineSchedule",
"defineSkill",
"defineTool",
];
/**
* `defineEval` rejects both `name:` and `id:`. Every other
* primitive only forbids `name:`.
*/
const FORBIDDEN_KEYS_BY_FN = {
defineEval: ["name", "id"],
};
const DEFAULT_FORBIDDEN_KEYS = ["name"];
const AUTHORED_PATH_RE = /(^|\/)(apps\/(?:[^/]+\/)?[^/]+\/(agent|evals)|agent|evals)\//;
/**
* @param {string} posix
* @param {string[]} lines
* @param {Set<string>} allowlist
* @param {Violation[]} violations
*/
function checkRule21(posix, lines, allowlist, violations) {
if (!AUTHORED_PATH_RE.test(posix)) return;
if (allowlist.has(posix)) return;
// Find each `defineXxx(` call and inspect the next ~80 lines for a
// top-level `name:` (or `id:`, for `defineEval`) property. We bail
// out at the first balanced `)` to avoid crossing into unrelated calls.
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const fn = DEFINE_FNS.find((candidate) => line.includes(`${candidate}(`));
if (fn === undefined) continue;
const forbiddenKeys = FORBIDDEN_KEYS_BY_FN[fn] ?? DEFAULT_FORBIDDEN_KEYS;
const forbiddenKeyRe = new RegExp(`^\\s*(?:${forbiddenKeys.join("|")})\\s*:`);
let depth = 0;
let started = false;
for (let j = i; j < Math.min(lines.length, i + 80); j++) {
const inner = lines[j];
for (const ch of inner) {
if (ch === "(" || ch === "{") {
depth++;
started = true;
} else if (ch === ")" || ch === "}") {
depth--;
}
}
// The forbidden key is only authored identity at the TOP level of the
// call's object literal — exactly depth 2 (the call paren plus the
// outer `{`). Deeper occurrences are legitimate nested data.
if (depth === 2 && forbiddenKeyRe.test(inner)) {
const matchedKey = forbiddenKeys.find((key) => new RegExp(`^\\s*${key}\\s*:`).test(inner));
violations.push({
rule: 21,
file: posix,
line: j + 1,
message: `authored ${fn}({ ${matchedKey ?? forbiddenKeys[0]}: ... }) — derive the identifier from the file path instead. Adding an authored \`${matchedKey ?? forbiddenKeys[0]}\` creates a redundant source of truth that can drift from the path. Remove the field; the framework derives "${
posix
.split("/")
.pop()
?.replace(/\.[^.]+$/, "") ?? "<filename>"
}" automatically.`,
});
break;
}
if (started && depth <= 0) break;
}
}
}
// ---------- Rule 23: `as unknown as T` double casts ----------
const UNKNOWN_CAST_RE = /\bas\s+unknown\s+as\b/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {{ baseline: Record<string, number>; current: Map<string, number> }} state
*/
function checkRule23(posix, lines, state) {
let count = 0;
for (const line of lines) {
if (UNKNOWN_CAST_RE.test(line)) count++;
}
if (count > 0) state.current.set(posix, count);
}
// ---------- Rule 25: install/reset/clear runtime session in test bodies ----------
const RUNTIME_SESSION_FN_RE =
/\b(installBundledCompiledArtifacts|resetBundledCompiledArtifacts|clearProcessDefaultRuntimeSession)\b/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {{ allowlist: Set<string>; new: Map<string, number> }} state
*/
function checkRule25(posix, lines, state) {
let count = 0;
for (const line of lines) {
if (RUNTIME_SESSION_FN_RE.test(line)) count++;
}
if (count === 0) return;
if (state.allowlist.has(posix)) return;
state.new.set(posix, count);
}
// ---------- Rule 26: `loadContext() as ContextContainer` ----------
const LOAD_CONTEXT_CAST_RE = /loadContext\s*\(\s*\)\s*as\s+ContextContainer\b/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule26(posix, lines, violations) {
lines.forEach((line, idx) => {
if (LOAD_CONTEXT_CAST_RE.test(line)) {
violations.push({
rule: 26,
file: posix,
line: idx + 1,
message: `\`loadContext() as ContextContainer\` cast detected. Pass \`ctx: ContextContainer\` as an explicit parameter instead — the cast hides the runtime invariant behind a TypeScript assertion and creates an implicit AsyncLocalStorage dependency.`,
});
}
});
}
// ---------- Rule 27: hook return shapes have no `state` field ----------
const HOOK_DEFINITIONS_PATH = "packages/eve/src/public/definitions/hook.ts";
/** Matches a `state:` (or `readonly state:`, `state?:`) struct member declaration. */
const HOOK_STATE_FIELD_RE = /^\s*(readonly\s+)?state\??\s*:/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule27(posix, lines, violations) {
if (posix !== HOOK_DEFINITIONS_PATH) return;
lines.forEach((line, idx) => {
if (HOOK_STATE_FIELD_RE.test(line)) {
violations.push({
rule: 27,
file: posix,
line: idx + 1,
message: `\`state:\` field detected on a hook type definition. Hook return shapes must not carry a parallel state-patch channel — durable state goes through \`ctx.eve\`. Remove the \`state\` field; if the hook truly needs to persist something across turns, write it to a context key via \`ctx.eve.set(...)\` instead.`,
});
}
});
}
// ---------- Rule 28: scaffold layer dependency whitelist ----------
const SCAFFOLD_PREFIX = "packages/eve/src/setup/scaffold/";
// The curated connection and channel catalogs read canonical identity from
// the private `@eve/catalog` workspace package through eve's vendored copy.
// This keeps the published package self-contained without allowing the
// scaffold layer to reach into runtime, compiler, or provider SDK modules.
// Terminal UI adapters live outside the scaffold in `packages/eve/src/setup/cli/`.
const SCAFFOLD_ALLOWED_PACKAGES = new Set([]);
const SCAFFOLD_ALLOWED_INTERNAL_IMPORTS = new Set(["#compiled/@eve/catalog/index.js"]);
// Only match top-of-line `import` statements, not strings nested inside
// template literals (e.g. the channel templates embed `from "react"` as
// generated source for the scaffolded project).
const SCAFFOLD_IMPORT_RE = /^\s*import\b[^"']*\sfrom\s+["']([^"']+)["']/;
/**
* @param {string} posix
* @param {string[]} lines
* @param {Violation[]} violations
*/
function checkRule28(posix, lines, violations) {
if (!posix.startsWith(SCAFFOLD_PREFIX)) return;
// Test files never ship in the eve tarball, so the bundle-size rationale
// doesn't apply to them. Allow vitest and other test-only dependencies.
if (/\.(test|integration\.test|scenario\.test)\.ts$/.test(posix)) return;
// Channel templates embed full source files inside backtick literals
// (`from "react"`, etc.). Track template literal depth so we ignore
// import-like lines that live inside an open backtick block.
let insideTemplate = false;
for (let idx = 0; idx < lines.length; idx++) {
const line = lines[idx];
if (!line) continue;
if (!insideTemplate) {
const match = line.match(SCAFFOLD_IMPORT_RE);
if (match) {
const spec = match[1];
if (
spec &&
!spec.startsWith("node:") &&
!spec.startsWith(".") &&
!SCAFFOLD_ALLOWED_PACKAGES.has(spec) &&
!SCAFFOLD_ALLOWED_INTERNAL_IMPORTS.has(spec)
) {
violations.push({
rule: 28,
file: posix,
line: idx + 1,
message: `import from "${spec}" not allowed in the packages/eve/src/setup/scaffold source layer. Scaffold modules allow only node:* builtins, relative files, and #compiled/@eve/catalog/index.js. Keep runtime, compiler, terminal UI, and provider SDK dependencies in their owning package.`,
});
}
}
}
// Toggle template state on each unescaped backtick on this line.
const backticks = (line.match(/(^|[^\\])`/g) ?? []).length;
if (backticks % 2 === 1) insideTemplate = !insideTemplate;
}
}
// ---------- Rule 29: changeset package names exist in the workspace ----------
const CHANGESET_DIR = ".changeset";
/**
* @returns {Promise<Violation[]>}
*/
async function checkRule29ChangesetPackageNames() {
const workspacePackageNames = await readWorkspacePackageNames();
const changesetPath = join(REPO_ROOT, CHANGESET_DIR);
/** @type {Violation[]} */
const violations = [];
let entries;
try {
entries = await readdir(changesetPath, { withFileTypes: true });
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return violations;
}
throw error;
}
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name === "README.md") continue;
const relPath = `${CHANGESET_DIR}/${entry.name}`;
const content = await readFile(join(REPO_ROOT, relPath), "utf8");
if (!startsWithFrontmatter(content)) {
violations.push({
rule: 29,
file: relPath,
message:
"changeset files must start with YAML frontmatter mapping package names to version bump types.",
});
continue;
}
let data;
try {
data = readFrontmatter(content);
} catch (error) {
violations.push({
rule: 29,
file: relPath,
message: `changeset frontmatter must be valid YAML: ${error instanceof Error ? error.message : String(error)}`,
});
continue;
}
if (data === null || typeof data !== "object" || Array.isArray(data)) {
violations.push({
rule: 29,
file: relPath,
message:
"changeset frontmatter must be an object mapping package names to version bump types.",
});
continue;
}
const releases = Object.entries(data);
if (releases.length === 0) {
violations.push({
rule: 29,
file: relPath,
message: "changeset frontmatter must declare at least one package bump.",
});
continue;
}
for (const [packageName] of releases) {
if (workspacePackageNames.has(packageName)) continue;
violations.push({
rule: 29,
file: relPath,
message: `changeset references package "${packageName}", but no workspace package has that name. Use the exact package.json "name" from the target workspace package; for packages/eve that is "eve".`,
});
}
}
return violations;
}
// ---------- Rule 30: vendored compiled output has no per-package package.json ----------
const VENDOR_COMPILED_DIR = "packages/eve/scripts/vendor-compiled";
// Matches a write/copy whose path argument is a `join(...)` ending in the
// `package.json` literal — i.e. emitting a package.json into the vendored
// output. Reads in `findPackageJson` use `readFile`, so keying on
// `writeFile`/`copyFile` distinguishes a write from a lookup. `[^)]*` keeps
// the match inside the single `join(...)` argument so an unrelated write
// (e.g. a stub `.d.ts`) followed later by a `package.json` read literal
// can't trigger a false positive.
const COMPILED_PACKAGE_JSON_WRITE_RE =
/(?:writeFile|copyFile)\s*\(\s*join\([^)]*["']package\.json["']/;
/**
* Rule 30. Scans the compiled-vendor scripts for any code that writes a
* `package.json` into a vendored output directory. Such a file shadows eve's
* `#compiled/*` imports map and silently turns cross-package vendored types
* into `any` (see the rule 30 note in the header). Scanning the scripts (not
* the generated artifact) keeps the guard meaningful in the `lint` CI job,
* which runs before any `build:compiled`.
*
* @returns {Promise<Violation[]>}
*/
async function checkRule30VendoredCompiledPackageJson() {
/** @type {Violation[]} */
const violations = [];
const scriptsRoot = join(REPO_ROOT, VENDOR_COMPILED_DIR);
for await (const { absPath, relPath } of walkFiles(scriptsRoot)) {
if (!absPath.endsWith(".mjs")) continue;
const content = await readFile(absPath, "utf8");
if (COMPILED_PACKAGE_JSON_WRITE_RE.test(content)) {
violations.push({
rule: 30,
file: toPosix(relPath),
message:
'vendored-compile pipeline writes a package.json into the compiled output. Remove it: a per-package package.json creates a scope that shadows eve\'s `#compiled/*` imports map, so cross-package vendored type references (e.g. @workflow/core -> @workflow/world -> zod) silently resolve to `any` under skipLibCheck. The bundled ESM inherits `"type": "module"` from eve\'s root package.json, so no per-package file is needed.',
});
}
}
return violations;
}
// Provided definitions must carry identity, not rely on their filesystem or runtime name.
async function checkFrameworkActionIdentity() {
const violations = [];
const roots = ["packages/eve/src/tools/provided", "packages/eve/src/tools/framework"];
const files = [];
for (const root of roots) {
for await (const file of walkFiles(join(REPO_ROOT, root))) files.push(file);
}
for (const { absPath, relPath } of files) {
if (!absPath.endsWith(".ts") || absPath.endsWith(".test.ts")) continue;
const source = await readFile(absPath, "utf8");
const ast = ts.createSourceFile(relPath, source, ts.ScriptTarget.Latest, true);
const report = (node, message) =>
violations.push({
rule: 49,
file: toPosix(relPath),
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
message,
});
const visit = (node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
const name = node.expression.text;
if (["defineTool", "defineWorkflowTool", "stampToolDefinition"].includes(name)) {
const parent = node.parent;
if (
!ts.isCallExpression(parent) ||
!ts.isIdentifier(parent.expression) ||
parent.expression.text !== "frameworkTool"
)
report(
node,
"Wrap provided tool definitions in frameworkTool(definition), so renamed tools remain marked in traces.",
);
}
}
if (ts.isObjectLiteralExpression(node)) {
const properties = new Map(
node.properties
.filter(ts.isPropertyAssignment)
.map((property) => [property.name.getText(ast), property.initializer]),
);
if (properties.has("frameworkAction")) {
const flag = properties.get("frameworkTool");
if (flag === undefined || flag.kind !== ts.SyntaxKind.TrueKeyword)
report(node, "Framework harness tools must declare frameworkTool: true.");
}
}
ts.forEachChild(node, visit);
};
visit(ast);
}
return violations;
}
// ---------- Rule 31: removed CLI entry points stay removed ----------
const ACTIVE_CLI_REFERENCE_EXTENSIONS = /\.(?:[cm]?[jt]sx?|mdx?|json|ya?ml)$/;
const ACTIVE_CLI_REFERENCE_ROOTS = [
"apps/",
"docs/",
"e2e/",
"packages/eve/src/",
"packages/eve/test/",
];
const ACTIVE_CLI_REFERENCE_ROOT_FILES = new Set(["AGENTS.md", "CONTRIBUTING.md", "README.md"]);
const REMOVED_CLI_REFERENCES = [
{
pattern: /\b(?:npm|pnpm|yarn)\s+create\s+eve(?:@[^\s`"'<>]+)?\b/i,
replacement: "`eve init <name>`",
},
{ pattern: /\bcreate-eve\b/i, replacement: "`eve init`" },
{ pattern: /\beve\s+setup\b/i, replacement: "the dedicated current eve command" },
];
/**
* @param {string} posix
*/
function isActiveCliReferenceFile(posix) {
if (!ACTIVE_CLI_REFERENCE_EXTENSIONS.test(posix)) return false;
return (
ACTIVE_CLI_REFERENCE_ROOT_FILES.has(posix) ||
ACTIVE_CLI_REFERENCE_ROOTS.some((prefix) => posix.startsWith(prefix))
);
}
/**
* @returns {Promise<Violation[]>}
*/
async function checkRule31RemovedCliReferences() {
/** @type {Violation[]} */
const violations = [];
for await (const { absPath, relPath } of walkFiles(REPO_ROOT)) {
const posix = toPosix(relPath);
if (!isActiveCliReferenceFile(posix)) continue;
const lines = (await readFile(absPath, "utf8")).split(/\r?\n/);
lines.forEach((line, index) => {
const removed = REMOVED_CLI_REFERENCES.find(({ pattern }) => pattern.test(line));
if (removed === undefined) return;
violations.push({
rule: 31,
file: posix,
line: index + 1,
message: `references a removed eve CLI entry point. Replace it with ${removed.replacement}. Historical mentions belong only in changelogs or changesets.`,
});
});
}
return violations;
}
// ---------- Rule 32: research document frontmatter ----------
const RESEARCH_DIR = "research";
const RESEARCH_LAST_UPDATED_RE = /^\d{4}-\d{2}-\d{2}$/;
/**
* @returns {Promise<Violation[]>}
*/
async function checkRule32ResearchFrontmatter() {
/** @type {Violation[]} */
const violations = [];
const researchRoot = join(REPO_ROOT, RESEARCH_DIR);
try {
await readdir(researchRoot);
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return violations;
}
throw error;
}
for await (const { absPath, relPath } of walkFiles(researchRoot)) {
const posix = toPosix(relPath);
if (!posix.endsWith(".md")) continue;
const content = await readFile(absPath, "utf8");
if (!startsWithFrontmatter(content)) {
violations.push({
rule: 32,
file: posix,
message:
"research documents must start with YAML frontmatter containing `issue`, `status`, and `last_updated` fields.",
});
continue;
}
let data;
try {
data = readFrontmatter(content);
} catch (error) {
violations.push({
rule: 32,
file: posix,
message: `research frontmatter must be valid YAML: ${error instanceof Error ? error.message : String(error)}`,
});
continue;
}
if (data === null || typeof data !== "object" || Array.isArray(data)) {
violations.push({
rule: 32,
file: posix,
message: "research frontmatter must parse to an object.",
});
continue;
}
for (const field of ["issue", "status"]) {
if (typeof data[field] === "string" && data[field].trim().length > 0) continue;
violations.push({
rule: 32,
file: posix,
message: `research frontmatter must set \`${field}\` to a non-empty string.`,
});
}
if (
typeof data.last_updated !== "string" ||
!RESEARCH_LAST_UPDATED_RE.test(data.last_updated)
) {
violations.push({
rule: 32,
file: posix,
message: "research frontmatter must set `last_updated` to a quoted `YYYY-MM-DD` string.",
});
}
}
return violations;
}
// ---------- Rule 34: no `phase` imports under GPU/shader boundaries ----------
const PHASE_BOUNDARY_DIRS = [
"apps/docs/app/[lang]/(home)/components/eve-logo-shader/render",
"apps/docs/app/[lang]/(home)/components/eve-logo-shader/shaders",
"apps/docs/scripts/eve-render",
];
const PHASE_IMPORT_RE =
/(from\s+|import\s+)(?:type\s+)?['"]phase(?:\/[^'"]*)?['"]|require\(\s*['"]phase(?:\/[^'")]*)?['"]\s*\)|import\(\s*['"]phase(?:\/[^'")]*)?['"]\s*\)/;
/**
* @returns {Promise<Violation[]>}
*/
async function checkRule34PhaseBoundary() {
/** @type {Violation[]} */
const violations = [];
for (const relDir of PHASE_BOUNDARY_DIRS) {
const absDir = join(REPO_ROOT, relDir);
let stats;
try {
stats = await lstat(absDir);
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
continue;
}
throw error;
}
if (!stats.isDirectory()) continue;
for await (const entry of walkFiles(absDir)) {
if (!entry.stat.isFile()) continue;
const content = await readFile(entry.absPath, "utf8");
const match = content.match(PHASE_IMPORT_RE);
if (!match) continue;
const before = content.slice(0, match.index ?? 0);
const line = before.split(/\r?\n/).length;
violations.push({
rule: 34,
file: entry.relPath,
line,
message:
"imports the `phase` package inside the GPU/shader boundary. Phase must stay in the lifecycle/runtime layer — add lifecycle hooks above render/ and keep render/, shaders/, and scripts/eve-render/ free of `phase` imports.",
});
}
}
return violations;
}
// ---------- Rule 38: one owner for the eve package build ----------
const NESTED_EVE_BUILD_RE = /\bpnpm\s+(?:--filter(?:=|\s+)eve|-F\s+eve)\s+(?:run\s+)?build\b/;
/**
* @returns {Promise<Violation[]>}
*/
async function checkRule38NoNestedEveBuild() {
/** @type {Violation[]} */
const violations = [];
for (const dir of await readPnpmWorkspacePackageDirs()) {
if (dir === "packages/eve") continue;
const packageJson = await readJsonIfExists(join(REPO_ROOT, dir, "package.json"));
for (const [scriptName, command] of Object.entries(packageJson?.scripts ?? {})) {
if (typeof command !== "string" || !NESTED_EVE_BUILD_RE.test(command)) continue;
violations.push({
rule: 38,
file: `${dir}/package.json`,
message: `script "${scriptName}" launches a nested eve package build. Declare eve as a workspace dependency and let Turbo's ^build edge produce it once; rebuilding eve inside a consumer races its destructive dist clean against other consumers.`,
});
}
}
return violations;
}
/**
* @returns {Promise<Set<string>>}
*/
async function readWorkspacePackageNames() {
const packageDirs = await readPnpmWorkspacePackageDirs();
const packageNames = new Set();
for (const dir of packageDirs) {
const packageJson = await readJsonIfExists(join(REPO_ROOT, dir, "package.json"));
if (packageJson?.name) packageNames.add(packageJson.name);
}
return packageNames;
}
/**
* @returns {Promise<string[]>}
*/
async function readPnpmWorkspacePackageDirs() {
const workspaceYaml = await readFile(join(REPO_ROOT, "pnpm-workspace.yaml"), "utf8");
const includeDirs = new Set();
const excludeDirs = new Set();
for (const rawPattern of readPnpmWorkspacePackagePatterns(workspaceYaml)) {
const excluded = rawPattern.startsWith("!");
const pattern = excluded ? rawPattern.slice(1) : rawPattern;
const dirs = await expandWorkspacePackagePattern(pattern);
if (!excluded && dirs.length === 0) {
throw new Error(`Workspace package pattern "${rawPattern}" matched no package.json files.`);
}
const target = excluded ? excludeDirs : includeDirs;
dirs.forEach((dir) => target.add(dir));
}
excludeDirs.forEach((dir) => includeDirs.delete(dir));
return [...includeDirs].sort();
}
/**
* @param {string} workspaceYaml
*/
function readPnpmWorkspacePackagePatterns(workspaceYaml) {
const patterns = [];
let inPackages = false;
for (const line of workspaceYaml.split(/\r?\n/)) {
if (/^\S/.test(line)) {
inPackages = /^packages:\s*$/.test(line);
continue;
}
if (!inPackages) continue;
const match = line.match(/^\s*-\s+(.+?)\s*$/);
if (!match) continue;
patterns.push(stripYamlString(match[1]));
}
return patterns;
}
/**
* @param {string} value
*/
function stripYamlString(value) {
const trimmed = value.trim();
if (
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
) {
return trimmed.slice(1, -1);
}
return trimmed;
}
/**
* @param {string} pattern
* @returns {Promise<string[]>}
*/
async function expandWorkspacePackagePattern(pattern) {
const normalizedPattern = pattern.replace(/\/+$/, "");
const dirs = [];
for await (const manifestPath of glob(`${normalizedPattern}/package.json`, {
cwd: REPO_ROOT,
})) {
dirs.push(toPosix(dirname(manifestPath)));
}
return dirs.sort();
}
/**
* @param {string} path
* @returns {Promise<any | undefined>}
*/
async function readJsonIfExists(path) {
try {
return JSON.parse(await readFile(path, "utf8"));
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return undefined;
}
throw error;
}
}
// ---------- Reporting helpers ----------
/**
* @param {Violation[]} violations
*/
function printViolations(violations) {
for (const v of violations) {
const where = v.line ? `${v.file}:${v.line}` : v.file;
process.stderr.write(` [rule ${v.rule}] ${where}\n ${v.message}\n`);
}
}
/**
* Compares per-file counts against a baseline and returns the offending
* entries. Files whose count exceeds the baseline (or are absent from it)
* are reported as additions; baselines never increase.
*
* @param {Map<string, number>} current
* @param {Record<string, number>} baseline
*/
function diffCounts(current, baseline) {
/** @type {{ file: string; was: number; now: number }[]} */
const additions = [];
for (const [file, now] of current) {
const was = baseline[file] ?? 0;
if (now > was) additions.push({ file, was, now });
}
return additions;
}
// ---------- Entry point ----------
async function main() {
const baselineRaw = await readFile(BASELINE_PATH, "utf8");
const baseline = JSON.parse(baselineRaw);
const state = {
rule13: { baseline: baseline.rule13_spreadTernaryByFile, current: new Map() },
rule19: {
allowlist: new Set(baseline.rule19_asyncLocalStorageAllowlist),
current: new Set(),
lines: new Map(),
},
rule21: {
allowlist: new Set(baseline.rule21_authoredNameAllowlist ?? []),
violations: /** @type {Violation[]} */ ([]),
},
rule23: { baseline: baseline.rule23_unknownCastByFile, current: new Map() },
rule25: {
allowlist: new Set(baseline.rule25_installRuntimeArtifactsAllowlist),
new: new Map(),
},
rule26: /** @type {Violation[]} */ ([]),
rule27: /** @type {Violation[]} */ ([]),
rule28: /** @type {Violation[]} */ ([]),
rule33: /** @type {Violation[]} */ ([]),
rule37: /** @type {Violation[]} */ ([]),
rule43: /** @type {Violation[]} */ ([]),
rule44: /** @type {Violation[]} */ ([]),
rule53: /** @type {Violation[]} */ ([]),
rule45: {
allowlist: new Set(baseline.rule45_providedToolPrivateImportAllowlist),
violations: /** @type {Violation[]} */ ([]),
},
rule46: /** @type {Violation[]} */ ([]),
rule47: /** @type {Violation[]} */ ([]),
rule48: /** @type {Violation[]} */ ([]),
rule50: /** @type {Violation[]} */ ([]),
rule51: /** @type {Violation[]} */ ([]),
rule52: /** @type {Violation[]} */ ([]),
symlinks: /** @type {string[]} */ ([]),
};
await scanRepo(state);
const violations = /** @type {Violation[]} */ ([]);
// Rule 9
for (const file of state.symlinks) {
violations.push({
rule: 9,
file,
message: `symlink detected. Symlinks are forbidden — they are too unpredictable for a framework to rely on. Replace it with a real file or a small loader that references the canonical location.`,
});
}
// Rule 13
for (const { file, was, now } of diffCounts(state.rule13.current, state.rule13.baseline)) {
violations.push({
rule: 13,
file,
message: `${now} spread-ternary object composition${now === 1 ? "" : "s"} detected (baseline: ${was}). Replace \`...(cond ? {} : { key: value })\` with explicit assignment: declare the object, then \`if (cond) obj.key = value;\` (or use the conditional form for the *value* not the spread).`,
});
}
// Rule 19
for (const file of state.rule19.current) {
if (state.rule19.allowlist.has(file)) continue;
const line = state.rule19.lines.get(file);
violations.push({
rule: 19,
file,
line,
message: `\`new AsyncLocalStorage()\` outside the allowlist. All ambient runtime state must flow through the unified EveContext (one AsyncLocalStorage). If you genuinely need a new ALS, justify it in code review and add this file to scripts/guard-invariants-baseline.json under "rule19_asyncLocalStorageAllowlist".`,
});
}
// Rule 21
violations.push(...state.rule21.violations);
// Rule 23
for (const { file, was, now } of diffCounts(state.rule23.current, state.rule23.baseline)) {
violations.push({
rule: 23,
file,
message: `${now} \`as unknown as T\` cast${now === 1 ? "" : "s"} detected (baseline: ${was}). Avoid double casts through \`unknown\` — they hide real type errors. Try a direct \`as T\`, fix the source type, or thread a properly typed parameter through. To lower the baseline after a cleanup, regenerate the baseline file. The baseline may shrink, never grow.`,
});
}
// Rule 25
for (const [file, count] of state.rule25.new) {
violations.push({
rule: 25,
file,
message: `${count} call${count === 1 ? "" : "s"} to install/reset/clear runtime-session helpers. Tests must scope runtime state through createTestRuntime().run(fn) / runAsSession(init, fn) / withRuntimeSession(...). Direct calls mutate the process-default RuntimeSession and leak state across tests.`,
});
}
// Rule 26
violations.push(...state.rule26);
// Rule 27
violations.push(...state.rule27);
// Rule 28
violations.push(...state.rule28);
// Rule 29
violations.push(...(await checkRule29ChangesetPackageNames()));
// Rule 30
violations.push(...(await checkRule30VendoredCompiledPackageJson()));
// Rule 31
violations.push(...(await checkRule31RemovedCliReferences()));
// Rule 32
violations.push(...(await checkRule32ResearchFrontmatter()));
// Rule 33
violations.push(...state.rule33);
// Rule 34
violations.push(...(await checkRule34PhaseBoundary()));
// Rule 36
for (const issue of await checkExtensionCapabilityContracts()) {
violations.push({ rule: 36, ...issue });
}
// Rule 37
violations.push(...state.rule37);
// Rule 38
violations.push(...(await checkRule38NoNestedEveBuild()));
// Rule 43
violations.push(...state.rule43);
// Rule 44
violations.push(...state.rule44);
// Rule 45
violations.push(...state.rule45.violations);
// Rule 46
violations.push(...state.rule46);
// Rule 47
violations.push(...state.rule47);
violations.push(...state.rule48);
violations.push(...(await checkFrameworkActionIdentity()));
violations.push(...state.rule50);
violations.push(...state.rule51);
violations.push(...state.rule52);
violations.push(...state.rule53);
if (violations.length === 0) {
process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");
return;
}
process.stderr.write(
`[eve:guard:invariants] FAIL: ${violations.length} violation${violations.length === 1 ? "" : "s"} of framework mechanical rules.\n\n`,
);
printViolations(violations);
process.stderr.write(
`\nEach rule above enforces a framework invariant. The header comment in scripts/guard-invariants.mjs explains the rationale for each rule ID. Fix the violation, or — if the failure is for a baselined rule and you have a deliberate reduction — update scripts/guard-invariants-baseline.json (counts and allowlists may shrink, never grow).\n`,
);
process.exit(1);
}
await main();