Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(e2e): phase 3 infra — schema-compat, trends, diff-scoping, stand job

Sergey Kozyrenko419c56317a44
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 50b53461..35dedcef 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -73,6 +73,23 @@ jobs:
retention-days: 7
if-no-files-found: ignore
+ - name: Append trend record
+ if: always()
+ working-directory: frontend
+ run: node e2e/tools/trend.mjs || true
+ env:
+ E2E_TREND_SHA: ${{ github.sha }}
+ E2E_TREND_REF: ${{ github.head_ref || github.ref_name }}
+
+ - name: Upload trend
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: e2e-trend
+ path: frontend/e2e/test-results/trend.jsonl
+ retention-days: 90
+ if-no-files-found: ignore
+
# Visual snapshots: pinned container = pixel-stable baselines. Advisory —
# never a required check.
e2e-visual:
@@ -161,3 +178,67 @@ jobs:
path: frontend/e2e/test-results
retention-days: 7
if-no-files-found: ignore
+
+ # Tier 3: real feature stand. Label-gated + a protected Environment whose
+ # required reviewers approve before any secret is exposed — even a mislabeled
+ # run blocks on a human. Fork PRs never reach it (they get Tier 1 only).
+ e2e-stand:
+ if: >
+ github.event_name == 'workflow_dispatch' ||
+ (github.event_name == 'pull_request' &&
+ contains(github.event.pull_request.labels.*.name, 'e2e:stand'))
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ environment: e2e-stand
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Install pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ package_json_file: frontend/package.json
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v6
+ with:
+ node-version-file: frontend/.nvmrc
+ cache: "pnpm"
+ cache-dependency-path: "frontend/pnpm-lock.yaml"
+
+ - name: Install dependencies
+ working-directory: frontend
+ run: pnpm install --frozen-lockfile
+
+ # Deploy-skew pre-flight: one readable failure instead of dozens of red
+ # specs when the stand's schema no longer satisfies the frontend contract.
+ - name: Schema-compat pre-flight
+ working-directory: frontend
+ run: node e2e/tools/schema-compat.mjs
+ env:
+ E2E_BASE_URL: ${{ secrets.E2E_STAND_URL }}
+ E2E_USER: ${{ secrets.E2E_STAND_USER }}
+ E2E_PASSWORD: ${{ secrets.E2E_STAND_PASSWORD }}
+
+ - name: Install Playwright browsers
+ working-directory: frontend
+ run: pnpm exec playwright install --with-deps chromium
+
+ - name: Run stand smoke
+ working-directory: frontend
+ run: E2E_TIER=stand npx playwright test -c e2e/playwright.config.ts --grep @smoke
+ env:
+ E2E_BASE_URL: ${{ secrets.E2E_STAND_URL }}
+ E2E_USER: ${{ secrets.E2E_STAND_USER }}
+ E2E_PASSWORD: ${{ secrets.E2E_STAND_PASSWORD }}
+
+ # Real-tier traces embed cookies and live payloads — keep them short-lived
+ # and never upload storageState.
+ - name: Upload report
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: e2e-stand-report
+ path: frontend/e2e/test-results
+ retention-days: 3
+ if-no-files-found: ignore
diff --git a/frontend/docs/e2e.md b/frontend/docs/e2e.md
index 71c39685..a4f95159 100644
--- a/frontend/docs/e2e.md
+++ b/frontend/docs/e2e.md
@@ -102,5 +102,56 @@ Key conventions:
production bundle strips app console output, so console-based asserts are
meaningless on the mock tier.
+## Stand tier (Tier 3)
+
+Runs the LLM-independent `@stand` smoke against a real deployment. Label a PR
+`e2e:stand` (or dispatch the workflow); the job runs in a protected
+`e2e-stand` Environment whose required reviewers approve before any secret is
+exposed, so even a mislabeled run blocks on a human. Fork PRs never reach it.
+
+Before the browser specs, a **schema-compat pre-flight**
+(`e2e/tools/schema-compat.mjs`) introspects the stand's live GraphQL schema and
+validates every frontend operation against it — a renamed or missing field
+fails once, readably, instead of as dozens of red specs (the deploy-skew class
+we hit manually). Run it anywhere: `E2E_BASE_URL=https://… node
+e2e/tools/schema-compat.mjs`.
+
+## Trends and selective runs
+
+- **Trend:** `node e2e/tools/trend.mjs` turns a run's `results.json` into one
+ JSONL record (p50/p95 spec duration, slowest three, pass/flaky/fail counts).
+ CI appends it to the retained `e2e-trend` artifact so duration creep and flake
+ are visible, not just green/red.
+- **Affected routes:** `pnpm exec tsx e2e/tools/affected.ts <base>` prints the
+ manifest routes a diff touches (backed by each route's owning `sources` in
+ `e2e/routes.ts`). Empty output = no frontend route changed. This is the
+ substrate for scoping runs and the exploratory agent to the changed surface;
+ the mapping logic is unit-tested (`e2e/affected-routes.unit.test.ts`).
+
+## LLM advisory layer (Phase 3, opt-in)
+
+Deterministic specs are the gate; an LLM is only ever an advisory second
+reviewer, **never** a merge gate. The intended stack is first-party, not a
+bespoke bot:
+
+1. `npx playwright init-agents --loop=claude` generates the planner / generator
+ / healer agent definitions; the connected **playwright-mcp** drives the
+ browser in accessibility-snapshot mode (a smaller prompt-injection surface
+ than raw DOM or vision).
+2. Scope the agent to the changed surface with `affected.ts` (the routes) — do
+ not hand it the whole app.
+3. Guardrails are mandatory because PentAGI renders adversarial content by
+ design (tool output, target responses): treat all page text as untrusted
+ data, never instructions; an action allowlist (no settings/token mutations,
+ no off-origin navigation) on real stands; throwaway scoped credentials; the
+ PR report renders page-derived strings as escaped, length-capped quotes;
+ screenshots posted publicly come only from mock/scripted tiers (a real
+ stand's api-tokens dialog shows a live secret); a hard per-run token cap.
+4. A generated spec merges only with its cassette (so it runs on the Tier-1
+ gate), a semantic-assertion review, and an `@generated` tag.
+
+This section is the recipe, not yet wired — the deterministic tiers above are
+the foundation it plugs into.
+
The full design (tiers, CI topology, mocking contract, roadmap) lives in the
team's E2E testing plan; scenario coverage maps 1:1 to the scenario catalog IDs.
diff --git a/frontend/e2e/affected-routes.ts b/frontend/e2e/affected-routes.ts
new file mode 100644
index 00000000..5e493bd0
--- /dev/null
+++ b/frontend/e2e/affected-routes.ts
@@ -0,0 +1,39 @@
+export interface RouteSource {
+ path: string;
+ sources: string[];
+}
+
+const owns = (dir: string, file: string): boolean => file === dir || file.startsWith(`${dir}/`);
+
+/**
+ * Maps a set of changed repo files to the manifest routes they touch, by
+ * prefix-matching each change against a route's owning source dirs. This is the
+ * substrate for selective runs and for scoping the exploratory agent to the
+ * changed surface. Pure — the CLI and the vitest unit test both drive it.
+ *
+ * - no frontend change → no routes (a backend-only diff; the caller falls back
+ * to the full suite, and schema-compat covers the backend contract);
+ * - a frontend change owned by no route → all routes (shared infra: the e2e
+ * engine, config, src/lib, a provider used everywhere) — conservative on
+ * purpose, since over-running is safe and under-running hides a regression;
+ * - otherwise → the routes whose `sources` the changes fall under.
+ *
+ * Paths are repo-relative (`frontend/...`); `sources` are `frontend/`-relative.
+ */
+export const affectedRoutes = (changedFiles: string[], manifest: RouteSource[]): RouteSource[] => {
+ const frontendChanges = changedFiles
+ .filter((file) => file.startsWith('frontend/'))
+ .map((file) => file.slice('frontend/'.length));
+
+ if (!frontendChanges.length) {
+ return [];
+ }
+
+ const isOwned = (file: string) => manifest.some((route) => route.sources.some((dir) => owns(dir, file)));
+
+ if (frontendChanges.some((file) => !isOwned(file))) {
+ return manifest;
+ }
+
+ return manifest.filter((route) => route.sources.some((dir) => frontendChanges.some((file) => owns(dir, file))));
+};
diff --git a/frontend/e2e/affected-routes.unit.test.ts b/frontend/e2e/affected-routes.unit.test.ts
new file mode 100644
index 00000000..217a94cd
--- /dev/null
+++ b/frontend/e2e/affected-routes.unit.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import type { RouteSource } from './affected-routes.ts';
+
+import { affectedRoutes } from './affected-routes.ts';
+
+const MANIFEST: RouteSource[] = [
+ { path: '/flows', sources: ['src/pages/flows', 'src/features/flows', 'src/providers/flows-provider.tsx'] },
+ { path: '/templates', sources: ['src/pages/templates', 'src/providers/templates-provider.tsx'] },
+ { path: '/settings/api-tokens', sources: ['src/pages/settings/settings-api-tokens.tsx'] },
+];
+
+describe('affectedRoutes', () => {
+ it('scopes to the routes owning the changed files', () => {
+ const result = affectedRoutes(['frontend/src/features/flows/flow-message.tsx'], MANIFEST);
+
+ expect(result.map((route) => route.path)).toEqual(['/flows']);
+ });
+
+ it('matches an exact-file source, not just a directory', () => {
+ const result = affectedRoutes(['frontend/src/pages/settings/settings-api-tokens.tsx'], MANIFEST);
+
+ expect(result.map((route) => route.path)).toEqual(['/settings/api-tokens']);
+ });
+
+ it('returns every route when shared infra changes', () => {
+ const result = affectedRoutes(['frontend/src/lib/apollo.ts'], MANIFEST);
+
+ expect(result).toHaveLength(MANIFEST.length);
+ });
+
+ it('returns every route when the e2e engine itself changes', () => {
+ const result = affectedRoutes(['frontend/e2e/mocks/world.ts'], MANIFEST);
+
+ expect(result).toHaveLength(MANIFEST.length);
+ });
+
+ it('ignores non-frontend changes', () => {
+ const result = affectedRoutes(['backend/pkg/server/router.go'], MANIFEST);
+
+ expect(result).toEqual([]);
+ });
+
+ it('collapses multiple changes in one route to a single entry', () => {
+ const result = affectedRoutes(
+ ['frontend/src/pages/flows/flow.tsx', 'frontend/src/features/flows/flow-form.tsx'],
+ MANIFEST,
+ );
+
+ expect(result.map((route) => route.path)).toEqual(['/flows']);
+ });
+});
diff --git a/frontend/e2e/specs/auth.setup.ts b/frontend/e2e/specs/auth.setup.ts
index ae3a5142..cfa2c1e1 100644
--- a/frontend/e2e/specs/auth.setup.ts
+++ b/frontend/e2e/specs/auth.setup.ts
@@ -6,6 +6,8 @@ const E2E_USER = process.env.E2E_USER ?? '[email protected]';
const E2E_PASSWORD = process.env.E2E_PASSWORD ?? 'admin';
setup('authenticate', async ({ page }) => {
+ // A real backend login + the websocket teardown can outrun the 30s default.
+ setup.setTimeout(90_000);
await page.goto('/login');
await page.getByLabel('Login').fill(E2E_USER);
await page.getByRole('textbox', { name: 'Password' }).fill(E2E_PASSWORD);
diff --git a/frontend/e2e/specs/real/stand-smoke.spec.ts b/frontend/e2e/specs/real/stand-smoke.spec.ts
new file mode 100644
index 00000000..4196cdfa
--- /dev/null
+++ b/frontend/e2e/specs/real/stand-smoke.spec.ts
@@ -0,0 +1,23 @@
+import { expect, test } from '@playwright/test';
+
+// LLM-independent integration smoke for a live backend (Tier 2 or a real
+// stand): the authenticated shell renders and each core route loads without an
+// uncaught error. No seeded data and no agent run — safe against a shared stand.
+const ROUTES = ['/flows', '/templates', '/knowledges', '/settings/prompts', '/settings/api-tokens'];
+
+test.describe('stand smoke', { tag: '@stand' }, () => {
+ for (const route of ROUTES) {
+ test(`renders ${route} without a page error`, async ({ page }) => {
+ const pageErrors: string[] = [];
+
+ page.on('pageerror', (error) => pageErrors.push(String(error)));
+
+ await page.goto(route);
+ // Staying on the route (not bounced to /login) proves the reused
+ // session authenticated — no dependency on the stand's username.
+ await expect(page).toHaveURL(new RegExp(route.replace(/\//g, '\\/')));
+ await expect(page.getByRole('link', { name: 'Templates' })).toBeVisible();
+ expect(pageErrors, `uncaught errors on ${route}`).toEqual([]);
+ });
+ }
+});
diff --git a/frontend/e2e/tools/affected.ts b/frontend/e2e/tools/affected.ts
new file mode 100644
index 00000000..f6c47420
--- /dev/null
+++ b/frontend/e2e/tools/affected.ts
@@ -0,0 +1,22 @@
+// Prints the routes touched by a diff — one path per line — for selective runs
+// and for scoping the exploratory agent. Empty output = no frontend route
+// changed (caller should run the full suite).
+//
+// Usage: pnpm exec tsx e2e/tools/affected.ts <base-ref> (default origin/main)
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+import { affectedRoutes } from '../affected-routes.ts';
+import { ROUTE_MANIFEST } from '../routes.ts';
+
+const base = process.argv[2] ?? 'origin/main';
+const repoRoot = fileURLToPath(new URL('../../..', import.meta.url));
+
+const changed = execFileSync('git', ['diff', '--name-only', `${base}...HEAD`], { cwd: repoRoot })
+ .toString()
+ .split('\n')
+ .filter(Boolean);
+
+for (const route of affectedRoutes(changed, ROUTE_MANIFEST)) {
+ console.log(route.path);
+}
diff --git a/frontend/e2e/tools/schema-compat.mjs b/frontend/e2e/tools/schema-compat.mjs
new file mode 100644
index 00000000..8606b5c8
--- /dev/null
+++ b/frontend/e2e/tools/schema-compat.mjs
@@ -0,0 +1,105 @@
+// Deploy-skew pre-flight for the stand tier: validates the frontend's persisted
+// GraphQL operations against the TARGET backend's live schema (fetched via
+// introspection), so a renamed/removed field fails in one readable step here
+// instead of as dozens of red specs. This is the RC-01/RC-02 class — a new
+// frontend field the deployed backend doesn't yet expose.
+//
+// Usage: node schema-compat.mjs
+// E2E_BASE_URL (required) e.g. https://localhost:8444
+// E2E_USER / E2E_PASSWORD (default [email protected] / admin)
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import {
+ buildClientSchema,
+ getIntrospectionQuery,
+ parse,
+ separateOperations,
+ validate,
+} from 'graphql';
+
+const BASE_URL = process.env.E2E_BASE_URL;
+const USER = process.env.E2E_USER ?? '[email protected]';
+const PASSWORD = process.env.E2E_PASSWORD ?? 'admin';
+
+if (!BASE_URL) {
+ console.error('schema-compat: E2E_BASE_URL is required');
+ process.exit(2);
+}
+
+// Node rejects the stack's self-signed cert otherwise; the target is trusted by
+// virtue of being the URL we were told to check.
+process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
+
+// Despite the name, this file holds the frontend's operations (named queries /
+// mutations / subscriptions + fragments), not a schema.
+const OPERATIONS_DOC = fileURLToPath(new URL('../../graphql-schema.graphql', import.meta.url));
+
+const login = async () => {
+ const response = await fetch(`${BASE_URL}/api/v1/auth/login`, {
+ body: JSON.stringify({ mail: USER, password: PASSWORD }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ throw new Error(`login failed: ${response.status}`);
+ }
+
+ const cookie = response.headers.get('set-cookie');
+
+ if (!cookie) {
+ throw new Error('login returned no session cookie');
+ }
+
+ return cookie.split(';')[0];
+};
+
+const introspect = async (cookie) => {
+ const response = await fetch(`${BASE_URL}/api/v1/graphql`, {
+ body: JSON.stringify({ query: getIntrospectionQuery() }),
+ headers: { 'content-type': 'application/json', cookie },
+ method: 'POST',
+ });
+ const { data, errors } = await response.json();
+
+ if (errors) {
+ throw new Error(`introspection failed: ${JSON.stringify(errors)}`);
+ }
+
+ return buildClientSchema(data);
+};
+
+const main = async () => {
+ const schema = await introspect(await login());
+ const document = parse(readFileSync(OPERATIONS_DOC, 'utf8'));
+ const operations = separateOperations(document);
+ const failures = [];
+
+ for (const [name, operation] of Object.entries(operations)) {
+ const errors = validate(schema, operation);
+
+ if (errors.length) {
+ failures.push({ errors: errors.map((error) => error.message), name });
+ }
+ }
+
+ if (failures.length) {
+ console.error(`schema-compat: ${failures.length} operation(s) incompatible with ${BASE_URL}\n`);
+
+ for (const { errors, name } of failures) {
+ console.error(` ✗ ${name}`);
+ errors.forEach((message) => console.error(` ${message}`));
+ }
+
+ console.error('\nThe deployed backend does not satisfy the frontend contract (deploy skew).');
+ process.exit(1);
+ }
+
+ console.log(`schema-compat: all ${Object.keys(operations).length} operations satisfied by ${BASE_URL}`);
+};
+
+main().catch((error) => {
+ console.error(`schema-compat: ${error.message}`);
+ process.exit(2);
+});
diff --git a/frontend/e2e/tools/trend.mjs b/frontend/e2e/tools/trend.mjs
new file mode 100644
index 00000000..50abf9bd
--- /dev/null
+++ b/frontend/e2e/tools/trend.mjs
@@ -0,0 +1,66 @@
+// Turns a Playwright JSON report into one trend record so a green/red gate also
+// surfaces slow regressions: duration p95, per-spec outliers, and flaky/failed
+// counts. Appends JSONL to the trend file (an artifact retained across runs).
+//
+// Usage: node trend.mjs [results.json] [trend.jsonl]
+// E2E_TREND_SHA / E2E_TREND_REF optional provenance stamped into the record
+import { appendFileSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const RESULTS = process.argv[2] ?? fileURLToPath(new URL('../test-results/results.json', import.meta.url));
+const TREND = process.argv[3] ?? fileURLToPath(new URL('../test-results/trend.jsonl', import.meta.url));
+
+const percentile = (values, p) => {
+ if (!values.length) {
+ return 0;
+ }
+
+ const sorted = [...values].sort((a, b) => a - b);
+ const index = Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1);
+
+ return sorted[index];
+};
+
+const collectSpecs = (report) => {
+ const specs = [];
+ const walk = (suite) => {
+ suite.suites?.forEach(walk);
+ suite.specs?.forEach((spec) => {
+ const ms = Math.max(0, ...(spec.tests ?? []).flatMap((test) => (test.results ?? []).map((r) => r.duration)));
+
+ specs.push({ ms, title: spec.title });
+ });
+ };
+
+ report.suites?.forEach(walk);
+
+ return specs;
+};
+
+const report = JSON.parse(readFileSync(RESULTS, 'utf8'));
+const specs = collectSpecs(report);
+const durations = specs.map((spec) => spec.ms);
+const { expected = 0, flaky = 0, skipped = 0, unexpected = 0 } = report.stats ?? {};
+
+const record = {
+ // A caller-provided timestamp keeps this pure (no Date.now in a determinism-
+ // sensitive tool); falls back to the report's own start time.
+ at: process.env.E2E_TREND_AT ?? report.stats?.startTime ?? '',
+ durationTotalMs: Math.round(report.stats?.duration ?? 0),
+ failed: unexpected,
+ flaky,
+ p50Ms: percentile(durations, 50),
+ p95Ms: percentile(durations, 95),
+ passed: expected,
+ ref: process.env.E2E_TREND_REF ?? '',
+ sha: process.env.E2E_TREND_SHA ?? '',
+ skipped,
+ slowest: [...specs].sort((a, b) => b.ms - a.ms).slice(0, 3),
+ specCount: specs.length,
+};
+
+appendFileSync(TREND, `${JSON.stringify(record)}\n`);
+console.log(
+ `trend: ${record.specCount} specs, p50 ${record.p50Ms}ms, p95 ${record.p95Ms}ms, ` +
+ `${record.passed} passed / ${record.failed} failed / ${record.flaky} flaky`,
+);
diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs
index 09aa9df5..bf04c8c3 100644
--- a/frontend/eslint.config.mjs
+++ b/frontend/eslint.config.mjs
@@ -95,7 +95,10 @@ const eslintConfig = [
perfectionist.configs['recommended-natural'],
{
...playwright.configs['flat/recommended'],
+ // *.unit.test.ts are vitest, not Playwright — the plugin's rules
+ // (no-standalone-expect) misfire on vitest's `it`.
files: ['e2e/**/*.ts'],
+ ignores: ['e2e/**/*.unit.test.ts'],
},
{
// Playwright fixtures take a `use` callback that the React hooks rule
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index 50419e71..4656d1aa 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -17,7 +17,9 @@ export default defineConfig({
test: {
environment: 'jsdom',
globals: false,
- include: ['src/**/*.{test,spec}.{ts,tsx}'],
+ // e2e/**/*.unit.test.ts = pure e2e-helper logic (no browser); Playwright
+ // specs are *.spec.ts and stay out of vitest.
+ include: ['src/**/*.{test,spec}.{ts,tsx}', 'e2e/**/*.unit.test.ts'],
setupFiles: ['./vitest.setup.ts'],
},
});