Files
openbot/scripts/dev-verify.ts
T
Aleksander DygońandClaude Opus 5.5 212eff2a80 Remove unit tests and keep E2E and protected tests (#2051)
* Remove unit tests and keep E2E and protected tests

Delete 591 vitest unit test files and their test-only harnesses. Keep
E2E and smoke scripts under scripts/, and keep vitest files only for
migrations, schema parity, the renderer-to-main trust boundary, secret
redaction, and check-rule fixtures.

Remove the test runners that have no tests now (site-router, remote/api,
contracts, brand, auth-api client), their CI jobs, and the transfer
budget report. Remove code and dependencies that only the deleted tests
used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Set the E2E-only test policy and remove references to deleted tests

AGENTS.md now permits vitest files only for migrations, the trust
boundary, secret redaction and check-rule fixtures. All other behaviour
gets an E2E script under scripts/.

Remove references to deleted tests, harnesses and commands from docs,
AGENTS.md files and skills. The release-upgrade-safety gates that ran a
deleted test now use a manual check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep migration tests and fix CI checks after the test removal

Move the migration cases out of the deleted mixed test files into
three migration test files: the v15 agent usage upgrade and rollback,
the read-state baseline from schema v2, and the remote control plane
and permanent invitation D1 migrations.

Keep error.agent.noStartingModel for the text that older hosts send,
and let i18n-check accept it. Lower two type baseline entries. Correct
comments and docs that named removed tests or test commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove the empty test patterns from the knip configuration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add E2E checks for Signal secrets, IPC input decoding and analytics redaction

- scripts/signal-security-e2e.ts starts the real Signal service with
  throwaway secrets. It checks the Telegram secret header, the Slack
  signature, signed account events, remote and route tickets, webhook
  headers, and that no frame or log line holds the bot token. CI runs
  it in the new Signal E2E job.
- scripts/ipc-input-e2e.ts sends malformed requests from a running dev
  app and checks that the main process decoders refuse them.
- scripts/analytics-redaction-e2e.ts checks that no captured analytics
  or failure report request holds a seeded secret. For this,
  OPENBOT_ANALYTICS_CAPTURE_URL sends analytics to a loopback capture
  server. Only an unpackaged build reads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Check the renderer analytics path and path traversal in the E2E scripts

The analytics E2E now loads the window again and waits for the renderer event, so the renderer send path cannot pass with no request. The IPC input E2E now sends an attachment id and a shared file path that try to leave their folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove an unused optional parameter from the read-state migration test

The parameter gave one exactOptionalPropertyTypes error, which the type ratchet refuses for a new file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:25:48 +02:00

338 lines
12 KiB
TypeScript

import { execFileSync, spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { extname, resolve } from "node:path";
import { supportedBunVersion } from "./prepare-dev-environment";
import { readScriptArguments } from "./script-arguments";
export type VerificationSurface = "desktop" | "renderer" | "mobile" | "api" | "remote" | "contracts" | "docs";
export interface DevVerificationReport {
ready: boolean;
reasons: string[];
setup: {
bun: { ready: boolean; current: string; expected: string };
dependencies: boolean;
developmentEnv: boolean;
};
changes: { files: string[]; surfaces: VerificationSurface[]; suggestedTests: string[] };
runtime: {
stackRunning: boolean;
appRunning: boolean;
isolatedApp: boolean;
orphanedStack: boolean;
ambiguousApp: boolean;
};
qa: {
required: boolean;
ready: boolean;
reasons: string[];
loop: string[];
};
commands: string[];
runnableCommands: string[];
qaCommands: string[];
}
const rendererQaLoop = [
"bun run dev:automation snapshot",
"bun run dev:automation <click|type> --role=<role> --name=<name> --allow-mutations --wait-for=<role>,<name>",
"bun run dev:automation snapshot --wait-for=<role>,<name>",
"bun run dev:automation screenshot --wait-for=<role>,<name>",
];
export function surfacesForFiles(files: string[]): VerificationSurface[] {
const surfaces = new Set<VerificationSurface>();
for (const file of files) {
if (file.startsWith("src/renderer/")) surfaces.add("renderer");
if (file.startsWith("src/main/") || file.startsWith("src/backend/") || file.startsWith("scripts/")) {
surfaces.add("desktop");
}
if (file.startsWith("apps/mobile/")) surfaces.add("mobile");
if (file.startsWith("apps/auth-api/") || file.startsWith("apps/site-router/")) surfaces.add("api");
if (file.startsWith("remote/")) surfaces.add("remote");
if (file.startsWith("packages/contracts/")) surfaces.add("contracts");
if (file.startsWith("docs/") || file === "README.md") surfaces.add("docs");
}
return [...surfaces].sort();
}
function isTestFile(file: string): boolean {
return /\.(test|dom\.test)\.tsx?$/u.test(file);
}
function isDesktopTest(file: string): boolean {
if (!isTestFile(file)) return false;
return [
"src/backend/",
"src/main/",
"src/preload/",
"src/renderer/",
"scripts/",
"packages/logging/",
"apps/mobile/src/",
].some((prefix) => file.startsWith(prefix));
}
function isDelegatedTest(file: string): boolean {
return file.startsWith("apps/auth-api/test/") && isTestFile(file);
}
function isSupportedTest(file: string): boolean {
return isDesktopTest(file) || isDelegatedTest(file);
}
export function suggestedTestsForFiles(files: string[], projectRoot = process.cwd()): string[] {
const tests = new Set(files.filter((file) => isSupportedTest(file) && existsSync(resolve(projectRoot, file))));
for (const file of files) {
if (isTestFile(file)) continue;
const extension = extname(file);
if (extension !== ".ts" && extension !== ".tsx") continue;
const stem = file.slice(0, -extension.length);
for (const suffix of [`.test${extension}`, `.dom.test${extension}`]) {
const candidate = `${stem}${suffix}`;
if (isSupportedTest(candidate) && existsSync(resolve(projectRoot, candidate))) tests.add(candidate);
}
}
return [...tests].sort();
}
interface VerificationCommandPlan {
commands: string[];
runnableCommands: string[];
runnableCommandArgs: string[][];
qaCommands: string[];
suggestedTests: string[];
}
function formatBunCommand(args: string[]): string {
return `bun ${args.join(" ")}`;
}
function testCommandArgs(tests: string[]): string[][] {
const desktop = tests.filter(isDesktopTest);
const auth = tests.filter((file) => file.startsWith("apps/auth-api/test/"));
const commands: string[][] = [];
if (desktop.length > 0) commands.push(["run", "test:desktop", "--", ...desktop]);
if (auth.length > 0) {
commands.push([
"run",
"--cwd",
"apps/auth-api",
"test",
"--",
...auth.map((file) => file.slice("apps/auth-api/".length)),
]);
}
return commands;
}
function workspaceTestCommandArgs(files: string[], suggestedTests: string[]): string[][] {
const commands: string[][] = [];
if (
files.some((file) => file.startsWith("apps/auth-api/")) &&
!suggestedTests.some((file) => file.startsWith("apps/auth-api/"))
) {
commands.push(["run", "test:api"]);
}
return commands;
}
export function verificationCommands(
files: string[],
surfaces: VerificationSurface[],
setupReady: boolean,
isolatedApp: boolean,
projectRoot = process.cwd(),
): Omit<VerificationCommandPlan, "runnableCommandArgs"> {
const plan = createVerificationCommandPlan(files, surfaces, setupReady, isolatedApp, projectRoot);
return {
commands: plan.commands,
runnableCommands: plan.runnableCommands,
qaCommands: plan.qaCommands,
suggestedTests: plan.suggestedTests,
};
}
function createVerificationCommandPlan(
files: string[],
surfaces: VerificationSurface[],
setupReady: boolean,
isolatedApp: boolean,
projectRoot = process.cwd(),
): VerificationCommandPlan {
const commands: string[] = [];
const runnableCommandArgs: string[][] = [];
const qaCommands: string[] = [];
if (!setupReady) commands.push("bun run dev:prepare");
const suggestedTests = suggestedTestsForFiles(files, projectRoot);
for (const args of testCommandArgs(suggestedTests)) {
commands.push(formatBunCommand(args));
runnableCommandArgs.push(args);
}
for (const args of [["run", "lint"], ["run", "typecheck"], ...workspaceTestCommandArgs(files, suggestedTests)]) {
const command = formatBunCommand(args);
if (!commands.includes(command)) commands.push(command);
if (!runnableCommandArgs.some((candidate) => formatBunCommand(candidate) === command))
runnableCommandArgs.push(args);
}
if (surfaces.includes("api")) commands.push("bun run check:api");
if (surfaces.includes("renderer")) {
commands.push("bun run check:ui");
runnableCommandArgs.push(["run", "check:ui"]);
}
if (surfaces.includes("renderer") && !isolatedApp) commands.push("bun run dev");
if (surfaces.includes("renderer")) {
qaCommands.push("bun run dev:automation snapshot", "bun run dev:automation screenshot");
commands.push(...qaCommands);
}
return {
commands,
runnableCommands: runnableCommandArgs.map(formatBunCommand),
runnableCommandArgs,
qaCommands,
suggestedTests,
};
}
function changedFiles(projectRoot: string): string[] {
const tracked = execFileSync("git", ["diff", "--name-only", "HEAD"], { cwd: projectRoot, encoding: "utf8" });
const untracked = execFileSync("git", ["ls-files", "--others", "--exclude-standard"], {
cwd: projectRoot,
encoding: "utf8",
});
return [
...new Set(
`${tracked}\n${untracked}`
.split("\n")
.map((file) => file.trim())
.filter(Boolean),
),
].sort();
}
function readinessReasons(setup: DevVerificationReport["setup"], runtime: DevVerificationReport["runtime"]): string[] {
const reasons: string[] = [];
if (!setup.bun.ready) reasons.push(`Bun ${setup.bun.expected} is required; current version is ${setup.bun.current}.`);
if (!setup.dependencies) reasons.push("node_modules is missing. Run bun run dev:prepare.");
if (!setup.developmentEnv) reasons.push(".openbot/dev-state.json is missing. Run bun run dev:prepare.");
if (runtime.orphanedStack) reasons.push("This worktree has an orphaned dev stack. Inspect bun run dev:status.");
if (runtime.ambiguousApp) reasons.push("More than one app instance matches this worktree.");
return reasons;
}
export function qaReadinessReasons(
surfaces: VerificationSurface[],
setupReady: boolean,
runtime: DevVerificationReport["runtime"],
): string[] {
if (!surfaces.includes("renderer")) return [];
const reasons: string[] = [];
if (!setupReady) reasons.push("Development setup is incomplete. Run bun run dev:prepare before renderer QA.");
if (runtime.orphanedStack) reasons.push("This worktree has an orphaned dev stack. Inspect bun run dev:status.");
if (runtime.ambiguousApp) reasons.push("More than one app instance matches this worktree.");
if (!runtime.appRunning && !runtime.ambiguousApp) reasons.push("No running app matches this worktree.");
if (runtime.appRunning && !runtime.isolatedApp) {
reasons.push(
"The running app uses the shared profile. Start bun run dev without --shared for isolated renderer QA.",
);
}
return reasons;
}
async function createDevVerificationState(
projectRoot = process.cwd(),
): Promise<{ report: DevVerificationReport; runnableCommandArgs: string[][]; setupReady: boolean }> {
const files = changedFiles(projectRoot);
const surfaces = surfacesForFiles(files);
const bunCurrent = process.versions.bun ?? "unknown";
const setup = {
bun: { ready: bunCurrent === supportedBunVersion, current: bunCurrent, expected: supportedBunVersion },
dependencies: existsSync(resolve(projectRoot, "node_modules")),
developmentEnv: existsSync(resolve(projectRoot, ".openbot/dev-state.json")),
};
const setupReady = setup.bun.ready && setup.dependencies && setup.developmentEnv;
let runtime: DevVerificationReport["runtime"] = {
stackRunning: false,
appRunning: false,
isolatedApp: false,
orphanedStack: false,
ambiguousApp: false,
};
if (setup.dependencies) {
const [{ readDevInstanceRecords }, { isOrphanedDevStack, isSameWorktree, readDevStackRecords }] = await Promise.all(
[import("./dev-automation/instance-registry"), import("./dev-automation/stack-registry")],
);
const localStacks = readDevStackRecords().filter((stack) => isSameWorktree(stack, projectRoot));
const appInstances = readDevInstanceRecords().filter(
(instance) => resolve(instance.projectRoot) === resolve(projectRoot) && instance.service === "app",
);
runtime = {
stackRunning: localStacks.length > 0,
appRunning: appInstances.length === 1,
isolatedApp: appInstances.length === 1 && appInstances[0]?.instanceId !== "default",
orphanedStack: localStacks.some((stack) => isOrphanedDevStack(stack)),
ambiguousApp: appInstances.length > 1,
};
}
const isolatedApp = runtime.isolatedApp;
const reasons = readinessReasons(setup, runtime);
const plan = createVerificationCommandPlan(files, surfaces, setupReady, isolatedApp, projectRoot);
const qaReasons = qaReadinessReasons(surfaces, setupReady, runtime);
const qaRequired = surfaces.includes("renderer");
const report = {
ready: reasons.length === 0,
reasons,
setup,
changes: { files, surfaces, suggestedTests: plan.suggestedTests },
runtime,
qa: {
required: qaRequired,
ready: !qaRequired || qaReasons.length === 0,
reasons: qaReasons,
loop: qaRequired ? rendererQaLoop : [],
},
commands: plan.commands,
runnableCommands: plan.runnableCommands,
qaCommands: plan.qaCommands,
};
return { report, runnableCommandArgs: plan.runnableCommandArgs, setupReady };
}
export async function createDevVerificationReport(projectRoot = process.cwd()): Promise<DevVerificationReport> {
return (await createDevVerificationState(projectRoot)).report;
}
function runBun(projectRoot: string, args: string[]): void {
process.stderr.write(`dev:verify running: bun ${args.join(" ")}\n`);
const result = spawnSync(process.execPath, args, { cwd: projectRoot, stdio: "inherit" });
if (result.status !== 0) process.exit(result.status ?? 1);
}
function runRecommendedChecks(commandArgs: string[][], projectRoot: string): void {
for (const args of commandArgs) runBun(projectRoot, args);
}
const USAGE = [
"Usage: bun run dev:verify [--run]",
"",
"Prints a JSON verification plan for the uncommitted changes in this worktree.",
" --run Also run the safe checks in the plan that change nothing.",
].join("\n");
if (import.meta.main) {
const parsed = readScriptArguments({ usage: USAGE, options: { run: { type: "boolean" } } });
if (parsed !== null) {
const projectRoot = process.cwd();
const { report, runnableCommandArgs, setupReady } = await createDevVerificationState(projectRoot);
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
if (parsed.values.run && setupReady) runRecommendedChecks(runnableCommandArgs, projectRoot);
}
}