Skip to content

armgit / bla

Public Imported from GitHub
0

πŸ›‘οΈ BLA (Blind LLM Agents) β€” Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.

feat(engine): bla_polymorph_report β€” objective cross-build drift

qybaihec932ddaed7b4
diff --git a/.agents/skills/blind-llm-agents/SKILL.md b/.agents/skills/blind-llm-agents/SKILL.md
index 6bd53d7..ac61012 100644
--- a/.agents/skills/blind-llm-agents/SKILL.md
+++ b/.agents/skills/blind-llm-agents/SKILL.md
@@ -119,6 +119,7 @@ Optional args (safe defaults): `intensity` (bankrupt), `emit_manifest` (false),
| Custom license/activation gate review | **`bla_lint_lanes`** `{ "path": "<gate.js>" }` (CLI: `bla lint-lanes`) |
| Re-check a prior harden run | **`bla_run_lookup`** `{ "summary_path": "<.bla-hardened or summary.json>", "run_id": "…" }` |
| REA constant drift / empirical report | **`bla_rea_drift`** / **`bla_redteam_report`** (unverified if REA absent; on-disk read β†’ available) |
+| Cross-build structural drift (seeded polymorphism) | **`bla_polymorph_report`** (driftScore only β€” not a cracking claim; prove equivalence with verify/REA) |
| Format-specific knobs | Load the matching appendix under `references/` |
## FORBIDDEN
diff --git a/src/engine/polymorph-report.ts b/src/engine/polymorph-report.ts
new file mode 100644
index 0000000..9987b41
--- /dev/null
+++ b/src/engine/polymorph-report.ts
@@ -0,0 +1,427 @@
+/**
+ * Cross-build structural drift report (Direction-1: seeded polymorphism).
+ *
+ * Compares two hardened artifact directories and reports objective structural
+ * differences. Does **not** claim "harder to reverse" β€” that stays with REA.
+ * Honesty: driftScore only measures "how different"; functional equivalence
+ * must be proven separately (bla_verify / REA).
+ */
+
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ readdirSync,
+ readFileSync,
+ statSync,
+} from "node:fs";
+import { extname, join, relative, resolve, sep } from "node:path";
+import { inspectWasmBinary } from "../shields/formats/wasm.js";
+
+export const POLYMORPH_REPORT_SCHEMA = "bla-polymorph-report/v1" as const;
+
+const SKIP_DIR_NAMES = new Set([
+ "node_modules",
+ ".git",
+ ".hg",
+ ".svn",
+ ".bla-hardened",
+ "coverage",
+ ".next",
+ ".turbo",
+ "vendor",
+ "__pycache__",
+]);
+
+const COMPARE_EXTS = new Set([
+ ".js",
+ ".mjs",
+ ".cjs",
+ ".ts",
+ ".tsx",
+ ".jsx",
+ ".wasm",
+ ".html",
+ ".htm",
+]);
+
+/** Files whose intentional content may include timestamps / run ids β€” skip byte compare. */
+const SKIP_BASENAMES = new Set([
+ "package-lock.json",
+ ".blarc",
+ "bla.config.json",
+]);
+
+export type PolymorphExpectMode = "same" | "different" | "report";
+
+export interface PolymorphReportOptions {
+ readonly dirA: string;
+ readonly dirB: string;
+ /**
+ * `same` β†’ refuse when driftScore β‰₯ sameThreshold (default 0.01).
+ * `different` β†’ refuse when driftScore < differentThreshold (default 0.35).
+ * `report` (default) β†’ never refuse; just emit metrics.
+ */
+ readonly expect?: PolymorphExpectMode;
+ readonly sameThreshold?: number;
+ readonly differentThreshold?: number;
+}
+
+
+export interface FilePairMetric {
+ readonly relativePath: string;
+ readonly kind: "js" | "wasm" | "html" | "other";
+ readonly byteEqual: boolean;
+ readonly byteDiffRatio: number;
+ readonly exportNameOverlap: number | null;
+ readonly exportOrderDistance: number | null;
+ readonly identifierOverlap: number | null;
+}
+
+export interface PolymorphReport {
+ readonly schema: typeof POLYMORPH_REPORT_SCHEMA;
+ readonly dirA: string;
+ readonly dirB: string;
+ readonly status: "ok" | "fail" | "error";
+ readonly expect: PolymorphExpectMode;
+ readonly driftScore: number;
+ readonly reproducible: boolean;
+ readonly polymorphic: boolean;
+ readonly pairedFileCount: number;
+ readonly onlyInA: readonly string[];
+ readonly onlyInB: readonly string[];
+ readonly files: readonly FilePairMetric[];
+ readonly summary: string;
+ readonly oneLineAdvice: string;
+}
+
+function walkFiles(root: string, maxDepth = 8): string[] {
+ const abs = resolve(root);
+ const out: string[] = [];
+ const stack: Array<{ dir: string; depth: number }> = [{ dir: abs, depth: 0 }];
+ while (stack.length > 0) {
+ const { dir, depth } = stack.pop()!;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const ent of entries) {
+ if (ent.name.startsWith(".") && ent.name !== ".blarc") {
+ // keep walking into non-dot; skip hidden dirs except we already filter
+ }
+ const full = join(dir, ent.name);
+ if (ent.isDirectory()) {
+ if (SKIP_DIR_NAMES.has(ent.name) || depth >= maxDepth) continue;
+ if (ent.name.startsWith(".")) continue;
+ stack.push({ dir: full, depth: depth + 1 });
+ } else if (ent.isFile()) {
+ if (SKIP_BASENAMES.has(ent.name)) continue;
+ const ext = extname(ent.name).toLowerCase();
+ if (!COMPARE_EXTS.has(ext)) continue;
+ out.push(full);
+ }
+ }
+ }
+ return out.sort();
+}
+
+function relKey(root: string, absFile: string): string {
+ return relative(resolve(root), absFile).split(sep).join("/");
+}
+
+function jaccard(a: readonly string[], b: readonly string[]): number {
+ if (a.length === 0 && b.length === 0) return 1;
+ const sa = new Set(a);
+ const sb = new Set(b);
+ let inter = 0;
+ for (const x of sa) if (sb.has(x)) inter++;
+ const union = sa.size + sb.size - inter;
+ return union === 0 ? 1 : inter / union;
+}
+
+/**
+ * Kendall-tau distance normalized to [0,1] over the intersection order.
+ * 0 = identical order among shared names; 1 = fully reversed (or no shared).
+ */
+function kendallTauDistance(
+ orderA: readonly string[],
+ orderB: readonly string[],
+): number {
+ const posB = new Map(orderB.map((n, i) => [n, i]));
+ const shared = orderA.filter((n) => posB.has(n));
+ const n = shared.length;
+ if (n <= 1) return 0;
+ let discordant = 0;
+ let pairs = 0;
+ for (let i = 0; i < n; i++) {
+ for (let j = i + 1; j < n; j++) {
+ pairs++;
+ const ai = i;
+ const aj = j;
+ const bi = posB.get(shared[i]!)!;
+ const bj = posB.get(shared[j]!)!;
+ const orderALess = ai < aj;
+ const orderBLess = bi < bj;
+ if (orderALess !== orderBLess) discordant++;
+ }
+ }
+ return pairs === 0 ? 0 : discordant / pairs;
+}
+
+function byteDiffRatio(a: Buffer, b: Buffer): number {
+ if (a.length === 0 && b.length === 0) return 0;
+ const maxLen = Math.max(a.length, b.length);
+ if (maxLen === 0) return 0;
+ // Fast path: equal lengths β†’ count unequal bytes; unequal β†’ size delta + prefix compare.
+ let unequal = Math.abs(a.length - b.length);
+ const lim = Math.min(a.length, b.length);
+ // Sample full compare for files ≀ 2 MiB; otherwise chunked 64 KiB windows.
+ if (maxLen <= 2 * 1024 * 1024) {
+ for (let i = 0; i < lim; i++) {
+ if (a[i] !== b[i]) unequal++;
+ }
+ return Math.min(1, unequal / maxLen);
+ }
+ const win = 64 * 1024;
+ let compared = 0;
+ let diff = unequal;
+ for (let off = 0; off < lim; off += win) {
+ const end = Math.min(off + win, lim);
+ const ha = createHash("sha256").update(a.subarray(off, end)).digest("hex");
+ const hb = createHash("sha256").update(b.subarray(off, end)).digest("hex");
+ compared += end - off;
+ if (ha !== hb) {
+ // Conservative: treat whole window as different when hashes diverge.
+ diff += end - off;
+ }
+ }
+ return Math.min(1, diff / Math.max(maxLen, compared));
+}
+
+const IDENT_RE =
+ /\b(?:function|const|let|var|class)\s+([A-Za-z_$][\w$]*)\b/g;
+const EXPORT_NAME_RE =
+ /\bexport\s+(?:async\s+)?(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)\b/g;
+const EXPORT_LIST_RE = /\bexport\s*\{([^}]+)\}/g;
+
+function extractJsIdentifiers(source: string): string[] {
+ const names = new Set<string>();
+ for (const re of [IDENT_RE, EXPORT_NAME_RE]) {
+ re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(source)) !== null) {
+ names.add(m[1]!);
+ }
+ }
+ EXPORT_LIST_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = EXPORT_LIST_RE.exec(source)) !== null) {
+ for (const part of m[1]!.split(",")) {
+ const bit = part.trim().split(/\s+as\s+/i).pop()?.trim();
+ if (bit && /^[A-Za-z_$][\w$]*$/.test(bit)) names.add(bit);
+ }
+ }
+ return [...names].sort();
+}
+
+function extractJsExportOrder(source: string): string[] {
+ const order: string[] = [];
+ const seen = new Set<string>();
+ const push = (n: string) => {
+ if (!seen.has(n)) {
+ seen.add(n);
+ order.push(n);
+ }
+ };
+ EXPORT_NAME_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = EXPORT_NAME_RE.exec(source)) !== null) push(m[1]!);
+ EXPORT_LIST_RE.lastIndex = 0;
+ while ((m = EXPORT_LIST_RE.exec(source)) !== null) {
+ for (const part of m[1]!.split(",")) {
+ const bit = part.trim().split(/\s+as\s+/i).pop()?.trim();
+ if (bit && /^[A-Za-z_$][\w$]*$/.test(bit)) push(bit);
+ }
+ }
+ return order;
+}
+
+function classify(path: string): FilePairMetric["kind"] {
+ const ext = extname(path).toLowerCase();
+ if (ext === ".wasm") return "wasm";
+ if (ext === ".html" || ext === ".htm") return "html";
+ if ([".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"].includes(ext)) return "js";
+ return "other";
+}
+
+function comparePair(
+ rel: string,
+ pathA: string,
+ pathB: string,
+): FilePairMetric {
+ const bufA = readFileSync(pathA);
+ const bufB = readFileSync(pathB);
+ const kind = classify(rel);
+ const ratio = byteDiffRatio(bufA, bufB);
+ let exportNameOverlap: number | null = null;
+ let exportOrderDistance: number | null = null;
+ let identifierOverlap: number | null = null;
+
+ if (kind === "wasm") {
+ try {
+ const ia = inspectWasmBinary(bufA);
+ const ib = inspectWasmBinary(bufB);
+ exportNameOverlap = jaccard(ia.exportNames, ib.exportNames);
+ exportOrderDistance = kendallTauDistance(ia.exportNames, ib.exportNames);
+ } catch {
+ // malformed wasm β€” leave nulls
+ }
+ } else if (kind === "js") {
+ const sa = bufA.toString("utf8");
+ const sb = bufB.toString("utf8");
+ const idA = extractJsIdentifiers(sa);
+ const idB = extractJsIdentifiers(sb);
+ identifierOverlap = jaccard(idA, idB);
+ const exA = extractJsExportOrder(sa);
+ const exB = extractJsExportOrder(sb);
+ if (exA.length + exB.length > 0) {
+ exportNameOverlap = jaccard(exA, exB);
+ exportOrderDistance = kendallTauDistance(exA, exB);
+ }
+ }
+
+ return {
+ relativePath: rel,
+ kind,
+ byteEqual: bufA.equals(bufB),
+ byteDiffRatio: ratio,
+ exportNameOverlap,
+ exportOrderDistance,
+ identifierOverlap,
+ };
+}
+
+/**
+ * Aggregate driftScore ∈ [0,1]: higher = more structural difference.
+ * Mixes byte diff, export-name divergence, order distance, identifier divergence.
+ */
+/**
+ * Weighted drift per file. Byte + identifier divergence dominate because
+ * public export *names* are often ABI-stable by design (preserving them must
+ * not dilute a real body/rename shuffle into a false "same structure" signal).
+ * Export-order distance still counts when rename+shuffle actually reorders.
+ */
+function aggregateDrift(files: readonly FilePairMetric[]): number {
+ if (files.length === 0) return 0;
+ let acc = 0;
+ for (const f of files) {
+ let weighted = 0;
+ let weightSum = 0;
+ const add = (value: number, w: number) => {
+ weighted += value * w;
+ weightSum += w;
+ };
+ add(f.byteDiffRatio, 0.45);
+ if (f.identifierOverlap !== null) add(1 - f.identifierOverlap, 0.3);
+ if (f.exportOrderDistance !== null) add(f.exportOrderDistance, 0.15);
+ if (f.exportNameOverlap !== null) add(1 - f.exportNameOverlap, 0.1);
+ acc += weightSum === 0 ? 0 : weighted / weightSum;
+ }
+ return Math.min(1, acc / files.length);
+}
+
+export function comparePolymorphArtifacts(
+ options: PolymorphReportOptions,
+): PolymorphReport {
+ const expect: PolymorphExpectMode = options.expect ?? "report";
+ const sameThreshold = options.sameThreshold ?? 0.01;
+ const differentThreshold = options.differentThreshold ?? 0.25;
+ const dirA = resolve(options.dirA);
+ const dirB = resolve(options.dirB);
+
+ if (!existsSync(dirA) || !statSync(dirA).isDirectory()) {
+ return errorReport(dirA, dirB, expect, `dirA is not a directory: ${dirA}`);
+ }
+ if (!existsSync(dirB) || !statSync(dirB).isDirectory()) {
+ return errorReport(dirA, dirB, expect, `dirB is not a directory: ${dirB}`);
+ }
+
+ const filesA = walkFiles(dirA);
+ const filesB = walkFiles(dirB);
+ const mapA = new Map(filesA.map((f) => [relKey(dirA, f), f]));
+ const mapB = new Map(filesB.map((f) => [relKey(dirB, f), f]));
+ const onlyInA = [...mapA.keys()].filter((k) => !mapB.has(k)).sort();
+ const onlyInB = [...mapB.keys()].filter((k) => !mapA.has(k)).sort();
+ const shared = [...mapA.keys()].filter((k) => mapB.has(k)).sort();
+
+ const files = shared.map((rel) =>
+ comparePair(rel, mapA.get(rel)!, mapB.get(rel)!),
+ );
+
+ // Unpaired files contribute full drift (structure not shared).
+ const unpairedPenalty =
+ onlyInA.length + onlyInB.length === 0
+ ? 0
+ : Math.min(
+ 1,
+ (onlyInA.length + onlyInB.length) /
+ Math.max(1, shared.length + onlyInA.length + onlyInB.length),
+ );
+
+ const baseDrift = aggregateDrift(files);
+ const driftScore = Math.min(1, baseDrift * 0.85 + unpairedPenalty * 0.15);
+ const reproducible = driftScore < sameThreshold && onlyInA.length === 0 && onlyInB.length === 0;
+ const polymorphic = driftScore >= differentThreshold;
+
+ let status: PolymorphReport["status"] = "ok";
+ if (expect === "same" && !reproducible) status = "fail";
+ if (expect === "different" && !polymorphic) status = "fail";
+
+ const summary =
+ `driftScore=${driftScore.toFixed(4)} paired=${files.length} ` +
+ `onlyA=${onlyInA.length} onlyB=${onlyInB.length} ` +
+ `reproducible=${reproducible} polymorphic=${polymorphic}`;
+
+ return {
+ schema: POLYMORPH_REPORT_SCHEMA,
+ dirA,
+ dirB,
+ status,
+ expect,
+ driftScore,
+ reproducible,
+ polymorphic,
+ pairedFileCount: files.length,
+ onlyInA,
+ onlyInB,
+ files,
+ summary,
+ oneLineAdvice:
+ "driftScore measures structural difference only β€” prove functional equivalence with bla_verify / REA; do not treat drift as a cracking-resistance claim.",
+ };
+}
+
+function errorReport(
+ dirA: string,
+ dirB: string,
+ expect: PolymorphExpectMode,
+ message: string,
+): PolymorphReport {
+ return {
+ schema: POLYMORPH_REPORT_SCHEMA,
+ dirA,
+ dirB,
+ status: "error",
+ expect,
+ driftScore: 0,
+ reproducible: false,
+ polymorphic: false,
+ pairedFileCount: 0,
+ onlyInA: [],
+ onlyInB: [],
+ files: [],
+ summary: message,
+ oneLineAdvice: message,
+ };
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index daf34f9..d58eb4f 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -54,6 +54,9 @@ import {
getRedteamReport,
runReaDriftCheck,
} from "../engine/rea-observability.js";
+import {
+ comparePolymorphArtifacts,
+} from "../engine/polymorph-report.js";
import { runShowcaseBenchmark } from "../engine/benchmark.js";
import {
emitCompileTimeNativeHeader,
@@ -887,6 +890,41 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
additionalProperties: false,
},
},
+
+ {
+ name: "bla_polymorph_report",
+ description:
+ "Compare two hardened artifact directories and report objective structural drift (export-name Jaccard, export-order Kendall-tau, byte-diff ratio, identifier overlap, aggregate driftScore). Honesty: drift β‰  cracking resistance β€” prove equivalence with bla_verify / REA. expect=same refuses when driftScore is not near zero; expect=different refuses when drift is too low.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ dir_a: {
+ type: "string",
+ description: "First artifact directory (e.g. harden output with seed A)",
+ },
+ dir_b: {
+ type: "string",
+ description: "Second artifact directory (e.g. harden output with seed B or a re-run of A)",
+ },
+ expect: {
+ type: "string",
+ enum: ["same", "different", "report"],
+ description:
+ "same β†’ fail unless near-byte-identical; different β†’ fail unless driftScore β‰₯ threshold; report (default) β†’ metrics only",
+ },
+ same_threshold: {
+ type: "number",
+ description: "driftScore upper bound for expect=same (default 0.01)",
+ },
+ different_threshold: {
+ type: "number",
+ description: "driftScore lower bound for expect=different (default 0.25)",
+ },
+ },
+ required: ["dir_a", "dir_b"],
+ additionalProperties: false,
+ },
+ },
{
name: "bla_redteam_report",
description:
@@ -1934,6 +1972,28 @@ export async function handleMcpRequest(
const status = (payload as { status: string }).status;
refused = status === "unverified" || status === "fail";
}
+
+ } else if (name === "bla_polymorph_report") {
+ const expectArg = typeof args.expect === "string" ? args.expect : "report";
+ const expectMode =
+ expectArg === "same" || expectArg === "different" || expectArg === "report"
+ ? expectArg
+ : "report";
+ payload = comparePolymorphArtifacts({
+ dirA: args.dir_a as string,
+ dirB: args.dir_b as string,
+ expect: expectMode,
+ ...(typeof args.same_threshold === "number"
+ ? { sameThreshold: args.same_threshold as number }
+ : {}),
+ ...(typeof args.different_threshold === "number"
+ ? { differentThreshold: args.different_threshold as number }
+ : {}),
+ });
+ {
+ const status = (payload as { status: string }).status;
+ refused = status === "fail" || status === "error";
+ }
} else if (name === "bla_redteam_report") {
payload = getRedteamReport({
execute: args.execute === true,
diff --git a/tests/mcp-engine-capability-parity.test.ts b/tests/mcp-engine-capability-parity.test.ts
index 173989d..604c39d 100644
--- a/tests/mcp-engine-capability-parity.test.ts
+++ b/tests/mcp-engine-capability-parity.test.ts
@@ -159,6 +159,10 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{
tool: "bla_rea_drift",
params: ["rea_root"],
},
+ {
+ tool: "bla_polymorph_report",
+ params: ["dir_a", "dir_b", "expect", "same_threshold", "different_threshold"],
+ },
{
tool: "bla_redteam_report",
params: ["execute", "rea_root", "report_path"],
diff --git a/tests/polymorph-report.test.ts b/tests/polymorph-report.test.ts
new file mode 100644
index 0000000..ab5811b
--- /dev/null
+++ b/tests/polymorph-report.test.ts
@@ -0,0 +1,140 @@
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { comparePolymorphArtifacts } from "../src/engine/polymorph-report.js";
+import { protectTarget } from "../src/engine/protector.js";
+import { handleMcpRequest } from "../src/mcp/server.js";
+import { deriveSeedLabel, SeededPrng } from "../src/core/prng.js";
+
+const tempDirs: string[] = [];
+afterEach(() => {
+ for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+const SRC = `
+export function unlockPremium(token) {
+ if (typeof token !== "string") return false;
+ return token.length >= 8 && token.startsWith("LIVE");
+}
+export function describePlan() {
+ return "premium";
+}
+`;
+
+function hardenTo(dir: string, seed: string): string {
+ mkdirSync(dir, { recursive: true });
+ const input = join(dir, "app.js");
+ writeFileSync(input, SRC, "utf8");
+ const outDir = join(dir, "out");
+ mkdirSync(outDir, { recursive: true });
+ const out = join(outDir, "app.js");
+ protectTarget({
+ inputPath: input,
+ outputPath: out,
+ intensity: "bankrupt",
+ seed,
+ });
+ return outDir;
+}
+
+describe("polymorph-report (seeded polymorphism)", () => {
+ it("same seed β†’ reproducible (expect=same passes)", () => {
+ const root = mkdtempSync(join(tmpdir(), "bla-poly-same-"));
+ tempDirs.push(root);
+ const a = hardenTo(join(root, "a"), "poly-seed-fixed");
+ const b = hardenTo(join(root, "b"), "poly-seed-fixed");
+ const report = comparePolymorphArtifacts({
+ dirA: a,
+ dirB: b,
+ expect: "same",
+ });
+ expect(report.status).toBe("ok");
+ expect(report.reproducible).toBe(true);
+ expect(report.driftScore).toBeLessThan(0.01);
+ expect(report.files.every((f) => f.byteEqual)).toBe(true);
+ });
+
+ it("different seeds β†’ polymorphic (expect=different passes)", () => {
+ const root = mkdtempSync(join(tmpdir(), "bla-poly-diff-"));
+ tempDirs.push(root);
+ const a = hardenTo(join(root, "a"), "poly-seed-A");
+ const b = hardenTo(join(root, "b"), "poly-seed-B");
+ const report = comparePolymorphArtifacts({
+ dirA: a,
+ dirB: b,
+ expect: "different",
+ });
+ expect(report.status).toBe("ok");
+ expect(report.polymorphic).toBe(true);
+ expect(report.driftScore).toBeGreaterThanOrEqual(0.25);
+ // At least one file must differ in bytes
+ expect(report.files.some((f) => !f.byteEqual)).toBe(true);
+ });
+
+ it("expect=same refuses when seeds differ", () => {
+ const root = mkdtempSync(join(tmpdir(), "bla-poly-refuse-"));
+ tempDirs.push(root);
+ const a = hardenTo(join(root, "a"), "seed-X");
+ const b = hardenTo(join(root, "b"), "seed-Y");
+ const report = comparePolymorphArtifacts({
+ dirA: a,
+ dirB: b,
+ expect: "same",
+ });
+ expect(report.status).toBe("fail");
+ expect(report.reproducible).toBe(false);
+ });
+
+ it("hardened output still exports unlockPremium (functional surface)", async () => {
+ const root = mkdtempSync(join(tmpdir(), "bla-poly-fn-"));
+ tempDirs.push(root);
+ const outDir = hardenTo(root, "poly-fn-seed");
+ const mod = await import(join(outDir, "app.js"));
+ expect(typeof mod.unlockPremium).toBe("function");
+ expect(mod.unlockPremium("LIVE-KEY-99")).toBe(true);
+ expect(mod.unlockPremium("nope")).toBe(false);
+ });
+
+ it("MCP bla_polymorph_report wires through", async () => {
+ const root = mkdtempSync(join(tmpdir(), "bla-poly-mcp-"));
+ tempDirs.push(root);
+ const a = hardenTo(join(root, "a"), "mcp-seed-1");
+ const b = hardenTo(join(root, "b"), "mcp-seed-1");
+ const res = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "bla_polymorph_report",
+ arguments: { dir_a: a, dir_b: b, expect: "same" },
+ },
+ });
+ expect(res?.error).toBeUndefined();
+ const result = res!.result as {
+ isError: boolean;
+ structuredContent: { status: string; reproducible: boolean; schema: string };
+ };
+ expect(result.isError).toBe(false);
+ expect(result.structuredContent.schema).toBe("bla-polymorph-report/v1");
+ expect(result.structuredContent.status).toBe("ok");
+ expect(result.structuredContent.reproducible).toBe(true);
+ });
+
+ it("bundler-style deriveSeedLabel keeps chunk streams independent but stable", () => {
+ const root = "build-root";
+ const s1 = deriveSeedLabel(root, "chunk-a.js");
+ const s2 = deriveSeedLabel(root, "chunk-a.js");
+ const s3 = deriveSeedLabel(root, "chunk-b.js");
+ expect(s1).toBe(s2);
+ expect(s1).not.toBe(s3);
+ const ids1 = new SeededPrng(s1).identifier({ style: "camel", hint: "x", entropy: 2 });
+ const ids2 = new SeededPrng(s1).identifier({ style: "camel", hint: "x", entropy: 2 });
+ expect(ids1).toBe(ids2);
+ });
+});
diff --git a/tests/skill-guide-contents.test.ts b/tests/skill-guide-contents.test.ts
index 1a27b3c..d016d27 100644
--- a/tests/skill-guide-contents.test.ts
+++ b/tests/skill-guide-contents.test.ts
@@ -31,6 +31,7 @@ describe("blind-llm-agents skill guide contents", () => {
expect(text).toContain("in_place");
expect(text).toContain("bla_run_lookup");
expect(text).toContain("bla_rea_drift");
+ expect(text).toContain("bla_polymorph_report");
expect(text).toContain("bla_redteam_report");
expect(text).toMatch(/unverified/i);
expect(text).toContain("available");