Add deep TLA+ specification check module
This commit is contained in:
1 parent
96dab3777e
commit
100eccc2a9
13 files changed
+1798
-46
No files matched your search
+158
-43
@@ -37,6 +37,12 @@ import * as path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { Type } from "typebox";
|
||||
import {
|
||||
createTlaVerification,
|
||||
type SpecificationOutcome,
|
||||
type TlaSettings,
|
||||
type TlaVerification,
|
||||
} from "./verify/tla.ts";
|
||||
|
||||
const EXT_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -45,6 +51,9 @@ const TLC_TIMEOUT_MS = 300_000;
|
||||
const SANY_TIMEOUT_MS = 60_000;
|
||||
const MAX_SETTLE_CONTINUATIONS = 3;
|
||||
|
||||
const JAVA_NOT_FOUND_TEXT =
|
||||
"Java not found on PATH. Install Java 11+ (e.g. `sudo apt-get install default-jre`).";
|
||||
|
||||
const SETUP_TEXT = [
|
||||
"TLA+ toolchain not found. To set it up:",
|
||||
" 1. Install Java 11+ (e.g. `sudo apt-get install default-jre`)",
|
||||
@@ -240,11 +249,6 @@ function translatePlusCal(jar: string, specAbs: string, signal?: AbortSignal): P
|
||||
return runJava(jar, ["pcal.trans", "-nocfg", specAbs], path.dirname(specAbs), SANY_TIMEOUT_MS, signal);
|
||||
}
|
||||
|
||||
/** SANY parse of a single spec file. */
|
||||
function sany(jar: string, specAbs: string, signal?: AbortSignal): Promise<RunResult> {
|
||||
return runJava(jar, ["tla2sany.SANY", specAbs], path.dirname(specAbs), SANY_TIMEOUT_MS, signal);
|
||||
}
|
||||
|
||||
function okResult(text: string) {
|
||||
return { content: [{ type: "text" as const, text }], details: {} };
|
||||
}
|
||||
@@ -266,6 +270,126 @@ function extractTlcErrors(out: string): string {
|
||||
return tail(out, 4000);
|
||||
}
|
||||
|
||||
function tlaSettings(root: string, config: VerifyConfig): TlaSettings {
|
||||
return {
|
||||
root,
|
||||
configuredJar: config.tla2toolsJar,
|
||||
tlcTimeoutMs: config.tlcTimeoutMs ?? TLC_TIMEOUT_MS,
|
||||
allowProjectJars: true,
|
||||
};
|
||||
}
|
||||
|
||||
function setupErrorText(outcome: Extract<SpecificationOutcome, { status: "setup-error" }>): string {
|
||||
switch (outcome.reason) {
|
||||
case "jar-missing":
|
||||
return SETUP_TEXT;
|
||||
case "java-missing":
|
||||
return JAVA_NOT_FOUND_TEXT;
|
||||
case "java-unsupported":
|
||||
return `Java is too old. Install Java 11+ (e.g. \`sudo apt-get install default-jre\`).\n\n${outcome.evidence}`;
|
||||
case "java-probe-failed":
|
||||
return `Could not determine a usable Java version. Install Java 11+ (e.g. \`sudo apt-get install default-jre\`).\n\n${outcome.evidence}`;
|
||||
}
|
||||
}
|
||||
|
||||
function phaseText(phase: "setup" | "translation" | "sany"): string {
|
||||
switch (phase) {
|
||||
case "setup":
|
||||
return "TLA+ setup";
|
||||
case "translation":
|
||||
return "PlusCal translation";
|
||||
case "sany":
|
||||
return "SANY";
|
||||
}
|
||||
}
|
||||
|
||||
function formatSpecificationCheck(
|
||||
outcome: SpecificationOutcome,
|
||||
requestedSpec: string,
|
||||
): { ok: boolean; text: string } {
|
||||
const name = path.basename(outcome.specPath);
|
||||
switch (outcome.status) {
|
||||
case "pass": {
|
||||
const plusCal = outcome.plusCalTranslated ? "; PlusCal re-translated" : "";
|
||||
return {
|
||||
ok: true,
|
||||
text: `SANY: ${name} parsed OK (no syntax/semantic errors${plusCal}).`,
|
||||
};
|
||||
}
|
||||
case "invalid-input":
|
||||
return { ok: false, text: `File not found: ${requestedSpec}` };
|
||||
case "setup-error":
|
||||
return { ok: false, text: setupErrorText(outcome) };
|
||||
case "translation-error":
|
||||
return {
|
||||
ok: false,
|
||||
text: `PlusCal translation failed:\n${outcome.evidence}`,
|
||||
};
|
||||
case "parse-error":
|
||||
return {
|
||||
ok: false,
|
||||
text: `SANY found parse errors in ${name}:\n\n${outcome.evidence}`,
|
||||
};
|
||||
case "semantic-error":
|
||||
return {
|
||||
ok: false,
|
||||
text: `SANY found semantic errors in ${name}:\n\n${outcome.evidence}`,
|
||||
};
|
||||
case "timeout": {
|
||||
const phase = phaseText(outcome.phase);
|
||||
const evidence = outcome.evidence ? `\n\n${outcome.evidence}` : "";
|
||||
return {
|
||||
ok: false,
|
||||
text: `${phase} timed out after ${outcome.timeoutMs / 1000}s.${evidence}`,
|
||||
};
|
||||
}
|
||||
case "aborted":
|
||||
return {
|
||||
ok: false,
|
||||
text: `${phaseText(outcome.phase)} aborted.${outcome.evidence ? `\n\n${outcome.evidence}` : ""}`,
|
||||
};
|
||||
case "tool-error": {
|
||||
const exit = outcome.exitCode === undefined || outcome.exitCode === null
|
||||
? ""
|
||||
: ` (exit ${outcome.exitCode})`;
|
||||
return {
|
||||
ok: false,
|
||||
text: `${phaseText(outcome.phase ?? "sany")} failed unexpectedly${exit}:\n\n${outcome.evidence}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Auto-SANY notes; null keeps the hook silent for setup and missing files. */
|
||||
function formatAutoSany(outcome: SpecificationOutcome): string | null {
|
||||
switch (outcome.status) {
|
||||
case "invalid-input":
|
||||
case "setup-error":
|
||||
return null;
|
||||
case "pass":
|
||||
return outcome.plusCalTranslated
|
||||
? "tla_check (auto): PlusCal re-translated; SANY parsed OK."
|
||||
: "tla_check (auto): SANY parsed OK.";
|
||||
case "parse-error":
|
||||
return `tla_check (auto): SANY found parse errors — fix before model checking:\n${tail(outcome.evidence, 2000)}`;
|
||||
case "semantic-error":
|
||||
return `tla_check (auto): SANY found semantic errors — fix before model checking:\n${tail(outcome.evidence, 2000)}`;
|
||||
case "translation-error":
|
||||
return `tla_check (auto): PlusCal translation failed — call tla_check for details:\n${tail(outcome.evidence, 1500)}`;
|
||||
case "timeout": {
|
||||
const phase = phaseText(outcome.phase);
|
||||
const evidence = outcome.evidence
|
||||
? `\n${tail(outcome.evidence, 1500)}`
|
||||
: "";
|
||||
return `tla_check (auto): ${phase} timed out after ${outcome.timeoutMs / 1000}s — call tla_check for details.${evidence}`;
|
||||
}
|
||||
case "aborted":
|
||||
return `tla_check (auto): ${phaseText(outcome.phase)} aborted — call tla_check for details.${outcome.evidence ? `\n${tail(outcome.evidence, 1500)}` : ""}`;
|
||||
case "tool-error":
|
||||
return `tla_check (auto): ${phaseText(outcome.phase ?? "sany")} failed unexpectedly — call tla_check for details:\n${tail(outcome.evidence, 1500)}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function runGates(root: string, filter?: string, signal?: AbortSignal, onlyOnSettle = false): Promise<GateResult[]> {
|
||||
const { config } = loadConfig(root);
|
||||
const gates = (config.gates ?? [])
|
||||
@@ -309,7 +433,20 @@ function formatGateResults(results: GateResult[], ms: number): string {
|
||||
return [header, "", ...lines].join("\n");
|
||||
}
|
||||
|
||||
export default function verifyExtension(pi: ExtensionAPI) {
|
||||
export interface VerifyExtensionOptions {
|
||||
/** Injectable deep TLA+ module for behavioral tests. */
|
||||
tla?: TlaVerification;
|
||||
/** Project root provider; production uses the process working directory. */
|
||||
root?: () => string;
|
||||
}
|
||||
|
||||
export default function verifyExtension(
|
||||
pi: ExtensionAPI,
|
||||
options: VerifyExtensionOptions = {},
|
||||
) {
|
||||
const getRoot = options.root ?? (() => process.cwd());
|
||||
const tla = options.tla ?? createTlaVerification();
|
||||
|
||||
// ------------------------------------------------------------------ tools
|
||||
|
||||
pi.registerTool({
|
||||
@@ -321,21 +458,15 @@ export default function verifyExtension(pi: ExtensionAPI) {
|
||||
spec: Type.String({ description: "Path to the .tla file, relative to the working directory" }),
|
||||
}),
|
||||
async execute(_toolCallId, params, signal) {
|
||||
const root = process.cwd();
|
||||
const file = path.resolve(root, params.spec);
|
||||
if (!fs.existsSync(file)) return errResult(`File not found: ${params.spec}`);
|
||||
const root = getRoot();
|
||||
const { config } = loadConfig(root);
|
||||
const jar = resolveJar(root, config);
|
||||
if (!jar) return errResult(SETUP_TEXT);
|
||||
if (!(await hasJava())) return errResult("Java not found on PATH. Install Java 11+ (e.g. `sudo apt-get install default-jre`).");
|
||||
if (hasPlusCalAlgorithm(file)) {
|
||||
const t = await translatePlusCal(jar, file, signal);
|
||||
if (t.code !== 0) return errResult(`PlusCal translation failed:\n${tail(t.stdout + t.stderr, 4000)}`);
|
||||
}
|
||||
const r = await sany(jar, file, signal);
|
||||
if (r.timedOut) return errResult("SANY timed out.");
|
||||
if (r.code === 0) return okResult(`SANY: ${path.basename(file)} parsed OK (no syntax/semantic errors).`);
|
||||
return errResult(`SANY found parse errors in ${path.basename(file)}:\n\n${tail(r.stdout + r.stderr, 4000)}`);
|
||||
const outcome = await tla.checkSpecification({
|
||||
spec: params.spec,
|
||||
settings: tlaSettings(root, config),
|
||||
signal,
|
||||
});
|
||||
const formatted = formatSpecificationCheck(outcome, params.spec);
|
||||
return formatted.ok ? okResult(formatted.text) : errResult(formatted.text);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -435,32 +566,16 @@ export default function verifyExtension(pi: ExtensionAPI) {
|
||||
if (event.toolName !== "edit" && event.toolName !== "write") return;
|
||||
const file = String((event.input as { path?: string } | undefined)?.path ?? "");
|
||||
if (!file.endsWith(".tla")) return;
|
||||
const root = process.cwd();
|
||||
const root = getRoot();
|
||||
const abs = path.resolve(root, file);
|
||||
if (!fs.existsSync(abs)) return;
|
||||
const { config } = loadConfig(root);
|
||||
const jar = resolveJar(root, config);
|
||||
if (!jar || !(await hasJava())) return; // silent: tla_check reports setup guidance
|
||||
let note: string;
|
||||
if (hasPlusCalAlgorithm(abs)) {
|
||||
const t = await translatePlusCal(jar, abs);
|
||||
if (t.code !== 0) {
|
||||
note = `tla_check (auto): PlusCal translation failed — call tla_check for details:\n${tail(t.stdout + t.stderr, 1500)}`;
|
||||
} else {
|
||||
const r = await sany(jar, abs);
|
||||
note =
|
||||
r.timedOut || r.code === 0
|
||||
? "tla_check (auto): PlusCal re-translated; SANY parsed OK."
|
||||
: `tla_check (auto): PlusCal re-translated; SANY found parse errors — fix before model checking:\n${tail(r.stdout + r.stderr, 2000)}`;
|
||||
}
|
||||
} else {
|
||||
const r = await sany(jar, abs);
|
||||
if (r.timedOut) return;
|
||||
note =
|
||||
r.code === 0
|
||||
? "tla_check (auto): SANY parsed OK."
|
||||
: `tla_check (auto): SANY found parse errors — fix before model checking:\n${tail(r.stdout + r.stderr, 2000)}`;
|
||||
}
|
||||
const outcome = await tla.checkSpecification({
|
||||
spec: abs,
|
||||
settings: tlaSettings(root, config),
|
||||
});
|
||||
const note = formatAutoSany(outcome);
|
||||
if (!note) return;
|
||||
const content = Array.isArray(event.content)
|
||||
? [...event.content, { type: "text" as const, text: note }]
|
||||
: [{ type: "text" as const, text: String(event.content ?? "") }, { type: "text" as const, text: note }];
|
||||
|
||||
@@ -0,0 +1,541 @@
|
||||
/**
|
||||
* Deep TLA+ verification module.
|
||||
*
|
||||
* Specification Check owns jar resolution, Java probing, PlusCal
|
||||
* translation, SANY execution, outcome classification, and evidence bounds.
|
||||
* Pi-facing wording and parameter adaptation stay in `extensions/verify.ts`.
|
||||
*
|
||||
* This module deliberately does not import Pi runtime values and never reads
|
||||
* the process-global working directory: callers pass an absolute project root
|
||||
* in `TlaSettings`.
|
||||
*/
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const SANY_TIMEOUT_MS = 60_000;
|
||||
export const JAVA_PROBE_TIMEOUT_MS = 15_000;
|
||||
export const DEFAULT_TLC_TIMEOUT_MS = 300_000;
|
||||
export const MINIMUM_JAVA_MAJOR = 11;
|
||||
|
||||
const EVIDENCE_LIMIT = 8_000;
|
||||
const MAX_BUFFER = 20_000_000;
|
||||
|
||||
const EXTENSION_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface TlaSettings {
|
||||
/** Absolute project root. All caller paths resolve from here. */
|
||||
root: string;
|
||||
/** Configured jar path; relative values resolve from `root`. */
|
||||
configuredJar?: string;
|
||||
/** TLC timeout used by the model-check operation. */
|
||||
tlcTimeoutMs: number;
|
||||
/** Whether project-local vendor/ and tools/ jars may be used. */
|
||||
allowProjectJars: boolean;
|
||||
}
|
||||
|
||||
export interface SpecificationCheckRequest {
|
||||
/** Spec path, relative to `settings.root` or absolute. */
|
||||
spec: string;
|
||||
settings: TlaSettings;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface JavaProbeResult {
|
||||
code: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
timedOut: boolean;
|
||||
aborted: boolean;
|
||||
/** Node spawn error code, for example ENOENT. */
|
||||
spawnError?: string;
|
||||
}
|
||||
|
||||
export interface JvmRunResult extends JavaProbeResult {}
|
||||
|
||||
/**
|
||||
* Narrow JVM seam. Production uses `createNodeJvm()`; behavioral tests use a
|
||||
* fake that records invocation order and arguments.
|
||||
*/
|
||||
export interface Jvm {
|
||||
probeJava(cwd: string, signal?: AbortSignal): Promise<JavaProbeResult>;
|
||||
runJava(
|
||||
jar: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JvmRunResult>;
|
||||
}
|
||||
|
||||
export type SetupErrorReason =
|
||||
| "jar-missing"
|
||||
| "java-missing"
|
||||
| "java-unsupported"
|
||||
| "java-probe-failed";
|
||||
|
||||
export type SpecificationPhase = "setup" | "translation" | "sany";
|
||||
export type SpecificationTimeoutPhase = "translation" | "sany";
|
||||
|
||||
interface SpecificationOutcomeBase {
|
||||
/** Absolute path after resolving the caller's spec from `settings.root`. */
|
||||
specPath: string;
|
||||
/** Bounded stdout/stderr evidence for caller-specific formatting. */
|
||||
evidence: string;
|
||||
exitCode?: number | null;
|
||||
plusCalTranslated?: boolean;
|
||||
}
|
||||
|
||||
export type SpecificationOutcome =
|
||||
| (SpecificationOutcomeBase & { status: "pass" })
|
||||
| (SpecificationOutcomeBase & { status: "invalid-input" })
|
||||
| (SpecificationOutcomeBase & { status: "setup-error"; reason: SetupErrorReason })
|
||||
| (SpecificationOutcomeBase & { status: "translation-error" })
|
||||
| (SpecificationOutcomeBase & { status: "parse-error" })
|
||||
| (SpecificationOutcomeBase & { status: "semantic-error" })
|
||||
| (SpecificationOutcomeBase & {
|
||||
status: "timeout";
|
||||
phase: SpecificationTimeoutPhase;
|
||||
timeoutMs: number;
|
||||
})
|
||||
| (SpecificationOutcomeBase & { status: "aborted"; phase: SpecificationPhase })
|
||||
| (SpecificationOutcomeBase & { status: "tool-error"; phase?: SpecificationPhase });
|
||||
|
||||
export interface TlaVerification {
|
||||
checkSpecification(request: SpecificationCheckRequest): Promise<SpecificationOutcome>;
|
||||
}
|
||||
|
||||
export interface TlaVerificationOptions {
|
||||
jvm?: Jvm;
|
||||
env?: Record<string, string | undefined>;
|
||||
homeDir?: string;
|
||||
/** Directory containing this module; the loose-layout vendor/ lives here. */
|
||||
extensionDir?: string;
|
||||
/** Package root containing package.json/vendor, or null when loose. */
|
||||
packageRoot?: string | null;
|
||||
}
|
||||
|
||||
function combineOutput(result: { stdout: string; stderr: string }): string {
|
||||
return result.stderr ? `${result.stdout}\n${result.stderr}` : result.stdout;
|
||||
}
|
||||
|
||||
/** Keep the tail: errors and counterexamples end with the actionable detail. */
|
||||
function boundedEvidence(output: string, limit = EVIDENCE_LIMIT): string {
|
||||
const cleaned = output.replace(/\r/g, "");
|
||||
if (cleaned.length <= limit) return cleaned;
|
||||
return cleaned.slice(cleaned.length - limit);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function parseJavaMajor(output: string): number | null {
|
||||
const match = /(?:java|openjdk)\s+version\s+"([^"]+)"/i.exec(output);
|
||||
if (!match) return null;
|
||||
const parts = match[1].split(/[._+-]/);
|
||||
const first = Number(parts[0]);
|
||||
if (!Number.isInteger(first)) return null;
|
||||
if (first === 1) {
|
||||
const second = Number(parts[1]);
|
||||
return Number.isInteger(second) ? second : null;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
function hasPlusCalAlgorithm(specPath: string): boolean {
|
||||
try {
|
||||
return /--(fair )?algorithm/.test(fs.readFileSync(specPath, "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFromRoot(root: string, candidate: string): string {
|
||||
return path.isAbsolute(candidate) ? candidate : path.resolve(root, candidate);
|
||||
}
|
||||
|
||||
function findPackageRoot(startDir: string): string | null {
|
||||
let dir = startDir;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
if (fs.existsSync(path.join(dir, "package.json"))) return dir;
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface JarResolutionEnvironment {
|
||||
env: Record<string, string | undefined>;
|
||||
homeDir: string;
|
||||
extensionDir: string;
|
||||
packageRoot: string | null;
|
||||
}
|
||||
|
||||
function resolveJar(settings: TlaSettings, environment: JarResolutionEnvironment): string | null {
|
||||
const candidates: Array<string | undefined> = [
|
||||
settings.configuredJar,
|
||||
environment.env.TLA2_TOOLS_JAR,
|
||||
environment.packageRoot
|
||||
? path.join(environment.packageRoot, "vendor", "tla2tools.jar")
|
||||
: undefined,
|
||||
path.join(environment.extensionDir, "vendor", "tla2tools.jar"),
|
||||
// Legacy loose layout: vendor/ beside the entry-point extension file.
|
||||
path.join(path.dirname(environment.extensionDir), "vendor", "tla2tools.jar"),
|
||||
path.join(environment.homeDir, ".pi", "agent", "vendor", "tla2tools.jar"),
|
||||
];
|
||||
if (settings.allowProjectJars) {
|
||||
candidates.push(
|
||||
path.join(settings.root, "vendor", "tla2tools.jar"),
|
||||
path.join(settings.root, "tools", "tla2tools.jar"),
|
||||
);
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue;
|
||||
const absolute = resolveFromRoot(settings.root, candidate);
|
||||
if (fs.existsSync(absolute)) return absolute;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function probeFailure(
|
||||
specPath: string,
|
||||
reason: SetupErrorReason,
|
||||
evidence: string,
|
||||
): SpecificationOutcome {
|
||||
return {
|
||||
status: "setup-error",
|
||||
reason,
|
||||
specPath,
|
||||
evidence: boundedEvidence(evidence),
|
||||
};
|
||||
}
|
||||
|
||||
function abortedOutcome(
|
||||
specPath: string,
|
||||
phase: SpecificationPhase,
|
||||
evidence = "",
|
||||
): SpecificationOutcome {
|
||||
return { status: "aborted", phase, specPath, evidence: boundedEvidence(evidence) };
|
||||
}
|
||||
|
||||
function classifySany(
|
||||
specPath: string,
|
||||
result: JvmRunResult,
|
||||
plusCalTranslated: boolean,
|
||||
): SpecificationOutcome {
|
||||
const output = combineOutput(result);
|
||||
const evidence = boundedEvidence(output);
|
||||
const base: SpecificationOutcomeBase = {
|
||||
specPath,
|
||||
evidence,
|
||||
exitCode: result.code,
|
||||
plusCalTranslated,
|
||||
};
|
||||
|
||||
if (result.spawnError || result.code === null) {
|
||||
return {
|
||||
...base,
|
||||
status: "tool-error",
|
||||
};
|
||||
}
|
||||
// Parse errors win when SANY reports both families.
|
||||
if (/\*\*\*Parse Error\*\*\*|Fatal errors? while parsing/i.test(output)) {
|
||||
return { ...base, status: "parse-error" };
|
||||
}
|
||||
if (/\*\*\* Errors?:|Semantic errors?:|Unknown operator:/i.test(output)) {
|
||||
return { ...base, status: "semantic-error" };
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { ...base, status: "pass" };
|
||||
}
|
||||
return { ...base, status: "tool-error" };
|
||||
}
|
||||
|
||||
export function createTlaVerification(
|
||||
options: TlaVerificationOptions = {},
|
||||
): TlaVerification {
|
||||
const jvm = options.jvm ?? createNodeJvm();
|
||||
const env = options.env ?? process.env;
|
||||
const homeDir = options.homeDir ?? os.homedir();
|
||||
const extensionDir = options.extensionDir ?? EXTENSION_DIR;
|
||||
const packageRoot =
|
||||
options.packageRoot !== undefined
|
||||
? options.packageRoot
|
||||
: findPackageRoot(extensionDir);
|
||||
const environment: JarResolutionEnvironment = {
|
||||
env,
|
||||
homeDir,
|
||||
extensionDir,
|
||||
packageRoot,
|
||||
};
|
||||
|
||||
return {
|
||||
async checkSpecification(
|
||||
request: SpecificationCheckRequest,
|
||||
): Promise<SpecificationOutcome> {
|
||||
const { settings, signal } = request;
|
||||
const specPath = resolveFromRoot(settings.root, request.spec);
|
||||
|
||||
if (signal?.aborted) return abortedOutcome(specPath, "setup");
|
||||
|
||||
if (!fs.existsSync(specPath)) {
|
||||
return {
|
||||
status: "invalid-input",
|
||||
specPath,
|
||||
evidence: `Spec not found: ${request.spec}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (signal?.aborted) return abortedOutcome(specPath, "setup");
|
||||
|
||||
const jar = resolveJar(settings, environment);
|
||||
if (!jar) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"jar-missing",
|
||||
"No tla2tools.jar found.",
|
||||
);
|
||||
}
|
||||
|
||||
if (signal?.aborted) return abortedOutcome(specPath, "setup");
|
||||
|
||||
let probe: JavaProbeResult;
|
||||
try {
|
||||
probe = await jvm.probeJava(settings.root, signal);
|
||||
} catch (error) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-probe-failed",
|
||||
`Java version probe failed: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
const probeOutput = combineOutput(probe);
|
||||
|
||||
if (signal?.aborted || probe.aborted) {
|
||||
return abortedOutcome(specPath, "setup", probeOutput);
|
||||
}
|
||||
if (probe.timedOut) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-probe-failed",
|
||||
`Java version probe timed out after ${JAVA_PROBE_TIMEOUT_MS}ms.\n${probeOutput}`,
|
||||
);
|
||||
}
|
||||
if (probe.spawnError === "ENOENT") {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-missing",
|
||||
"java was not found on PATH.",
|
||||
);
|
||||
}
|
||||
if (probe.spawnError) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-probe-failed",
|
||||
`Java version probe could not start (${probe.spawnError}).\n${probeOutput}`,
|
||||
);
|
||||
}
|
||||
if (probe.code !== 0) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-probe-failed",
|
||||
`java -version exited with code ${String(probe.code)}.\n${probeOutput}`,
|
||||
);
|
||||
}
|
||||
const javaMajor = parseJavaMajor(probeOutput);
|
||||
if (javaMajor === null) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-probe-failed",
|
||||
`Could not parse the Java version.\n${probeOutput}`,
|
||||
);
|
||||
}
|
||||
if (javaMajor < MINIMUM_JAVA_MAJOR) {
|
||||
return probeFailure(
|
||||
specPath,
|
||||
"java-unsupported",
|
||||
`Java ${javaMajor} is too old; Java ${MINIMUM_JAVA_MAJOR}+ is required.\n${probeOutput}`,
|
||||
);
|
||||
}
|
||||
|
||||
const plusCal = hasPlusCalAlgorithm(specPath);
|
||||
let plusCalTranslated = false;
|
||||
|
||||
if (plusCal) {
|
||||
if (signal?.aborted) return abortedOutcome(specPath, "translation");
|
||||
let translation: JvmRunResult;
|
||||
try {
|
||||
translation = await jvm.runJava(
|
||||
jar,
|
||||
["pcal.trans", "-nocfg", specPath],
|
||||
path.dirname(specPath),
|
||||
SANY_TIMEOUT_MS,
|
||||
signal,
|
||||
);
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "tool-error",
|
||||
phase: "translation",
|
||||
specPath,
|
||||
evidence: boundedEvidence(
|
||||
`PlusCal translation failed to start: ${errorMessage(error)}`,
|
||||
),
|
||||
exitCode: null,
|
||||
plusCalTranslated: false,
|
||||
};
|
||||
}
|
||||
const translationOutput = combineOutput(translation);
|
||||
if (signal?.aborted || translation.aborted) {
|
||||
return abortedOutcome(specPath, "translation", translationOutput);
|
||||
}
|
||||
if (translation.timedOut) {
|
||||
return {
|
||||
status: "timeout",
|
||||
phase: "translation",
|
||||
timeoutMs: SANY_TIMEOUT_MS,
|
||||
specPath,
|
||||
evidence: boundedEvidence(translationOutput),
|
||||
exitCode: translation.code,
|
||||
plusCalTranslated: false,
|
||||
};
|
||||
}
|
||||
if (translation.spawnError || translation.code === null) {
|
||||
return {
|
||||
status: "tool-error",
|
||||
phase: "translation",
|
||||
specPath,
|
||||
evidence: boundedEvidence(translationOutput),
|
||||
exitCode: translation.code,
|
||||
plusCalTranslated: false,
|
||||
};
|
||||
}
|
||||
if (translation.code !== 0) {
|
||||
return {
|
||||
status: "translation-error",
|
||||
specPath,
|
||||
evidence: boundedEvidence(translationOutput),
|
||||
exitCode: translation.code,
|
||||
plusCalTranslated: false,
|
||||
};
|
||||
}
|
||||
plusCalTranslated = true;
|
||||
}
|
||||
|
||||
if (signal?.aborted) return abortedOutcome(specPath, "sany");
|
||||
|
||||
let sanyResult: JvmRunResult;
|
||||
try {
|
||||
sanyResult = await jvm.runJava(
|
||||
jar,
|
||||
["tla2sany.SANY", specPath],
|
||||
path.dirname(specPath),
|
||||
SANY_TIMEOUT_MS,
|
||||
signal,
|
||||
);
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "tool-error",
|
||||
phase: "sany",
|
||||
specPath,
|
||||
evidence: boundedEvidence(`SANY failed to start: ${errorMessage(error)}`),
|
||||
exitCode: null,
|
||||
plusCalTranslated,
|
||||
};
|
||||
}
|
||||
const sanyOutput = combineOutput(sanyResult);
|
||||
|
||||
if (signal?.aborted || sanyResult.aborted) {
|
||||
return abortedOutcome(specPath, "sany", sanyOutput);
|
||||
}
|
||||
if (sanyResult.timedOut) {
|
||||
return {
|
||||
status: "timeout",
|
||||
phase: "sany",
|
||||
timeoutMs: SANY_TIMEOUT_MS,
|
||||
specPath,
|
||||
evidence: boundedEvidence(sanyOutput),
|
||||
exitCode: sanyResult.code,
|
||||
plusCalTranslated,
|
||||
};
|
||||
}
|
||||
|
||||
return classifySany(specPath, sanyResult, plusCalTranslated);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface ExecFileOutcome {
|
||||
code: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
timedOut: boolean;
|
||||
aborted: boolean;
|
||||
spawnError?: string;
|
||||
}
|
||||
|
||||
function runExecFile(
|
||||
file: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ExecFileOutcome> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
{
|
||||
cwd,
|
||||
timeout: timeoutMs,
|
||||
killSignal: "SIGKILL",
|
||||
maxBuffer: MAX_BUFFER,
|
||||
signal,
|
||||
},
|
||||
(error, stdout, stderr) => {
|
||||
const e = error as
|
||||
| (Error & { code?: number | string; killed?: boolean })
|
||||
| null;
|
||||
const aborted = signal?.aborted === true;
|
||||
const timedOut = !!e && e.killed === true && !aborted;
|
||||
const spawnError =
|
||||
e && typeof e.code === "string" ? e.code : undefined;
|
||||
const code = e
|
||||
? typeof e.code === "number"
|
||||
? e.code
|
||||
: null
|
||||
: 0;
|
||||
resolve({
|
||||
code,
|
||||
stdout: String(stdout ?? ""),
|
||||
stderr: String(stderr ?? ""),
|
||||
timedOut,
|
||||
aborted,
|
||||
spawnError,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Production Node/JVM adapter. Java runs directly, never through a shell. */
|
||||
export function createNodeJvm(): Jvm {
|
||||
return {
|
||||
probeJava(cwd, signal) {
|
||||
return runExecFile("java", ["-version"], cwd, JAVA_PROBE_TIMEOUT_MS, signal);
|
||||
},
|
||||
runJava(jar, args, cwd, timeoutMs, signal) {
|
||||
return runExecFile(
|
||||
"java",
|
||||
["-XX:+UseParallelGC", "-cp", jar, ...args],
|
||||
cwd,
|
||||
timeoutMs,
|
||||
signal,
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
-1
@@ -26,7 +26,8 @@
|
||||
]
|
||||
},
|
||||
"scripts": {
|
||||
"check": "tsc --noEmit"
|
||||
"check": "tsc --noEmit",
|
||||
"test": "node --test test/behavior/*.test.ts"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "*",
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
import assert from "node:assert/strict";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
createTlaVerification,
|
||||
type SpecificationOutcome,
|
||||
type TlaSettings,
|
||||
} from "../../extensions/verify/tla.ts";
|
||||
import {
|
||||
cleanup,
|
||||
copySpec,
|
||||
FakeJvm,
|
||||
fixtureText,
|
||||
javaProbe,
|
||||
jvmRun,
|
||||
makeTempDir,
|
||||
writeFile,
|
||||
} from "../fixtures/support.ts";
|
||||
|
||||
interface Context {
|
||||
root: string;
|
||||
specAbs: string;
|
||||
jar: string;
|
||||
settings: TlaSettings;
|
||||
jvm: FakeJvm;
|
||||
tla: ReturnType<typeof createTlaVerification>;
|
||||
}
|
||||
|
||||
function makeContext(specName = "Plain.tla", settings: Partial<TlaSettings> = {}): Context {
|
||||
const root = makeTempDir();
|
||||
const specAbs = copySpec(root, specName);
|
||||
const jar = writeFile(root, "custom-tla2tools.jar", "fake jar");
|
||||
const resolvedSettings: TlaSettings = {
|
||||
root,
|
||||
configuredJar: jar,
|
||||
tlcTimeoutMs: 300_000,
|
||||
allowProjectJars: true,
|
||||
...settings,
|
||||
};
|
||||
const jvm = new FakeJvm();
|
||||
const tla = createTlaVerification({
|
||||
jvm,
|
||||
env: {},
|
||||
homeDir: path.join(root, "home"),
|
||||
extensionDir: path.join(root, "extension"),
|
||||
packageRoot: null,
|
||||
});
|
||||
return { root, specAbs, jar, settings: resolvedSettings, jvm, tla };
|
||||
}
|
||||
|
||||
async function check(ctx: Context, signal?: AbortSignal): Promise<SpecificationOutcome> {
|
||||
return ctx.tla.checkSpecification({
|
||||
spec: path.basename(ctx.specAbs),
|
||||
settings: ctx.settings,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
function expectStatus<K extends SpecificationOutcome["status"]>(
|
||||
outcome: SpecificationOutcome,
|
||||
status: K,
|
||||
): Extract<SpecificationOutcome, { status: K }> {
|
||||
assert.equal(outcome.status, status, JSON.stringify(outcome));
|
||||
return outcome as Extract<SpecificationOutcome, { status: K }>;
|
||||
}
|
||||
|
||||
test("SANY pass is a specification pass and invokes SANY once", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 0, stdout: fixtureText("sany/pass.txt") }));
|
||||
|
||||
const outcome = await check(ctx);
|
||||
|
||||
const pass = expectStatus(outcome, "pass");
|
||||
assert.equal(pass.plusCalTranslated, false);
|
||||
assert.match(pass.evidence, /SANY2 Version/);
|
||||
const calls = ctx.jvm.runCalls();
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].jar, ctx.jar);
|
||||
assert.deepEqual(calls[0].args, ["tla2sany.SANY", ctx.specAbs]);
|
||||
assert.equal(calls[0].cwd, path.dirname(ctx.specAbs));
|
||||
assert.equal(calls[0].timeoutMs, 60_000);
|
||||
});
|
||||
|
||||
test("SANY parse errors are parse-errors, regardless of a nonzero exit", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 255, stdout: fixtureText("sany/parse-error.txt") }));
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "parse-error");
|
||||
|
||||
assert.equal(outcome.exitCode, 255);
|
||||
assert.match(outcome.evidence, /\*\*\*Parse Error\*\*\*/);
|
||||
});
|
||||
|
||||
test("SANY semantic errors cannot pass because the process exited 0", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 0, stdout: fixtureText("sany/semantic-error.txt") }));
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "semantic-error");
|
||||
|
||||
assert.equal(outcome.exitCode, 0);
|
||||
assert.match(outcome.evidence, /Semantic errors:/);
|
||||
});
|
||||
|
||||
test("parse markers take precedence when SANY also reports semantic errors", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({
|
||||
code: 0,
|
||||
stdout: "***Parse Error***\nSemantic errors:\n*** Errors: 1",
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "parse-error");
|
||||
|
||||
assert.equal(outcome.exitCode, 0);
|
||||
});
|
||||
|
||||
test("SANY abort reports aborted, not a timeout or failure", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: null, stdout: "interrupted", aborted: true }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "aborted");
|
||||
|
||||
assert.equal(outcome.phase, "sany");
|
||||
assert.equal(ctx.jvm.runCalls().length, 1);
|
||||
});
|
||||
|
||||
test("unknown nonzero SANY failure is a tool-error", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 17, stdout: fixtureText("sany/unknown-failure.txt") }));
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "tool-error");
|
||||
|
||||
assert.equal(outcome.exitCode, 17);
|
||||
assert.match(outcome.evidence, /FileNotFoundException/);
|
||||
});
|
||||
|
||||
test("SANY timeout is a timeout, not a pass", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: null, stdout: "still running", timedOut: true }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "timeout");
|
||||
|
||||
assert.equal(outcome.phase, "sany");
|
||||
assert.equal(outcome.timeoutMs, 60_000);
|
||||
assert.match(outcome.evidence, /still running/);
|
||||
});
|
||||
|
||||
test("a pre-aborted specification check is aborted before probing or running", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
|
||||
const outcome = expectStatus(await check(ctx, controller.signal), "aborted");
|
||||
|
||||
assert.equal(outcome.phase, "setup");
|
||||
assert.equal(ctx.jvm.calls.length, 0);
|
||||
});
|
||||
|
||||
test("PlusCal is translated with -nocfg before SANY, in the spec directory", async (t) => {
|
||||
const ctx = makeContext("Counter.tla");
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: 0, stdout: "Translation completed." }),
|
||||
jvmRun({ code: 0, stdout: fixtureText("sany/pass.txt") }),
|
||||
);
|
||||
|
||||
const outcome = await check(ctx);
|
||||
|
||||
const pass = expectStatus(outcome, "pass");
|
||||
assert.equal(pass.plusCalTranslated, true);
|
||||
const calls = ctx.jvm.runCalls();
|
||||
assert.equal(calls.length, 2);
|
||||
assert.deepEqual(calls[0].args, ["pcal.trans", "-nocfg", ctx.specAbs]);
|
||||
assert.equal(calls[0].cwd, path.dirname(ctx.specAbs));
|
||||
assert.equal(calls[0].timeoutMs, 60_000);
|
||||
assert.deepEqual(calls[1].args, ["tla2sany.SANY", ctx.specAbs]);
|
||||
});
|
||||
|
||||
test("PlusCal translation failure stops before SANY", async (t) => {
|
||||
const ctx = makeContext("Counter.tla");
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: 1, stdout: "Translation failed: syntax error" }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "translation-error");
|
||||
|
||||
assert.match(outcome.evidence, /Translation failed/);
|
||||
assert.equal(ctx.jvm.runCalls().length, 1);
|
||||
});
|
||||
|
||||
test("PlusCal translation timeout identifies the translation phase and stops before SANY", async (t) => {
|
||||
const ctx = makeContext("Counter.tla");
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: null, stdout: "translating", timedOut: true }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "timeout");
|
||||
|
||||
assert.equal(outcome.phase, "translation");
|
||||
assert.equal(outcome.timeoutMs, 60_000);
|
||||
assert.equal(ctx.jvm.runCalls().length, 1);
|
||||
});
|
||||
|
||||
test("abort during PlusCal translation stops before SANY", async (t) => {
|
||||
const ctx = makeContext("Counter.tla");
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.runQueue.push(
|
||||
jvmRun({ code: null, stdout: "translating", aborted: true }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "aborted");
|
||||
|
||||
assert.equal(outcome.phase, "translation");
|
||||
assert.equal(ctx.jvm.runCalls().length, 1);
|
||||
});
|
||||
|
||||
test("missing specification is invalid input before toolchain setup", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
|
||||
const outcome = expectStatus(
|
||||
await ctx.tla.checkSpecification({
|
||||
spec: "DoesNotExist.tla",
|
||||
settings: { ...ctx.settings, configuredJar: undefined },
|
||||
}),
|
||||
"invalid-input",
|
||||
);
|
||||
|
||||
assert.match(outcome.evidence, /DoesNotExist\.tla/);
|
||||
assert.equal(ctx.jvm.calls.length, 0);
|
||||
});
|
||||
|
||||
test("Java 8 is rejected as unsupported before SANY", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(
|
||||
javaProbe({
|
||||
code: 0,
|
||||
stderr: 'java version "1.8.0_402"\nJava(TM) SE Runtime Environment\n',
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(outcome.reason, "java-unsupported");
|
||||
assert.match(outcome.evidence, /1\.8\.0_402/);
|
||||
assert.equal(ctx.jvm.runCalls().length, 0);
|
||||
});
|
||||
|
||||
for (const [label, version] of [
|
||||
["Java 11", 'openjdk version "11.0.24" 2024-07-16'],
|
||||
["modern Java", 'openjdk version "21.0.5" 2024-10-15'],
|
||||
] as const) {
|
||||
test(`${label} is accepted and the probe is reused for SANY`, async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(javaProbe({ code: 0, stderr: version }));
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 0, stdout: fixtureText("sany/pass.txt") }));
|
||||
|
||||
expectStatus(await check(ctx), "pass");
|
||||
|
||||
assert.equal(ctx.jvm.probeCalls().length, 1);
|
||||
assert.equal(ctx.jvm.runCalls().length, 1);
|
||||
});
|
||||
}
|
||||
|
||||
test("missing Java executable is a setup-error", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(
|
||||
javaProbe({ code: null, stdout: "", spawnError: "ENOENT" }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(outcome.reason, "java-missing");
|
||||
assert.equal(ctx.jvm.runCalls().length, 0);
|
||||
});
|
||||
|
||||
test("malformed Java version output is a failed probe", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(javaProbe({ code: 0, stdout: "not a Java version" }));
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(outcome.reason, "java-probe-failed");
|
||||
assert.match(outcome.evidence, /not a Java version/);
|
||||
});
|
||||
|
||||
test("a failing Java version probe is a setup-error", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(
|
||||
javaProbe({ code: 2, stdout: "", stderr: "java: cannot execute" }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(outcome.reason, "java-probe-failed");
|
||||
assert.match(outcome.evidence, /cannot execute/);
|
||||
});
|
||||
|
||||
test("a Java probe timeout is surfaced as a setup-error", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(
|
||||
javaProbe({ code: null, stdout: "", timedOut: true }),
|
||||
);
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(outcome.reason, "java-probe-failed");
|
||||
assert.match(outcome.evidence, /timed out/i);
|
||||
});
|
||||
|
||||
test("Java probing is not cached across specification checks", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
ctx.jvm.probeQueue.push(
|
||||
javaProbe({ code: 0, stderr: 'openjdk version "17.0.9"' }),
|
||||
javaProbe({ code: 1, stdout: "", stderr: "probe broke" }),
|
||||
);
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 0, stdout: fixtureText("sany/pass.txt") }));
|
||||
|
||||
expectStatus(await check(ctx), "pass");
|
||||
expectStatus(await check(ctx), "setup-error");
|
||||
|
||||
assert.equal(ctx.jvm.probeCalls().length, 2);
|
||||
});
|
||||
|
||||
test("evidence is bounded for noisy tool failures", async (t) => {
|
||||
const ctx = makeContext();
|
||||
t.after(() => cleanup(ctx.root));
|
||||
const noisy = `${"x".repeat(20_000)}END-OF-OUTPUT`;
|
||||
ctx.jvm.runQueue.push(jvmRun({ code: 99, stdout: noisy }));
|
||||
|
||||
const outcome = expectStatus(await check(ctx), "tool-error");
|
||||
|
||||
assert.ok(outcome.evidence.length <= 8_000, `evidence was ${outcome.evidence.length} bytes`);
|
||||
assert.match(outcome.evidence, /END-OF-OUTPUT/);
|
||||
});
|
||||
|
||||
interface JarScenario {
|
||||
name: string;
|
||||
configuredJar?: "relative" | "missing" | "absolute";
|
||||
envJar?: "relative" | "absolute";
|
||||
packageJar?: boolean;
|
||||
looseJar?: boolean;
|
||||
legacyLooseJar?: boolean;
|
||||
homeJar?: boolean;
|
||||
projectVendorJar?: boolean;
|
||||
projectToolsJar?: boolean;
|
||||
allowProjectJars?: boolean;
|
||||
expected?: "configured" | "env" | "package" | "loose" | "legacy-loose" | "home" | "project-vendor" | "project-tools";
|
||||
}
|
||||
|
||||
async function runJarScenario(scenario: JarScenario) {
|
||||
const root = makeTempDir();
|
||||
const projectRoot = path.join(root, "project");
|
||||
fs.mkdirSync(projectRoot, { recursive: true });
|
||||
const specAbs = copySpec(projectRoot);
|
||||
const paths = {
|
||||
configured: writeFile(projectRoot, "config/custom.jar", "jar"),
|
||||
env: writeFile(projectRoot, "environment/env.jar", "jar"),
|
||||
package: writeFile(root, "package/vendor/tla2tools.jar", "jar"),
|
||||
loose: writeFile(root, "extension/vendor/tla2tools.jar", "jar"),
|
||||
legacyLoose: writeFile(root, "vendor/tla2tools.jar", "jar"),
|
||||
home: writeFile(root, "home/.pi/agent/vendor/tla2tools.jar", "jar"),
|
||||
projectVendor: writeFile(projectRoot, "vendor/tla2tools.jar", "jar"),
|
||||
projectTools: writeFile(projectRoot, "tools/tla2tools.jar", "jar"),
|
||||
};
|
||||
const keep = new Set<string>([
|
||||
paths.configured,
|
||||
paths.env,
|
||||
paths.package,
|
||||
paths.loose,
|
||||
paths.legacyLoose,
|
||||
paths.home,
|
||||
paths.projectVendor,
|
||||
paths.projectTools,
|
||||
]);
|
||||
const chosen = {
|
||||
configured:
|
||||
scenario.configuredJar === "relative" || scenario.configuredJar === "absolute"
|
||||
? paths.configured
|
||||
: undefined,
|
||||
env:
|
||||
scenario.envJar === "relative" || scenario.envJar === "absolute"
|
||||
? paths.env
|
||||
: undefined,
|
||||
package: scenario.packageJar ? paths.package : undefined,
|
||||
loose: scenario.looseJar ? paths.loose : undefined,
|
||||
legacyLoose: scenario.legacyLooseJar ? paths.legacyLoose : undefined,
|
||||
home: scenario.homeJar ? paths.home : undefined,
|
||||
projectVendor: scenario.projectVendorJar ? paths.projectVendor : undefined,
|
||||
projectTools: scenario.projectToolsJar ? paths.projectTools : undefined,
|
||||
};
|
||||
for (const file of keep) {
|
||||
if (!Object.values(chosen).includes(file)) fs.rmSync(file, { force: true });
|
||||
}
|
||||
const settings: TlaSettings = {
|
||||
root: projectRoot,
|
||||
configuredJar:
|
||||
scenario.configuredJar === "relative"
|
||||
? "config/custom.jar"
|
||||
: scenario.configuredJar === "missing"
|
||||
? "config/missing.jar"
|
||||
: chosen.configured,
|
||||
tlcTimeoutMs: 300_000,
|
||||
allowProjectJars: scenario.allowProjectJars ?? true,
|
||||
};
|
||||
const jvm = new FakeJvm();
|
||||
jvm.runQueue.push(jvmRun({ code: 0, stdout: fixtureText("sany/pass.txt") }));
|
||||
const tla = createTlaVerification({
|
||||
jvm,
|
||||
env:
|
||||
scenario.envJar === "relative"
|
||||
? { TLA2_TOOLS_JAR: "environment/env.jar" }
|
||||
: chosen.env
|
||||
? { TLA2_TOOLS_JAR: chosen.env }
|
||||
: {},
|
||||
homeDir: path.join(root, "home"),
|
||||
extensionDir: path.join(root, "extension"),
|
||||
packageRoot: path.join(root, "package"),
|
||||
});
|
||||
const outcome = await tla.checkSpecification({
|
||||
spec: path.basename(specAbs),
|
||||
settings,
|
||||
});
|
||||
const run = jvm.runCalls()[0];
|
||||
const labels: Record<keyof typeof chosen, string> = {
|
||||
configured: "configured",
|
||||
env: "env",
|
||||
package: "package",
|
||||
loose: "loose",
|
||||
legacyLoose: "legacy-loose",
|
||||
home: "home",
|
||||
projectVendor: "project-vendor",
|
||||
projectTools: "project-tools",
|
||||
};
|
||||
const key = run
|
||||
? (Object.keys(chosen) as Array<keyof typeof chosen>).find(
|
||||
(candidate) => chosen[candidate] === run.jar,
|
||||
)
|
||||
: undefined;
|
||||
const actual = key ? labels[key] : undefined;
|
||||
cleanup(root);
|
||||
return { outcome, actual };
|
||||
}
|
||||
|
||||
test("jar precedence and allowProjectJars at the module seam", async (t) => {
|
||||
const scenarios: JarScenario[] = [
|
||||
{
|
||||
name: "configured relative path wins",
|
||||
configuredJar: "relative",
|
||||
envJar: "absolute",
|
||||
packageJar: true,
|
||||
looseJar: true,
|
||||
homeJar: true,
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
expected: "configured",
|
||||
},
|
||||
{
|
||||
name: "missing configured path falls through to the environment",
|
||||
configuredJar: "missing",
|
||||
envJar: "absolute",
|
||||
packageJar: true,
|
||||
expected: "env",
|
||||
},
|
||||
{
|
||||
name: "relative environment path resolves from the project root",
|
||||
envJar: "relative",
|
||||
packageJar: true,
|
||||
expected: "env",
|
||||
},
|
||||
{
|
||||
name: "packaged jar wins over loose, home, and project jars",
|
||||
packageJar: true,
|
||||
looseJar: true,
|
||||
homeJar: true,
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
expected: "package",
|
||||
},
|
||||
{
|
||||
name: "loose extension jar wins over home and project jars",
|
||||
looseJar: true,
|
||||
homeJar: true,
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
expected: "loose",
|
||||
},
|
||||
{
|
||||
name: "legacy loose vendor beside the entry-point extension still resolves",
|
||||
legacyLooseJar: true,
|
||||
homeJar: true,
|
||||
projectVendorJar: true,
|
||||
expected: "legacy-loose",
|
||||
},
|
||||
{
|
||||
name: "user-level jar wins over project jars",
|
||||
homeJar: true,
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
expected: "home",
|
||||
},
|
||||
{
|
||||
name: "project vendor jar wins over project tools",
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
expected: "project-vendor",
|
||||
},
|
||||
{
|
||||
name: "project tools jar is the last candidate",
|
||||
projectToolsJar: true,
|
||||
expected: "project-tools",
|
||||
},
|
||||
{
|
||||
name: "project jars are skipped when untrusted",
|
||||
projectVendorJar: true,
|
||||
projectToolsJar: true,
|
||||
allowProjectJars: false,
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
await t.test(scenario.name, async () => {
|
||||
const { outcome, actual } = await runJarScenario(scenario);
|
||||
if (scenario.expected) {
|
||||
expectStatus(outcome, "pass");
|
||||
assert.equal(actual, scenario.expected);
|
||||
} else {
|
||||
const setup = expectStatus(outcome, "setup-error");
|
||||
assert.equal(setup.reason, "jar-missing");
|
||||
assert.equal(actual, undefined);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
import assert from "node:assert/strict";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import verifyExtension from "../../extensions/verify.ts";
|
||||
import {
|
||||
createTlaVerification,
|
||||
type SpecificationCheckRequest,
|
||||
type SpecificationOutcome,
|
||||
type TlaVerification,
|
||||
} from "../../extensions/verify/tla.ts";
|
||||
import {
|
||||
cleanup,
|
||||
copySpec,
|
||||
FakeJvm,
|
||||
fixtureText,
|
||||
jvmRun,
|
||||
makeTempDir,
|
||||
writeFile,
|
||||
} from "../fixtures/support.ts";
|
||||
|
||||
interface RegisteredToolLike {
|
||||
name: string;
|
||||
parameters: {
|
||||
type: string;
|
||||
properties: Record<string, unknown>;
|
||||
required?: string[];
|
||||
};
|
||||
execute: (
|
||||
toolCallId: string,
|
||||
params: Record<string, unknown>,
|
||||
signal: AbortSignal | undefined,
|
||||
onUpdate: undefined,
|
||||
ctx: unknown,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
type ToolResultHandler = (
|
||||
event: Record<string, unknown>,
|
||||
ctx: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text: string }> } | undefined>;
|
||||
|
||||
class FakePi {
|
||||
readonly tools = new Map<string, RegisteredToolLike>();
|
||||
readonly handlers = new Map<string, Array<(...args: never[]) => unknown>>();
|
||||
readonly commands = new Map<string, unknown>();
|
||||
|
||||
registerTool(tool: RegisteredToolLike): void {
|
||||
this.tools.set(tool.name, tool);
|
||||
}
|
||||
|
||||
on(event: string, handler: (...args: never[]) => unknown): () => void {
|
||||
const list = this.handlers.get(event) ?? [];
|
||||
list.push(handler);
|
||||
this.handlers.set(event, list);
|
||||
return () => {};
|
||||
}
|
||||
|
||||
registerCommand(name: string, options: unknown): void {
|
||||
this.commands.set(name, options);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeTla implements TlaVerification {
|
||||
readonly outcomes: SpecificationOutcome[] = [];
|
||||
readonly requests: SpecificationCheckRequest[] = [];
|
||||
|
||||
async checkSpecification(
|
||||
request: SpecificationCheckRequest,
|
||||
): Promise<SpecificationOutcome> {
|
||||
this.requests.push(request);
|
||||
const outcome = this.outcomes.shift();
|
||||
if (!outcome) throw new Error("No fake TLA+ outcome queued");
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
function outcome(
|
||||
status: SpecificationOutcome["status"],
|
||||
extra: Partial<SpecificationOutcome> = {},
|
||||
): SpecificationOutcome {
|
||||
return {
|
||||
status,
|
||||
specPath: "/project/Spec.tla",
|
||||
evidence: "CAPTURED EVIDENCE",
|
||||
...extra,
|
||||
} as SpecificationOutcome;
|
||||
}
|
||||
|
||||
function textOf(result: unknown): string {
|
||||
const content = (result as { content?: Array<{ type: string; text: string }> })
|
||||
.content;
|
||||
assert.ok(Array.isArray(content), "expected a tool result with content");
|
||||
return content.map((part) => part.text).join("\n");
|
||||
}
|
||||
|
||||
async function callTool(
|
||||
pi: FakePi,
|
||||
name: string,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
const tool = pi.tools.get(name);
|
||||
assert.ok(tool, `tool ${name} is registered`);
|
||||
return tool.execute("tool-call", params, undefined, undefined, {});
|
||||
}
|
||||
|
||||
async function callAutoSany(
|
||||
pi: FakePi,
|
||||
file: string,
|
||||
): Promise<{ content: Array<{ type: string; text: string }> } | undefined> {
|
||||
const handler = pi.handlers.get("tool_result")?.[0] as ToolResultHandler | undefined;
|
||||
assert.ok(handler, "auto-SANY tool_result handler is registered");
|
||||
return handler(
|
||||
{
|
||||
type: "tool_result",
|
||||
toolCallId: "edit-1",
|
||||
toolName: "edit",
|
||||
input: { path: file },
|
||||
content: [{ type: "text", text: "edited" }],
|
||||
isError: false,
|
||||
},
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
function makeAdapter(
|
||||
tla: TlaVerification,
|
||||
root: string,
|
||||
): { pi: FakePi; tla: TlaVerification } {
|
||||
const pi = new FakePi();
|
||||
verifyExtension(pi as never, { tla, root: () => root });
|
||||
return { pi, tla };
|
||||
}
|
||||
|
||||
function tempProject(name = "Plain.tla"): { root: string; spec: string } {
|
||||
const root = makeTempDir();
|
||||
const spec = copySpec(root, name);
|
||||
return { root, spec };
|
||||
}
|
||||
|
||||
test("existing tools and parameter schemas remain registered", async () => {
|
||||
const root = makeTempDir();
|
||||
try {
|
||||
const { pi } = makeAdapter(new FakeTla(), root);
|
||||
assert.deepEqual([...pi.tools.keys()].sort(), [
|
||||
"run_gates",
|
||||
"tla_check",
|
||||
"tlc",
|
||||
]);
|
||||
|
||||
const tlaCheck = pi.tools.get("tla_check")!;
|
||||
assert.deepEqual(Object.keys(tlaCheck.parameters.properties), ["spec"]);
|
||||
assert.deepEqual(tlaCheck.parameters.required, ["spec"]);
|
||||
|
||||
const tlc = pi.tools.get("tlc")!;
|
||||
assert.deepEqual(Object.keys(tlc.parameters.properties).sort(), [
|
||||
"cfg",
|
||||
"ignore_deadlock",
|
||||
"spec",
|
||||
"timeout_sec",
|
||||
]);
|
||||
assert.deepEqual(tlc.parameters.required, ["spec"]);
|
||||
|
||||
const runGates = pi.tools.get("run_gates")!;
|
||||
assert.deepEqual(Object.keys(runGates.parameters.properties), ["filter"]);
|
||||
assert.equal(runGates.parameters.required, undefined);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
const formattingScenarios: Array<{
|
||||
status: SpecificationOutcome["status"];
|
||||
outcome: SpecificationOutcome;
|
||||
toolText: RegExp;
|
||||
autoText: RegExp;
|
||||
}> = [
|
||||
{
|
||||
status: "pass",
|
||||
outcome: outcome("pass", { evidence: "SANY2 Version 2.1\nSemantic processing" }),
|
||||
toolText: /parsed OK/,
|
||||
autoText: /parsed OK/,
|
||||
},
|
||||
{
|
||||
status: "pass",
|
||||
outcome: outcome("pass", {
|
||||
evidence: "Translation completed.\nSANY2 Version 2.1",
|
||||
plusCalTranslated: true,
|
||||
}),
|
||||
toolText: /PlusCal re-translated/,
|
||||
autoText: /PlusCal re-translated; SANY parsed OK/,
|
||||
},
|
||||
{
|
||||
status: "parse-error",
|
||||
outcome: outcome("parse-error", { evidence: "***Parse Error*** detail" }),
|
||||
toolText: /parse errors[\s\S]*\*\*\*Parse Error\*\*\*/,
|
||||
autoText: /parse errors[\s\S]*\*\*\*Parse Error\*\*\*/,
|
||||
},
|
||||
{
|
||||
status: "semantic-error",
|
||||
outcome: outcome("semantic-error", {
|
||||
evidence: "Semantic errors:\n*** Errors: 2\nUnknown operator: +",
|
||||
}),
|
||||
toolText: /semantic errors[\s\S]*Unknown operator/,
|
||||
autoText: /semantic errors[\s\S]*Unknown operator/,
|
||||
},
|
||||
{
|
||||
status: "translation-error",
|
||||
outcome: outcome("translation-error", {
|
||||
evidence: "Translation failed: bad syntax",
|
||||
}),
|
||||
toolText: /PlusCal translation failed[\s\S]*bad syntax/,
|
||||
autoText: /PlusCal translation failed[\s\S]*bad syntax/,
|
||||
},
|
||||
{
|
||||
status: "timeout",
|
||||
outcome: outcome("timeout", {
|
||||
phase: "sany",
|
||||
timeoutMs: 60_000,
|
||||
evidence: "still running",
|
||||
}),
|
||||
toolText: /timed out[\s\S]*still running/,
|
||||
autoText: /timed out[\s\S]*still running/,
|
||||
},
|
||||
{
|
||||
status: "tool-error",
|
||||
outcome: outcome("tool-error", {
|
||||
exitCode: 17,
|
||||
evidence: "unexpected JVM failure",
|
||||
}),
|
||||
toolText: /unexpected[\s\S]*unexpected JVM failure/,
|
||||
autoText: /unexpected[\s\S]*unexpected JVM failure/,
|
||||
},
|
||||
{
|
||||
status: "aborted",
|
||||
outcome: outcome("aborted", { phase: "sany", evidence: "" }),
|
||||
toolText: /abort/i,
|
||||
autoText: /abort/i,
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of formattingScenarios) {
|
||||
test(`tla_check and auto-SANY report ${scenario.status} consistently`, async () => {
|
||||
const { root, spec } = tempProject();
|
||||
try {
|
||||
const fake = new FakeTla();
|
||||
fake.outcomes.push(scenario.outcome, scenario.outcome);
|
||||
const { pi } = makeAdapter(fake, root);
|
||||
|
||||
const toolText = textOf(
|
||||
await callTool(pi, "tla_check", { spec: path.basename(spec) }),
|
||||
);
|
||||
const auto = await callAutoSany(pi, path.basename(spec));
|
||||
assert.ok(auto, "auto-SANY should surface this outcome");
|
||||
const autoText = textOf(auto);
|
||||
|
||||
assert.match(toolText, scenario.toolText);
|
||||
assert.match(autoText, scenario.autoText);
|
||||
assert.equal(toolText.includes("CAPTURED EVIDENCE"), false);
|
||||
assert.equal(autoText.includes("CAPTURED EVIDENCE"), false);
|
||||
if (scenario.outcome.status !== "pass") {
|
||||
assert.ok(
|
||||
scenario.outcome.evidence === "" ||
|
||||
toolText.includes(scenario.outcome.evidence),
|
||||
"tla_check should include the structured evidence",
|
||||
);
|
||||
assert.ok(
|
||||
scenario.outcome.evidence === "" ||
|
||||
autoText.includes(scenario.outcome.evidence),
|
||||
"auto-SANY should include the structured evidence",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("auto-SANY stays silent only for missing toolchain and missing files", async () => {
|
||||
const { root, spec } = tempProject();
|
||||
try {
|
||||
const fake = new FakeTla();
|
||||
fake.outcomes.push(
|
||||
outcome("setup-error", { reason: "jar-missing" }),
|
||||
outcome("setup-error", { reason: "java-missing" }),
|
||||
outcome("invalid-input", { evidence: "Spec not found: Missing.tla" }),
|
||||
);
|
||||
const { pi } = makeAdapter(fake, root);
|
||||
|
||||
const setupText = textOf(
|
||||
await callTool(pi, "tla_check", { spec: path.basename(spec) }),
|
||||
);
|
||||
assert.match(setupText, /TLA\+ toolchain not found/);
|
||||
assert.equal(await callAutoSany(pi, path.basename(spec)), undefined);
|
||||
|
||||
const missing = await callTool(pi, "tla_check", { spec: "Missing.tla" });
|
||||
assert.match(textOf(missing), /File not found: Missing\.tla/);
|
||||
const autoMissing = await callAutoSany(pi, "Missing.tla");
|
||||
assert.equal(autoMissing, undefined);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test("auto-SANY cannot report a PlusCal timeout as success", async () => {
|
||||
const root = makeTempDir();
|
||||
try {
|
||||
const spec = copySpec(root, "Counter.tla");
|
||||
writeFile(root, "custom.jar", "fake jar");
|
||||
writeFile(root, ".pi/verify.json", '{"tla2toolsJar":"custom.jar"}');
|
||||
const jvm = new FakeJvm();
|
||||
jvm.runQueue.push(
|
||||
// Translation succeeds, then SANY times out for each entry point.
|
||||
// The old `timedOut || code === 0` branch reported this as success.
|
||||
jvmRun({ code: 0, stdout: "Translation completed." }),
|
||||
jvmRun({ code: null, stdout: "SANY still running", timedOut: true }),
|
||||
jvmRun({ code: 0, stdout: "Translation completed." }),
|
||||
jvmRun({ code: null, stdout: "SANY still running", timedOut: true }),
|
||||
);
|
||||
const tla = createTlaVerification({
|
||||
jvm,
|
||||
env: {},
|
||||
homeDir: path.join(root, "home"),
|
||||
extensionDir: path.join(root, "extension"),
|
||||
packageRoot: null,
|
||||
});
|
||||
const { pi } = makeAdapter(tla, root);
|
||||
|
||||
const toolText = textOf(
|
||||
await callTool(pi, "tla_check", { spec: path.basename(spec) }),
|
||||
);
|
||||
const autoResult = await callAutoSany(pi, path.basename(spec));
|
||||
assert.ok(autoResult);
|
||||
const autoText = textOf(autoResult);
|
||||
|
||||
assert.match(toolText, /timed out/i);
|
||||
assert.match(autoText, /timed out/i);
|
||||
assert.doesNotMatch(toolText, /parsed OK/);
|
||||
assert.doesNotMatch(autoText, /parsed OK/);
|
||||
assert.equal(
|
||||
jvm.runCalls().filter((call) => call.args?.[0] === "tla2sany.SANY").length,
|
||||
2,
|
||||
);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test("the TLA+ module has no Pi runtime import or process.cwd dependency", async () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL("../../extensions/verify/tla.ts", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
assert.doesNotMatch(source, /@earendil-works\/pi-coding-agent/);
|
||||
assert.doesNotMatch(source, /process\.cwd\s*\(/);
|
||||
});
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
|
||||
****** SANY2 Version 2.1 created 24 February 2014
|
||||
|
||||
Parsing file /tmp/tla-probe/ParseBad.tla
|
||||
***Parse Error***
|
||||
Was expecting "Expression or Instance"
|
||||
Encountered "Beginning of definition" at line 3, column 9 and token "=="
|
||||
|
||||
Residual stack trace follows:
|
||||
Definition starting at line 3, column 1.
|
||||
Module body starting at line 2, column 1.
|
||||
Module definition starting at line 1, column 1.
|
||||
|
||||
|
||||
Fatal errors while parsing TLA+ spec in file /tmp/tla-probe/ParseBad.tla
|
||||
|
||||
tla2sany.semantic.AbortException
|
||||
*** Abort messages: 1
|
||||
|
||||
In module ParseBad
|
||||
|
||||
Could not parse module ParseBad from file /tmp/tla-probe/ParseBad.tla
|
||||
|
||||
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
|
||||
****** SANY2 Version 2.1 created 24 February 2014
|
||||
|
||||
Parsing file /tmp/tla-probe/Good.tla
|
||||
Parsing file /tmp/Naturals.tla
|
||||
Semantic processing of module Naturals
|
||||
Semantic processing of module Good
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
|
||||
****** SANY2 Version 2.1 created 24 February 2014
|
||||
|
||||
Parsing file /tmp/tla-probe/SemanticBad.tla
|
||||
Semantic processing of module SemanticBad
|
||||
Semantic errors:
|
||||
|
||||
*** Errors: 2
|
||||
|
||||
line 4, col 16 to line 4, col 16 of module SemanticBad
|
||||
|
||||
Could not find declaration or definition of symbol '+'.
|
||||
|
||||
|
||||
line 4, col 14 to line 4, col 26 of module SemanticBad
|
||||
|
||||
Couldn't resolve infix operator symbol `+'.
|
||||
|
||||
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
****** SANY2 Version 2.1 created 24 February 2014
|
||||
|
||||
Parsing file /workspace/Broken.tla
|
||||
java.io.FileNotFoundException: /workspace/Broken.tla (No such file or directory)
|
||||
at java.base/java.io.FileInputStream.open0(Native Method)
|
||||
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
---- MODULE Counter ----
|
||||
EXTENDS Naturals
|
||||
(* --algorithm Counter
|
||||
variables x = 0;
|
||||
begin
|
||||
A: x := x + 1;
|
||||
end algorithm; *)
|
||||
====
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
---- MODULE Plain ----
|
||||
EXTENDS Naturals
|
||||
VARIABLE x
|
||||
Init == x = 0
|
||||
Next == x' = x + 1
|
||||
Spec == Init /\ [][Next]_x
|
||||
====
|
||||
Vendored
+109
@@ -0,0 +1,109 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type {
|
||||
JavaProbeResult,
|
||||
Jvm,
|
||||
JvmRunResult,
|
||||
} from "../../extensions/verify/tla.ts";
|
||||
|
||||
export const FIXTURES = fileURLToPath(new URL(".", import.meta.url));
|
||||
|
||||
export interface RecordedJvmCall {
|
||||
kind: "probe" | "run";
|
||||
cwd: string;
|
||||
jar?: string;
|
||||
args?: string[];
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
type RunResultFactory = (signal: AbortSignal | undefined) => JvmRunResult;
|
||||
|
||||
export class FakeJvm implements Jvm {
|
||||
readonly calls: RecordedJvmCall[] = [];
|
||||
readonly probeQueue: JavaProbeResult[] = [];
|
||||
readonly runQueue: Array<JvmRunResult | RunResultFactory> = [];
|
||||
|
||||
async probeJava(cwd: string, _signal?: AbortSignal): Promise<JavaProbeResult> {
|
||||
this.calls.push({ kind: "probe", cwd });
|
||||
return (
|
||||
this.probeQueue.shift() ?? {
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: 'openjdk version "17.0.9" 2024-10-15\nOpenJDK Runtime Environment\n',
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async runJava(
|
||||
jar: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JvmRunResult> {
|
||||
this.calls.push({ kind: "run", jar, args, cwd, timeoutMs });
|
||||
const next = this.runQueue.shift();
|
||||
if (!next) throw new Error(`Unexpected JVM invocation: ${args.join(" ")}`);
|
||||
return typeof next === "function" ? next(signal) : next;
|
||||
}
|
||||
|
||||
runCalls(): RecordedJvmCall[] {
|
||||
return this.calls.filter((call) => call.kind === "run");
|
||||
}
|
||||
|
||||
probeCalls(): RecordedJvmCall[] {
|
||||
return this.calls.filter((call) => call.kind === "probe");
|
||||
}
|
||||
}
|
||||
|
||||
export function jvmRun(
|
||||
result: Partial<JvmRunResult> & Pick<JvmRunResult, "code" | "stdout">,
|
||||
): JvmRunResult {
|
||||
return {
|
||||
stderr: "",
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
export function javaProbe(
|
||||
result: Partial<JavaProbeResult> & Pick<JavaProbeResult, "code">,
|
||||
): JavaProbeResult {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
export function fixtureText(relativePath: string): string {
|
||||
return fs.readFileSync(path.join(FIXTURES, relativePath), "utf8");
|
||||
}
|
||||
|
||||
export function makeTempDir(prefix = "pi-verify-tla-"): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
export function writeFile(root: string, relativePath: string, content = ""): string {
|
||||
const file = path.join(root, relativePath);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, content);
|
||||
return file;
|
||||
}
|
||||
|
||||
export function copySpec(root: string, name = "Plain.tla"): string {
|
||||
const target = path.join(root, name);
|
||||
fs.copyFileSync(path.join(FIXTURES, "specs", name), target);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function cleanup(root: string): void {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
+3
-2
@@ -8,7 +8,8 @@
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"allowImportingTsExtensions": true
|
||||
},
|
||||
"include": ["extensions/**/*.ts"]
|
||||
"include": ["extensions/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user