Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.
JavaScript agent-skillsai-agentsbrowser-agentbrowser-automationdecision-modeldeep-researchinstagramjevlinkedinlocal-firstopen-sourceosintresearch-agentsocaisocial-listeningsocial-mediasocial-media-researchsocmintsystem-onetiktok
feat: add reproducible benchmark runner (#48)
Asklvfd66f00c488e
diff --git a/benchmark/README.md b/benchmark/README.mdindex da445bc..536b744 100644--- a/benchmark/README.md+++ b/benchmark/README.md@@ -1,6 +1,60 @@-# Benchmark row contract+# Reproducible benchmark-`schema.js` validates one privacy-safe row for the reproducible live benchmark proposed in [#32](https://github.com/socai-io/jev-social/issues/32). It does not run a browser, call Jev, or collect live measurements.+The benchmark tools implement the collection and aggregation protocol tracked in [#24](https://github.com/socai-io/jev-social/issues/24). The strict row contract was delivered in [#32](https://github.com/socai-io/jev-social/issues/32). No live measurements or performance claims are included in the repository yet.++Three fixed public-research tasks live under `benchmark/tasks/`: one each for Instagram, TikTok, and LinkedIn. Do not edit a task between repetitions. Create a new task ID when the goal, result limit, or step budget changes.++## Collect a run++Use a compatible `socai CLI`, an accessible browser profile, and either OpenRouter Jev or an explicit loopback System One endpoint. Pin the exact values recorded in the row:++```bash+npm run --silent benchmark:run -- \+ --task benchmark/tasks/instagram.json \+ --jev-model typesafe/jev-1.13-20260917 \+ --socai-version 0.6.0 \+ --socai-commit 0123456789abcdef0123456789abcdef01234567 \+ --profile-mode existing \+ --region cn-east \+ --condition cold >> benchmark-rows.ndjson+```++The command writes exactly one validated NDJSON row to stdout. Stage names go to stderr. It never writes the goal, evidence text, source URLs, local paths, browser endpoints, account identifiers, or credentials into a row. Runtime failures and partial runs remain in the dataset.++An installed package also exposes the same collector as `jev-social-benchmark`. `SIGINT` and `SIGTERM` stop the active operation through its abort signal and preserve an `interrupted` row before the process exits.++Run each exact task/environment group at least ten times. A shell loop is acceptable because each invocation emits one row:++```bash+for run in $(seq 1 10); do+ npm run --silent benchmark:run -- \+ --task benchmark/tasks/instagram.json \+ --jev-model typesafe/jev-1.13-20260917 \+ --socai-version 0.6.0 \+ --socai-commit 0123456789abcdef0123456789abcdef01234567 \+ --profile-mode existing \+ --region cn-east \+ --condition warm >> benchmark-rows.ndjson+done+```++`cold` means the first run after restarting the browser/CLI research session and clearing only documented application caches. `warm` means an immediate repeat in the same browser profile without clearing caches. Never clear browser cookies, login state, or personal data for this benchmark. Record a stable, non-identifying region label and describe its meaning beside any published dataset.++The runner requires `socai --version` to return the declared version and requires every successful decision response to report the immutable model supplied by `--jev-model`. Floating aliases such as `jev-latest` and `kev-latest` are rejected. Build or install `socai` from the declared commit before collecting; current CLI metadata does not expose a verifiable build commit, so the operator remains responsible for that pin. `--profile-mode` records the browser setup used for the run; it does not create or modify a browser profile.++Jev and browser-operation component timers use a monotonic clock, including failed attempts. For TikTok, `timing_ms.media` is the full elapsed time of each `socai` operation that requested a download. It can overlap `timing_ms.socai_browser` and is an upper bound on download-only work. Media counts and bytes include only recognized media files tied to the explicit download target and resolved below configured `socai` run roots; paths never enter the row.++## Generate the summary++```bash+npm run --silent benchmark:summarize -- --input benchmark-rows.ndjson > benchmark-summary.md+```++The generator validates every row before aggregation, rejects duplicate run IDs, groups only exact task and environment matches, uses nearest-rank p50/p95, and reports success, partial, failed, failure rate, evidence coverage, and non-success reasons. A summary is `READY` only when every included group has at least ten distinct rows. Invalid rows fail the command instead of disappearing.++## Row contract++`schema.js` validates one privacy-safe row:```jsimport { validateBenchmarkRow } from "jev-social/benchmark/schema";@@ -28,4 +82,4 @@ Use these stable terminal mappings:Successful rows use `goal_satisfied` with a null failure category.-Use `fixtures/valid-row.json` only as synthetic test data. Live collection, aggregation, the coverage rubric, and publication of benchmark results remain tracked in #32.+Use `fixtures/valid-row.json` only as synthetic test data. Publishing live rows and a dated comparison table still requires the full coverage and review gate in #24.diff --git a/benchmark/run.js b/benchmark/run.jsnew file mode 100644index 0000000..9abc9cd--- /dev/null+++ b/benchmark/run.js@@ -0,0 +1,600 @@+#!/usr/bin/env node++import crypto from "node:crypto";+import { performance } from "node:perf_hooks";+import { mkdtemp, readFile, realpath, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { pathToFileURL } from "node:url";++import { sourceUrl } from "../src/actions.js";+import { getPrivateRunMedia, runSearch } from "../src/app.js";+import { readConfig, resolveApiKey } from "../src/config.js";+import { loadLocalEnv } from "../src/env.js";+import { listRuns, readRun } from "../src/runs.js";+import { probeSocai } from "../src/socai.js";+import {+ BENCHMARK_CONDITIONS,+ BENCHMARK_PLATFORMS,+ BENCHMARK_PROFILE_MODES,+ validateBenchmarkRow,+} from "./schema.js";++const TASK_FIELDS = new Set(["task_id", "platform", "goal", "result_limit", "max_steps"]);+const MAX_TASK_BYTES = 16 * 1024;+const MEDIA_EXTENSIONS = new Set([+ ".avif", ".gif", ".jpeg", ".jpg", ".m4v", ".mov", ".mp4", ".png", ".webm", ".webp",+]);+const FLOATING_MODEL = /(?:^~|(?:^|[/_.-])latest(?=$|[:/_.-]))/i;++const HELP = `jev-social benchmark runner++Usage:+ node benchmark/run.js --task <file> --jev-model <id> --socai-version <semver> \\+ --socai-commit <sha> --profile-mode <existing|isolated> --region <id> \\+ --condition <cold|warm>++The command writes exactly one validated, privacy-safe NDJSON row to stdout.+Progress stages go to stderr. Runtime failures are retained as failed or partial+rows instead of being silently dropped.+`;++const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);++const requiredString = (value, name, { max = 512, pattern } = {}) => {+ if (typeof value !== "string") throw new TypeError(`${name} must be a string`);+ const cleaned = value.trim();+ if (!cleaned || cleaned.length > max || /[\u0000-\u001f\u007f]/.test(cleaned)) {+ throw new TypeError(`${name} has an invalid format`);+ }+ if (pattern && !pattern.test(cleaned)) throw new TypeError(`${name} has an invalid format`);+ return cleaned;+};++const requiredInteger = (value, name, min, max) => {+ if (!Number.isSafeInteger(value) || value < min || value > max) {+ throw new TypeError(`${name} must be an integer from ${min} to ${max}`);+ }+ return value;+};++const pinnedModel = (value) => {+ const model = requiredString(value, "jev_model", { max: 128 });+ if (FLOATING_MODEL.test(model)) {+ throw new TypeError("jev_model must be an immutable model identifier, not a latest alias");+ }+ return model;+};++export function validateBenchmarkTask(value) {+ if (!isRecord(value)) throw new TypeError("benchmark task must be an object");+ for (const key of Object.keys(value)) {+ if (!TASK_FIELDS.has(key)) throw new TypeError(`${key}: unknown field`);+ }+ for (const key of TASK_FIELDS) {+ if (!Object.hasOwn(value, key)) throw new TypeError(`${key}: field is required`);+ }+ const taskId = requiredString(value.task_id, "task_id", {+ max: 36,+ pattern: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,+ }).toLowerCase();+ if (!BENCHMARK_PLATFORMS.includes(value.platform)) {+ throw new TypeError(`platform must be one of: ${BENCHMARK_PLATFORMS.join(", ")}`);+ }+ return {+ task_id: taskId,+ platform: value.platform,+ goal: requiredString(value.goal, "goal"),+ result_limit: requiredInteger(value.result_limit, "result_limit", 1, 100),+ max_steps: requiredInteger(value.max_steps, "max_steps", 1, 30),+ };+}++const numericDuration = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;++const publicItems = (run) => Array.isArray(run?.result?.items) ? run.result.items : [];++const commentCount = (items) => items.reduce((total, item) => {+ const comments = Array.isArray(item?.top_comments)+ ? item.top_comments+ : Array.isArray(item?.comments)+ ? item.comments+ : [];+ return total + comments.length;+}, 0);++const runtimeCode = (run, error) => {+ if (typeof error?.code === "string") return error.code;+ if (typeof error?.name === "string" && /abort|interrupt/i.test(error.name)) return error.name;+ const failed = [...(run?.actions || [])].reverse().find((entry) => entry?.status === "failed");+ return typeof failed?.observation?.code === "string" ? failed.observation.code : "";+};++const terminalState = (run, error, records) => {+ const status = run?.status;+ const text = String(run?.stopReason || "").toLowerCase();+ const code = runtimeCode(run, error).toUpperCase();+ let stopReason;++ if (!error && status === "completed" && records > 0) stopReason = "goal_satisfied";+ else if (status === "step_limit") stopReason = "step_limit";+ else if (status === "interrupted" || /ABORT|INTERRUPT/.test(code)) {+ stopReason = "interrupted";+ }+ else if (+ status === "decision_failed"+ || /JEV|DECISION|CLASSIFICATION|ONBOARDING|UNSUPPORTED_TASK|LOW_ACTION|MODEL_PIN/.test(code)+ ) {+ stopReason = "decision_failed";+ } else if (/login_required|\blogin\b|sign.?in/.test(text)) {+ stopReason = "login_required";+ } else if (/challenge_required|captcha|challenge/.test(text)) {+ stopReason = "challenge_required";+ } else if (/rate_limited|rate.?limit/.test(text)) {+ stopReason = "rate_limited";+ } else if (run?.reportStatus === "failed" || /REPORT/.test(code)) {+ stopReason = "report_failed";+ } else if (/VIDEO_CAPABILITY|MEDIA/.test(code)) {+ stopReason = "media_unavailable";+ } else if (/^(?:BROWSER_|REMOTE_SESSION_)/.test(code)) {+ stopReason = "browser_unavailable";+ } else if (/SOCAI_VERSION_|CAPABILITY|NOT_FOUND/.test(code)) {+ stopReason = "capability_unavailable";+ } else if (+ /TIMEOUT|SOCAI_FAILED|SOCAI_OUTPUT_TOO_LARGE|(?:EMPTY|INVALID)_SOCAI_OUTPUT|CLI/.test(code)+ ) {+ stopReason = "cli_failed";+ } else if (/NETWORK|FETCH/.test(code)) {+ stopReason = "network_error";+ } else if (records === 0 && run) {+ stopReason = "empty_results";+ } else {+ stopReason = "unknown";+ }++ const failureCategory = {+ step_limit: "step_limit",+ login_required: "access_gate",+ challenge_required: "access_gate",+ rate_limited: "access_gate",+ empty_results: "empty_results",+ capability_unavailable: "unavailable",+ browser_unavailable: "unavailable",+ media_unavailable: "unavailable",+ decision_failed: "execution_error",+ cli_failed: "execution_error",+ network_error: "execution_error",+ report_failed: "execution_error",+ interrupted: "interrupted",+ unknown: "unknown",+ }[stopReason];++ return {+ outcome: stopReason === "goal_satisfied" ? "success" : records > 0 ? "partial" : "failed",+ stopReason,+ failureCategory: stopReason === "goal_satisfied" ? null : failureCategory,+ };+};++const decisionTimings = (run, expectedModel, error) => {+ const decisions = [+ run?.classification && {+ model: run?.classification.model,+ modelVerified: run?.classification.modelVerified,+ elapsedMs: run?.classification.elapsedMs,+ },+ ...(Array.isArray(run?.actions)+ ? run.actions.map((entry) => ({+ model: entry?.model,+ modelVerified: entry?.modelVerified,+ elapsedMs: entry?.jevElapsedMs,+ }))+ : []),+ ...(Array.isArray(run?.decisionFailures)+ ? run.decisionFailures.map((entry) => ({ ...entry, failed: true }))+ : []),+ ...(!run?.decisionFailures?.length && Number.isSafeInteger(error?.details?.elapsedMs)+ ? [{+ model: error.details.model,+ modelVerified: error.details.modelVerified,+ elapsedMs: error.details.elapsedMs,+ failed: true,+ }]+ : []),+ ]+ .filter((entry) => entry && Number.isSafeInteger(entry.elapsedMs))+ .map((entry) => ({+ model: entry.model,+ modelVerified: entry.modelVerified,+ failed: Boolean(entry.failed),+ elapsedMs: numericDuration(entry.elapsedMs),+ }));+ for (const decision of decisions) {+ if (decision.model && decision.model !== expectedModel) {+ const mismatch = new TypeError("resolved decision model does not match the declared benchmark pin");+ mismatch.code = "MODEL_PIN_MISMATCH";+ throw mismatch;+ }+ if (!decision.failed && decision.modelVerified === false) {+ const unverified = new TypeError("decision provider did not report the resolved model");+ unverified.code = "MODEL_PIN_UNVERIFIED";+ throw unverified;+ }+ }+ return decisions.map(({ elapsedMs }) => elapsedMs);+};++const retainMeasuredRunForPinFailure = (run, expectedModel) => {+ if (!run) return undefined;+ const normalizeDecision = (entry, elapsedKey) => {+ if (!entry || !Number.isSafeInteger(entry[elapsedKey])) return entry;+ return { ...entry, model: expectedModel, modelVerified: true };+ };+ return {+ ...run,+ classification: normalizeDecision(run.classification, "elapsedMs"),+ actions: Array.isArray(run.actions)+ ? run.actions.map((entry) => normalizeDecision(entry, "jevElapsedMs"))+ : run.actions,+ decisionFailures: Array.isArray(run.decisionFailures)+ ? run.decisionFailures.map((entry) => normalizeDecision(entry, "elapsedMs"))+ : run.decisionFailures,+ };+};++export function buildBenchmarkRow({+ task: taskInput,+ metadata,+ run,+ error,+ startedAt,+ endedAt,+ totalMs,+ runId = crypto.randomUUID(),+ media = { count: 0, bytes: 0 },+}) {+ const task = validateBenchmarkTask(taskInput);+ const model = pinnedModel(metadata?.jev_model);+ const items = publicItems(run);+ const terminal = terminalState(run, error, items.length);+ const jevSteps = decisionTimings(run, model, error);+ const actions = Array.isArray(run?.actions) ? run.actions : [];+ const socaiBrowserMs = actions.reduce(+ (sum, entry) => sum + numericDuration(entry?.elapsedMs),+ 0,+ );+ const mediaMs = actions.reduce(+ (sum, entry) => sum + (entry?.action?.downloadMedia ? numericDuration(entry?.elapsedMs) : 0),+ 0,+ );++ return validateBenchmarkRow({+ schema_version: 1,+ run_id: runId,+ task_id: task.task_id,+ started_at: startedAt,+ ended_at: endedAt,+ platform: task.platform,+ outcome: terminal.outcome,+ jev_model: model,+ socai_version: metadata?.socai_version,+ socai_commit: metadata?.socai_commit,+ result_limit: task.result_limit,+ max_steps: task.max_steps,+ profile_mode: metadata?.profile_mode,+ region: metadata?.region,+ condition: metadata?.condition,+ jev_step_latency_ms: jevSteps,+ timing_ms: {+ jev_total: jevSteps.reduce((sum, duration) => sum + duration, 0),+ socai_browser: socaiBrowserMs,+ media: mediaMs,+ total: Math.round(totalMs),+ },+ evidence: {+ records: items.length,+ comments: commentCount(items),+ downloaded_media_count: Number.isSafeInteger(media?.count) ? media.count : 0,+ downloaded_media_bytes: Number.isSafeInteger(media?.bytes) ? media.bytes : 0,+ },+ stop_reason: terminal.stopReason,+ failure_category: terminal.failureCategory,+ });+}++const collectLocalPaths = (value, output = []) => {+ if (Array.isArray(value)) {+ for (const child of value) collectLocalPaths(child, output);+ return output;+ }+ if (!isRecord(value)) return output;+ for (const [key, child] of Object.entries(value)) {+ if (/(?:^|_)local_path$/i.test(key) && typeof child === "string") output.push(child);+ else collectLocalPaths(child, output);+ }+ return output;+};++const allowedMediaRoots = async (env) => {+ const candidates = [+ env.SOCAI_RUNS_DIR,+ env.SOCAI_HOME && path.join(env.SOCAI_HOME, "runs"),+ path.join(env.HOME || os.homedir(), ".socai", "runs"),+ ].filter(Boolean);+ return Promise.all(candidates.map(async (candidate) =>+ realpath(candidate).catch(() => path.resolve(candidate)),+ ));+};++async function collectVerifiedMedia(items, { env = process.env } = {}) {+ const roots = await allowedMediaRoots(env);+ const files = new Map();+ for (const candidate of collectLocalPaths(items)) {+ try {+ const resolved = await realpath(candidate);+ if (!roots.some((root) => resolved === root || resolved.startsWith(`${root}${path.sep}`))) continue;+ if (!MEDIA_EXTENSIONS.has(path.extname(resolved).toLowerCase())) continue;+ const metadata = await stat(resolved);+ if (!metadata.isFile() || metadata.size <= 0) continue;+ files.set(`${metadata.dev}:${metadata.ino}`, metadata.size);+ } catch {+ // Missing, unreadable, and out-of-scope media remain zero-coverage evidence.+ }+ }+ return {+ count: files.size,+ bytes: [...files.values()].reduce((sum, size) => sum + size, 0),+ };+}++const evidenceSource = (item, platform) => sourceUrl(+ item?.url || item?.web_url || item?.share_url || item?.locator,+ platform,+);++export async function collectDownloadedMedia(run, items, { env = process.env } = {}) {+ if (run?.platform !== "tiktok" || !Array.isArray(items)) return { count: 0, bytes: 0 };+ const targets = new Set((run.actions || [])+ .filter((entry) => entry?.action?.downloadMedia === true)+ .map((entry) => sourceUrl(entry.action.target, "tiktok"))+ .filter(Boolean));+ if (!targets.size) return { count: 0, bytes: 0 };+ return collectVerifiedMedia(+ items.filter((item) => targets.has(evidenceSource(item, "tiktok"))),+ { env },+ );+}++const parseArgs = (args) => {+ const result = {};+ const names = new Map([+ ["--task", "task"],+ ["--jev-model", "jev_model"],+ ["--socai-version", "socai_version"],+ ["--socai-commit", "socai_commit"],+ ["--profile-mode", "profile_mode"],+ ["--region", "region"],+ ["--condition", "condition"],+ ]);+ for (let index = 0; index < args.length; index += 1) {+ const token = args[index];+ if (token === "--help" || token === "-h") return { help: true };+ const name = names.get(token);+ if (!name) throw new TypeError(`unknown option: ${token}`);+ const value = args[index + 1];+ if (!value || value.startsWith("--")) throw new TypeError(`${token} requires a value`);+ if (Object.hasOwn(result, name)) throw new TypeError(`${token} may be provided only once`);+ result[name] = value;+ index += 1;+ }+ for (const name of names.values()) {+ if (!result[name]) throw new TypeError(`--${name.replaceAll("_", "-")} is required`);+ }+ if (!BENCHMARK_PROFILE_MODES.includes(result.profile_mode)) {+ throw new TypeError("--profile-mode must be existing or isolated");+ }+ if (!BENCHMARK_CONDITIONS.includes(result.condition)) {+ throw new TypeError("--condition must be cold or warm");+ }+ return result;+};++const loadTaskFile = async (filename) => {+ try {+ const metadata = await stat(filename);+ if (!metadata.isFile() || metadata.size > MAX_TASK_BYTES) throw new Error();+ return validateBenchmarkTask(JSON.parse(await readFile(filename, "utf8")));+ } catch {+ throw new TypeError("could not read a valid benchmark task file");+ }+};++const codedError = (code) => Object.assign(new Error(code), { code });++const defaultDependencies = () => ({+ env: process.env,+ loadLocalEnv,+ loadTaskFile,+ readConfig,+ createStateDir: (prefix) => mkdtemp(prefix),+ removeStateDir: (directory) => rm(directory, { recursive: true, force: true }),+ probeSocai,+ runSearch,+ listRuns,+ readRun,+ getPrivateRunMedia,+ collectDownloadedMedia,+});++export async function executeBenchmark(+ args,+ { signal, onStage = () => {}, dependencies = {} } = {},+) {+ const runtime = { ...defaultDependencies(), ...dependencies };+ const baseEnv = { ...runtime.env };+ await runtime.loadLocalEnv(baseEnv);+ const task = validateBenchmarkTask(await runtime.loadTaskFile(args.task));+ const validationTimestamp = new Date().toISOString();+ const validatedMetadata = buildBenchmarkRow({+ task,+ metadata: args,+ error: { code: "BENCHMARK_METADATA_VALIDATION" },+ startedAt: validationTimestamp,+ endedAt: validationTimestamp,+ totalMs: 0,+ });+ const metadata = {+ jev_model: validatedMetadata.jev_model,+ socai_version: validatedMetadata.socai_version,+ socai_commit: validatedMetadata.socai_commit,+ profile_mode: validatedMetadata.profile_mode,+ region: validatedMetadata.region,+ condition: validatedMetadata.condition,+ };+ const originalConfig = await runtime.readConfig(baseEnv);+ const isolatedHome = await runtime.createStateDir(path.join(os.tmpdir(), "jev-social-benchmark-"));+ const env = {+ ...baseEnv,+ JEV_SOCIAL_HOME: isolatedHome,+ OPENROUTER_REPORT_MODEL: "off",+ ...(originalConfig.socaiBin && !baseEnv.SOCAI_BIN+ ? { SOCAI_BIN: originalConfig.socaiBin }+ : {}),+ ...(resolveApiKey(originalConfig, baseEnv) && !baseEnv.OPENROUTER_API_KEY+ ? { OPENROUTER_API_KEY: resolveApiKey(originalConfig, baseEnv) }+ : {}),+ };+ if (env.JEV_SOCIAL_SYSTEM_ONE_URL?.trim()) {+ env.JEV_SOCIAL_SYSTEM_ONE_MODEL = metadata.jev_model;+ } else {+ env.OPENROUTER_JEV_MODEL = metadata.jev_model;+ }++ const startedWallMs = Date.now();+ const startedMonoMs = performance.now();+ let run;+ let error;+ let media = { count: 0, bytes: 0 };+ let lastStage;+ const emitStage = (stage) => {+ const label = String(stage || "");+ if (!/^[a-z][a-z0-9_]{0,31}$/.test(label) || label === lastStage) return;+ lastStage = label;+ onStage(label);+ };++ try {+ try {+ const probe = await runtime.probeSocai({}, env, signal);+ if (!probe.version) throw codedError("SOCAI_VERSION_UNVERIFIABLE");+ if (probe.version !== metadata.socai_version) throw codedError("SOCAI_VERSION_MISMATCH");+ run = await runtime.runSearch(+ {+ query: task.goal,+ platform: task.platform,+ limit: task.result_limit,+ maxSteps: task.max_steps,+ },+ {+ env,+ signal,+ reportChunkDelayMs: 0,+ onEvent(event) {+ emitStage(event.stage);+ },+ },+ );+ } catch (caught) {+ error = caught;+ try {+ const [latest] = await runtime.listRuns(env);+ if (latest) run = await runtime.readRun(latest.id, env);+ } catch {+ emitStage("recovery_failed");+ }+ }+ try {+ const privateItems = run ? runtime.getPrivateRunMedia(run)?.downloadItems : undefined;+ if (privateItems) media = await runtime.collectDownloadedMedia(run, privateItems, { env });+ } catch {+ error ||= codedError("BENCHMARK_MEDIA_COLLECTION_FAILED");+ emitStage("media_verification_failed");+ }++ const totalMs = Math.max(0, Math.round(performance.now() - startedMonoMs));+ const rowInput = {+ task,+ metadata,+ run,+ error,+ startedAt: new Date(startedWallMs).toISOString(),+ endedAt: new Date(Date.now()).toISOString(),+ totalMs,+ media,+ };+ try {+ return buildBenchmarkRow(rowInput);+ } catch (rowError) {+ emitStage("row_invalid");+ const pinFailure = /^MODEL_PIN_(?:MISMATCH|UNVERIFIED)$/.test(String(rowError?.code || ""));+ return buildBenchmarkRow({+ ...rowInput,+ run: pinFailure ? retainMeasuredRunForPinFailure(run, metadata.jev_model) : undefined,+ media: pinFailure ? media : { count: 0, bytes: 0 },+ error: codedError(rowError?.code || "BENCHMARK_ROW_INVALID"),+ });+ }+ } finally {+ try {+ await runtime.removeStateDir(isolatedHome);+ } catch {+ emitStage("cleanup_failed");+ }+ }+}++export async function runBenchmarkCli(+ argv,+ {+ stdout = process.stdout,+ stderr = process.stderr,+ signal,+ dependencies,+ } = {},+) {+ try {+ const args = parseArgs(argv);+ if (args.help) {+ stdout.write(HELP);+ return { exitCode: 0 };+ }+ const row = await executeBenchmark(args, {+ signal,+ dependencies,+ onStage: (stage) => stderr.write(`[benchmark] ${stage}\n`),+ });+ stdout.write(`${JSON.stringify(row)}\n`);+ return { exitCode: 0, row };+ } catch {+ stderr.write("[benchmark] invalid_input\n");+ return { exitCode: 1 };+ }+}++async function main() {+ const controller = new AbortController();+ const interrupt = () => controller.abort();+ process.once("SIGINT", interrupt);+ process.once("SIGTERM", interrupt);+ try {+ const result = await runBenchmarkCli(process.argv.slice(2), { signal: controller.signal });+ process.exitCode = result.exitCode;+ } finally {+ process.removeListener("SIGINT", interrupt);+ process.removeListener("SIGTERM", interrupt);+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {+ await main();+}diff --git a/benchmark/schema.js b/benchmark/schema.jsindex 250aec8..1f3e11f 100644--- a/benchmark/schema.js+++ b/benchmark/schema.js@@ -306,6 +306,14 @@ export const validateBenchmarkRow = (value) => {max: 40,pattern: /^[a-f0-9]{7,40}$/i,}).toLowerCase();+ const jevModel = cleanString(value.jev_model, "jev_model", {+ max: 128,+ pattern:+ /^~?[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}(?::[A-Za-z0-9][A-Za-z0-9._-]*)?$/,+ });+ if (/(?:^~|(?:^|[/_.-])latest(?=$|[:/_.-]))/i.test(jevModel)) {+ fail("jev_model", "must be an immutable model identifier, not a latest alias");+ }return {schema_version: integer(value.schema_version, "schema_version", { min: 1, max: 1 }),@@ -315,11 +323,7 @@ export const validateBenchmarkRow = (value) => {ended_at: endedAt,platform,outcome,- jev_model: cleanString(value.jev_model, "jev_model", {- max: 128,- pattern:- /^~?[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}(?::[A-Za-z0-9][A-Za-z0-9._-]*)?$/,- }),+ jev_model: jevModel,socai_version: socaiVersion,socai_commit: socaiCommit,result_limit: integer(value.result_limit, "result_limit", { min: 1, max: 100 }),diff --git a/benchmark/summary.js b/benchmark/summary.jsnew file mode 100644index 0000000..c1dcdde--- /dev/null+++ b/benchmark/summary.js@@ -0,0 +1,199 @@+#!/usr/bin/env node++import { readFile, stat } from "node:fs/promises";+import path from "node:path";+import { pathToFileURL } from "node:url";++import { validateBenchmarkRow } from "./schema.js";++const MINIMUM_RUNS = 10;+const MAX_INPUT_BYTES = 16 * 1024 * 1024;+const MAX_ROWS = 10_000;+const GROUP_FIELDS = [+ "task_id",+ "platform",+ "jev_model",+ "socai_version",+ "socai_commit",+ "result_limit",+ "max_steps",+ "profile_mode",+ "region",+ "condition",+];++const percentile = (values, fraction) => {+ const sorted = [...values].sort((left, right) => left - right);+ if (!sorted.length) return 0;+ return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)];+};++const metric = (rows, select) => {+ const values = rows.map(select);+ return { p50: percentile(values, 0.5), p95: percentile(values, 0.95) };+};++const groupIdentity = (row) => Object.fromEntries(GROUP_FIELDS.map((field) => [field, row[field]]));+const groupKey = (row) => JSON.stringify(groupIdentity(row));++export function summarizeBenchmarkRows(inputRows) {+ if (!Array.isArray(inputRows) || inputRows.length === 0) {+ throw new TypeError("at least one benchmark row is required");+ }+ if (inputRows.length > MAX_ROWS) throw new TypeError(`benchmark input exceeds ${MAX_ROWS} rows`);+ const rows = inputRows.map(validateBenchmarkRow);+ const runIds = new Set();+ for (const row of rows) {+ if (runIds.has(row.run_id)) throw new TypeError(`duplicate run_id: ${row.run_id}`);+ runIds.add(row.run_id);+ }+ const grouped = new Map();+ for (const row of rows) {+ const key = groupKey(row);+ if (!grouped.has(key)) grouped.set(key, []);+ grouped.get(key).push(row);+ }++ const groups = [...grouped.entries()]+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([, entries], index) => {+ const outcomes = { success: 0, partial: 0, failed: 0 };+ const stopReasons = {};+ for (const row of entries) {+ outcomes[row.outcome] += 1;+ if (row.stop_reason !== "goal_satisfied") {+ stopReasons[row.stop_reason] = (stopReasons[row.stop_reason] || 0) + 1;+ }+ }+ return {+ id: `G${index + 1}`,+ ...groupIdentity(entries[0]),+ runs: entries.length,+ publicationStatus: entries.length >= MINIMUM_RUNS+ ? "READY"+ : `INCOMPLETE (${entries.length}/${MINIMUM_RUNS})`,+ startedAt: entries.map((row) => row.started_at).sort()[0],+ endedAt: entries.map((row) => row.ended_at).sort().at(-1),+ outcomes,+ failureRatePercent: (outcomes.failed / entries.length) * 100,+ stopReasons: Object.fromEntries(Object.entries(stopReasons).sort(([left], [right]) =>+ left.localeCompare(right),+ )),+ metrics: {+ total: metric(entries, (row) => row.timing_ms.total),+ jev: metric(entries, (row) => row.timing_ms.jev_total),+ socaiBrowser: metric(entries, (row) => row.timing_ms.socai_browser),+ media: metric(entries, (row) => row.timing_ms.media),+ records: metric(entries, (row) => row.evidence.records),+ comments: metric(entries, (row) => row.evidence.comments),+ downloadedMedia: metric(entries, (row) => row.evidence.downloaded_media_count),+ },+ };+ });++ return {+ schemaVersion: 1,+ minimumRuns: MINIMUM_RUNS,+ rowCount: rows.length,+ publicationReady: groups.every((group) => group.runs >= MINIMUM_RUNS),+ groups,+ };+}++const number = (value) => new Intl.NumberFormat("en-US").format(value);+const pair = ({ p50, p95 }) => `${number(p50)} / ${number(p95)}`;+const shortCommit = (value) => value.slice(0, 12);++export function renderBenchmarkSummary(summary) {+ const lines = [+ "# Jev Social benchmark summary",+ "",+ `Publication gate: ${summary.publicationReady ? "READY" : "INCOMPLETE"}`,+ "",+ `Validated rows: ${number(summary.rowCount)}. Each exact task and environment group needs at least ${summary.minimumRuns} rows before publication. All terminal outcomes are included; failures and partial runs are never dropped.`,+ "",+ "Timing percentiles use the nearest-rank method across every row in the group. Media-op time is the full socai operation that requested a download, so it may overlap socai/browser time and is an upper bound on download-only work.",+ "",+ "## Results",+ "",+ "| Group | Platform | Condition | Runs | Success / partial / failed | Failure rate | Total ms p50 / p95 | Jev ms p50 / p95 | socai/browser ms p50 / p95 | Media-op ms p50 / p95 | Records p50 / p95 | Comments p50 / p95 | Media count p50 / p95 |",+ "| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",+ ];+ for (const group of summary.groups) {+ lines.push(`| ${group.id} | ${group.platform} | ${group.condition} | ${group.runs} | ${group.outcomes.success} / ${group.outcomes.partial} / ${group.outcomes.failed} | ${group.failureRatePercent.toFixed(1)}% | ${pair(group.metrics.total)} | ${pair(group.metrics.jev)} | ${pair(group.metrics.socaiBrowser)} | ${pair(group.metrics.media)} | ${pair(group.metrics.records)} | ${pair(group.metrics.comments)} | ${pair(group.metrics.downloadedMedia)} |`);+ }++ lines.push(+ "",+ "## Environment",+ "",+ "| Group | Task ID | Jev model | socai | Profile | Region | Limit / steps | Date window (UTC) | Status |",+ "| --- | --- | --- | --- | --- | --- | ---: | --- | --- |",+ );+ for (const group of summary.groups) {+ lines.push(`| ${group.id} | ${group.task_id} | ${group.jev_model} | ${group.socai_version} @ ${shortCommit(group.socai_commit)} | ${group.profile_mode} | ${group.region} | ${group.result_limit} / ${group.max_steps} | ${group.startedAt} – ${group.endedAt} | ${group.publicationStatus} |`);+ }++ lines.push(+ "",+ "## Non-success outcomes",+ "",+ "| Group | Stop reason | Count |",+ "| --- | --- | ---: |",+ );+ let failureRows = 0;+ for (const group of summary.groups) {+ for (const [reason, count] of Object.entries(group.stopReasons)) {+ lines.push(`| ${group.id} | ${reason} | ${count} |`);+ failureRows += 1;+ }+ }+ if (!failureRows) lines.push("| — | none | 0 |");+ lines.push("");+ return lines.join("\n");+}++const parseArgs = (args) => {+ if (args.includes("--help") || args.includes("-h")) return { help: true };+ if (args.length !== 2 || args[0] !== "--input" || !args[1]) {+ throw new TypeError("usage: node benchmark/summary.js --input <rows.ndjson>");+ }+ return { input: args[1] };+};++const loadRows = async (filename) => {+ let source;+ try {+ const metadata = await stat(filename);+ if (!metadata.isFile() || metadata.size > MAX_INPUT_BYTES) throw new Error();+ source = await readFile(filename, "utf8");+ } catch {+ throw new TypeError("could not read benchmark NDJSON input");+ }+ return source.split(/\r?\n/).flatMap((line, index) => {+ if (!line.trim()) return [];+ try {+ return [JSON.parse(line)];+ } catch {+ throw new TypeError(`line ${index + 1}: invalid JSON`);+ }+ });+};++async function main() {+ try {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ process.stdout.write("Usage: node benchmark/summary.js --input <rows.ndjson>\n");+ return;+ }+ process.stdout.write(renderBenchmarkSummary(summarizeBenchmarkRows(await loadRows(args.input))));+ } catch (error) {+ process.stderr.write(`benchmark summary failed: ${error.message}\n`);+ process.exitCode = 1;+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {+ await main();+}diff --git a/benchmark/tasks/instagram.json b/benchmark/tasks/instagram.jsonnew file mode 100644index 0000000..eb4dceb--- /dev/null+++ b/benchmark/tasks/instagram.json@@ -0,0 +1,7 @@+{+ "task_id": "7d897510-3fe9-4dc7-8c32-97dc80dc88cf",+ "platform": "instagram",+ "goal": "Find public posts from independent ceramic artists, open relevant posts, and read available comments.",+ "result_limit": 4,+ "max_steps": 12+}diff --git a/benchmark/tasks/linkedin.json b/benchmark/tasks/linkedin.jsonnew file mode 100644index 0000000..855f480--- /dev/null+++ b/benchmark/tasks/linkedin.json@@ -0,0 +1,7 @@+{+ "task_id": "b61d7f1b-e12a-4581-bf83-10273f35a2ab",+ "platform": "linkedin",+ "goal": "Find public posts about AI product management, open relevant posts or profiles, and inspect available evidence.",+ "result_limit": 4,+ "max_steps": 12+}diff --git a/benchmark/tasks/tiktok.json b/benchmark/tasks/tiktok.jsonnew file mode 100644index 0000000..0ece42e--- /dev/null+++ b/benchmark/tasks/tiktok.json@@ -0,0 +1,7 @@+{+ "task_id": "e3aa1eef-bf7d-4d7f-a38f-d72defe67f88",+ "platform": "tiktok",+ "goal": "Find beginner watercolor videos, read comments, and download one selected video.",+ "result_limit": 4,+ "max_steps": 12+}diff --git a/package.json b/package.jsonindex b4a23b6..25beb76 100644--- a/package.json+++ b/package.json@@ -4,11 +4,14 @@"description": "Jev-directed Instagram, TikTok, and LinkedIn browser operations through the socai CLI","type": "module","bin": {- "jev-social": "bin/jev-social.js"+ "jev-social": "bin/jev-social.js",+ "jev-social-benchmark": "benchmark/run.js"},"exports": {".": "./src/index.js",- "./benchmark/schema": "./benchmark/schema.js"+ "./benchmark/run": "./benchmark/run.js",+ "./benchmark/schema": "./benchmark/schema.js",+ "./benchmark/summary": "./benchmark/summary.js"},"repository": {"type": "git",@@ -19,9 +22,14 @@"url": "https://github.com/socai-io/jev-social/issues"},"files": [+ "benchmark/run.js","benchmark/schema.js",+ "benchmark/summary.js","benchmark/README.md","benchmark/fixtures/valid-row.json",+ "benchmark/tasks/instagram.json",+ "benchmark/tasks/linkedin.json",+ "benchmark/tasks/tiktok.json","bin","docs/troubleshooting.md","public",@@ -33,7 +41,9 @@"scripts": {"start": "node ./bin/jev-social.js","dev": "node --watch ./bin/jev-social.js serve --no-open",- "check": "node --check ./bin/jev-social.js && node --check ./benchmark/schema.js && node --check ./src/server.js && node --check ./src/decision-provider.js && node --check ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js",+ "benchmark:run": "node ./benchmark/run.js",+ "benchmark:summarize": "node ./benchmark/summary.js",+ "check": "node --check ./bin/jev-social.js && node --check ./benchmark/run.js && node --check ./benchmark/schema.js && node --check ./benchmark/summary.js && node --check ./src/server.js && node --check ./src/decision-provider.js && node --check ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js","test": "node --test"},"engines": {diff --git a/src/actions.js b/src/actions.jsindex 8749521..832a037 100644--- a/src/actions.js+++ b/src/actions.js@@ -190,6 +190,15 @@ export async function chooseAction({ goal, platform, actions, history, items, li},};const decision = await requestChoice({ ...options, request, key: "action" });- if (decision.confidence < 0.35) throw new AppError("Jev is uncertain about the next operation. Narrow the request and try again.", { code: "LOW_ACTION_CONFIDENCE" });+ if (decision.confidence < 0.35) {+ throw new AppError("Jev is uncertain about the next operation. Narrow the request and try again.", {+ code: "LOW_ACTION_CONFIDENCE",+ details: {+ elapsedMs: decision.elapsedMs,+ model: decision.model,+ modelVerified: decision.modelVerified,+ },+ });+ }return { ...decision, action: actions.find((action) => action.id === decision.choice) };}diff --git a/src/app.js b/src/app.jsindex 602ffc7..ed3f7bc 100644--- a/src/app.js+++ b/src/app.js@@ -1,4 +1,5 @@import crypto from "node:crypto";+import { performance } from "node:perf_hooks";import { setTimeout as delay } from "node:timers/promises";import { classifySearch } from "./classifier.js";import { availableActions, chooseAction } from "./actions.js";@@ -120,15 +121,32 @@ export async function runSearch(capabilities,...decisionOptions,});- if (!classification.platform) throw new AppError("This request is not a supported read-only social task.", { code: "UNSUPPORTED_TASK" });- if (classification.confidence < 0.35) throw new AppError("Jev is uncertain about the platform. Select one explicitly.", { code: "LOW_CLASSIFICATION_CONFIDENCE" });+ const classificationDetails = {+ elapsedMs: classification.elapsedMs,+ model: classification.model,+ modelVerified: classification.modelVerified,+ };+ if (!classification.platform) {+ throw new AppError("This request is not a supported read-only social task.", {+ code: "UNSUPPORTED_TASK",+ details: classificationDetails,+ });+ }+ if (classification.confidence < 0.35) {+ throw new AppError("Jev is uncertain about the platform. Select one explicitly.", {+ code: "LOW_CLASSIFICATION_CONFIDENCE",+ details: classificationDetails,+ });+ }const selectedPlatform = classification.platform;const commands = await actionCapabilities({ config, env, platform: selectedPlatform, signal, capabilities });const searchQuery = extractSearchQuery(request);const createdAt = new Date().toISOString();const id = `${createdAt.replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;let items = [];+ let downloadItems = [];const actions = [];+ const decisionFailures = [];const executions = [];let status = "running";let stopReason = "Research is still in progress.";@@ -157,10 +175,13 @@ export async function runSearch(requestedPlatform: platform, platform: selectedPlatform,classification: publicEvidence(classification),actions: actions.map(({ command: _command, ...entry }) => publicEvidence(entry)),+ decisionFailures: publicEvidence(decisionFailures),status, stopReason: publicStopReason, maxSteps,socaiExitCode: executions.at(-1)?.exitCode ?? null,socaiElapsedMs: executions.reduce((sum, execution) => sum + execution.elapsedMs, 0),- jevElapsedMs: classification.elapsedMs + actions.reduce((sum, entry) => sum + (entry.jevElapsedMs || 0), 0),+ jevElapsedMs: classification.elapsedMs+ + actions.reduce((sum, entry) => sum + (entry.jevElapsedMs || 0), 0)+ + decisionFailures.reduce((sum, entry) => sum + entry.elapsedMs, 0),elapsedMs: Date.now() - startedAt,result: { ok: status === "completed", query: publicQuery, items: publicItems },report,@@ -187,6 +208,14 @@ export async function runSearch(try {decision = await chooseAction({ goal: request, platform: selectedPlatform, actions: candidates, history: actions, items, limit, remainingSteps: maxSteps - step, ...decisionOptions });} catch (error) {+ const elapsedMs = error?.details?.elapsedMs;+ if (Number.isSafeInteger(elapsedMs) && elapsedMs >= 0) {+ decisionFailures.push({+ elapsedMs,+ model: error.details.model || model,+ modelVerified: Boolean(error.details.modelVerified),+ });+ }if (!actions.length || signal?.aborted) throw error;status = "decision_failed";stopReason = safeProgress(error.message) || "Jev could not choose another safe operation.";@@ -195,7 +224,8 @@ export async function runSearch(const action = decision.action;const entry = {step: step + 1, action, confidence: decision.confidence,- model: decision.model, usage: decision.usage, jevElapsedMs: decision.elapsedMs,+ model: decision.model, modelVerified: decision.modelVerified,+ usage: decision.usage, jevElapsedMs: decision.elapsedMs,status: "selected",};activeEntry = entry;@@ -211,6 +241,7 @@ export async function runSearch(await checkpoint();const stage = action.downloadMedia ? "downloading" : action.kind === "search" ? "searching" : "reading";await emit({ stage, message: action.label, step: step + 1, action: { kind: action.kind, target: action.target } });+ const actionStartedAt = performance.now();try {const execution = await runSocaiAction({action, config, env, signal,@@ -222,9 +253,15 @@ export async function runSearch(await flushProgress();executions.push(execution);const captured = extractEvidence(execution.data, action);+ if (action.downloadMedia) downloadItems = mergeEvidence(downloadItems, captured);items = mergeEvidence(items, captured);const observation = resultObservation(execution.data, captured);- Object.assign(entry, { command: execution.command, elapsedMs: execution.elapsedMs, observation, status: observation.ok ? "completed" : "failed" });+ Object.assign(entry, {+ command: execution.command,+ elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),+ observation,+ status: observation.ok ? "completed" : "failed",+ });if (observation.blocked) {status = "blocked";stopReason = `The platform requires attention: ${observation.reason || observation.status || "login or access check"}.`;@@ -236,7 +273,11 @@ export async function runSearch(} catch (error) {if (error?.name === "AbortError") throw error;signal?.throwIfAborted();- Object.assign(entry, { status: "failed", observation: { ok: false, code: error.code, error: safeProgress(error.message) || "Browser operation failed." } });+ Object.assign(entry, {+ elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),+ status: "failed",+ observation: { ok: false, code: error.code, error: safeProgress(error.message) || "Browser operation failed." },+ });await checkpoint();activeEntry = undefined;await emit({ stage: "planning", message: "The operation failed. Jev is considering the remaining options." });@@ -332,7 +373,7 @@ export async function runSearch(throw error;}const stored = await checkpoint();- privateRunMedia.set(stored, { items });+ privateRunMedia.set(stored, { items, downloadItems });await emit({ stage: "complete", status, message: status === "completed" ? "Evidence ready." : `Partial evidence saved. ${stopReason}` });return stored;}diff --git a/src/classifier.js b/src/classifier.jsindex e5429be..14a81e5 100644--- a/src/classifier.js+++ b/src/classifier.js@@ -1,5 +1,6 @@import { AppError } from "./errors.js";import { requestDecision } from "./decision-provider.js";+import { performance } from "node:perf_hooks";export const SUPPORTED_PLATFORMS = new Set(["instagram", "tiktok", "linkedin"]);const ROUTE_TO_PLATFORM = {@@ -94,7 +95,13 @@ export async function classifySearch({`Jev route '${selected}' conflicts with the explicitly selected ${normalizedPlatform} platform.`,{code: "JEV_ROUTE_MISMATCH",- details: { requestedPlatform: normalizedPlatform, selectedRoute: selected },+ details: {+ requestedPlatform: normalizedPlatform,+ selectedRoute: selected,+ elapsedMs: decision.elapsedMs,+ model: decision.model,+ modelVerified: decision.modelVerified,+ },},);}@@ -103,17 +110,51 @@ export async function classifySearch({export async function requestChoice({ request, key, apiKey, provider, client, fetchImpl = fetch, signal }) {signal?.throwIfAborted();- const startedAt = Date.now();+ const startedAt = performance.now();let response;try {response = client? await client.systemOne(request, { signal }): await requestDecision({ provider, apiKey, request, fetchImpl, signal });} catch (error) {- signal?.throwIfAborted();- throw new AppError(`Jev decision failed: ${error.message}`, { code: "JEV_UNAVAILABLE", status: 502 });+ const details = {+ elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),+ model: request.model,+ modelVerified: false,+ };+ if (signal?.aborted || error?.name === "AbortError") {+ const interrupted = new AppError("Jev decision was interrupted.", {+ code: "JEV_ABORTED",+ status: 499,+ details,+ });+ interrupted.name = "AbortError";+ throw interrupted;+ }+ throw new AppError(`Jev decision failed: ${error.message}`, {+ code: "JEV_UNAVAILABLE",+ status: 502,+ details,+ });}- signal?.throwIfAborted();+ if (signal?.aborted) {+ const interrupted = new AppError("Jev decision was interrupted.", {+ code: "JEV_ABORTED",+ status: 499,+ details: {+ elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),+ model: request.model,+ modelVerified: false,+ },+ });+ interrupted.name = "AbortError";+ throw interrupted;+ }+ const elapsedMs = Math.max(0, Math.round(performance.now() - startedAt));+ const resolvedModel = typeof response?.model === "string" && response.model.trim()+ ? response.model.trim()+ : request.model;+ const modelVerified = typeof response?.model === "string" && Boolean(response.model.trim());const answer = response?.answers?.[key];const selected = answer?.choice;const confidence = answer?.confidence;@@ -138,14 +179,16 @@ export async function requestChoice({ request, key, apiKey, provider, client, fethrow new AppError("Jev returned an invalid decision response.", {code: "INVALID_JEV_RESPONSE",status: 502,+ details: { elapsedMs, model: resolvedModel, modelVerified },});}return {choice: selected,confidence,probabilities,- model: response.model || request.model,+ model: resolvedModel,+ modelVerified,usage: response.usage || {},- elapsedMs: Date.now() - startedAt,+ elapsedMs,};}diff --git a/test/app.test.js b/test/app.test.jsindex c12e92b..a7e5116 100644--- a/test/app.test.js+++ b/test/app.test.js@@ -3,7 +3,7 @@ import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import test from "node:test";-import { runSearch } from "../src/app.js";+import { getPrivateRunMedia, runSearch } from "../src/app.js";import { listRuns, readRun } from "../src/runs.js";async function fixture() {@@ -15,7 +15,8 @@ const [platform, command] = args;const result = (data) => console.log(JSON.stringify(data));if (args.includes('--help')) console.log('Commands: search get-posts get-videos profile author company history page_state');else if (command === 'search') {- if (args[2] === 'gated') result({ok:false, reason:'login_required', results:[]});+ if (String(args[2]).startsWith('fail')) process.exitCode=2;+ else if (args[2] === 'gated') result({ok:false, reason:'login_required', results:[]});else if (args[2] === 'empty') result({ok:true, results:[]});else if (platform === 'tiktok') result({ok:true, cards:[{video_id:'111',url:'https://www.tiktok.com/@demo/video/111',title:'Unrelated'},@@ -178,6 +179,8 @@ test("runSearch downloads only the TikTok video selected by Jev after an expliciassert.equal(run.command, undefined);assert.equal(run.actions[1].action.downloadMedia,true);assert.equal(run.result.items.find((item)=>item.url.endsWith('/222')).video.local_path, undefined);+ assert.equal(getPrivateRunMedia(run).downloadItems.length, 1);+ assert.equal(getPrivateRunMedia(run).downloadItems[0].video.local_path, "/tmp/video.mp4");assert.doesNotMatch(JSON.stringify(run), /\/tmp\/video\.mp4|local_path|socaiOutputs/);} finally { await rm(directory,{recursive:true,force:true}); }});@@ -209,6 +212,21 @@ test("step exhaustion and login gates preserve honest partial results", async ()} finally { await rm(directory,{recursive:true,force:true}); }});+test("failed browser operations retain monotonic elapsed time", async () => {+ const { directory, env } = await fixture();+ const client = choices("instagram", (criteria, step) =>+ step === 0 ? matching(criteria, /^Search instagram/) : "finish",+ );+ try {+ const run = await runSearch({ query: "fail on Instagram" }, { env, client });+ assert.equal(run.actions[0].status, "failed");+ assert.ok(Number.isSafeInteger(run.actions[0].elapsedMs));+ assert.ok(run.actions[0].elapsedMs >= 0);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});+test("an invented action never reaches the CLI", async () => {const {directory,env} = await fixture();try {diff --git a/test/benchmark-runner.test.js b/test/benchmark-runner.test.jsnew file mode 100644index 0000000..068f174--- /dev/null+++ b/test/benchmark-runner.test.js@@ -0,0 +1,536 @@+import assert from "node:assert/strict";+import { execFileSync, spawn } from "node:child_process";+import crypto from "node:crypto";+import { chmod, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";++import {+ buildBenchmarkRow,+ collectDownloadedMedia,+ runBenchmarkCli,+ validateBenchmarkTask,+} from "../benchmark/run.js";++const task = {+ task_id: "11111111-1111-4111-8111-111111111111",+ platform: "tiktok",+ goal: "Find beginner watercolor videos, read comments, and download one selected video.",+ result_limit: 4,+ max_steps: 12,+};++const metadata = {+ jev_model: "typesafe/jev-1.13-20260917",+ socai_version: "0.6.0",+ socai_commit: "0123456789abcdef0123456789abcdef01234567",+ profile_mode: "existing",+ region: "synthetic-us",+ condition: "warm",+};++const completedRun = () => ({+ status: "completed",+ stopReason: "Jev chose to finish with the evidence captured so far.",+ classification: { model: metadata.jev_model, modelVerified: true, elapsedMs: 100 },+ actions: [+ {+ action: { kind: "search", platform: "tiktok" },+ model: metadata.jev_model,+ modelVerified: true,+ jevElapsedMs: 200,+ elapsedMs: 3_000,+ status: "completed",+ },+ {+ action: { kind: "read_post", platform: "tiktok", downloadMedia: true },+ model: metadata.jev_model,+ modelVerified: true,+ jevElapsedMs: 300,+ elapsedMs: 4_000,+ status: "completed",+ },+ {+ action: { kind: "finish", platform: "tiktok" },+ model: metadata.jev_model,+ modelVerified: true,+ jevElapsedMs: 150,+ status: "completed",+ },+ ],+ result: {+ items: [{ url: "https://www.tiktok.com/@demo/video/1", top_comments: [{ text: "A" }, { text: "B" }] }],+ },+});++test("validates fixed benchmark task files without retaining extra fields", () => {+ assert.deepEqual(validateBenchmarkTask(task), task);++ assert.throws(+ () => validateBenchmarkTask({ ...task, account: "private-user" }),+ /unknown field/i,+ );+ assert.throws(+ () => validateBenchmarkTask({ ...task, platform: "youtube" }),+ /platform/i,+ );+ assert.throws(+ () => validateBenchmarkTask({ ...task, goal: "\u0000unsafe" }),+ /goal/i,+ );+});++test("builds one validated row from a completed run and keeps component timings separate", () => {+ const row = buildBenchmarkRow({+ task,+ metadata,+ run: completedRun(),+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:09.000Z",+ totalMs: 9_000,+ runId: "00000000-0000-4000-8000-000000000010",+ media: { count: 1, bytes: 4_096 },+ });++ assert.equal(row.outcome, "success");+ assert.equal(row.stop_reason, "goal_satisfied");+ assert.deepEqual(row.jev_step_latency_ms, [100, 200, 300, 150]);+ assert.deepEqual(row.timing_ms, {+ jev_total: 750,+ socai_browser: 7_000,+ media: 4_000,+ total: 9_000,+ });+ assert.deepEqual(row.evidence, {+ records: 1,+ comments: 2,+ downloaded_media_count: 1,+ downloaded_media_bytes: 4_096,+ });+});++test("keeps access gates, empty results, and preflight failures in the dataset", () => {+ const blocked = completedRun();+ blocked.status = "blocked";+ blocked.stopReason = "The platform requires attention: login_required.";+ blocked.result.items = [];+ blocked.actions = blocked.actions.slice(0, 1);+ const blockedRow = buildBenchmarkRow({+ task,+ metadata,+ run: blocked,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:04.000Z",+ totalMs: 4_000,+ runId: "00000000-0000-4000-8000-000000000011",+ });+ assert.equal(blockedRow.outcome, "failed");+ assert.equal(blockedRow.stop_reason, "login_required");+ assert.equal(blockedRow.failure_category, "access_gate");++ const empty = completedRun();+ empty.status = "partial";+ empty.stopReason = "Jev stopped without usable evidence.";+ empty.result.items = [];+ const emptyRow = buildBenchmarkRow({+ task,+ metadata,+ run: empty,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:09.000Z",+ totalMs: 9_000,+ runId: "00000000-0000-4000-8000-000000000012",+ });+ assert.equal(emptyRow.stop_reason, "empty_results");+ assert.equal(emptyRow.failure_category, "empty_results");++ const unavailable = buildBenchmarkRow({+ task,+ metadata,+ error: { code: "SOCAI_CAPABILITY_MISSING" },+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:01.000Z",+ totalMs: 1_000,+ runId: "00000000-0000-4000-8000-000000000013",+ });+ assert.equal(unavailable.outcome, "failed");+ assert.equal(unavailable.stop_reason, "capability_unavailable");+ assert.equal(unavailable.failure_category, "unavailable");++ const browserUnavailable = buildBenchmarkRow({+ task,+ metadata,+ error: { code: "BROWSER_PERMISSION_REQUIRED" },+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:01.000Z",+ totalMs: 1_000,+ runId: "00000000-0000-4000-8000-000000000015",+ });+ assert.equal(browserUnavailable.stop_reason, "browser_unavailable");+ assert.equal(browserUnavailable.failure_category, "unavailable");++ const reportFailed = completedRun();+ reportFailed.status = "failed";+ reportFailed.reportStatus = "failed";+ const reportFailedRow = buildBenchmarkRow({+ task,+ metadata,+ run: reportFailed,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:09.000Z",+ totalMs: 9_000,+ runId: "00000000-0000-4000-8000-000000000016",+ });+ assert.equal(reportFailedRow.outcome, "partial");+ assert.equal(reportFailedRow.stop_reason, "report_failed");+ assert.equal(reportFailedRow.failure_category, "execution_error");++ for (const code of [+ "EMPTY_SOCAI_OUTPUT",+ "INVALID_SOCAI_OUTPUT",+ "SOCAI_OUTPUT_TOO_LARGE",+ ]) {+ const failedRun = completedRun();+ failedRun.status = "partial";+ failedRun.result.items = [];+ failedRun.actions = [{+ ...failedRun.actions[0],+ status: "failed",+ elapsedMs: 750,+ observation: { code },+ }];+ const failedRow = buildBenchmarkRow({+ task,+ metadata,+ run: failedRun,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:01.000Z",+ totalMs: 1_000,+ runId: crypto.randomUUID(),+ });+ assert.equal(failedRow.stop_reason, "cli_failed");+ assert.equal(failedRow.timing_ms.socai_browser, 750);+ }++ const lowConfidence = buildBenchmarkRow({+ task,+ metadata,+ error: {+ code: "LOW_ACTION_CONFIDENCE",+ details: { elapsedMs: 320, model: metadata.jev_model },+ },+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:01.000Z",+ totalMs: 1_000,+ runId: crypto.randomUUID(),+ });+ assert.equal(lowConfidence.stop_reason, "decision_failed");+ assert.deepEqual(lowConfidence.jev_step_latency_ms, [320]);+});++test("rejects a run whose resolved decision model differs from the declared pin", () => {+ const run = completedRun();+ run.classification.model = "typesafe/jev-other";++ assert.throws(+ () => buildBenchmarkRow({+ task,+ metadata,+ run,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:09.000Z",+ totalMs: 9_000,+ runId: "00000000-0000-4000-8000-000000000014",+ }),+ /decision model/i,+ );+});++test("rejects successful decisions when the provider omits the resolved model", () => {+ const run = completedRun();+ run.classification.modelVerified = false;++ assert.throws(+ () => buildBenchmarkRow({+ task,+ metadata,+ run,+ startedAt: "2026-09-25T00:00:00.000Z",+ endedAt: "2026-09-25T00:00:09.000Z",+ totalMs: 9_000,+ runId: crypto.randomUUID(),+ }),+ /did not report the resolved model/i,+ );+});++test("counts only media tied to an explicit download action below configured run roots", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-benchmark-media-"));+ const runs = path.join(directory, "runs");+ const inside = path.join(runs, "video.mp4");+ const outside = path.join(directory, "outside.mp4");+ const artifact = path.join(runs, "trace.json");+ const unrelated = path.join(runs, "unrelated.mp4");+ await mkdir(runs);+ await writeFile(inside, Buffer.alloc(4_096, 1));+ await writeFile(outside, Buffer.alloc(8_192, 1));+ await writeFile(artifact, Buffer.alloc(512, 1));+ await writeFile(unrelated, Buffer.alloc(1_024, 1));++ try {+ const media = await collectDownloadedMedia(+ {+ platform: "tiktok",+ actions: [{+ status: "completed",+ action: {+ kind: "read_post",+ downloadMedia: true,+ target: "https://www.tiktok.com/@demo/video/1",+ },+ }],+ },+ [+ {+ url: "https://www.tiktok.com/@demo/video/1",+ video: { local_path: inside },+ artifact: { local_path: artifact },+ duplicate: { local_path: inside },+ },+ { url: "https://www.tiktok.com/@demo/video/2", video: { local_path: unrelated } },+ { url: "https://www.tiktok.com/@demo/video/1", poster: { local_path: outside } },+ ],+ { env: { ...process.env, SOCAI_RUNS_DIR: runs } },+ );+ assert.deepEqual(media, { count: 1, bytes: 4_096 });+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++const cliArguments = [+ "--task", "benchmark/tasks/tiktok.json",+ "--jev-model", metadata.jev_model,+ "--socai-version", metadata.socai_version,+ "--socai-commit", metadata.socai_commit,+ "--profile-mode", metadata.profile_mode,+ "--region", metadata.region,+ "--condition", metadata.condition,+];++const cliDependencies = (overrides = {}) => ({+ env: { HOME: "/non-sensitive-test-home" },+ loadLocalEnv: async () => {},+ loadTaskFile: async () => task,+ readConfig: async () => ({}),+ createStateDir: async () => "/virtual/benchmark-state",+ removeStateDir: async () => {},+ probeSocai: async () => ({ installed: true, version: metadata.socai_version }),+ runSearch: async (_request, options) => {+ await options.onEvent({ stage: "searching", message: "must not reach stderr" });+ const run = completedRun();+ run.classification.elapsedMs = 0;+ for (const action of run.actions) {+ action.jevElapsedMs = 0;+ if (action.elapsedMs !== undefined) action.elapsedMs = 0;+ }+ return run;+ },+ listRuns: async () => [],+ readRun: async () => null,+ getPrivateRunMedia: () => undefined,+ ...overrides,+});++test("the executable contract emits one row and fixed stage-only stderr", async () => {+ let stdout = "";+ let stderr = "";+ const result = await runBenchmarkCli(cliArguments, {+ stdout: { write: (value) => { stdout += value; } },+ stderr: { write: (value) => { stderr += value; } },+ dependencies: cliDependencies(),+ });++ assert.equal(result.exitCode, 0);+ assert.equal(stdout.trim().split("\n").length, 1);+ assert.equal(JSON.parse(stdout).outcome, "success");+ assert.equal(stderr, "[benchmark] searching\n");+ assert.doesNotMatch(stderr, /must not reach|virtual|non-sensitive/);+});++test("unverifiable versions and interruptions remain privacy-safe rows", async () => {+ for (const [probeSocai, expectedReason, signal] of [+ [async () => ({ installed: true, version: null }), "capability_unavailable", undefined],+ [async () => ({ installed: true, version: metadata.socai_version }), "interrupted", AbortSignal.abort()],+ ]) {+ let stdout = "";+ let stderr = "";+ const result = await runBenchmarkCli(cliArguments, {+ stdout: { write: (value) => { stdout += value; } },+ stderr: { write: (value) => { stderr += value; } },+ signal,+ dependencies: cliDependencies({+ probeSocai,+ runSearch: async (_request, options) => {+ options.signal?.throwIfAborted();+ return completedRun();+ },+ }),+ });+ assert.equal(result.exitCode, 0);+ assert.equal(stdout.trim().split("\n").length, 1);+ assert.equal(JSON.parse(stdout).stop_reason, expectedReason);+ assert.doesNotMatch(stderr, /\/virtual|\/Users|OPENROUTER/i);+ }+});++test("a provider model mismatch becomes a retained failed row", async () => {+ let stdout = "";+ let stderr = "";+ const result = await runBenchmarkCli(cliArguments, {+ stdout: { write: (value) => { stdout += value; } },+ stderr: { write: (value) => { stderr += value; } },+ dependencies: cliDependencies({+ runSearch: async () => {+ const run = completedRun();+ run.classification.model = "typesafe/jev-other-pinned";+ run.classification.elapsedMs = 5;+ for (const action of run.actions) {+ action.jevElapsedMs = 0;+ if (action.elapsedMs !== undefined) action.elapsedMs = 0;+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+ return run;+ },+ }),+ });+ assert.equal(result.exitCode, 0);+ const row = JSON.parse(stdout);+ assert.equal(row.stop_reason, "decision_failed");+ assert.deepEqual(row.jev_step_latency_ms, [5, 0, 0, 0]);+ assert.equal(row.timing_ms.jev_total, 5);+ assert.equal(row.evidence.records, 1);+ assert.equal(stderr, "[benchmark] row_invalid\n");+});++test("an abort during a Jev request is retained as interrupted", async () => {+ let stdout = "";+ const result = await runBenchmarkCli(cliArguments, {+ stdout: { write: (value) => { stdout += value; } },+ stderr: { write: () => {} },+ dependencies: cliDependencies({+ runSearch: async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ const error = new Error("interrupted");+ error.name = "AbortError";+ error.code = "JEV_ABORTED";+ error.details = {+ elapsedMs: 4,+ model: metadata.jev_model,+ modelVerified: false,+ };+ throw error;+ },+ }),+ });++ assert.equal(result.exitCode, 0);+ const row = JSON.parse(stdout);+ assert.equal(row.stop_reason, "interrupted");+ assert.equal(row.failure_category, "interrupted");+ assert.deepEqual(row.jev_step_latency_ms, [4]);+});++test("floating model pins fail before a live attempt", async () => {+ let stdout = "";+ let stderr = "";+ let called = false;+ const args = [...cliArguments];+ args[args.indexOf("--jev-model") + 1] = "typesafe/jev-latest";+ const result = await runBenchmarkCli(args, {+ stdout: { write: (value) => { stdout += value; } },+ stderr: { write: (value) => { stderr += value; } },+ dependencies: cliDependencies({+ probeSocai: async () => {+ called = true;+ return { installed: true, version: metadata.socai_version };+ },+ }),+ });+ assert.equal(result.exitCode, 1);+ assert.equal(called, false);+ assert.equal(stdout, "");+ assert.equal(stderr, "[benchmark] invalid_input\n");+});++test("SIGINT produces an interrupted row instead of dropping the attempt", {+ skip: process.platform === "win32",+}, async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-benchmark-signal-"));+ const mock = path.join(directory, "socai-hang.mjs");+ await writeFile(mock, "#!/usr/bin/env node\nsetInterval(() => {}, 30_000);\n", { mode: 0o755 });+ await chmod(mock, 0o755);+ const root = new URL("..", import.meta.url);+ const child = spawn(process.execPath, ["benchmark/run.js", ...cliArguments], {+ cwd: root,+ env: { ...process.env, SOCAI_BIN: mock },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (chunk) => { stdout += chunk; });+ child.stderr.on("data", (chunk) => { stderr += chunk; });++ try {+ await new Promise((resolve) => setTimeout(resolve, 250));+ child.kill("SIGINT");+ const { code, signal } = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", (code, signal) => resolve({ code, signal }));+ });+ assert.equal(signal, null);+ assert.equal(code, 0);+ assert.equal(stdout.trim().split("\n").length, 1);+ assert.equal(JSON.parse(stdout).stop_reason, "interrupted");+ assert.doesNotMatch(stderr, new RegExp(directory.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));+ } finally {+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");+ await rm(directory, { recursive: true, force: true });+ }+});++test("ships one fixed, privacy-safe task per supported platform", async () => {+ const filenames = ["instagram.json", "tiktok.json", "linkedin.json"];+ const tasks = await Promise.all(filenames.map(async (filename) =>+ validateBenchmarkTask(JSON.parse(+ await readFile(new URL(`../benchmark/tasks/${filename}`, import.meta.url), "utf8"),+ )),+ ));++ assert.deepEqual(tasks.map(({ platform }) => platform), ["instagram", "tiktok", "linkedin"]);+ assert.equal(new Set(tasks.map(({ task_id: taskId }) => taskId)).size, tasks.length);+ assert.match(tasks[1].goal, /download one selected video/i);+ for (const benchmarkTask of tasks) {+ assert.equal(benchmarkTask.result_limit, 4);+ assert.equal(benchmarkTask.max_steps, 12);+ assert.doesNotMatch(benchmarkTask.goal, /@|https?:\/\/|\/Users\//i);+ }+});++test("benchmark commands expose offline help without loading live configuration", () => {+ const root = new URL("..", import.meta.url);+ const runner = execFileSync(process.execPath, ["benchmark/run.js", "--help"], {+ cwd: root,+ encoding: "utf8",+ });+ const summary = execFileSync(process.execPath, ["benchmark/summary.js", "--help"], {+ cwd: root,+ encoding: "utf8",+ });++ assert.match(runner, /writes exactly one validated/i);+ assert.match(summary, /--input <rows\.ndjson>/i);+});diff --git a/test/benchmark-schema.test.js b/test/benchmark-schema.test.jsindex 73ec4a0..befbea2 100644--- a/test/benchmark-schema.test.js+++ b/test/benchmark-schema.test.js@@ -180,7 +180,7 @@ test("requires opaque IDs and pinned socai metadata", () => {const canonical = clone();canonical.socai_version = "v0.6.0-beta.1+sha.abcdef";canonical.socai_commit = canonical.socai_commit.toUpperCase();- canonical.jev_model = "typesafe/jev-latest:free";+ canonical.jev_model = "typesafe/jev-1.13-20260917:free";const normalized = validateBenchmarkRow(canonical);assert.equal(normalized.socai_version, "0.6.0-beta.1+sha.abcdef");assert.equal(normalized.socai_commit, canonical.socai_commit.toLowerCase());@@ -189,6 +189,15 @@ test("requires opaque IDs and pinned socai metadata", () => {const nestedModel = clone();nestedModel.jev_model = "org/team/jev";assert.equal(validateBenchmarkRow(nestedModel).jev_model, nestedModel.jev_model);++ for (const value of ["~typesafe/jev-latest", "typesafe/jev-latest:free", "kev-latest"]) {+ const row = clone();+ row.jev_model = value;+ assert.throws(+ () => validateBenchmarkRow(row),+ (error) => error instanceof BenchmarkRowValidationError && error.path === "jev_model",+ );+ }});test("keeps outcome and stop state consistent", () => {@@ -300,9 +309,15 @@ test("keeps downloaded media counts possible and TikTok-only", () => {assert.equal(validateBenchmarkRow(tiktokDownload).evidence.downloaded_media_count, 1);});-test("the packaged benchmark schema has an explicit import path", async () => {+test("the packaged benchmark tools have explicit import paths", async () => {const packaged = await import("jev-social/benchmark/schema");+ const runner = await import("jev-social/benchmark/run");+ const summary = await import("jev-social/benchmark/summary");assert.equal(packaged.validateBenchmarkRow, validateBenchmarkRow);+ assert.equal(typeof runner.buildBenchmarkRow, "function");+ assert.equal(typeof runner.executeBenchmark, "function");+ assert.equal(typeof runner.runBenchmarkCli, "function");+ assert.equal(typeof summary.summarizeBenchmarkRows, "function");});test("the package contains only the intended benchmark artifacts", () => {@@ -324,7 +339,12 @@ test("the package contains only the intended benchmark artifacts", () => {assert.deepEqual(files, ["benchmark/fixtures/valid-row.json","benchmark/README.md",+ "benchmark/run.js","benchmark/schema.js",+ "benchmark/summary.js",+ "benchmark/tasks/instagram.json",+ "benchmark/tasks/linkedin.json",+ "benchmark/tasks/tiktok.json",]);} finally {rmSync(cache, { recursive: true, force: true });diff --git a/test/benchmark-summary.test.js b/test/benchmark-summary.test.jsnew file mode 100644index 0000000..45f06b7--- /dev/null+++ b/test/benchmark-summary.test.js@@ -0,0 +1,88 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ renderBenchmarkSummary,+ summarizeBenchmarkRows,+} from "../benchmark/summary.js";++const fixture = JSON.parse(+ readFileSync(new URL("../benchmark/fixtures/valid-row.json", import.meta.url), "utf8"),+);++const row = (index) => {+ const value = structuredClone(fixture);+ const total = (index + 1) * 1_000;+ value.run_id = `00000000-0000-4000-8000-${String(index + 100).padStart(12, "0")}`;+ value.started_at = `2026-09-25T00:00:${String(index).padStart(2, "0")}.000Z`;+ value.ended_at = new Date(Date.parse(value.started_at) + total).toISOString();+ value.jev_step_latency_ms = [100];+ value.timing_ms = {+ jev_total: 100,+ socai_browser: Math.max(0, total - 100),+ media: 0,+ total,+ };+ value.evidence.records = 4;+ value.evidence.comments = index;+ if (index === 8) {+ value.outcome = "partial";+ value.stop_reason = "step_limit";+ value.failure_category = "step_limit";+ }+ if (index === 9) {+ value.outcome = "failed";+ value.stop_reason = "empty_results";+ value.failure_category = "empty_results";+ value.evidence.records = 0;+ value.evidence.comments = 0;+ }+ return value;+};++test("summarizes every terminal outcome with deterministic p50 and p95 values", () => {+ const summary = summarizeBenchmarkRows(Array.from({ length: 10 }, (_, index) => row(index)));++ assert.equal(summary.publicationReady, true);+ assert.equal(summary.groups.length, 1);+ assert.equal(summary.groups[0].outcomes.success, 8);+ assert.equal(summary.groups[0].outcomes.partial, 1);+ assert.equal(summary.groups[0].outcomes.failed, 1);+ assert.equal(summary.groups[0].failureRatePercent, 10);+ assert.deepEqual(summary.groups[0].metrics.total, { p50: 5_000, p95: 10_000 });+ assert.deepEqual(summary.groups[0].stopReasons, { empty_results: 1, step_limit: 1 });++ const markdown = renderBenchmarkSummary(summary);+ assert.match(markdown, /Publication gate: READY/);+ assert.match(markdown, /8 \/ 1 \/ 1/);+ assert.match(markdown, /10\.0%/);+ assert.match(markdown, /5,000 \/ 10,000/);+ assert.match(markdown, /empty_results/);+ assert.match(markdown, /All terminal outcomes are included/);+});++test("marks every exact environment group with fewer than ten rows as incomplete", () => {+ const secondEnvironment = row(1);+ secondEnvironment.condition = "cold";+ const summary = summarizeBenchmarkRows([row(0), secondEnvironment]);++ assert.equal(summary.publicationReady, false);+ assert.equal(summary.groups.length, 2);+ assert.ok(summary.groups.every((group) => group.publicationStatus === "INCOMPLETE (1/10)"));+ assert.match(renderBenchmarkSummary(summary), /Publication gate: INCOMPLETE/);+});++test("rejects invalid rows instead of silently dropping them", () => {+ const invalid = row(0);+ invalid.api_key = "secret";+ assert.throws(() => summarizeBenchmarkRows([row(1), invalid]), /api_key/);+});++test("rejects duplicate run IDs before they can satisfy the publication gate", () => {+ const duplicate = row(0);+ assert.throws(+ () => summarizeBenchmarkRows(Array.from({ length: 10 }, () => structuredClone(duplicate))),+ /duplicate run_id/i,+ );+});diff --git a/test/classifier.test.js b/test/classifier.test.jsindex 28b7173..920d468 100644--- a/test/classifier.test.js+++ b/test/classifier.test.js@@ -29,6 +29,8 @@ test("classifySearch routes a search with Jev's structured answer", async () =>assert.equal(result.platform, "tiktok");assert.equal(result.route, "tiktok_search");+ assert.equal(result.modelVerified, true);+ assert.ok(Number.isSafeInteger(result.elapsedMs));assert.equal(request.state.requested_platform, "tiktok");assert.equal(request.questions.route.type, "choice");});@@ -136,9 +138,28 @@ test("classifySearch fails closed on a malformed Jev decision", async () => {return { answers: { route: { type: "choice", choice: "tiktok_search" } } };},};+ await assert.rejects(classifySearch({ goal: "find creators", client }), (error) => {+ assert.equal(error.code, "INVALID_JEV_RESPONSE");+ assert.ok(Number.isSafeInteger(error.details?.elapsedMs));+ assert.equal(error.details?.model, "~typesafe/jev-latest");+ return true;+ });+});++test("failed Jev calls preserve monotonic attempt time without leaking provider details", async () => {await assert.rejects(- classifySearch({ goal: "find creators", client }),- (error) => error.code === "INVALID_JEV_RESPONSE",+ classifySearch({+ goal: "find creators",+ model: "typesafe/jev-pinned",+ client: { async systemOne() { throw new Error("private provider detail"); } },+ }),+ (error) => {+ assert.equal(error.code, "JEV_UNAVAILABLE");+ assert.ok(Number.isSafeInteger(error.details?.elapsedMs));+ assert.equal(error.details?.model, "typesafe/jev-pinned");+ assert.equal(error.details?.modelVerified, false);+ return true;+ },);});