refactor!: simplify runtime tools and remove replay engines (#572)

* fix(hopper): report unavailable procedure body coverage

* refactor!: simplify runtime tools and remove replay engines

Keep direct inspection, capture, and comparison tools. Bind handlers to named contracts and let agents compose experiments with commands and local fixture servers.

BREAKING CHANGE: Remove controlled replay, Node characterization, finite replay-machine, managed runtime planning, and redundant string-tracing tools. Retire process replay, shims, reactive scenarios, custom checkpoints, and active browser replay and origin-scope inputs.
This commit is contained in:
morluto
2026-10-05 21:15:04 +08:00
committed by GitHub
parent c6d3bdf597
commit e07b81649e
258 changed files with 1193 additions and 22444 deletions
-7
View File
@@ -12,7 +12,6 @@ import {
HopperTimeoutError,
NoBinaryOpenError,
ProviderSelectionError,
ReplayPlanStaleError,
UnknownRegistryError,
type AnalysisError,
type AnalysisErrorProjection,
@@ -38,15 +37,12 @@ export const analysisErrorRemediationAction = (
return "Correct the listed arguments and retry.";
if (error instanceof UnknownRegistryError && error.reason === "not-found")
return "Check that the unknown_id belongs to this session, then retry.";
if (error instanceof ReplayPlanStaleError)
return "Rebuild the replay plan and retry with its current digest.";
return analysisErrorUserMessage(error);
};
export const analysisErrorCategory = (
error: AnalysisError,
): AnalysisErrorProjection["category"] => {
if (error instanceof ReplayPlanStaleError) return "integrity_mismatch";
if (
error instanceof ProviderSelectionError &&
error.reason === "provider_unavailable"
@@ -109,8 +105,6 @@ const STATIC_ERROR_CATEGORIES: Readonly<
};
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof ReplayPlanStaleError)
return "The controlled replay plan changed before execution. Refresh the current state and try again.";
if (error instanceof AnalysisInputError)
return "Analysis input is invalid. Check the arguments and try again.";
const hopperMessage = hopperErrorUserMessage(error);
@@ -250,7 +244,6 @@ const KNOWN_ERROR_TAGS = {
ConfigurationError: true,
NoBinaryOpenError: true,
BinaryTargetError: true,
ReplayPlanStaleError: true,
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
export const assertKnownAnalysisErrorTag = (tag: AnalysisErrorTag): void => {
+4 -9
View File
@@ -10,7 +10,6 @@ import {
HopperStartError,
HopperTimeoutError,
ProviderAdapterError,
ReplayPlanStaleError,
UnknownRegistryError,
projectAnalysisError,
} from "./errors.js";
@@ -18,7 +17,7 @@ import {
describe("analysis error projection: provider failures", () => {
it("reports a timed-out active Hopper request and actionable retry guidance", () => {
const projected = projectAnalysisError(
new HopperTimeoutError(30_000, "find_code_for_string", 42, "busy"),
new HopperTimeoutError(30_000, "trace_feature", 42, "busy"),
);
expect(projected).toMatchObject({
@@ -27,7 +26,7 @@ describe("analysis error projection: provider failures", () => {
retryable: true,
details: {
stage: "analysis",
operation: "find_code_for_string",
operation: "trace_feature",
request_id: 42,
provider_state: "busy",
timeout_ms: 30_000,
@@ -64,7 +63,7 @@ describe("analysis error projection: provider failures", () => {
"Hopper analysis failed in the selected document",
{
diagnosticType: "bridge_exception",
operation: "find_code_for_string",
operation: "trace_feature",
requestId: 43,
},
),
@@ -75,7 +74,7 @@ describe("analysis error projection: provider failures", () => {
stage: "analysis",
provider_code: 7,
diagnostic_type: "bridge_exception",
operation: "find_code_for_string",
operation: "trace_feature",
request_id: 43,
},
message: expect.stringContaining("Hopper analysis failed"),
@@ -144,16 +143,12 @@ describe("analysis error projection: caller contract", () => {
cause: secretCause,
}),
),
projectAnalysisError(
new ReplayPlanStaleError("a".repeat(64), "b".repeat(64)),
),
];
expect(projected.map(({ code }) => code)).toEqual([
"invalid_request",
"capability_unavailable",
"target_unavailable",
"plan_stale",
]);
expect(projected[1]).toMatchObject({ category: "unsupported_provider" });
expect(projected[2]).toMatchObject({
-10
View File
@@ -15,7 +15,6 @@ import {
HopperTimeoutError,
ProviderAdapterError,
ProviderSelectionError,
ReplayPlanStaleError,
UnknownRegistryError,
type AnalysisError,
type AnalysisErrorProjection,
@@ -49,7 +48,6 @@ export const projectAnalysisError = (
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
if (error.cleanupIncomplete) return "cleanup_incomplete";
if (error instanceof ReplayPlanStaleError) return "plan_stale";
if (error instanceof ProviderSelectionError)
return error.reason === "provider_unavailable"
? "provider_unavailable"
@@ -121,7 +119,6 @@ type SpecializedErrorTag =
| "EvidenceFileError"
| "ProcessCaptureError"
| "ProviderSelectionError"
| "ReplayPlanStaleError"
| "UnknownRegistryError";
const STATIC_ERROR_CODES = {
@@ -158,7 +155,6 @@ const staticErrorCode = (
case "EvidenceFileError":
case "ProcessCaptureError":
case "ProviderSelectionError":
case "ReplayPlanStaleError":
case "UnknownRegistryError":
throw new TypeError(`Unhandled specialized analysis error: ${tag}`);
default:
@@ -196,12 +192,6 @@ const requestErrorDetails = (
expected: error.expected,
actual: error.actual,
};
if (error instanceof ReplayPlanStaleError)
return {
expected_plan_digest: error.expectedDigest,
actual_plan_digest: error.actualDigest,
application_code_admitted: false,
};
return undefined;
};
+24 -54
View File
@@ -2,7 +2,7 @@ import { expect, it } from "vitest";
import { browserScenarioSchema } from "./browserScenario.js";
it("accepts scenarios beyond former action, secret, storage, and replay-route counts", () => {
it("accepts large action, secret, and storage selections", () => {
const actions = Array.from({ length: 129 }, (_, index) => ({
step_id: `fill_${index}`,
action: "fill",
@@ -25,12 +25,6 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
name: `entry_${index}`,
value: { source: "literal", value: "value" },
}));
const routes = Array.from({ length: 257 }, (_, index) => ({
route_id: `route_${index}`,
method: "GET",
request: { url: `https://app.example.test/${index}` },
response: { kind: "response", status: 200 },
}));
const result = browserScenarioSchema.parse({
browser: {
@@ -38,7 +32,6 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
executable_path: "/opt/chromium",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
actions,
secrets,
storage: {
@@ -50,11 +43,6 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
{ origin: "https://app.example.test", entries: storageEntries },
],
},
request_replay: {
mode: "exact",
unmatched: "abort",
routes,
},
});
expect(result.actions).toHaveLength(129);
@@ -62,12 +50,9 @@ it("accepts scenarios beyond former action, secret, storage, and replay-route co
expect(result.storage.cookies).toHaveLength(129);
expect(result.storage.local_storage[0]?.entries).toHaveLength(129);
expect(result.storage.session_storage[0]?.entries).toHaveLength(129);
expect(
result.request_replay.mode === "exact" && result.request_replay.routes,
).toHaveLength(257);
});
it("defaults scenario scope to the start URL origin", () => {
it("does not require duplicate origin scope declarations", () => {
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
@@ -75,11 +60,31 @@ it("defaults scenario scope to the start URL origin", () => {
},
start_url: { url: "https://app.example.test/" },
actions: [
{ step_id: "settle", action: "wait_for_timeout", duration_ms: 1 },
{
step_id: "navigate",
action: "goto",
destination: { url: "https://other.example.test/" },
wait_until: "load",
},
],
storage: {
local_storage: [
{
origin: "https://storage.example.test",
entries: [
{ name: "theme", value: { source: "literal", value: "dark" } },
],
},
],
},
});
expect(scenario.allowed_origins).toEqual(["https://app.example.test"]);
expect(scenario.actions[0]).toMatchObject({
destination: { url: "https://other.example.test/" },
});
expect(scenario.storage.local_storage[0]?.origin).toBe(
"https://storage.example.test",
);
});
it("accepts complete browser inputs beyond former string length caps", () => {
@@ -93,7 +98,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
executable_path: longPath,
},
start_url: { url: `https://app.example.test${longPath}` },
allowed_origins: ["https://app.example.test"],
secrets: [
{
secret_id: longToken,
@@ -123,30 +127,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
},
],
},
request_replay: {
mode: "exact",
unmatched: "abort",
routes: [
{
route_id: longToken,
method: "GET",
request: { url: "https://app.example.test/" },
response: {
kind: "response",
status: 200,
headers: [
{
name: longToken,
value: {
source: "literal",
value: longValue,
},
},
],
},
},
],
},
});
expect(result.actions[0]?.step_id).toBe(longToken);
@@ -158,15 +138,6 @@ it("accepts complete browser inputs beyond former string length caps", () => {
).toBe(longToken);
expect(result.storage.cookies[0]?.name).toBe(longToken);
expect(result.secrets[0]?.environment_variable).toBe(longEnvironmentVariable);
const replayRoute =
result.request_replay.mode === "exact"
? result.request_replay.routes[0]
: undefined;
expect(
replayRoute?.response.kind === "response"
? replayRoute.response.headers[0]?.name
: undefined,
).toBe(longToken);
});
it("accepts caller-selected viewport sizes and click counts without ceilings", () => {
@@ -176,7 +147,6 @@ it("accepts caller-selected viewport sizes and click counts without ceilings", (
executable_path: "/opt/chromium",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
environment: {
viewport: { width: 20_000, height: 10_000, device_scale_factor: 8 },
},
+7 -155
View File
@@ -2,11 +2,9 @@ import { z } from "zod";
import {
browserScenarioActionSchema,
browserScenarioAllowedOriginsSchema,
browserScenarioBrowserSchema,
browserScenarioCaptureSchema,
browserScenarioEnvironmentSchema,
browserScenarioRequestReplaySchema,
browserScenarioSecretSchema,
browserScenarioStorageSchema,
browserScenarioUrlSchema,
@@ -31,18 +29,12 @@ export const browserScenarioInputSchema = z.strictObject({
start_url: browserScenarioUrlSchema.describe(
"Required initial HTTP(S) URL. Query values must be declared separately as public literals or secret references.",
),
allowed_origins: browserScenarioAllowedOriginsSchema
.default([])
.describe(
"Optional exact HTTP(S) origins for later navigation, storage seed, and replay routes. Defaults to the start URL origin.",
),
environment: browserScenarioEnvironmentSchema,
actions: z
.array(browserScenarioActionSchema)
.min(1)
.describe("Required sequence of explicit browser actions."),
storage: browserScenarioStorageSchema,
request_replay: browserScenarioRequestReplaySchema,
secrets: z
.array(browserScenarioSecretSchema)
.default([])
@@ -70,23 +62,6 @@ const assertUnique = (
addIssue(context, path, `${label} must be unique`);
};
const originFor = (destination: BrowserScenarioUrl): string =>
new URL(destination.url).origin;
const assertAllowedDestination = (
destination: BrowserScenarioUrl,
allowedOrigins: ReadonlySet<string>,
path: PropertyKey[],
context: z.RefinementCtx,
): void => {
if (!allowedOrigins.has(originFor(destination)))
addIssue(
context,
path,
`URL origin ${originFor(destination)} is not declared in allowed_origins`,
);
};
const secretReferencesInValue = (
value: BrowserScenarioValue | undefined,
): readonly string[] => (value?.source === "secret" ? [value.secret_id] : []);
@@ -106,117 +81,20 @@ const actionSecretReferences = (
return [];
};
const validateStorage = (
scenario: ScenarioShape,
allowedOrigins: ReadonlySet<string>,
context: z.RefinementCtx,
): readonly string[] => {
const validateStorage = (scenario: ScenarioShape): readonly string[] => {
const references: string[] = [];
scenario.storage.cookies.forEach((cookie, index) => {
assertAllowedDestination(
cookie.destination,
allowedOrigins,
["storage", "cookies", index, "destination"],
context,
);
scenario.storage.cookies.forEach((cookie) => {
references.push(...secretReferencesInValue(cookie.value));
references.push(...destinationSecretReferences(cookie.destination));
});
for (const collection of ["local_storage", "session_storage"] as const)
scenario.storage[collection].forEach((storage, index) => {
if (!allowedOrigins.has(storage.origin))
addIssue(
context,
["storage", collection, index, "origin"],
`Storage origin ${storage.origin} is not declared in allowed_origins`,
);
scenario.storage[collection].forEach((storage) => {
for (const entry of storage.entries)
references.push(...secretReferencesInValue(entry.value));
});
return references;
};
const FORBIDDEN_REPLAY_HEADERS = new Set([
"content-length",
"location",
"transfer-encoding",
]);
const validateRequestReplay = (
scenario: ScenarioShape,
allowedOrigins: ReadonlySet<string>,
context: z.RefinementCtx,
): readonly string[] => {
if (scenario.request_replay.mode === "disabled") return [];
assertUnique(
scenario.request_replay.routes.map(({ route_id: id }) => id),
["request_replay", "routes"],
"Replay route IDs",
context,
);
assertUnique(
scenario.request_replay.routes.map(
({ method, request }) =>
`${method} ${request.url}?${request.query
.map(({ name, value }) =>
value.source === "secret"
? `${name}=\${secret:${value.secret_id}}`
: `${name}=${value.value}`,
)
.join("&")}`,
),
["request_replay", "routes"],
"Replay request matchers",
context,
);
const references: string[] = [];
scenario.request_replay.routes.forEach((route, routeIndex) => {
assertAllowedDestination(
route.request,
allowedOrigins,
["request_replay", "routes", routeIndex, "request"],
context,
);
references.push(...destinationSecretReferences(route.request));
if (route.response.kind === "redirect") {
assertAllowedDestination(
route.response.destination,
allowedOrigins,
["request_replay", "routes", routeIndex, "response", "destination"],
context,
);
references.push(
...destinationSecretReferences(route.response.destination),
);
return;
}
assertUnique(
route.response.headers.map(({ name }) => name.toLowerCase()),
["request_replay", "routes", routeIndex, "response", "headers"],
"Replay response header names",
context,
);
route.response.headers.forEach((header, headerIndex) => {
if (FORBIDDEN_REPLAY_HEADERS.has(header.name))
addIssue(
context,
[
"request_replay",
"routes",
routeIndex,
"response",
"headers",
headerIndex,
],
`Replay header ${header.name} must be modeled by the provider`,
);
references.push(...secretReferencesInValue(header.value));
});
references.push(...secretReferencesInValue(route.response.body));
});
return references;
};
const validateSecretReferences = (
scenario: ScenarioShape,
references: readonly string[],
@@ -236,17 +114,6 @@ const validateBrowserScenario = (
scenario: ScenarioShape,
context: z.RefinementCtx,
): void => {
const allowedOrigins = new Set(
scenario.allowed_origins.length > 0
? scenario.allowed_origins
: [originFor(scenario.start_url)],
);
assertAllowedDestination(
scenario.start_url,
allowedOrigins,
["start_url"],
context,
);
assertUnique(
scenario.actions.map(({ step_id: id }) => id),
["actions"],
@@ -267,28 +134,13 @@ const validateBrowserScenario = (
);
const references = scenario.actions.flatMap(actionSecretReferences);
for (const [index, action] of scenario.actions.entries())
if (action.action === "goto")
assertAllowedDestination(
action.destination,
allowedOrigins,
["actions", index, "destination"],
context,
);
references.push(...destinationSecretReferences(scenario.start_url));
references.push(...validateStorage(scenario, allowedOrigins, context));
references.push(...validateRequestReplay(scenario, allowedOrigins, context));
references.push(...validateStorage(scenario));
validateSecretReferences(scenario, references, context);
};
/** Strict provider-neutral contract for one controlled browser scenario. */
export const browserScenarioSchema = browserScenarioInputSchema
.superRefine(validateBrowserScenario)
.transform((scenario) => ({
...scenario,
allowed_origins:
scenario.allowed_origins.length > 0
? scenario.allowed_origins
: [originFor(scenario.start_url)],
}));
export const browserScenarioSchema = browserScenarioInputSchema.superRefine(
validateBrowserScenario,
);
export type BrowserScenario = z.infer<typeof browserScenarioSchema>;
+1 -7
View File
@@ -141,12 +141,8 @@ it("accepts complete storage, history, and text artifacts beyond former caps", (
expect(parsed.success).toBe(true);
});
it("accepts complete scenario output beyond former string and origin caps", () => {
it("accepts complete scenario output beyond former string caps", () => {
const longText = "detail".repeat(1_000);
const origins = Array.from(
{ length: 33 },
(_, index) => `https://site-${index}.example.test`,
);
const step = (index: number) => ({
step_index: index,
step_id: longText,
@@ -183,7 +179,6 @@ it("accepts complete scenario output beyond former string and origin caps", () =
},
scenario: {
start_origin: longText,
allowed_origins: origins,
action_count: 1,
secret_references: [longText],
},
@@ -199,7 +194,6 @@ it("accepts complete scenario output beyond former string and origin caps", () =
limitations: Array.from({ length: 65 }, () => longText),
});
expect(parsed.scenario.allowed_origins).toHaveLength(33);
expect(parsed.steps[0]?.step_id).toBe(longText);
expect(parsed.limitations).toHaveLength(65);
});
-1
View File
@@ -33,7 +33,6 @@ export const browserScenarioCaptureSchema = z
}),
scenario: z.strictObject({
start_origin: z.string().min(1),
allowed_origins: z.array(z.string().min(1)).min(1),
action_count: z.number().int().min(1),
secret_references: z.array(z.string().min(1)),
}),
-1
View File
@@ -344,7 +344,6 @@ const scenarioCapture = (
},
scenario: {
start_origin: "https://app.example.test",
allowed_origins: ["https://app.example.test"],
action_count: 1,
secret_references: [],
},
+1 -3
View File
@@ -266,9 +266,7 @@ const captureContextsMatch = (
): boolean =>
before.browser.product === after.browser.product &&
before.browser.version === after.browser.version &&
before.scenario.start_origin === after.scenario.start_origin &&
digestCanonicalJson([...before.scenario.allowed_origins].sort()) ===
digestCanonicalJson([...after.scenario.allowed_origins].sort());
before.scenario.start_origin === after.scenario.start_origin;
interface CompareStepArtifactsInput {
readonly beforeCapture: BrowserScenarioCapture;
-55
View File
@@ -1,7 +1,6 @@
import { z } from "zod";
import {
browserAllowedOriginsSchema,
browserEndpointSchema,
browserOriginSchema,
} from "./browserObservation.js";
@@ -255,58 +254,6 @@ export const browserScenarioStorageSchema = z
"Optional initial cookies, local storage, or session storage. Defaults to empty; every supplied value and origin must be declared and within the allowed origins.",
);
const headerNameSchema = z
.string()
.min(1)
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u)
.transform((value) => value.toLowerCase());
const replayHeaderSchema = z.strictObject({
name: headerNameSchema,
value: browserScenarioValueSchema,
});
const replayResponseSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("response"),
status: z.number().int().min(100).max(599),
headers: z.array(replayHeaderSchema).default([]),
body: browserScenarioValueSchema.optional(),
}),
z.strictObject({
kind: z.literal("redirect"),
status: z.union([
z.literal(301),
z.literal(302),
z.literal(303),
z.literal(307),
z.literal(308),
]),
destination: browserScenarioUrlSchema,
}),
]);
const replayRouteSchema = z.strictObject({
route_id: scenarioIdentifierSchema,
method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]),
request: browserScenarioUrlSchema,
response: replayResponseSchema,
});
export const browserScenarioRequestReplaySchema = z
.discriminatedUnion("mode", [
z.strictObject({ mode: z.literal("disabled") }),
z.strictObject({
mode: z.literal("exact"),
unmatched: z.enum(["abort", "passthrough-declared-origins"]),
routes: z.array(replayRouteSchema).min(1),
}),
])
.default({ mode: "disabled" })
.describe(
"Optional exact request replay. Defaults to disabled; replay routes and unmatched-request behavior must be explicitly declared when enabled.",
);
export const browserScenarioSecretSchema = z.strictObject({
secret_id: scenarioIdentifierSchema,
environment_variable: z
@@ -350,5 +297,3 @@ export const browserScenarioCaptureSchema = z
.describe(
"Optional retained artifacts and event families. Defaults to only a final sanitized URL; request screenshots, DOM, accessibility, history, storage, and event capture explicitly.",
);
export const browserScenarioAllowedOriginsSchema = browserAllowedOriginsSchema;
+5 -7
View File
@@ -60,7 +60,7 @@ const processResult = (
terminal: "unchanged" | "changed" | "unknown" | "truncated";
interaction: "unchanged" | "changed" | "unknown" | "truncated";
exit: "unchanged" | "changed" | "unknown" | "truncated";
shim: "unchanged" | "changed" | "unknown" | "truncated";
process: "unchanged" | "changed" | "unknown" | "truncated";
}> = {},
): JsonValue => ({
status: overrides.status ?? "unchanged",
@@ -68,9 +68,7 @@ const processResult = (
interaction: overrides.interaction ?? "unchanged",
exit: overrides.exit ?? "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
shim: overrides.shim ?? "unchanged",
process: overrides.process ?? "unchanged",
first_divergence:
overrides.status === "changed"
? {
@@ -133,13 +131,13 @@ describe("changed behavior", () => {
expect(result.behavior_status).toBe("observed_unchanged");
});
it("reports interaction and shim-only process changes", () => {
it("reports interaction and process changes", () => {
const evidence = comparison(
"compare_process_captures",
processResult({
status: "changed",
interaction: "changed",
shim: "changed",
process: "changed",
}),
);
@@ -152,7 +150,7 @@ describe("changed behavior", () => {
dimension: "interaction",
scope: "runtime",
}),
expect.objectContaining({ dimension: "shim", scope: "protocol" }),
expect.objectContaining({ dimension: "process", scope: "runtime" }),
]),
},
});
-2
View File
@@ -250,9 +250,7 @@ const processFindings = (evidence: Evidence): Finding[] => {
["interaction", result.interaction, "runtime"],
["exit", result.exit, "runtime"],
["filesystem", result.filesystem, "resource"],
["protocol", result.protocol, "protocol"],
["process", result.process, "runtime"],
["shim", result.shim, "protocol"],
] as const;
return dimensions.flatMap(([dimension, status, scope]) =>
status === "unchanged"
+1 -15
View File
@@ -44,7 +44,6 @@ const ANALYSIS_ERROR_TAGS = [
"ConfigurationError",
"NoBinaryOpenError",
"BinaryTargetError",
"ReplayPlanStaleError",
] as const;
/** Stable tag for an expected analysis failure. */
@@ -487,8 +486,7 @@ export interface AnalysisErrorProjection
| "revision_conflict"
| "configuration_invalid"
| "target_unavailable"
| "execution_failure"
| "plan_stale";
| "execution_failure";
readonly category:
| "invalid_input"
| "unsupported_provider"
@@ -505,15 +503,3 @@ export interface AnalysisErrorProjection
}>;
readonly details?: Readonly<Record<string, JsonValue>>;
}
/** Replay commitment no longer matches the immediately rebuilt plan. */
export class ReplayPlanStaleError extends AnalysisError {
readonly _tag = "ReplayPlanStaleError" as const;
constructor(
readonly expectedDigest: string,
readonly actualDigest: string,
) {
super("Controlled replay plan changed before execution");
}
}
@@ -1,99 +0,0 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { instrumentJavaScriptExport } from "./javascriptExportInstrumentation.js";
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
const sha256 = (value: Uint8Array): string =>
createHash("sha256").update(value).digest("hex");
describe("JavaScript export instrumentation", () => {
it("retains a long caller-provided artifact path in the manifest", () => {
const source = encode("const value = 1;");
const path = `/${"deep/".repeat(1_000)}app.js`;
const output = instrumentJavaScriptExport(source, {
artifact_path: path,
artifact_sha256: sha256(source),
selection: {
byte_start: 14,
byte_end: 15,
selected_sha256: sha256(encode("1")),
export_name: "value",
},
});
expect(output.manifest.artifact_path).toBe(path);
});
it.each([
[
"plain",
"const hidden = (value) => value.trim();",
"(value) => value.trim()",
],
["minified", "const x=a=>a+1,y=2;", "a=>a+1"],
[
"bundle",
"(()=>{const registry={7:(m)=>m.exports=(x)=>x*2};globalThis.r=registry})()",
"(x)=>x*2",
],
])(
"deterministically exposes one exact %s expression",
(_name, text, selectedText) => {
const source = encode(text);
const original = source.slice();
const start = text.indexOf(selectedText);
const selected = encode(selectedText);
const input = {
artifact_path: "/approved/app.js",
artifact_sha256: sha256(source),
selection: {
byte_start: start,
byte_end: start + selected.byteLength,
selected_sha256: sha256(selected),
export_name: "selected",
},
};
const first = instrumentJavaScriptExport(source, input);
const second = instrumentJavaScriptExport(source, input);
expect(first).toEqual(second);
expect(source).toEqual(original);
expect(first.manifest).toMatchObject({
original_sha256: sha256(source),
instrumented_sha256: sha256(first.bytes),
output_format: "commonjs-factory",
inserted_ranges: [
{ purpose: "factory-prefix" },
{ purpose: "export-binding" },
{ purpose: "factory-suffix" },
],
});
},
);
it("rejects stale artifacts and ambiguous caller-selected bytes", () => {
const source = encode("const hidden = () => 1;");
const input = {
artifact_path: "/approved/app.js",
artifact_sha256: "0".repeat(64),
selection: {
byte_start: 15,
byte_end: 22,
selected_sha256: "1".repeat(64),
export_name: "hidden",
},
};
expect(() => instrumentJavaScriptExport(source, input)).toThrow(
/artifact digest mismatch/u,
);
expect(() =>
instrumentJavaScriptExport(source, {
...input,
artifact_sha256: sha256(source),
}),
).toThrow(/selection digest mismatch/u);
});
});
@@ -1,129 +0,0 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { digestSchema } from "./../domain/digests.js";
export const javascriptExportInstrumentationInputSchema = z.strictObject({
artifact_path: z.string().min(1),
artifact_sha256: digestSchema,
selection: z.strictObject({
byte_start: z.number().int().min(0),
byte_end: z.number().int().min(1),
selected_sha256: digestSchema,
export_name: z.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]{0,199}$/u),
}),
});
export const javascriptExportTransformationManifestSchema = z.strictObject({
kind: z.literal("commonjs-factory-export-v1"),
artifact_path: z.string().min(1),
original_sha256: digestSchema,
original_byte_length: z.number().int().min(0),
instrumented_sha256: digestSchema,
instrumented_byte_length: z.number().int().min(0),
selected_range: z.strictObject({
byte_start: z.number().int().min(0),
byte_end: z.number().int().min(1),
selected_sha256: digestSchema,
}),
inserted_ranges: z
.array(
z.strictObject({
byte_start: z.number().int().min(0),
byte_end: z.number().int().min(1),
inserted_sha256: digestSchema,
purpose: z.enum(["factory-prefix", "export-binding", "factory-suffix"]),
}),
)
.length(3),
output_format: z.literal("commonjs-factory"),
source_map: z.literal(null),
});
export interface JavaScriptExportInstrumentation {
readonly bytes: Uint8Array;
readonly manifest: z.infer<
typeof javascriptExportTransformationManifestSchema
>;
}
/** Instrument one exact UTF-8 expression range without mutating source bytes. */
export const instrumentJavaScriptExport = (
source: Uint8Array,
rawInput: unknown,
): JavaScriptExportInstrumentation => {
const input = javascriptExportInstrumentationInputSchema.parse(rawInput);
if (sha256(source) !== input.artifact_sha256)
throw new TypeError("JavaScript instrumentation artifact digest mismatch");
const { byte_start: start, byte_end: end } = input.selection;
if (end <= start || end > source.byteLength)
throw new TypeError(
"JavaScript instrumentation selection is out of bounds",
);
const selected = source.slice(start, end);
if (sha256(selected) !== input.selection.selected_sha256)
throw new TypeError("JavaScript instrumentation selection digest mismatch");
decodeUtf8(source);
decodeUtf8(selected);
const prefix = encode("function(module, exports, require) {\n");
const binding = encode(
`\nmodule.exports[${JSON.stringify(input.selection.export_name)}] = (${decodeUtf8(selected)});\n`,
);
const suffix = encode("}\n");
const bytes = concatenate([prefix, source, binding, suffix]);
const bindingStart = prefix.byteLength + source.byteLength;
const suffixStart = bindingStart + binding.byteLength;
const manifest = javascriptExportTransformationManifestSchema.parse({
kind: "commonjs-factory-export-v1",
artifact_path: input.artifact_path,
original_sha256: input.artifact_sha256,
original_byte_length: source.byteLength,
instrumented_sha256: sha256(bytes),
instrumented_byte_length: bytes.byteLength,
selected_range: {
byte_start: start,
byte_end: end,
selected_sha256: input.selection.selected_sha256,
},
inserted_ranges: [
range(0, prefix, "factory-prefix"),
range(bindingStart, binding, "export-binding"),
range(suffixStart, suffix, "factory-suffix"),
],
output_format: "commonjs-factory",
source_map: null,
});
return { bytes, manifest };
};
const range = (
start: number,
bytes: Uint8Array,
purpose: "factory-prefix" | "export-binding" | "factory-suffix",
) => ({
byte_start: start,
byte_end: start + bytes.byteLength,
inserted_sha256: sha256(bytes),
purpose,
});
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
const decodeUtf8 = (value: Uint8Array): string =>
new TextDecoder("utf-8", { fatal: true }).decode(value);
const concatenate = (values: readonly Uint8Array[]): Uint8Array => {
const output = new Uint8Array(
values.reduce((total, value) => total + value.byteLength, 0),
);
let offset = 0;
for (const value of values) {
output.set(value, offset);
offset += value.byteLength;
}
return output;
};
const sha256 = (value: Uint8Array): string =>
createHash("sha256").update(value).digest("hex");
@@ -71,11 +71,6 @@ export const compareJavaScriptExportShapes = (
coverage,
evidence_links: evidenceLinks,
limitations,
runtime_validation: {
recommended_tool: "run_controlled_replay" as const,
automatically_started: false as const,
required_for: "runtime-semantics" as const,
},
};
return javaScriptExportShapeComparisonResultSchema.parse({
...semantic,
@@ -181,7 +176,7 @@ const comparisonLimitations = (
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
"Return variants are paired only by unique exact literal discriminants, never by source order.",
"Dynamic values, incomplete object coverage, and ambiguous variants remain unknown.",
"Controlled replay is recommended separately for runtime semantics and was not started.",
"This static comparison cannot establish runtime semantics; run behavioral probes directly against the relevant application versions when that evidence is required.",
...left.limitations,
...right.limitations,
...(status === "truncated"
@@ -152,11 +152,6 @@ it("accepts complete candidate and change inventories without page ceilings", ()
},
evidence_links: [evidenceId, `ev_${"c".repeat(64)}`],
limitations: [],
runtime_validation: {
recommended_tool: "run_controlled_replay",
automatically_started: false,
required_for: "runtime-semantics",
},
}).changes,
).toHaveLength(10_001);
});
@@ -284,11 +284,6 @@ export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
}),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(textSchema),
runtime_validation: z.strictObject({
recommended_tool: z.literal("run_controlled_replay"),
automatically_started: z.literal(false),
required_for: z.literal("runtime-semantics"),
}),
});
export type ProjectedExportReturnShapes = z.output<
-420
View File
@@ -1,420 +0,0 @@
import { z } from "zod";
import { evidenceEnvelopeSchema } from "./evidence.js";
import { digestSchema } from "./../domain/digests.js";
const absolutePathSchema = z.string().startsWith("/");
const aliasSchema = z
.string()
.min(1)
.regex(/^[A-Za-z0-9_./:@-]+$/u);
const replayModuleSchema = z
.object({
alias: aliasSchema,
path: absolutePathSchema,
format: z.enum(["esm", "commonjs-factory"]),
role: z.enum(["module", "stub"]).default("module"),
dependencies: z.record(z.string().min(1), aliasSchema).default({}),
})
.strict();
const replaySideSchema = z
.object({
modules: z.array(replayModuleSchema).min(1),
entry_alias: aliasSchema,
entry_export: z.string().min(1).default("default"),
})
.strict();
const explicitCaseSchema = z
.object({
case_id: z.string().min(1),
arguments: z.array(z.json()),
})
.strict();
const generatorSchema = z
.object({
preset: z.enum([
"parser-boundaries",
"sanitizer-boundaries",
"clipboard-boundaries",
]),
seed: z.number().int().min(0).max(0xffff_ffff),
count: z.number().int().safe().min(1),
})
.strict();
const replayLimitsSchema = z
.object({
wall_time_ms: z.number().int().safe().min(1).default(3_000),
memory_bytes: z
.number()
.int()
.safe()
.positive()
.default(128 * 1024 * 1024),
tasks: z.number().int().safe().min(1).default(8),
cpu_quota_percent: z.number().int().safe().min(1).default(50),
tmpfs_bytes: z
.number()
.int()
.safe()
.min(1)
.default(16 * 1024 * 1024),
module_bytes: z
.number()
.int()
.safe()
.min(1)
.default(4 * 1024 * 1024),
input_bytes: z
.number()
.int()
.safe()
.min(1)
.default(256 * 1024),
protocol_bytes: z
.number()
.int()
.safe()
.min(1)
.default(16 * 1024 * 1024),
output_bytes: z
.number()
.int()
.safe()
.min(1)
.default(512 * 1024),
stderr_bytes: z
.number()
.int()
.safe()
.min(0)
.default(32 * 1024),
result_depth: z.number().int().safe().min(1).default(16),
result_nodes: z.number().int().safe().min(1).default(10_000),
})
.strict();
const determinismSchema = z
.object({
clock_iso: z.iso.datetime().default("2000-01-01T00:00:00.000Z"),
random_seed: z.number().int().min(0).max(0xffff_ffff).default(0),
locale: z.literal("en-US").default("en-US"),
timezone: z.literal("UTC").default("UTC"),
platform: z.literal("linux").default("linux"),
})
.strict();
const controlledReplayCommonInputShape = {
left: replaySideSchema,
right: replaySideSchema.optional(),
determinism: determinismSchema.default({
clock_iso: "2000-01-01T00:00:00.000Z",
random_seed: 0,
locale: "en-US",
timezone: "UTC",
platform: "linux",
}),
limits: replayLimitsSchema.default({
wall_time_ms: 3_000,
memory_bytes: 128 * 1024 * 1024,
tasks: 8,
cpu_quota_percent: 50,
tmpfs_bytes: 16 * 1024 * 1024,
module_bytes: 4 * 1024 * 1024,
input_bytes: 256 * 1024,
protocol_bytes: 16 * 1024 * 1024,
output_bytes: 512 * 1024,
stderr_bytes: 32 * 1024,
result_depth: 16,
result_nodes: 10_000,
}),
reproducer_export: z
.strictObject({
path: absolutePathSchema,
include_sources: z.boolean().default(false),
})
.optional(),
} as const;
/** Parse a replay request that can only construct a plan. */
export const controlledReplayPlanInputSchema = z.strictObject({
...controlledReplayCommonInputShape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema.optional(),
mode: z.literal("plan"),
});
/** Parse a replay request carrying the digest for one exact plan. */
export const controlledReplayExecutionInputSchema = z.strictObject({
...controlledReplayCommonInputShape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema.optional(),
mode: z.literal("execute"),
plan_digest: digestSchema,
});
const replayWithExplicitCases = <Shape extends z.ZodRawShape>(shape: Shape) =>
z.strictObject({
...shape,
cases: z.array(explicitCaseSchema).min(1),
});
const replayWithGeneratedCases = <Shape extends z.ZodRawShape>(shape: Shape) =>
z.strictObject({
...shape,
cases: z.array(explicitCaseSchema).default([]),
generator: generatorSchema,
});
/** Parse replay requests with explicit cases or a generated case preset. */
export const controlledReplayInputSchema = z.union([
replayWithExplicitCases({
...controlledReplayCommonInputShape,
mode: z.literal("plan"),
}),
replayWithGeneratedCases({
...controlledReplayCommonInputShape,
mode: z.literal("plan"),
}),
replayWithExplicitCases({
...controlledReplayCommonInputShape,
mode: z.literal("execute"),
plan_digest: digestSchema,
}),
replayWithGeneratedCases({
...controlledReplayCommonInputShape,
mode: z.literal("execute"),
plan_digest: digestSchema,
}),
]);
const moduleCommitmentSchema = z
.object({
alias: aliasSchema,
canonical_path: z.string().min(1),
format: z.enum(["esm", "commonjs-factory"]),
role: z.enum(["module", "stub"]),
byte_count: z.number().int().min(0),
sha256: digestSchema,
dependencies: z.record(z.string(), aliasSchema),
})
.strict();
const runtimeIdentitySchema = z
.object({
path: z.string().min(1),
version: z.string().min(1),
sha256: digestSchema,
})
.strict();
const runtimeFileIdentitySchema = z
.object({
source_path: z.string().min(1),
destination_path: z.string().min(1),
sha256: digestSchema,
})
.strict();
const replayPlanSchema = z
.object({
plan_digest: digestSchema,
policy_version: z.literal("linux-bwrap-systemd-v1"),
policy_sha256: digestSchema,
network: z.literal("none"),
filesystem: z
.object({
host_writes: z.literal(false),
private_tmpfs_bytes: z.number().int().nonnegative(),
})
.strict(),
runtime: z
.object({
executable: runtimeIdentitySchema,
worker: runtimeIdentitySchema,
read_only_files: z.array(runtimeFileIdentitySchema).min(1),
})
.strict(),
sandbox: z
.object({
bubblewrap: runtimeIdentitySchema,
systemd_run: runtimeIdentitySchema,
systemctl: runtimeIdentitySchema,
shell: runtimeIdentitySchema,
seccomp_sha256: digestSchema,
})
.strict(),
left: z
.object({
modules: z.array(moduleCommitmentSchema),
entry_alias: aliasSchema,
entry_export: z.string(),
})
.strict(),
right: z
.object({
modules: z.array(moduleCommitmentSchema),
entry_alias: aliasSchema,
entry_export: z.string(),
})
.strict()
.optional(),
cases: z.array(
z
.object({
case_id: z.string(),
arguments: z.array(z.json()),
sha256: digestSchema,
})
.strict(),
),
determinism: determinismSchema,
limits: replayLimitsSchema,
effects: z.array(z.string()),
reproducer_export: z
.object({
path: z.string().min(1),
include_sources: z.boolean(),
})
.strict()
.nullable(),
})
.strict();
const replayOutcomeFacts = {
case_id: z.string(),
input_sha256: digestSchema,
} as const;
const replayExceptionSchema = z
.object({
name: z.string(),
message: z.string(),
stack: z.string().nullable(),
})
.strict();
const replayOutcomeSchema = z.discriminatedUnion("outcome", [
z.strictObject({
...replayOutcomeFacts,
outcome: z.literal("return"),
value: z.json(),
output_sha256: digestSchema,
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.enum(["exception", "serialization_error", "denied"]),
exception: z.object(replayExceptionSchema.shape).strict(),
output_sha256: digestSchema,
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.enum(["timeout", "oom", "crash", "cancelled"]),
output_sha256: z.null(),
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.literal("protocol_error"),
output_sha256: z.null(),
truncated: z.literal(true),
}),
]);
export const replayExecutionResultSchema = z
.object({
plan_digest: digestSchema,
outcomes: z.array(replayOutcomeSchema),
comparison: z
.array(
z
.object({
case_id: z.string(),
status: z.enum(["equal", "changed", "unknown"]),
left_index: z.number().int(),
right_index: z.number().int(),
})
.strict(),
)
.optional(),
stderr: z.string(),
termination: z.enum([
"completed",
"timeout",
"oom",
"crash",
"cancelled",
"protocol_error",
]),
cleanup: z
.object({
state: z.enum(["complete", "incomplete"]),
residual_resources: z.array(z.string()),
})
.strict(),
limitations: z.array(z.string()),
reproducer: z
.discriminatedUnion("state", [
z
.object({
state: z.literal("written"),
path: z.string(),
sha256: digestSchema,
})
.strict(),
z
.object({
state: z.literal("failed"),
path: z.string(),
error: z.string(),
})
.strict(),
])
.nullable(),
})
.strict();
export const replayEvidenceSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: replayExecutionResultSchema });
/** A replay plan result with no claimed runtime observation. */
export const controlledReplayPlanOutputSchema = z.strictObject({
phase: z.literal("plan"),
plan: replayPlanSchema,
source_evidence: z
.array(replayEvidenceSchema)
.length(0)
.brand<"NoReplayEvidence">(),
evidence: z.null(),
});
/** An executed replay result with its required source and aggregate Evidence. */
export const controlledReplayExecutionOutputSchema = z.strictObject({
phase: z.literal("execute"),
plan: z.null(),
source_evidence: z.array(replayEvidenceSchema).min(1),
evidence: replayEvidenceSchema,
});
/** Parse replay output into its legal plan or execution state. */
export const controlledReplayOutputSchema = z.discriminatedUnion("phase", [
controlledReplayPlanOutputSchema,
controlledReplayExecutionOutputSchema,
]);
export type ControlledReplayInput =
| z.output<typeof controlledReplayPlanInputSchema>
| z.output<typeof controlledReplayExecutionInputSchema>;
export type ControlledReplayExecutionInput = z.output<
typeof controlledReplayExecutionInputSchema
>;
export type ControlledReplayExecutionOutput = z.infer<
typeof controlledReplayExecutionOutputSchema
>;
export type ReplayPlan = z.infer<typeof replayPlanSchema>;
export type ReplayExecutionResult = z.infer<typeof replayExecutionResultSchema>;
-207
View File
@@ -1,207 +0,0 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "./evidence.js";
import {
cliMetadataGuidSchema,
managedMemberInspectionSchema,
} from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1);
const managedRuntimeEffectSchema = z.enum([
"attach",
"load",
"debugger",
"reflection",
"instrumentation",
]);
const managedRuntimeHostSchema = z.strictObject({
os: z.enum(["linux", "macos", "windows"]),
clr_family: z.enum(["dotnet", "dotnet-framework", "mono", "unknown"]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
});
const managedRuntimeBoundsSchema = z.strictObject({
timeout_ms: z.number().int().min(1).default(5_000),
max_threads: z.number().int().min(1).default(32),
max_output_bytes: z.number().int().min(0).default(65_536),
allow_network: z.boolean().default(false),
allow_ui: z.boolean().default(false),
});
export const managedRuntimeCorrelationInputSchema = z.strictObject({
static_members: evidenceSchema,
method: z.strictObject({
token: tokenSchema,
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
}),
requested_effect: managedRuntimeEffectSchema,
host: managedRuntimeHostSchema,
bounds: managedRuntimeBoundsSchema.default({
timeout_ms: 5_000,
max_threads: 32,
max_output_bytes: 65_536,
allow_network: false,
allow_ui: false,
}),
});
export const managedRuntimeCorrelationResultSchema = z.strictObject({
correlation_id: prefixedDigestSchema("mrc"),
phase: z.literal("correlation-plan"),
executed: z.literal(false),
static_observation: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1),
byte_length: z.number().int().min(0),
module_name: z.string().nullable(),
mvid: cliMetadataGuidSchema.nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
}),
method_lock: z.strictObject({
token: tokenSchema,
declaring_type: z.string().nullable(),
name: z.string(),
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
body_sha256: digestSchema.nullable(),
il_size: z.number().int().min(0),
body_status: z.enum([
"present",
"partial",
"absent",
"malformed",
"too-large",
]),
exact_build_required: z.literal(true),
}),
requested_runtime: z.strictObject({
effect: managedRuntimeEffectSchema,
host: managedRuntimeHostSchema,
executable_path: z.string().min(1),
network: z.enum(["none", "host"]),
confinement: z.literal("not-established"),
}),
effect_taxonomy: z.strictObject({
attaches_process: z.boolean(),
loads_target: z.boolean(),
uses_debugger: z.boolean(),
uses_reflection: z.boolean(),
instruments_code: z.boolean(),
invokes_target_code: z.literal(false),
}),
bounds: managedRuntimeBoundsSchema,
unsupported_until_executor_exists: z.literal(true),
evidence_links: z.array(evidenceIdSchema).length(1),
limitations: z.array(boundedTextSchema),
});
export type ManagedRuntimeCorrelationInput = z.infer<
typeof managedRuntimeCorrelationInputSchema
>;
export type ManagedRuntimeCorrelationResult = z.infer<
typeof managedRuntimeCorrelationResultSchema
>;
const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed runtime correlation canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
/** Authenticate static managed Evidence and build a non-executing runtime plan. */
export const planManagedRuntimeCorrelation = (
input: ManagedRuntimeCorrelationInput,
executablePath: string,
): ManagedRuntimeCorrelationResult => {
const staticEvidence = parseEvidence(input.static_members);
if (staticEvidence.operation !== "inspect_managed_members")
throw new TypeError("Evidence operation is not inspect_managed_members");
const members = managedMemberInspectionSchema.parse(
staticEvidence.normalized_result,
);
const method = members.methods.find(
(item) =>
item.token === input.method.token &&
item.signature.raw_sha256 === input.method.signature_sha256 &&
item.body.status === "present" &&
item.body.normalized_il_sha256 !== null &&
input.method.normalized_il_sha256 !== null &&
item.body.normalized_il_sha256 === input.method.normalized_il_sha256,
);
if (method === undefined)
throw new TypeError(
"Requested method lock does not match a static managed member observation",
);
const withoutId = {
phase: "correlation-plan" as const,
executed: false as const,
static_observation: {
evidence_id: staticEvidence.evidence_id,
artifact_sha256: members.artifact.sha256,
artifact_path: members.artifact.path,
byte_length: members.artifact.byte_length,
module_name: members.module?.name ?? null,
mvid: members.module?.mvid ?? null,
metadata_status: members.metadata.status,
},
method_lock: {
token: method.token,
declaring_type: method.declaring_type,
name: method.name,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
body_sha256: method.body.il_sha256,
il_size: method.body.il_size,
body_status: method.body.status,
exact_build_required: true as const,
},
requested_runtime: {
effect: input.requested_effect,
host: input.host,
executable_path: executablePath,
network: input.bounds.allow_network
? ("host" as const)
: ("none" as const),
confinement: "not-established" as const,
},
effect_taxonomy: effectTaxonomy(input.requested_effect),
bounds: input.bounds,
unsupported_until_executor_exists: true as const,
evidence_links: [staticEvidence.evidence_id],
limitations: [
"This operation admits and records a runtime-correlation plan only; it did not attach, load, debug, reflect, instrument, invoke, or execute target code.",
"Runtime agreement would be a separate runtime observation and would not retroactively turn static inference into a byte observation.",
"The exact artifact SHA-256, MVID, method signature, and normalized IL shape must match before any future executor can run.",
"The selected runtime executable and host prerequisites are unverified because planning does not launch the runtime.",
"No filesystem, network, or UI confinement was established; the requested bounds describe a future executor configuration only.",
],
};
return managedRuntimeCorrelationResultSchema.parse({
...withoutId,
correlation_id: `mrc_${sha256(withoutId)}`,
});
};
const effectTaxonomy = (
effect: ManagedRuntimeCorrelationInput["requested_effect"],
): ManagedRuntimeCorrelationResult["effect_taxonomy"] => ({
attaches_process: effect === "attach",
loads_target: effect === "load" || effect === "reflection",
uses_debugger: effect === "debugger",
uses_reflection: effect === "reflection",
instruments_code: effect === "instrumentation",
invokes_target_code: false,
});
-90
View File
@@ -1,90 +0,0 @@
import { z } from "zod";
import {
controlledReplayExecutionOutputSchema,
controlledReplayPlanInputSchema,
controlledReplayPlanOutputSchema,
} from "./javascriptReplay.js";
import {
javascriptExportInstrumentationInputSchema,
javascriptExportTransformationManifestSchema,
} from "./javascriptExportInstrumentation.js";
import { runtimeCharacterizationPlanSchema } from "./runtimeCharacterization.js";
import { evidenceRecordSchema } from "./evidence.js";
import { digestSchema } from "./../domain/digests.js";
const nodeCharacterizationExpectedEffectSchema = z.enum([
"pure",
"observation-only",
]);
const nodeRuntimeCharacterizationPlanSchema =
runtimeCharacterizationPlanSchema.extend({
expected_effect: nodeCharacterizationExpectedEffectSchema,
});
export const nodeCharacterizationPreparationInputSchema = z
.strictObject({
selected_alias: z.string().min(1),
expected_effect: nodeCharacterizationExpectedEffectSchema,
instrumentation: javascriptExportInstrumentationInputSchema,
replay: controlledReplayPlanInputSchema,
})
.superRefine((input, context) => {
const selected = input.replay.left.modules.filter(
({ alias }) => alias === input.selected_alias,
);
if (
selected.length !== 1 ||
selected[0]?.path !== input.instrumentation.artifact_path ||
selected[0]?.format !== "commonjs-factory"
)
context.addIssue({
code: "custom",
path: ["selected_alias"],
message:
"Selected alias must identify exactly one commonjs-factory instrumented artifact",
});
if (input.replay.left.entry_alias !== input.selected_alias)
context.addIssue({
code: "custom",
path: ["replay", "left", "entry_alias"],
message: "Instrumented alias must be the characterization entry",
});
if (
input.replay.left.entry_export !==
input.instrumentation.selection.export_name
)
context.addIssue({
code: "custom",
path: ["replay", "left", "entry_export"],
message: "Replay entry export must match the instrumented export",
});
});
export const nodeCharacterizationExecutionInputSchema = z.strictObject({
plan_sha256: digestSchema.describe(
"SHA-256 content identity of the prepared plan; execution rejects a mismatch.",
),
preparation: nodeCharacterizationPreparationInputSchema,
});
export const nodeCharacterizationPreparationOutputSchema = z.strictObject({
phase: z.literal("preparation"),
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
transformation_evidence: evidenceRecordSchema,
replay: controlledReplayPlanOutputSchema,
});
export const nodeCharacterizationExecutionOutputSchema = z.strictObject({
phase: z.literal("execution"),
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
transformation_evidence: evidenceRecordSchema,
evidence: evidenceRecordSchema,
replay: controlledReplayExecutionOutputSchema,
});
export type NodeCharacterizationPreparationInput = z.infer<
typeof nodeCharacterizationPreparationInputSchema
>;
+30 -26
View File
@@ -22,10 +22,6 @@ it("classifies missing observations as unknown and one-sided evidence as added",
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -61,7 +57,6 @@ it("classifies missing observations as unknown and one-sided evidence as added",
base,
);
expect(unknown.process).toBe("unknown");
expect(unknown.shim).toBe("unchanged");
expect(unknown.status).toBe("unknown");
});
@@ -102,10 +97,6 @@ it("compares raw terminal chunks even when rendered states agree", () => {
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -146,10 +137,6 @@ it("keeps filesystem evidence unknown when stable snapshots match", () => {
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -169,26 +156,43 @@ it("keeps filesystem evidence unknown when stable snapshots match", () => {
expect(comparison.status).toBe("unknown");
const complete = { ...capture, residual_unknowns: [] };
const transient = compareProcessCaptures(complete, {
const finalFile = {
path: "root_0:created.txt",
type: "file" as const,
mode: 0o644,
size: 4,
sha256: "a".repeat(64),
symlink_target: null,
};
const changed = compareProcessCaptures(complete, {
...complete,
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "during_run",
at_ms: 10,
files: [],
effects: [],
truncated: false,
},
{
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
at_ms: 10,
files: [finalFile],
effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
truncated: false,
},
],
files_after: [finalFile],
filesystem_effects: [
{
path: finalFile.path,
status: "created",
before: null,
after: finalFile,
},
],
});
expect(transient.filesystem).toBe("changed");
expect(transient.status).toBe("changed");
expect(changed.filesystem).toBe("changed");
expect(changed.status).toBe("changed");
});
@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { digestProcessCommitment } from "./processCapture.js";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
@@ -32,10 +31,6 @@ it("detects changes in normalized process sample metadata", () => {
},
],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -65,60 +60,3 @@ it("detects changes in normalized process sample metadata", () => {
expect(comparison.process).toBe("changed");
expect(comparison.status).toBe("changed");
});
it("compares replay state transitions as protocol evidence", () => {
const replayPlan = {
machine: {
initial_state: "anonymous",
states: [
{ name: "anonymous" },
{ name: "authenticated", terminal: true },
],
transitions: [
{
id: "login",
from: "anonymous",
to: "authenticated",
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, body: "" }],
max_uses: 1,
},
],
max_transitions: 1,
},
};
const empty = emptyCapture();
const baseline = {
...empty,
manifest: {
...empty.manifest,
replay_plan: replayPlan,
replay_plan_sha256: digestProcessCommitment(replayPlan),
},
};
const transitioned = {
...baseline,
replay_transitions: [
{
sequence: 0,
at_ms: 0,
transition_id: "login",
state_before: "anonymous",
state_after: "authenticated",
sensitive_aliases: ["token"],
},
],
};
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
status: "changed",
protocol: "added",
});
});
+8 -134
View File
@@ -2,12 +2,6 @@ import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { normalizationSchema } from "./processScenario.js";
import type {
ProcessReactiveStatus,
ProcessReactiveTransitionRecord,
} from "./processReactiveRuntime.js";
import { processReactiveRunSchema } from "./processCaptureReactiveSchema.js";
import type { ReplayTransitionRecord } from "./replayMachineRuntime.js";
import { collectProcessCaptureIssues } from "./processCaptureValidation.js";
export * from "./processScenario.js";
@@ -37,7 +31,7 @@ export interface InteractionEvent {
readonly sequence: number;
readonly scheduled_at_ms: number;
readonly dispatched_at_ms: number;
readonly type: "input" | "resize" | "stdin_close" | "signal";
readonly type: "input" | "resize" | "signal";
readonly data: string;
readonly outcome: "dispatched" | "target_exited" | "failed";
}
@@ -101,9 +95,7 @@ export interface ProcessSample {
readonly session_id: number | null;
}
/**
* Named filesystem state whose effects are relative to the prior checkpoint.
*/
/** Initial or final filesystem snapshot selected for observation. */
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
@@ -112,39 +104,6 @@ export interface FilesystemCheckpoint {
readonly truncated: boolean;
}
/** Recorded deterministic dependency invocation and route-match outcome. */
export interface ShimEvent {
readonly sequence: number;
readonly at_ms: number;
readonly command: string;
readonly route_index: number | null;
readonly arguments: readonly string[];
readonly working_directory: string;
readonly outcome: "matched" | "unmatched" | "exhausted";
}
/** A bounded loopback replay observation. */
export interface ProtocolEvent {
readonly sequence: number;
readonly at_ms: number;
readonly protocol: "http" | "websocket";
readonly direction: "request" | "response" | "received" | "sent";
readonly method: string | null;
readonly path: string | null;
readonly data: string;
readonly outcome:
| "matched"
| "unmatched"
| "script_exhausted"
| "disconnected"
| "invalid_state"
| "guard_failed"
| "transition_exhausted"
| "invalid_capture"
| "unexpected_reconnect"
| "limit_exhausted";
}
/** Capture collection whose members participate in global observation order. */
export const PROCESS_CAPTURE_EVENT_COLLECTIONS = [
"frames",
@@ -153,9 +112,6 @@ export const PROCESS_CAPTURE_EVENT_COLLECTIONS = [
"lifecycle",
"process_samples",
"filesystem_checkpoints",
"shim_events",
"protocol_events",
"replay_transitions",
] as const;
export type ProcessCaptureEventCollection =
@@ -168,18 +124,6 @@ export interface ProcessCaptureEventJournalEntry {
readonly index: number;
}
/** Ordered control input that terminated or superseded a reactive run. */
export interface ProcessReactiveControlRecord {
readonly sequence: number;
readonly kind:
| "state_deadline"
| "scenario_deadline"
| "target_lost"
| "cancelled"
| "cleanup_failed";
readonly after_capture_order: number;
}
/** Shared observation callback used by every process-capture producer. */
export type RecordProcessCaptureEvent = (
collection: ProcessCaptureEventCollection,
@@ -216,14 +160,10 @@ export interface UnverifiedProcessCapture {
readonly completed_at: string;
readonly scenario: Readonly<Record<string, unknown>>;
readonly comparison_contract: Readonly<Record<string, unknown>>;
readonly shim_plan: readonly unknown[];
readonly replay_plan: Readonly<Record<string, unknown>>;
readonly full_scenario_sha256: string;
readonly comparison_contract_sha256: string;
readonly executable_sha256: string;
readonly normalization_sha256: string;
readonly shim_plan_sha256: string;
readonly replay_plan_sha256: string;
};
readonly normalization: z.infer<typeof normalizationSchema>;
readonly frames: readonly TerminalFrame[];
@@ -237,16 +177,6 @@ export interface UnverifiedProcessCapture {
readonly settlement: ProcessSettlement;
readonly process_samples: readonly ProcessSample[];
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
readonly shim_events: readonly ShimEvent[];
readonly protocol_events: readonly ProtocolEvent[];
readonly replay_transitions: readonly ReplayTransitionRecord[];
readonly reactive_run:
| ({
readonly active_state: string;
readonly transitions: readonly ProcessReactiveTransitionRecord[];
readonly controls: readonly ProcessReactiveControlRecord[];
} & ProcessReactiveStatus)
| null;
/**
* Global observation order across independently recorded collections.
*
@@ -265,8 +195,6 @@ export interface UnverifiedProcessCapture {
| "exit"
| "process"
| "filesystem"
| "protocol"
| "shim"
| "cleanup"
| "network"
| "environment";
@@ -327,9 +255,9 @@ const fileEffectSchema = z.discriminatedUnion("status", [
}),
]);
/** Exact serialized shape of a process capture. */
const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
{
manifest: z.object({
const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> =
z.strictObject({
manifest: z.strictObject({
rea_version: z.string().min(1),
provider_version: z.string().min(1),
platform: z.string().min(1),
@@ -339,14 +267,10 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
completed_at: z.iso.datetime(),
scenario: z.record(z.string(), jsonValueSchema),
comparison_contract: z.record(z.string(), jsonValueSchema),
shim_plan: z.array(jsonValueSchema),
replay_plan: z.record(z.string(), jsonValueSchema),
full_scenario_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
comparison_contract_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
shim_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
replay_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
}),
normalization: normalizationSchema,
frames: z.array(
@@ -374,7 +298,7 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
sequence: z.number().int().nonnegative(),
scheduled_at_ms: z.number().int().nonnegative(),
dispatched_at_ms: z.number().int().nonnegative(),
type: z.enum(["input", "resize", "stdin_close", "signal"]),
type: z.enum(["input", "resize", "signal"]),
data: z.string(),
outcome: z.enum(["dispatched", "target_exited", "failed"]),
}),
@@ -408,60 +332,13 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
),
filesystem_checkpoints: z.array(
z.object({
name: z.string(),
name: z.enum(["before", "after_settlement"]),
at_ms: z.number().int().nonnegative(),
files: z.array(fileStateSchema),
effects: z.array(fileEffectSchema),
truncated: z.boolean(),
}),
),
shim_events: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
command: z.string(),
route_index: z.number().int().nonnegative().nullable(),
arguments: z.array(z.string()),
working_directory: z.string(),
outcome: z.enum(["matched", "unmatched", "exhausted"]),
}),
),
protocol_events: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
protocol: z.enum(["http", "websocket"]),
direction: z.enum(["request", "response", "received", "sent"]),
method: z.string().nullable(),
path: z.string().nullable(),
data: z.string(),
outcome: z.enum([
"matched",
"unmatched",
"script_exhausted",
"disconnected",
"invalid_state",
"guard_failed",
"transition_exhausted",
"invalid_capture",
"unexpected_reconnect",
"limit_exhausted",
]),
}),
),
replay_transitions: z
.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
transition_id: z.string().min(1),
state_before: z.string().min(1),
state_after: z.string().min(1),
sensitive_aliases: z.array(z.string().min(1)),
}),
)
.default([]),
reactive_run: processReactiveRunSchema.nullable().default(null),
event_journal: z
.array(
z.object({
@@ -484,8 +361,6 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
"exit",
"process",
"filesystem",
"protocol",
"shim",
"cleanup",
"network",
"environment",
@@ -497,8 +372,7 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
owned_process_group: z.literal("verified"),
temporary_root: z.literal("removed"),
}),
},
);
});
/** Exact serialized shape plus all process-capture semantic invariants. */
export const processCaptureSchema = processCaptureShapeSchema.superRefine(
@@ -28,10 +28,6 @@ it("never considers truncated captures equivalent", () => {
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
replay_transitions: [],
reactive_run: null,
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -146,77 +142,6 @@ it("accepts old captures without a journal and validates complete journals", ()
}
});
it.each([
["machine limit", 1, 5, 10],
["transition use limit", 5, 1, 10],
["state visit limit", 5, 5, 1],
])(
"rejects replay journals that exceed the declared %s",
(_name, maxTransitions, maxUses, maxVisits) => {
const replayPlan = {
machine: {
initial_state: "active",
states: [
{ name: "active", max_visits: maxVisits },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "again",
from: "active",
to: "active",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "again",
},
actions: [{ type: "websocket_send", data: "again" }],
max_uses: maxUses,
},
{
id: "finish",
from: "active",
to: "complete",
trigger: {
protocol: "websocket_message",
path: "/ws",
body: "finish",
},
actions: [{ type: "websocket_send", data: "done" }],
max_uses: 1,
},
],
max_transitions: maxTransitions,
},
};
const capture = emptyCapture();
const candidate: UnverifiedProcessCapture = {
...capture,
manifest: {
...capture.manifest,
replay_plan: replayPlan,
replay_plan_sha256: digestProcessCommitment(replayPlan),
},
replay_transitions: [0, 1].map((sequence) => ({
sequence,
at_ms: sequence,
transition_id: "again",
state_before: "active",
state_after: "active",
sensitive_aliases: [],
})),
};
expect(processCaptureIssues(candidate)).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: expect.stringContaining("limit"),
}),
]),
);
},
);
it("requires compatible contracts and enforces capture age through a clock seam", () => {
const capture = emptyCapture();
expect(() =>
-9
View File
@@ -10,8 +10,6 @@ const normalization = {
};
const scenario = { executable_sha256: "0".repeat(64) };
const comparisonContract = {};
const shimPlan: JsonValue[] = [];
const replayPlan = {};
/** Minimal valid process capture retained as a public contract example. */
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
@@ -25,14 +23,10 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
completed_at: "2026-01-01T00:00:00.001Z",
scenario,
comparison_contract: comparisonContract,
shim_plan: shimPlan,
replay_plan: replayPlan,
full_scenario_sha256: digestProcessCommitment(scenario),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
executable_sha256: "0".repeat(64),
normalization_sha256: digestProcessCommitment(normalization),
shim_plan_sha256: digestProcessCommitment(shimPlan),
replay_plan_sha256: digestProcessCommitment(replayPlan),
},
normalization,
frames: [],
@@ -55,9 +49,6 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
truncated: false,
},
],
shim_events: [],
protocol_events: [],
replay_transitions: [],
files_before: [],
files_after: [],
filesystem_effects: [],
@@ -1,34 +0,0 @@
import { describe, expect, it } from "vitest";
import { processReactiveRunSchema } from "./processCaptureReactiveSchema.js";
describe("process reactive capture schema", () => {
it("accepts every committed transition without a fixed journal ceiling", () => {
const transitions = Array.from({ length: 130 }, (_, sequence) => ({
sequence,
transition_id: `transition_${String(sequence)}`,
state_before: "active",
state_after: "active",
outcome: null,
trigger_event_ids: Array.from(
{ length: 80 },
(_, index) => `event_${String(index)}`,
),
action_event_ids: Array.from(
{ length: 300 },
(_, index) => `action_${String(index)}`,
),
action_types: Array.from({ length: 300 }, () => "send_input" as const),
}));
const parsed = processReactiveRunSchema.safeParse({
status: "running",
outcome: null,
active_state: "active",
transitions,
});
expect(parsed.success).toBe(true);
if (parsed.success) expect(parsed.data.transitions).toHaveLength(130);
});
});
@@ -1,77 +0,0 @@
import { z } from "zod";
const processReactiveOutcomeSchema = z.enum([
"passed",
"predicate_timeout",
"scenario_deadline",
"ambiguous_match",
"action_rejected",
"target_lost",
"capture_incomplete",
"cancelled",
"cleanup_failed",
]);
const processReactiveTransitionShape = {
sequence: z.number().int().nonnegative(),
transition_id: z.string().min(1),
state_before: z.string().min(1),
trigger_event_ids: z.array(z.string().min(1)),
action_event_ids: z.array(z.string().min(1)),
action_types: z.array(
z.enum([
"send_input",
"resize",
"close_stdin",
"send_signal",
"checkpoint",
]),
),
};
const processReactiveTransitionSchema = z.union([
z.object({
...processReactiveTransitionShape,
state_after: z.string().min(1),
outcome: z.null(),
}),
z.object({
...processReactiveTransitionShape,
state_after: z.null(),
outcome: z.literal("passed"),
}),
]);
const processReactiveRunShape = {
active_state: z.string().min(1),
controls: z
.array(
z.object({
sequence: z.number().int().nonnegative(),
kind: z.enum([
"state_deadline",
"scenario_deadline",
"target_lost",
"cancelled",
"cleanup_failed",
]),
after_capture_order: z.number().int().min(-1),
}),
)
.default([]),
transitions: z.array(processReactiveTransitionSchema),
};
/** Serialized reactive reducer state admitted by process capture. */
export const processReactiveRunSchema = z.discriminatedUnion("status", [
z.object({
status: z.literal("running"),
outcome: z.null(),
...processReactiveRunShape,
}),
z.object({
status: z.literal("finished"),
outcome: processReactiveOutcomeSchema,
...processReactiveRunShape,
}),
]);
@@ -1,275 +0,0 @@
import canonicalize from "canonicalize";
import type { UnverifiedProcessCapture } from "./processCapture.js";
import {
projectProcessObservation,
type ProcessObservation,
} from "./processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
type ProcessReactiveDecision,
type ProcessReactiveInput,
type ProcessReactiveSnapshot,
} from "./processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveScenario,
} from "./processReactiveScenario.js";
type RequireInvariant = (
condition: boolean,
path: string,
message: string,
) => void;
type ReactiveRun = NonNullable<UnverifiedProcessCapture["reactive_run"]>;
type ReactiveTransition = ReactiveRun["transitions"][number];
const admittedCollection = (
collection: NonNullable<
UnverifiedProcessCapture["event_journal"]
>[number]["collection"],
): boolean =>
[
"frames",
"interaction_events",
"process_samples",
"filesystem_checkpoints",
"shim_events",
"protocol_events",
].includes(collection);
const reactiveObservations = (
capture: UnverifiedProcessCapture,
): readonly ProcessObservation[] =>
(capture.event_journal ?? []).flatMap((location) => {
if (!admittedCollection(location.collection)) return [];
const observation = projectProcessObservation(capture, location);
return observation === null ? [] : [observation];
});
const validateTransitionDeclaration = (
transition: ReactiveTransition,
next: ReactiveTransition | undefined,
context: {
readonly index: number;
readonly scenario: ProcessReactiveScenario;
readonly require: RequireInvariant;
},
): void => {
const { index, scenario, require } = context;
const path = `reactive_run.transitions[${String(index)}]`;
const declared = scenario.states
.find(({ id }) => id === transition.state_before)
?.on.find(({ id }) => id === transition.transition_id);
require(declared !==
undefined, path, "reactive transition is not declared by its recorded source state");
if (declared !== undefined) {
const stateAfter =
declared.target.kind === "goto" ? declared.target.state : null;
const outcome = declared.target.kind === "finish" ? "passed" : null;
require(transition.state_after === stateAfter &&
transition.outcome ===
outcome, path, "reactive transition target or outcome differs from the committed graph");
require(canonicalize(transition.action_types) ===
canonicalize(
declared.actions.map(({ type }) => type),
), `${path}.action_types`, "reactive transition actions differ from the committed graph");
}
require(transition.sequence ===
index, `${path}.sequence`, "reactive transition sequence must be contiguous from zero");
if (next !== undefined)
require(transition.state_after ===
next.state_before, `reactive_run.transitions[${String(index + 1)}].state_before`, "reactive transition states must be contiguous");
};
const validateTransitionDeclarations = (
run: ReactiveRun,
scenario: ProcessReactiveScenario,
require: RequireInvariant,
): void => {
require(run.transitions[0]?.state_before === scenario.initial_state ||
run.transitions.length ===
0, "reactive_run.transitions[0].state_before", "reactive transition journal must start at the declared initial state");
for (const [index, transition] of run.transitions.entries())
validateTransitionDeclaration(transition, run.transitions[index + 1], {
index,
scenario,
require,
});
};
const commitRecordedEffects = (options: {
readonly scenario: ProcessReactiveScenario;
readonly proposal: Extract<
ProcessReactiveDecision,
{ readonly kind: "proposal" }
>;
readonly expected: ReactiveTransition | undefined;
readonly observations: ReadonlyMap<string, ProcessObservation>;
readonly recordedFailure: "action_rejected" | "target_lost" | undefined;
}): ProcessReactiveDecision =>
commitProcessReactiveProposal(
options.scenario,
options.proposal,
options.recordedFailure === undefined
? options.proposal.effects.map((_, index) => {
const eventId = options.expected?.action_event_ids[index];
const observation =
eventId === undefined
? undefined
: options.observations.get(eventId);
return observation === undefined
? { status: "rejected" as const }
: { status: "succeeded" as const, observation };
})
: [
options.recordedFailure === "target_lost"
? { status: "target_lost" as const }
: { status: "rejected" as const },
],
{ committedSensitiveInputs: true },
);
const replayTransitions = (
scenario: ProcessReactiveScenario,
run: ReactiveRun,
observations: readonly ProcessObservation[],
require: RequireInvariant,
): ProcessReactiveSnapshot => {
const observationsById = new Map(
observations.map((observation) => [observation.event_id, observation]),
);
let snapshot = createProcessReactiveSnapshot(scenario);
let transitionIndex = 0;
const advance = (input: ProcessReactiveInput): void => {
let decision = reduceProcessReactiveScenario(scenario, snapshot, input);
if (decision.kind === "proposal") {
const proposal = decision;
decision = commitRecordedEffects({
scenario,
proposal: decision,
expected: run.transitions[transitionIndex],
observations: observationsById,
recordedFailure:
run.transitions[transitionIndex] === undefined &&
decision.effects.length > 0 &&
(run.outcome === "action_rejected" || run.outcome === "target_lost")
? run.outcome
: undefined,
});
require(decision.kind !== "finished" ||
decision.outcome !== "action_rejected" ||
run.outcome ===
"action_rejected", `reactive_run.transitions[${String(transitionIndex)}].action_event_ids`, `recorded action observations do not match proposed effects: ${canonicalize(
{
effects: proposal.effects,
observations: run.transitions[transitionIndex]?.action_event_ids.map(
(eventId) => observationsById.get(eventId),
),
},
)}`);
}
if (decision.kind === "transition") {
const expected = run.transitions[transitionIndex];
require(expected !== undefined &&
canonicalize(decision.record) ===
canonicalize(
expected,
), `reactive_run.transitions[${String(transitionIndex)}]`, "reactive transition differs from deterministic journal replay");
transitionIndex += 1;
}
snapshot = decision.snapshot;
};
const advanceControl = (
control: ReactiveRun["controls"][number],
index: number,
): void => {
require(snapshot.status !== "finished" ||
control.kind ===
"cleanup_failed", `reactive_run.controls[${String(index)}]`, "reactive control cannot follow a finished run");
advance(
control.kind === "state_deadline"
? {
kind: control.kind,
state_id: snapshot.active_state,
state_entry_capture_order: snapshot.state_entry_capture_order,
}
: { kind: control.kind },
);
};
let controlIndex = 0;
for (const observation of observations) {
while (
(run.controls[controlIndex]?.after_capture_order ??
Number.MAX_SAFE_INTEGER) < observation.capture_order
) {
const control = run.controls[controlIndex];
if (control === undefined) break;
advanceControl(control, controlIndex);
controlIndex += 1;
}
advance({ kind: "observation", observation });
}
for (; controlIndex < run.controls.length; controlIndex += 1) {
const control = run.controls[controlIndex];
if (control === undefined) break;
advanceControl(control, controlIndex);
}
require(transitionIndex ===
run.transitions
.length, "reactive_run.transitions", `reactive transition journal is not reproduced by deterministic replay (replayed ${String(transitionIndex)} of ${String(run.transitions.length)}; outcome ${snapshot.outcome})`);
return snapshot;
};
const validateControls = (
run: ReactiveRun,
observations: readonly ProcessObservation[],
require: RequireInvariant,
): void => {
const admittedOrders = new Set([
-1,
...observations.map(({ capture_order }) => capture_order),
]);
for (const [index, control] of run.controls.entries()) {
require(control.sequence ===
index, `reactive_run.controls[${String(index)}].sequence`, "reactive control sequence must be contiguous");
require(admittedOrders.has(
control.after_capture_order,
), `reactive_run.controls[${String(index)}].after_capture_order`, "reactive control cutoff must identify the last admitted observation");
const previous = run.controls.at(index - 1);
require(index === 0 ||
(previous !== undefined &&
control.after_capture_order >=
previous.after_capture_order), `reactive_run.controls[${String(index)}].after_capture_order`, "reactive control cutoffs must be ordered");
}
};
/** Validate one capture's reactive journal by replaying the production reducer. */
export const validateProcessCaptureReactiveRun = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const declared = capture.manifest.scenario["reactive"];
const run = capture.reactive_run;
const declaredReactive = declared !== undefined && declared !== null;
require(declaredReactive ===
(run !==
null), "reactive_run", "reactive result presence must match the committed scenario");
if (run === null) return;
const parsed = processReactiveScenarioSchema.safeParse(declared);
require(parsed.success, "manifest.scenario.reactive", "committed reactive scenario does not satisfy its declared schema");
if (!parsed.success) return;
require(run.status === "finished" &&
run.outcome !==
null, "reactive_run.outcome", "completed capture requires a finished reactive outcome");
validateTransitionDeclarations(run, parsed.data, require);
const observations = reactiveObservations(capture);
validateControls(run, observations, require);
const snapshot = replayTransitions(parsed.data, run, observations, require);
require(snapshot.outcome ===
run.outcome, "reactive_run.outcome", "reactive outcome differs from deterministic journal replay");
require(snapshot.active_state ===
run.active_state, "reactive_run.active_state", "reactive active state differs from deterministic journal replay");
};
+16 -211
View File
@@ -1,9 +1,7 @@
import type { UnverifiedProcessCapture } from "./processCapture.js";
import { validateProcessCaptureReactiveRun } from "./processCaptureReactiveValidation.js";
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
import { digestProcessCommitment } from "./processScenario.js";
/** One pure semantic validation failure in an otherwise shaped v4 capture. */
/** One pure semantic validation failure in a shaped process capture. */
export interface ProcessCaptureValidationIssue {
readonly path: string;
readonly message: string;
@@ -23,12 +21,6 @@ const orderedTimestamps = (
return previous === undefined || value.at_ms >= previous.at_ms;
});
const transitionsAreContiguous = (
previous: UnverifiedProcessCapture["replay_transitions"][number] | undefined,
current: UnverifiedProcessCapture["replay_transitions"][number],
): boolean =>
previous !== undefined && previous.state_after === current.state_before;
const validateCommitments = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
@@ -40,8 +32,6 @@ const validateCommitments = (
["full_scenario_sha256", manifest.scenario],
["comparison_contract_sha256", manifest.comparison_contract],
["normalization_sha256", capture.normalization],
["shim_plan_sha256", manifest.shim_plan],
["replay_plan_sha256", manifest.replay_plan],
] as const)
require(manifest[field] ===
digestProcessCommitment(
@@ -61,9 +51,6 @@ const validateOrdering = (
["frames", capture.frames],
["rendered_frames", capture.rendered_frames],
["interaction_events", capture.interaction_events],
["shim_events", capture.shim_events],
["protocol_events", capture.protocol_events],
["replay_transitions", capture.replay_transitions],
] as const)
require(values.every(
({ sequence }, index) => sequence === index,
@@ -72,42 +59,24 @@ const validateOrdering = (
["frames", capture.frames],
["rendered_frames", capture.rendered_frames],
["process_samples", capture.process_samples],
["filesystem_checkpoints", capture.filesystem_checkpoints],
["shim_events", capture.shim_events],
["protocol_events", capture.protocol_events],
["replay_transitions", capture.replay_transitions],
] as const)
require(orderedTimestamps(values), name, "timestamps must be ordered");
};
const journalCollectionSizes = (
capture: UnverifiedProcessCapture,
): Readonly<
Record<
NonNullable<
UnverifiedProcessCapture["event_journal"]
>[number]["collection"],
number
>
> => ({
frames: capture.frames.length,
rendered_frames: capture.rendered_frames.length,
interaction_events: capture.interaction_events.length,
lifecycle: 2,
process_samples: capture.process_samples.length,
filesystem_checkpoints: capture.filesystem_checkpoints.length,
shim_events: capture.shim_events.length,
protocol_events: capture.protocol_events.length,
replay_transitions: capture.replay_transitions.length,
});
const validateEventJournal = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const journal = capture.event_journal ?? [];
if (journal.length === 0) return;
const sizes = journalCollectionSizes(capture);
const sizes = {
frames: capture.frames.length,
rendered_frames: capture.rendered_frames.length,
interaction_events: capture.interaction_events.length,
lifecycle: 2,
process_samples: capture.process_samples.length,
filesystem_checkpoints: capture.filesystem_checkpoints.length,
};
const references = new Set<string>();
for (const [position, entry] of journal.entries()) {
require(entry.capture_order ===
@@ -134,180 +103,19 @@ const validateLifecycle = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const checkpointNames = capture.filesystem_checkpoints.map(
({ name }) => name,
);
require(new Set(checkpointNames).size ===
checkpointNames.length, "filesystem_checkpoints", "checkpoint names must be unique");
require(checkpointNames[0] ===
"before", "filesystem_checkpoints", "first checkpoint must be before");
require(checkpointNames.at(-1) ===
"after_settlement", "filesystem_checkpoints", "last checkpoint must be after_settlement");
require(capture.filesystem_checkpoints.map(({ name }) => name).join(",") ===
"before,after_settlement", "filesystem_checkpoints", "capture must include initial and final filesystem snapshots");
require(orderedTimestamps(
capture.filesystem_checkpoints,
), "filesystem_checkpoints", "filesystem snapshot times must be ordered");
require(!capture.filesystem_checkpoints.some(({ truncated }) => truncated) ||
capture.truncated, "truncated", "checkpoint truncation must propagate to the capture");
capture.truncated, "truncated", "filesystem snapshot truncation must propagate to the capture");
require(capture.exit.reason === "exited" ||
capture.exit.code ===
null, "exit", "deadline termination cannot declare a normal exit code");
};
const shimPlans = (capture: UnverifiedProcessCapture) =>
capture.manifest.shim_plan.flatMap((shim) =>
typeof shim === "object" &&
shim !== null &&
"name" in shim &&
"routes" in shim &&
typeof shim.name === "string" &&
Array.isArray(shim.routes)
? shim.routes.map((route, routeIndex) => ({
command: shim.name,
route,
routeIndex,
}))
: [],
);
const validateShimEvents = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const plans = shimPlans(capture);
for (const event of capture.shim_events) {
const declared = plans.some(
({ command, routeIndex }) =>
command === event.command && routeIndex === event.route_index,
);
require(event.outcome === "unmatched"
? event.route_index === null
: declared, "shim_events", "shim event has no declared route");
}
for (const plan of plans) {
const maximum =
typeof plan.route === "object" &&
plan.route !== null &&
"max_calls" in plan.route &&
typeof plan.route.max_calls === "number"
? plan.route.max_calls
: 0;
const matches = capture.shim_events.filter(
(event) =>
event.command === plan.command &&
event.route_index === plan.routeIndex &&
event.outcome === "matched",
).length;
require(matches <=
maximum, "shim_events", "matched shim events exceed the declared route max_calls");
}
};
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null;
const machinePlan = (
replayPlan: Readonly<Record<string, unknown>>,
): ReplayMachine | undefined => {
const parsed = replayMachineSchema.safeParse(replayPlan["machine"]);
return parsed.success ? parsed.data : undefined;
};
const matchesHttpPlan = (
value: unknown,
event: UnverifiedProcessCapture["protocol_events"][number],
): boolean => {
if (!isRecord(value)) return false;
const route = isRecord(value["trigger"]) ? value["trigger"] : value;
return (
(route["protocol"] === undefined || route["protocol"] === "http") &&
route["method"] === event.method &&
route["path"] === event.path
);
};
const validateMatchedHttpEvents = (
capture: UnverifiedProcessCapture,
plans: readonly unknown[],
require: RequireInvariant,
): void => {
for (const event of capture.protocol_events) {
if (
event.protocol !== "http" ||
event.direction !== "request" ||
event.outcome !== "matched"
)
continue;
require(plans.some((plan) =>
matchesHttpPlan(plan, event),
), "protocol_events", "matched HTTP event has no declared replay route");
}
};
const validateReplayEvents = (
capture: UnverifiedProcessCapture,
require: RequireInvariant,
): void => {
const replayPlan = capture.manifest.replay_plan;
const routes = Array.isArray(replayPlan["http"]) ? replayPlan["http"] : [];
const machine = machinePlan(replayPlan);
require(replayPlan["machine"] === undefined ||
replayPlan["machine"] === null ||
machine !==
undefined, "manifest.replay_plan.machine", "replay machine does not satisfy its declared schema");
validateMatchedHttpEvents(
capture,
[...routes, ...(machine?.transitions ?? [])],
require,
);
const plans = new Map(
(machine?.transitions ?? []).map((transition) => [
transition.id,
transition,
]),
);
const transitionUses = new Map<string, number>();
const stateVisits = new Map<string, number>();
if (machine !== undefined) stateVisits.set(machine.initial_state, 1);
require(machine === undefined ||
capture.replay_transitions.length <=
machine.max_transitions, "replay_transitions", "replay transition journal exceeds the declared machine limit");
for (const [index, transition] of capture.replay_transitions.entries()) {
const plan = plans.get(transition.transition_id);
require(plan !==
undefined, "replay_transitions", "replay transition has no declared machine transition");
if (plan === undefined) continue;
require(transition.state_before === plan.from &&
transition.state_after ===
plan.to, "replay_transitions", "replay transition states do not match the declared transition");
require(JSON.stringify(transition.sensitive_aliases) ===
JSON.stringify(
plan.captures
.filter(({ sensitive }) => sensitive)
.map(({ variable }) => variable)
.sort(),
), "replay_transitions", "replay transition sensitive aliases do not match the declared captures");
const uses = (transitionUses.get(plan.id) ?? 0) + 1;
transitionUses.set(plan.id, uses);
require(uses <=
plan.max_uses, "replay_transitions", "replay transition journal exceeds the transition use limit");
const visits = (stateVisits.get(transition.state_after) ?? 0) + 1;
stateVisits.set(transition.state_after, visits);
const state = machine?.states.find(
({ name }) => name === transition.state_after,
);
require(state === undefined ||
visits <=
state.max_visits, "replay_transitions", "replay transition journal exceeds the state visit limit");
if (index === 0)
require(transition.state_before ===
machine?.initial_state, "replay_transitions", "first replay transition does not start at the declared initial state");
const previous = capture.replay_transitions[index - 1];
if (index > 0)
require(transitionsAreContiguous(
previous,
transition,
), "replay_transitions", "replay transition states are not contiguous");
}
};
/** Recompute v4 commitments and cross-field invariants without side effects. */
/** Recompute commitments and cross-field invariants without side effects. */
export const collectProcessCaptureIssues = (
capture: UnverifiedProcessCapture,
): readonly ProcessCaptureValidationIssue[] => {
@@ -319,8 +127,5 @@ export const collectProcessCaptureIssues = (
validateOrdering(capture, require);
validateEventJournal(capture, require);
validateLifecycle(capture, require);
validateShimEvents(capture, require);
validateReplayEvents(capture, require);
validateProcessCaptureReactiveRun(capture, require);
return issues;
};
+3 -37
View File
@@ -32,9 +32,7 @@ export const PROCESS_COMPARISON_DIMENSIONS = [
"interaction",
"exit",
"filesystem",
"protocol",
"process",
"shim",
] as const;
/** Derive the overall comparison status from every process dimension. */
@@ -59,9 +57,7 @@ export const processCaptureComparisonSchema = z
interaction: comparisonStatusSchema,
exit: comparisonStatusSchema,
filesystem: comparisonStatusSchema,
protocol: comparisonStatusSchema,
process: comparisonStatusSchema,
shim: comparisonStatusSchema,
first_divergence: z.discriminatedUnion("status", [
z.object({ status: z.literal("none") }),
z.object({ status: z.literal("unknown"), reason: z.string() }),
@@ -72,9 +68,7 @@ export const processCaptureComparisonSchema = z
"interaction",
"exit",
"filesystem",
"protocol",
"process",
"shim",
]),
index: z.number().int().nonnegative(),
left_at_ms: z.number().int().nonnegative().nullable(),
@@ -115,16 +109,8 @@ const terminalObservations = (capture: ProcessCapture): readonly unknown[] =>
return left.sequence - right.sequence;
});
const filesystemObservations = (
capture: ProcessCapture,
): readonly unknown[] => [
...capture.filesystem_checkpoints,
{
name: "final",
files: capture.files_after,
effects: capture.filesystem_effects,
},
];
const filesystemObservations = (capture: ProcessCapture): readonly unknown[] =>
capture.filesystem_checkpoints;
const sameJsonValue = (left: unknown, right: unknown): boolean => {
const encodedLeft = canonicalize(left);
@@ -145,12 +131,8 @@ export const processDimensionObservations = (
return [{ ...capture.exit, settlement: capture.settlement }];
case "filesystem":
return filesystemObservations(capture);
case "protocol":
return [...capture.protocol_events, ...capture.replay_transitions];
case "process":
return capture.process_samples;
case "shim":
return capture.shim_events;
}
};
@@ -268,9 +250,7 @@ const truncatedComparison = (): ProcessCaptureComparison => ({
interaction: "truncated",
exit: "truncated",
filesystem: "truncated",
protocol: "truncated",
process: "truncated",
shim: "truncated",
first_divergence: {
status: "unknown",
reason: "At least one capture is truncated.",
@@ -320,21 +300,13 @@ const applyTraceVerdict = (
interaction: statusFor("interaction"),
exit: statusFor("exit"),
filesystem: statusFor("filesystem"),
protocol: statusFor("protocol"),
process: statusFor("process"),
shim: statusFor("shim"),
};
};
type ComparisonDimensions = Pick<
ProcessCaptureComparison,
| "terminal"
| "interaction"
| "exit"
| "filesystem"
| "protocol"
| "process"
| "shim"
"terminal" | "interaction" | "exit" | "filesystem" | "process"
>;
const compareDimensions = (
@@ -375,13 +347,7 @@ const compareDimensions = (
filesystemObservations(left),
filesystemObservations(right),
),
protocol: classify(
"protocol",
[...left.protocol_events, ...left.replay_transitions],
[...right.protocol_events, ...right.replay_transitions],
),
process: classify("process", left.process_samples, right.process_samples),
shim: classify("shim", left.shim_events, right.shim_events),
};
};
+1 -45
View File
@@ -48,43 +48,10 @@ const capture: UnverifiedProcessCapture = {
session_id: 1,
},
],
shim_events: [
{
sequence: 0,
at_ms: 5,
command: "helper",
route_index: 0,
arguments: [],
working_directory: "/fixture",
outcome: "matched",
},
],
protocol_events: [
{
sequence: 0,
at_ms: 6,
protocol: "http",
direction: "request",
method: "GET",
path: "/done",
data: "",
outcome: "matched",
},
],
replay_transitions: [
{
sequence: 0,
at_ms: 7,
transition_id: "done",
state_before: "open",
state_after: "closed",
sensitive_aliases: [],
},
],
};
describe("process observation vocabulary", () => {
it("projects every capture collection without timestamp sorting", () => {
it("projects capture collections without timestamp sorting", () => {
const locations = [
{ collection: "frames", index: 0, capture_order: 4 },
{ collection: "rendered_frames", index: 0, capture_order: 3 },
@@ -93,14 +60,10 @@ describe("process observation vocabulary", () => {
{ collection: "lifecycle", index: 1, capture_order: 9 },
{ collection: "process_samples", index: 0, capture_order: 1 },
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
{ collection: "shim_events", index: 0, capture_order: 5 },
{ collection: "protocol_events", index: 0, capture_order: 6 },
{ collection: "replay_transitions", index: 0, capture_order: 7 },
] as const;
const observations = locations.map((location) =>
projectProcessObservation(capture, location),
);
expect(observations.map((value) => value?.source)).toEqual([
"terminal_raw",
"terminal_rendered",
@@ -109,9 +72,6 @@ describe("process observation vocabulary", () => {
"lifecycle",
"process",
"filesystem",
"shim",
"http",
"replay_transition",
]);
expect(observations.map((value) => value?.capture_order)).toEqual(
locations.map(({ capture_order }) => capture_order),
@@ -122,10 +82,6 @@ describe("process observation vocabulary", () => {
captured_at_ms: 4,
subject_id: "process:2",
});
expect(observations[7]).toMatchObject({
event_id: "obs.shim_events.0",
subject_id: "shim:helper:route:0",
});
expect(observations[3]?.captured_at_ms).toBeNull();
expect(observations[4]?.captured_at_ms).toBeNull();
});
+1 -32
View File
@@ -11,10 +11,6 @@ export const processObservationSourceSchema = z.enum([
"lifecycle",
"process",
"filesystem",
"http",
"websocket",
"shim",
"replay_transition",
]);
export type ProcessObservationSource = z.infer<
typeof processObservationSourceSchema
@@ -29,9 +25,6 @@ export const processObservationLocationSchema = z.strictObject({
"lifecycle",
"process_samples",
"filesystem_checkpoints",
"shim_events",
"protocol_events",
"replay_transitions",
]),
index: z.number().int().nonnegative(),
capture_order: z.number().int().nonnegative(),
@@ -40,7 +33,7 @@ export type ProcessObservationLocation = z.infer<
typeof processObservationLocationSchema
>;
/** Provider-neutral event offered to a reactive scenario or offline assertion. */
/** Provider-neutral event projected into an offline trace assertion. */
export interface ProcessObservation {
readonly event_id: string;
readonly source: ProcessObservationSource;
@@ -124,14 +117,6 @@ export const processObservationSubject = (
typeof value.name === "string"
)
return `checkpoint:${value.name}`;
if (
source === "shim" &&
"command" in value &&
typeof value.command === "string"
)
return "route_index" in value && typeof value.route_index === "number"
? `shim:${value.command}:route:${String(value.route_index)}`
: `shim:${value.command}:unmatched`;
return null;
};
@@ -178,22 +163,6 @@ const projectedRecord = (
source: "filesystem" as const,
value: capture.filesystem_checkpoints[location.index],
};
case "shim_events":
return {
source: "shim" as const,
value: capture.shim_events[location.index],
};
case "protocol_events": {
const event = capture.protocol_events[location.index];
return event === undefined
? null
: { source: event.protocol, value: event };
}
case "replay_transitions":
return {
source: "replay_transition" as const,
value: capture.replay_transitions[location.index],
};
}
})();
if (projected === null || projected.value === undefined) return null;
@@ -1,41 +0,0 @@
import type { ProcessReactiveScenario } from "./processReactiveScenario.js";
/** Checkpoints guaranteed on every known path entering each reactive state. */
export const definitelyAvailableCheckpoints = (
scenario: ProcessReactiveScenario,
): ReadonlyMap<string, ReadonlySet<string>> => {
const available = new Map<string, Set<string>>([
[scenario.initial_state, new Set()],
]);
let changed = true;
while (changed) {
changed = false;
for (const state of scenario.states) {
const before = available.get(state.id);
if (before === undefined) continue;
for (const transition of state.on) {
if (transition.target.kind !== "goto") continue;
const after = new Set(before);
for (const name of transition.actions.flatMap((action) =>
action.type === "checkpoint" ? [action.name] : [],
))
after.add(name);
const prior = available.get(transition.target.state);
const next =
prior === undefined
? after
: new Set([...prior].filter((name) => after.has(name)));
if (prior !== undefined && setsEqual(prior, next)) continue;
available.set(transition.target.state, next);
changed = true;
}
}
}
return available;
};
const setsEqual = (
left: ReadonlySet<string>,
right: ReadonlySet<string>,
): boolean =>
left.size === right.size && [...left].every((value) => right.has(value));
-275
View File
@@ -1,275 +0,0 @@
import canonicalize from "canonicalize";
import type { ProcessObservation } from "./processObservation.js";
import { comparableProcessObservationPayload } from "./processObservation.js";
import type {
ProcessReactiveFrontier,
ProcessReactiveTrigger,
} from "./processReactiveScenario.js";
import type { ProcessReactiveSnapshot } from "./processReactiveRuntime.js";
/** Trigger match result used by the pure reducer. */
export type ProcessReactiveTriggerMatch = {
readonly eventIds: readonly string[];
readonly consumeIds: readonly string[];
readonly lastOrder: number;
readonly matched: boolean;
};
interface TriggerMatchContext {
readonly snapshot: ProcessReactiveSnapshot;
readonly afterOrder: number;
readonly upperOrder: number | null;
}
const noMatch = (): ProcessReactiveTriggerMatch => ({
eventIds: [],
consumeIds: [],
lastOrder: -1,
matched: false,
});
const frontierOrder = (
frontier: ProcessReactiveFrontier,
snapshot: ProcessReactiveSnapshot,
): number | null => {
switch (frontier.kind) {
case "scenario_start":
return -1;
case "state_entry":
return snapshot.state_entry_capture_order - 1;
case "checkpoint":
return (
snapshot.checkpoints.findLast(({ name }) => name === frontier.name)
?.capture_order ?? null
);
case "event_id":
return (
snapshot.observations.find(
({ event_id }) => event_id === frontier.event_id,
)?.capture_order ?? null
);
}
};
const eligibleObservations = (
frontier: ProcessReactiveFrontier,
context: TriggerMatchContext,
): readonly ProcessObservation[] => {
const frontierValue = frontierOrder(frontier, context.snapshot);
if (frontierValue === null) return [];
const lowerBound = Math.max(frontierValue, context.afterOrder);
const consumed = new Set(context.snapshot.consumed_event_ids);
return context.snapshot.observations.filter(
({ capture_order, event_id }) =>
capture_order > lowerBound &&
(context.upperOrder === null || capture_order <= context.upperOrder) &&
!consumed.has(event_id),
);
};
const canonicalJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Reactive scenario value is not canonical JSON");
return serialized;
};
const matchEvent = (
trigger: Extract<ProcessReactiveTrigger, { readonly kind: "event" }>,
context: TriggerMatchContext,
): ProcessReactiveTriggerMatch => {
const expected = canonicalJson(
comparableProcessObservationPayload(trigger.exact, trigger.ignore_fields),
);
const matches: ProcessObservation[] = [];
for (const observation of eligibleObservations(trigger.since, context)) {
if (
observation.source === trigger.source &&
canonicalJson(
comparableProcessObservationPayload(
observation.payload,
trigger.ignore_fields,
),
) === expected
)
matches.push(observation);
}
if (
matches.length < trigger.cardinality.min ||
matches.length > trigger.cardinality.max
)
return noMatch();
const eventIds = matches.map(({ event_id }) => event_id);
return {
eventIds,
consumeIds: trigger.consume ? eventIds : [],
lastOrder: matches.at(-1)?.capture_order ?? context.afterOrder,
matched: true,
};
};
const occurrenceRange = (
haystack: string,
needle: string,
occurrence: number,
): { readonly start: number; readonly end: number } | null => {
let offset = 0;
let start = -1;
for (let found = 0; found < occurrence; found += 1) {
start = haystack.indexOf(needle, offset);
if (start < 0) return null;
offset = start + needle.length;
}
return { start, end: offset };
};
const matchTerminalText = (
trigger: Extract<ProcessReactiveTrigger, { readonly kind: "terminal_text" }>,
context: TriggerMatchContext,
): ProcessReactiveTriggerMatch => {
const chunks: { observation: ProcessObservation; text: string }[] = [];
for (const observation of eligibleObservations(trigger.since, context)) {
if (
observation.source === "terminal_raw" &&
typeof observation.payload === "object" &&
observation.payload !== null &&
!Array.isArray(observation.payload) &&
typeof observation.payload["data"] === "string"
)
chunks.push({ observation, text: observation.payload["data"] });
}
const range = occurrenceRange(
chunks.map(({ text }) => text).join(""),
trigger.literal,
trigger.occurrence,
);
if (range === null) return noMatch();
let firstChunk = 0;
let lastChunk = 0;
let characters = 0;
for (const [index, chunk] of chunks.entries()) {
characters += chunk.text.length;
if (characters <= range.start) firstChunk = index + 1;
if (characters >= range.end) {
lastChunk = index;
break;
}
}
const matched = chunks
.slice(firstChunk, lastChunk + 1)
.map(({ observation }) => observation);
const eventIds = matched.map(({ event_id }) => event_id);
return {
eventIds,
consumeIds: trigger.consume ? eventIds : [],
lastOrder: matched.at(-1)?.capture_order ?? context.afterOrder,
matched: true,
};
};
const mergeMatches = (
matches: readonly ProcessReactiveTriggerMatch[],
): ProcessReactiveTriggerMatch => {
const eventIds = new Set<string>();
const consumeIds = new Set<string>();
let lastOrder = -1;
let matched = true;
for (const match of matches) {
for (const eventId of match.eventIds) eventIds.add(eventId);
for (const eventId of match.consumeIds) consumeIds.add(eventId);
lastOrder = Math.max(lastOrder, match.lastOrder);
matched &&= match.matched;
}
return {
eventIds: [...eventIds],
consumeIds: [...consumeIds],
lastOrder,
matched,
};
};
const matchEarliestPrefix = (
trigger: ProcessReactiveTrigger,
context: TriggerMatchContext,
): ProcessReactiveTriggerMatch => {
for (const observation of context.snapshot.observations) {
if (observation.capture_order <= context.afterOrder) continue;
if (
context.upperOrder !== null &&
observation.capture_order > context.upperOrder
)
break;
const matched = matchTrigger(trigger, {
...context,
upperOrder: observation.capture_order,
});
if (matched.matched) return matched;
}
return noMatch();
};
const matchTrigger = (
trigger: ProcessReactiveTrigger,
context: TriggerMatchContext,
): ProcessReactiveTriggerMatch => {
if (trigger.kind === "event") return matchEvent(trigger, context);
if (trigger.kind === "terminal_text")
return matchTerminalText(trigger, context);
if (trigger.kind === "all")
return mergeMatches(
trigger.triggers.map((child) => matchTrigger(child, context)),
);
if (trigger.kind === "any") {
const evaluated = trigger.triggers.map((child) =>
matchTrigger(child, context),
);
const matches = evaluated.filter(({ matched }) => matched);
return matches.length === 0 ? noMatch() : mergeMatches(matches);
}
if (trigger.kind === "sequence") {
const matches: ProcessReactiveTriggerMatch[] = [];
let cursor = context.afterOrder;
for (const child of trigger.triggers) {
const matched = matchEarliestPrefix(child, {
...context,
afterOrder: cursor,
});
if (!matched.matched) return noMatch();
matches.push(matched);
cursor = matched.lastOrder;
}
return mergeMatches(matches);
}
const matches: ProcessReactiveTriggerMatch[] = [];
let cursor = context.afterOrder;
while (matches.length < trigger.max) {
const matched = matchEarliestPrefix(trigger.trigger, {
...context,
afterOrder: cursor,
});
if (!matched.matched || matched.lastOrder <= cursor) break;
matches.push(matched);
cursor = matched.lastOrder;
}
if (matches.length === trigger.max) {
const excess = matchEarliestPrefix(trigger.trigger, {
...context,
afterOrder: cursor,
});
if (excess.matched) return noMatch();
}
if (matches.length < trigger.min) return noMatch();
return mergeMatches(matches);
};
/** Match one trigger against every eligible retained observation. */
export const matchProcessReactiveTrigger = (
trigger: ProcessReactiveTrigger,
snapshot: ProcessReactiveSnapshot,
): ProcessReactiveTriggerMatch =>
matchTrigger(trigger, {
snapshot,
afterOrder: -1,
upperOrder: null,
});
@@ -1,144 +0,0 @@
import {
createProcessObservation,
type ProcessObservationSource,
} from "./processObservation.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "./processReactiveRuntime.js";
import {
processReactiveScenarioSchema,
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "./processReactiveScenario.js";
export const terminalTrigger = (literal = "Ready") => ({
kind: "terminal_text" as const,
literal,
occurrence: 1,
since: { kind: "scenario_start" as const },
consume: false,
});
export const scenarioWith = (
transitions: readonly unknown[],
): ProcessReactiveScenario =>
processReactiveScenarioSchema.parse({
initial_state: "starting",
deadline_ms: 30000,
states: [
{
id: "starting",
max_visits: 4,
deadline_ms: 5000,
on: transitions,
},
],
});
export const finish = (
id: string,
when: unknown,
priority = 100,
actions: readonly unknown[] = [],
) => ({
id,
priority,
max_uses: 4,
when,
actions,
target: { kind: "finish" },
});
export const collectionFor = (source: ProcessObservationSource) => {
switch (source) {
case "terminal_raw":
return "frames" as const;
case "terminal_rendered":
return "rendered_frames" as const;
case "process":
return "process_samples" as const;
case "filesystem":
return "filesystem_checkpoints" as const;
case "shim":
return "shim_events" as const;
case "http":
case "websocket":
return "protocol_events" as const;
case "replay_transition":
return "replay_transitions" as const;
case "interaction":
return "interaction_events" as const;
case "lifecycle":
return "lifecycle" as const;
}
};
export const observation = (
source: ProcessObservationSource,
order: number,
payload: unknown,
) =>
createProcessObservation({
source,
source_sequence: order,
captured_at_ms: order,
subject_id: null,
location: {
collection: collectionFor(source),
index: order,
capture_order: order,
},
payload,
});
export const succeededEffect = (
action: ProcessReactiveAction,
order: number,
) => ({
status: "succeeded" as const,
observation:
action.type === "checkpoint"
? observation("filesystem", order, { name: action.name })
: observation("interaction", order, {
type:
action.type === "send_input"
? "input"
: action.type === "resize"
? "resize"
: action.type === "close_stdin"
? "stdin_close"
: "signal",
data:
action.type === "send_input"
? action.sensitive
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
: action.data
: action.type === "resize"
? `${String(action.columns)}x${String(action.rows)}`
: action.type === "close_stdin"
? ""
: action.signal,
outcome: "dispatched",
}),
});
export const offer = (
scenario: ProcessReactiveScenario,
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
value: ReturnType<typeof observation>,
) => {
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
kind: "observation",
observation: value,
});
return proposed.kind === "proposal"
? commitProcessReactiveProposal(
scenario,
proposed,
proposed.effects.map((effect, index) => ({
...succeededEffect(
effect,
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
index +
1,
),
})),
)
: proposed;
};
-531
View File
@@ -1,531 +0,0 @@
import {
finish,
observation,
offer,
scenarioWith,
succeededEffect,
terminalTrigger,
} from "./processReactiveRuntime.fixture.js";
import {
commitProcessReactiveProposal,
createProcessReactiveSnapshot,
reduceProcessReactiveScenario,
} from "./processReactiveRuntime.js";
import { processReactiveScenarioSchema } from "./processReactiveScenario.js";
import { describe, expect, it } from "vitest";
describe("process reactive runtime: terminal text matching", () => {
it("matches decoded terminal text across PTY chunks and emits declarative effects", () => {
const scenario = scenarioWith([
finish("ready", terminalTrigger(), 100, [
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
{ type: "checkpoint", name: "ready" },
]),
]);
const first = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, {
sequence: 0,
at_ms: 0,
data: "Re",
}),
);
expect(first.kind).toBe("waiting");
const second = offer(
scenario,
first.snapshot,
observation("terminal_raw", 1, {
sequence: 1,
at_ms: 1,
data: "ady\n",
}),
);
expect(second.kind).toBe("transition");
if (second.kind !== "transition") return;
expect(second.record).toEqual({
sequence: 0,
transition_id: "ready",
state_before: "starting",
state_after: null,
outcome: "passed",
trigger_event_ids: ["obs.frames.0", "obs.frames.1"],
action_event_ids: [
"obs.interaction_events.2",
"obs.filesystem_checkpoints.3",
],
action_types: ["send_signal", "checkpoint"],
});
});
it("treats redaction-shaped live input as ordinary sensitive data", () => {
const scenario = scenarioWith([
finish("ready", terminalTrigger(), 100, [
{
type: "send_input",
data: "<redacted-input:1-bytes>",
sensitive: true,
},
]),
]);
const decision = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(decision).toMatchObject({
kind: "transition",
record: { outcome: "passed" },
});
});
it("reports only the minimal terminal chunk span containing the occurrence", () => {
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
let snapshot = createProcessReactiveSnapshot(scenario);
for (const [order, data] of ["unrelated\n", "Re"].entries()) {
const decision = offer(
scenario,
snapshot,
observation("terminal_raw", order, { data }),
);
expect(decision.kind).toBe("waiting");
snapshot = decision.snapshot;
}
const matched = offer(
scenario,
snapshot,
observation("terminal_raw", 2, { data: "ady" }),
);
expect(matched.kind).toBe("transition");
if (matched.kind === "transition")
expect(matched.record.trigger_event_ids).toEqual([
"obs.frames.1",
"obs.frames.2",
]);
});
});
describe("process reactive runtime: observation retention", () => {
it("matches terminal text after the previous retained-data ceiling", () => {
const scenario = scenarioWith([finish("large_output", terminalTrigger())]);
const decision = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, {
data: `${"x".repeat(70_000)}Ready`,
}),
},
);
expect(decision.kind).toBe("proposal");
});
it("evaluates all configured predicates against all retained observations", () => {
const transitions = Array.from({ length: 80 }, (_, index) =>
finish(`event_${String(index)}`, {
kind: "event",
source: "shim",
exact: { name: `expected_${String(index)}` },
ignore_fields: ["sequence"],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 1, max: 1 },
}),
);
const scenario = scenarioWith(transitions);
const retained = Array.from({ length: 130 }, (_, order) =>
observation("shim", order, { name: "other", sequence: order }),
);
const snapshot = {
...createProcessReactiveSnapshot(scenario),
observations: retained,
};
const decision = offer(
scenario,
snapshot,
observation("shim", retained.length, {
name: "other",
sequence: retained.length,
}),
);
expect(decision).toMatchObject({ kind: "waiting" });
if (decision.kind === "waiting")
expect(decision.snapshot.observations).toHaveLength(131);
});
});
describe("process reactive runtime: effect commit ordering", () => {
it("does not commit state, checkpoints, consumption, or history before effects succeed", () => {
const scenario = scenarioWith([
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
{ type: "checkpoint", name: "ready" },
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
]),
]);
const proposed = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, { data: "Ready" }),
},
);
expect(proposed.kind).toBe("proposal");
if (proposed.kind !== "proposal") return;
expect(proposed.snapshot).toMatchObject({
status: "running",
checkpoints: [],
consumed_event_ids: [],
transitions: [],
});
const rejected = commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{ status: "rejected" },
]);
expect(rejected).toMatchObject({
kind: "finished",
outcome: "action_rejected",
snapshot: {
checkpoints: [],
consumed_event_ids: [],
transitions: [],
},
});
expect(
commitProcessReactiveProposal(scenario, proposed, [
{ status: "target_lost" },
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]),
).toMatchObject({ kind: "finished", outcome: "target_lost" });
const committed = commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]);
expect(committed.snapshot).toMatchObject({
checkpoints: [
{
name: "ready",
event_id: "obs.filesystem_checkpoints.1",
capture_order: 1,
},
],
});
expect(
commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "other" }),
},
{
status: "succeeded",
observation: observation("interaction", 2, {
type: "signal",
data: "SIGINT",
outcome: "dispatched",
}),
},
]),
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
const changedScenario = scenarioWith([
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
{ type: "checkpoint", name: "changed" },
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
]),
]);
expect(
commitProcessReactiveProposal(changedScenario, proposed, [
succeededEffect({ type: "checkpoint", name: "ready" }, 1),
succeededEffect(
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGINT",
},
2,
),
]),
).toMatchObject({ kind: "finished", outcome: "target_lost" });
expect(
commitProcessReactiveProposal(scenario, proposed, [
{
status: "succeeded",
observation: observation("filesystem", 1, { name: "ready" }),
},
{
status: "succeeded",
observation: {
...observation("filesystem", 2, { name: "ready" }),
event_id: "obs.filesystem_checkpoints.1",
},
},
]),
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
});
});
describe("process reactive runtime: predicate selection", () => {
it("selects a unique priority and reports equal-priority ambiguity", () => {
const preferred = scenarioWith([
finish("fallback", terminalTrigger(), 20),
finish("preferred", terminalTrigger(), 10),
]);
const selected = offer(
preferred,
createProcessReactiveSnapshot(preferred),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(selected.kind).toBe("transition");
if (selected.kind === "transition")
expect(selected.record.transition_id).toBe("preferred");
for (const transitions of [
[finish("one", terminalTrigger()), finish("two", terminalTrigger())],
[finish("two", terminalTrigger()), finish("one", terminalTrigger())],
]) {
const ambiguous = scenarioWith(transitions);
const decision = offer(
ambiguous,
createProcessReactiveSnapshot(ambiguous),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "ambiguous_match",
});
}
});
it("matches caller supplied terminal literals longer than the former schema cap", () => {
const literal = "Ready".repeat(2_001);
const scenario = scenarioWith([
finish("long_literal", terminalTrigger(literal)),
]);
const decision = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, { data: `prefix${literal}suffix` }),
);
expect(decision).toMatchObject({
kind: "transition",
record: { transition_id: "long_literal" },
});
});
it("evaluates ordered and repeated predicates without array-order arbitration", () => {
const event = (name: string) => ({
kind: "event" as const,
source: "shim" as const,
exact: { name },
ignore_fields: ["sequence" as const],
since: { kind: "scenario_start" as const },
consume: true,
cardinality: { min: 1, max: 1 },
});
const scenario = scenarioWith([
finish("sequence", {
kind: "sequence",
triggers: [
event("start"),
{ kind: "repeat", trigger: event("tick"), min: 2, max: 2 },
event("done"),
],
}),
]);
let snapshot = createProcessReactiveSnapshot(scenario);
for (const [order, name] of ["start", "tick", "tick"].entries()) {
const decision = offer(
scenario,
snapshot,
observation("shim", order, { name, sequence: order }),
);
expect(decision.kind).toBe("waiting");
snapshot = decision.snapshot;
}
const decision = offer(
scenario,
snapshot,
observation("shim", 3, { name: "done", sequence: 3 }),
);
expect(decision.kind).toBe("transition");
if (decision.kind === "transition")
expect(decision.record.trigger_event_ids).toEqual([
"obs.shim_events.0",
"obs.shim_events.1",
"obs.shim_events.2",
"obs.shim_events.3",
]);
});
it("applies state-entry frontiers and explicit consumption", () => {
const secondTrigger = {
...terminalTrigger(),
since: { kind: "state_entry" as const },
consume: true,
};
const scenario = processReactiveScenarioSchema.parse({
initial_state: "one",
deadline_ms: 30000,
states: [
{
id: "one",
max_visits: 1,
deadline_ms: 5000,
on: [
{
...finish("advance", terminalTrigger()),
target: { kind: "goto", state: "two" },
},
],
},
{
id: "two",
max_visits: 1,
deadline_ms: 5000,
on: [finish("finish", secondTrigger)],
},
],
});
const advanced = offer(
scenario,
createProcessReactiveSnapshot(scenario),
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(advanced.kind).toBe("transition");
const waiting = offer(
scenario,
advanced.snapshot,
observation("shim", 1, { name: "unrelated" }),
);
expect(waiting.kind).toBe("waiting");
const finished = offer(
scenario,
waiting.snapshot,
observation("terminal_raw", 2, { data: "Ready" }),
);
expect(finished.kind).toBe("transition");
expect(finished.snapshot.consumed_event_ids).toEqual(["obs.frames.2"]);
});
});
describe("process reactive runtime: visit and deadline classification", () => {
it("rejects an exhausted state visit before proposing effects", () => {
const scenario = processReactiveScenarioSchema.parse({
initial_state: "loop",
deadline_ms: 30000,
states: [
{
id: "loop",
max_visits: 1,
deadline_ms: 5000,
on: [
{
...finish("again", terminalTrigger(), 100, [
{
type: "send_signal",
target: { kind: "root" },
signal: "SIGKILL",
},
]),
target: { kind: "goto", state: "loop" },
},
],
},
],
});
const decision = reduceProcessReactiveScenario(
scenario,
createProcessReactiveSnapshot(scenario),
{
kind: "observation",
observation: observation("terminal_raw", 0, { data: "Ready" }),
},
);
expect(decision).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
expect(decision).not.toHaveProperty("effects");
});
it("classifies deadlines and non-monotonic observation input", () => {
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
const initial = createProcessReactiveSnapshot(scenario);
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "state_deadline",
state_id: "starting",
state_entry_capture_order: 0,
}),
).toMatchObject({ kind: "finished", outcome: "predicate_timeout" });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "state_deadline",
state_id: "previous",
state_entry_capture_order: 0,
}),
).toMatchObject({ kind: "waiting", snapshot: initial });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "scenario_deadline",
}),
).toMatchObject({ kind: "finished", outcome: "scenario_deadline" });
expect(
reduceProcessReactiveScenario(scenario, initial, { kind: "cancelled" }),
).toMatchObject({ kind: "finished", outcome: "cancelled" });
expect(
reduceProcessReactiveScenario(scenario, initial, {
kind: "cleanup_failed",
}),
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
const passed = offer(
scenario,
initial,
observation("terminal_raw", 0, { data: "Ready" }),
);
expect(
reduceProcessReactiveScenario(scenario, passed.snapshot, {
kind: "cleanup_failed",
}),
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
const first = offer(
scenario,
initial,
observation("shim", 1, { name: "later" }),
);
const invalid = offer(
scenario,
first.snapshot,
observation("shim", 0, { name: "earlier" }),
);
expect(invalid).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
const duplicate = observation("shim", 1, { name: "later" });
expect(offer(scenario, first.snapshot, duplicate)).toMatchObject({
kind: "finished",
outcome: "capture_incomplete",
});
expect(
offer(scenario, first.snapshot, {
...duplicate,
payload: { name: "changed" },
}),
).toMatchObject({ kind: "finished", outcome: "capture_incomplete" });
});
});
-287
View File
@@ -1,287 +0,0 @@
import type { ProcessObservation } from "./processObservation.js";
import { matchProcessReactiveTrigger } from "./processReactiveMatching.js";
import {
type ProcessReactiveAction,
type ProcessReactiveScenario,
} from "./processReactiveScenario.js";
export { commitProcessReactiveProposal } from "./processReactiveTransition.js";
/** Terminal and failure outcomes produced by the pure reactive reducer. */
export type ProcessReactiveOutcome =
| "passed"
| "predicate_timeout"
| "scenario_deadline"
| "ambiguous_match"
| "action_rejected"
| "target_lost"
| "capture_incomplete"
| "cancelled"
| "cleanup_failed";
/** Lifecycle state shared by the reducer snapshot and its durable projection. */
export type ProcessReactiveStatus =
| { readonly status: "running"; readonly outcome: null }
| {
readonly status: "finished";
readonly outcome: ProcessReactiveOutcome;
};
interface ProcessReactiveTransitionState {
readonly sequence: number;
readonly transition_id: string;
readonly state_before: string;
readonly trigger_event_ids: readonly string[];
readonly action_event_ids: readonly string[];
readonly action_types: readonly ProcessReactiveAction["type"][];
}
/** One deterministic scenario transition suitable for later Evidence projection. */
export type ProcessReactiveTransitionRecord = ProcessReactiveTransitionState &
(
| { readonly state_after: string; readonly outcome: null }
| { readonly state_after: null; readonly outcome: "passed" }
);
interface Counter {
readonly id: string;
readonly count: number;
}
interface ReactiveCheckpoint {
readonly name: string;
readonly event_id: string;
readonly capture_order: number;
}
interface ProcessReactiveSnapshotState {
readonly active_state: string;
readonly state_entry_capture_order: number;
readonly observations: readonly ProcessObservation[];
readonly consumed_event_ids: readonly string[];
readonly transition_uses: readonly Counter[];
readonly state_visits: readonly Counter[];
readonly checkpoints: readonly ReactiveCheckpoint[];
readonly transitions: readonly ProcessReactiveTransitionRecord[];
}
/** Immutable reducer state owned by one validated reactive scenario run. */
export type ProcessReactiveSnapshot = ProcessReactiveSnapshotState &
ProcessReactiveStatus;
/** External fact offered to the pure reducer. */
export type ProcessReactiveInput =
| { readonly kind: "observation"; readonly observation: ProcessObservation }
| {
readonly kind: "state_deadline";
readonly state_id: string;
readonly state_entry_capture_order: number;
}
| { readonly kind: "scenario_deadline" }
| { readonly kind: "target_lost" }
| { readonly kind: "cancelled" }
| { readonly kind: "cleanup_failed" };
/** Per-transition matching summary returned without caller payloads. */
export interface ProcessReactiveEvaluation {
readonly transition_id: string;
readonly status: "matched" | "unmatched" | "exhausted";
readonly matched_event_ids: readonly string[];
}
/** Host acknowledgement for one proposed declarative effect. */
export type ProcessReactiveEffectResult =
| {
readonly status: "succeeded";
readonly observation: ProcessObservation;
}
| { readonly status: "rejected" }
| { readonly status: "target_lost" };
/** Immutable transition proposal awaiting host effect results. */
export interface ProcessReactiveTransitionProposal {
readonly transition_id: string;
readonly transition_identity: string;
readonly observation_event_id: string;
readonly trigger_event_ids: readonly string[];
readonly consume_event_ids: readonly string[];
}
/** Pure scenario decision; effects remain declarative for an authorized host. */
export type ProcessReactiveDecision =
| {
readonly kind: "waiting" | "already_finished";
readonly snapshot: ProcessReactiveSnapshot;
readonly evaluations: readonly ProcessReactiveEvaluation[];
}
| {
readonly kind: "proposal";
readonly snapshot: ProcessReactiveSnapshot;
readonly evaluations: readonly ProcessReactiveEvaluation[];
readonly effects: readonly ProcessReactiveAction[];
readonly proposal: ProcessReactiveTransitionProposal;
}
| {
readonly kind: "transition";
readonly snapshot: ProcessReactiveSnapshot;
readonly evaluations: readonly ProcessReactiveEvaluation[];
readonly record: ProcessReactiveTransitionRecord;
}
| {
readonly kind: "finished";
readonly snapshot: ProcessReactiveSnapshot;
readonly evaluations: readonly ProcessReactiveEvaluation[];
readonly outcome: ProcessReactiveOutcome;
};
const counterValue = (counters: readonly Counter[], id: string): number =>
counters.find((counter) => counter.id === id)?.count ?? 0;
type ObservationAdmission =
| { readonly kind: "new"; readonly snapshot: ProcessReactiveSnapshot }
| { readonly kind: "invalid" };
const observeInput = (
snapshot: ProcessReactiveSnapshot,
observation: ProcessObservation,
): ObservationAdmission => {
const duplicate = snapshot.observations.find(
({ event_id }) => event_id === observation.event_id,
);
if (duplicate !== undefined) return { kind: "invalid" };
const prior = snapshot.observations.at(-1);
if (prior !== undefined && observation.capture_order <= prior.capture_order)
return { kind: "invalid" };
return {
kind: "new",
snapshot: {
...snapshot,
observations: [...snapshot.observations, observation],
},
};
};
/** Create the initial immutable reducer state for one validated scenario. */
export const createProcessReactiveSnapshot = (
scenario: ProcessReactiveScenario,
): ProcessReactiveSnapshot => ({
status: "running",
outcome: null,
active_state: scenario.initial_state,
state_entry_capture_order: 0,
observations: [],
consumed_event_ids: [],
transition_uses: [],
state_visits: [{ id: scenario.initial_state, count: 1 }],
checkpoints: [],
transitions: [],
});
const finishedDecision = (
snapshot: ProcessReactiveSnapshot,
outcome: ProcessReactiveOutcome,
evaluations: readonly ProcessReactiveEvaluation[] = [],
): ProcessReactiveDecision => ({
kind: "finished",
outcome,
evaluations,
snapshot: { ...snapshot, status: "finished", outcome },
});
const reduceControlInput = (
snapshot: ProcessReactiveSnapshot,
input: ProcessReactiveInput,
): ProcessReactiveDecision | null => {
if (input.kind === "cleanup_failed")
return finishedDecision(snapshot, "cleanup_failed");
if (snapshot.status === "finished")
return { kind: "already_finished", snapshot, evaluations: [] };
if (input.kind === "observation") return null;
if (input.kind === "state_deadline")
return input.state_id === snapshot.active_state &&
input.state_entry_capture_order === snapshot.state_entry_capture_order
? finishedDecision(snapshot, "predicate_timeout")
: { kind: "waiting", snapshot, evaluations: [] };
if (input.kind === "scenario_deadline")
return finishedDecision(snapshot, "scenario_deadline");
if (input.kind === "target_lost")
return finishedDecision(snapshot, "target_lost");
return finishedDecision(snapshot, "cancelled");
};
/** Advance one validated scenario using only an observation or explicit deadline. */
export const reduceProcessReactiveScenario = (
scenario: ProcessReactiveScenario,
snapshot: ProcessReactiveSnapshot,
input: ProcessReactiveInput,
): ProcessReactiveDecision => {
const controlDecision = reduceControlInput(snapshot, input);
if (controlDecision !== null) return controlDecision;
if (input.kind !== "observation")
return finishedDecision(snapshot, "capture_incomplete");
const admitted = observeInput(snapshot, input.observation);
if (admitted.kind === "invalid")
return finishedDecision(snapshot, "capture_incomplete");
const observed = admitted.snapshot;
const state = scenario.states.find(({ id }) => id === observed.active_state);
if (state === undefined) return finishedDecision(observed, "target_lost");
const matches = state.on.map((transition) => ({
transition,
match: matchProcessReactiveTrigger(transition.when, observed),
uses: counterValue(observed.transition_uses, transition.id),
}));
const evaluations: ProcessReactiveEvaluation[] = matches.map(
({ transition, match, uses }) => ({
transition_id: transition.id,
status:
uses >= transition.max_uses
? "exhausted"
: match.matched
? "matched"
: "unmatched",
matched_event_ids: match.eventIds,
}),
);
const eligible = matches.filter(
({ transition, match, uses }) =>
match.matched && uses < transition.max_uses,
);
if (eligible.length === 0)
return { kind: "waiting", snapshot: observed, evaluations };
const minimumPriority = eligible.reduce(
(minimum, { transition }) => Math.min(minimum, transition.priority),
Number.POSITIVE_INFINITY,
);
const winners = eligible.filter(
({ transition }) => transition.priority === minimumPriority,
);
if (winners.length !== 1)
return finishedDecision(observed, "ambiguous_match", evaluations);
const winner = winners[0];
if (winner === undefined)
return finishedDecision(observed, "capture_incomplete", evaluations);
const targetDeclaration = winner.transition.target;
if (targetDeclaration.kind === "goto") {
const target = scenario.states.find(
({ id }) => id === targetDeclaration.state,
);
if (
target === undefined ||
counterValue(observed.state_visits, target.id) >= target.max_visits
)
return finishedDecision(observed, "capture_incomplete", evaluations);
}
return {
kind: "proposal",
snapshot: observed,
evaluations,
effects: winner.transition.actions,
proposal: {
transition_id: winner.transition.id,
transition_identity: canonicalize(winner.transition) ?? "",
observation_event_id: input.observation.event_id,
trigger_event_ids: winner.match.eventIds,
consume_event_ids: winner.match.consumeIds,
},
};
};
import canonicalize from "canonicalize";
-504
View File
@@ -1,504 +0,0 @@
import { describe, expect, it } from "vitest";
import {
PROCESS_REACTIVE_LIMITS,
processReactiveScenarioSchema,
} from "./processReactiveScenario.js";
const terminalTrigger = () => ({
kind: "terminal_text" as const,
literal: "Ready",
});
const finishTransition = () => ({
id: "finish",
priority: 100,
max_uses: 1,
when: terminalTrigger(),
actions: [{ type: "checkpoint" as const, name: "ready" }],
target: { kind: "finish" as const },
});
const baseScenario = () => ({
initial_state: "starting",
deadline_ms: 30_000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [finishTransition()],
},
],
});
const buildLargeCallerScenario = () => {
const states = Array.from({ length: 40 }, (_, index) => ({
id: `state_${String(index)}`,
max_visits: 300,
deadline_ms: 30_000,
on: [] as unknown[],
}));
const manyPredicates = {
kind: "repeat",
trigger: {
kind: "all",
triggers: Array.from({ length: 20 }, () => terminalTrigger()),
},
min: 1,
max: 1_000,
};
const sendInputs = Array.from({ length: 300 }, () => ({
type: "send_input",
data: "x",
}));
states[0]!.on = Array.from({ length: 130 }, (_, index) => ({
id: `transition_${String(index)}`,
priority: index,
max_uses: 300,
when: index === 0 ? manyPredicates : terminalTrigger(),
actions: index === 0 ? sendInputs : [],
target:
index > 0 && index <= 39
? { kind: "goto", state: `state_${String(index)}` }
: { kind: "finish" },
}));
for (let index = 1; index < states.length; index += 1) {
const state = states[index]!;
state.on = [
{
...finishTransition(),
id: `finish_${String(index)}`,
max_uses: 300,
actions: [{ type: "checkpoint", name: `ready_${String(index)}` }],
},
];
}
return processReactiveScenarioSchema.safeParse({
initial_state: "state_0",
deadline_ms: 30_000,
states,
});
};
/**
* The field each rejection row below is meant to invalidate. Asserting only
* that the scenario is rejected would still pass if a typo in the fixture
* made it invalid for an unrelated reason, so each row must also produce an
* issue pointing at the intended path with the expected code.
*/
const REJECTION_FIELD: Readonly<
Record<
string,
{ readonly path: readonly (string | number)[]; readonly code: string }
>
> = {
"unknown major version": { path: [], code: "unrecognized_keys" },
"missing state bound": {
path: ["states", 0, "max_visits"],
code: "invalid_type",
},
"missing transition bound": {
path: ["states", 0, "on", 0, "max_uses"],
code: "invalid_type",
},
"unsupported trigger": {
path: ["states", 0, "on", 0, "when", "kind"],
code: "invalid_union",
},
"zero-minimum event absence predicate": {
path: ["states", 0, "on", 0, "when", "cardinality", "min"],
code: "too_small",
},
};
describe("process reactive scenario schema", () => {
it("parses a terminal scenario", () => {
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
initial_state: "starting",
states: [
{
on: [
{
when: {
occurrence: 1,
since: { kind: "scenario_start" },
consume: false,
},
},
],
},
],
});
});
it("accepts caller-defined scenario sizes without count ceilings", () => {
const parsed = buildLargeCallerScenario();
expect(
parsed.success,
parsed.success ? "" : JSON.stringify(parsed.error.issues),
).toBe(true);
});
it("accepts long caller supplied identifiers, terminal matchers, and input", () => {
const identifier = `transition_${"x".repeat(128)}`;
const checkpoint = `checkpoint_${"x".repeat(128)}`;
const literal = "Ready".repeat(2_001);
const data = "input".repeat(200_001);
const parsed = processReactiveScenarioSchema.safeParse({
initial_state: "starting",
deadline_ms: 30_000,
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [
{
...finishTransition(),
id: identifier,
when: { ...terminalTrigger(), literal },
actions: [
{ type: "checkpoint", name: checkpoint },
{ type: "send_input", data },
],
},
],
},
],
});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.states[0]?.on[0]?.id).toBe(identifier);
expect(parsed.data.states[0]?.on[0]?.when).toMatchObject({ literal });
expect(parsed.data.states[0]?.on[0]?.actions[1]).toMatchObject({ data });
}
});
it.each([
["unknown major version", { ...baseScenario(), version: 2 }],
[
"missing state bound",
{
...baseScenario(),
states: [
{ id: "starting", deadline_ms: 5_000, on: [finishTransition()] },
],
},
],
[
"missing transition bound",
{
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [{ ...finishTransition(), max_uses: undefined }],
},
],
},
],
[
"unsupported trigger",
{
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [{ ...finishTransition(), when: { kind: "callback" } }],
},
],
},
],
[
"zero-minimum event absence predicate",
{
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [
{
...finishTransition(),
when: {
kind: "event",
source: "shim",
exact: { name: "missing" },
ignore_fields: [],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 0, max: 1 },
},
},
],
},
],
},
],
])("rejects %s at the expected field", (_name, input) => {
const expected = REJECTION_FIELD[_name];
expect(expected, `no expected rejection field for ${_name}`).toBeDefined();
if (expected === undefined) return;
const parsed = processReactiveScenarioSchema.safeParse(input);
expect(parsed.success).toBe(false);
if (parsed.success) return;
expect(
parsed.error.issues.map((issue) => ({
path: issue.path,
code: issue.code,
})),
).toContainEqual({ path: [...expected.path], code: expected.code });
});
});
describe("process reactive scenario graph validation", () => {
it("rejects unknown targets, unreachable states, and duplicate transition ids", () => {
const input = {
...baseScenario(),
states: [
{
id: "starting",
max_visits: 1,
deadline_ms: 5_000,
on: [
{
...finishTransition(),
target: { kind: "goto" as const, state: "missing" },
},
],
},
{
id: "unreachable",
max_visits: 1,
deadline_ms: 5_000,
on: [finishTransition()],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toEqual(
expect.arrayContaining([
"transition target state is not declared",
"state is unreachable from the initial state",
"transition ids must be unique",
]),
);
});
it("accepts only explicitly bounded cycles", () => {
const cycle = {
initial_state: "one",
deadline_ms: 10_000,
states: [
{
id: "one",
max_visits: 2,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "to_two",
max_uses: 2,
actions: [],
target: { kind: "goto" as const, state: "two" },
},
],
},
{
id: "two",
max_visits: 2,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "to_one",
max_uses: 2,
actions: [],
target: { kind: "goto" as const, state: "one" },
},
],
},
],
};
expect(processReactiveScenarioSchema.safeParse(cycle).success).toBe(true);
const unbounded = {
...cycle,
states: cycle.states.map((state) => ({
...state,
max_visits: undefined,
})),
};
expect(processReactiveScenarioSchema.safeParse(unbounded).success).toBe(
false,
);
});
});
describe("process reactive scenario checkpoint validation", () => {
it("rejects impossible checkpoint frontiers and volatile exact fields", () => {
const exact = {
kind: "event" as const,
source: "http" as const,
exact: { sequence: 0, path: "/ready" },
ignore_fields: ["sequence" as const],
since: { kind: "checkpoint" as const, name: "missing" },
consume: false,
cardinality: { min: 1, max: 1 },
};
const input = {
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [{ ...finishTransition(), when: exact, actions: [] }],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toEqual(
expect.arrayContaining([
"exact payload must omit every ignored field",
"checkpoint frontier is not definitely available before this transition",
]),
);
});
it("rejects checkpoint frontiers produced only by self or later transitions", () => {
const checkpointTrigger = (name: string) => ({
...terminalTrigger(),
since: { kind: "checkpoint" as const, name },
});
const input = {
initial_state: "one",
deadline_ms: 10_000,
states: [
{
id: "one",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "self",
when: checkpointTrigger("self_checkpoint"),
actions: [
{ type: "checkpoint" as const, name: "self_checkpoint" },
],
target: { kind: "goto" as const, state: "two" },
},
],
},
{
id: "two",
max_visits: 1,
deadline_ms: 2_000,
on: [
{
...finishTransition(),
id: "later",
when: checkpointTrigger("later_checkpoint"),
actions: [
{ type: "checkpoint" as const, name: "later_checkpoint" },
],
},
],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(
result.error.issues.filter(({ message }) =>
message.includes("not definitely available"),
),
).toHaveLength(2);
});
});
describe("process reactive scenario nesting validation", () => {
it("rejects trigger trees beyond the declared depth", () => {
let trigger: unknown = terminalTrigger();
for (
let depth = 0;
depth < PROCESS_REACTIVE_LIMITS.triggerDepth;
depth += 1
)
trigger = { kind: "repeat", trigger, min: 1, max: 1 };
const input = {
...baseScenario(),
states: [
{
...baseScenario().states[0],
on: [{ ...finishTransition(), when: trigger }],
},
],
};
const result = processReactiveScenarioSchema.safeParse(input);
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map(({ message }) => message)).toContain(
"trigger nesting exceeds the configured limit",
);
let hostile: unknown = terminalTrigger();
for (let depth = 0; depth < 10_000; depth += 1)
hostile = { kind: "repeat", trigger: hostile, min: 1, max: 1 };
const hostileInput = {
...input,
states: [
{
...input.states[0],
on: [{ ...finishTransition(), when: hostile }],
},
],
};
expect(() =>
processReactiveScenarioSchema.safeParse(hostileInput),
).not.toThrow();
expect(processReactiveScenarioSchema.safeParse(hostileInput).success).toBe(
false,
);
let deepJson: unknown = "leaf";
for (let depth = 0; depth < 10_000; depth += 1)
deepJson = { child: deepJson };
const deepJsonInput = {
...input,
states: [
{
...input.states[0],
on: [
{
...finishTransition(),
when: {
kind: "event",
source: "shim",
exact: deepJson,
ignore_fields: [],
since: { kind: "scenario_start" },
consume: false,
cardinality: { min: 1, max: 1 },
},
},
],
},
],
};
expect(() =>
processReactiveScenarioSchema.safeParse(deepJsonInput),
).not.toThrow();
expect(processReactiveScenarioSchema.safeParse(deepJsonInput).success).toBe(
false,
);
});
});
-426
View File
@@ -1,426 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { processObservationSourceSchema } from "./processObservation.js";
import { definitelyAvailableCheckpoints } from "./processReactiveCheckpointDataflow.js";
import { preflightProcessReactiveScenario } from "./processReactiveScenarioPreflight.js";
/** Structural depth guard for recursive Zod parsing. */
export const PROCESS_REACTIVE_LIMITS = {
// Recursive Zod schemas need a practical stack guard, not a small tree quota.
triggerDepth: 256,
jsonDepth: 256,
} as const;
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]*$/u);
const checkpointNameSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/u);
const positiveRuntime = z.number().int().safe().positive();
const frontierSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("scenario_start") }),
z.strictObject({ kind: z.literal("state_entry") }),
z.strictObject({ kind: z.literal("checkpoint"), name: checkpointNameSchema }),
z.strictObject({ kind: z.literal("event_id"), event_id: identifierSchema }),
]);
export type ProcessReactiveFrontier = z.infer<typeof frontierSchema>;
const ignoredFieldSchema = z.enum([
"sequence",
"at_ms",
"scheduled_at_ms",
"dispatched_at_ms",
"elapsed_ms",
"files",
"effects",
"truncated",
]);
interface EventTrigger {
readonly kind: "event";
readonly source: z.infer<typeof processObservationSourceSchema>;
readonly exact: z.infer<typeof jsonValueSchema>;
readonly ignore_fields: readonly z.infer<typeof ignoredFieldSchema>[];
readonly since: ProcessReactiveFrontier;
readonly consume: boolean;
readonly cardinality: { readonly min: number; readonly max: number };
}
interface TerminalTextTrigger {
readonly kind: "terminal_text";
readonly literal: string;
readonly occurrence: number;
readonly since: ProcessReactiveFrontier;
readonly consume: boolean;
}
type TriggerGroup =
| {
readonly kind: "all";
readonly triggers: readonly ProcessReactiveTrigger[];
}
| {
readonly kind: "any";
readonly triggers: readonly ProcessReactiveTrigger[];
}
| {
readonly kind: "sequence";
readonly triggers: readonly ProcessReactiveTrigger[];
};
interface RepeatTrigger {
readonly kind: "repeat";
readonly trigger: ProcessReactiveTrigger;
readonly min: number;
readonly max: number;
}
/** Declarative, bounded predicate tree evaluated against process observations. */
export type ProcessReactiveTrigger =
| EventTrigger
| TerminalTextTrigger
| TriggerGroup
| RepeatTrigger;
const processReactiveTriggerSchema: z.ZodType<ProcessReactiveTrigger> = z.lazy(
() =>
z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("event"),
source: processObservationSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
.array(ignoredFieldSchema)
.default([])
.refine((values) => new Set(values).size === values.length, {
message: "ignored event fields must be unique",
}),
since: frontierSchema.default({ kind: "scenario_start" }),
consume: z.boolean().default(false),
cardinality: z
.strictObject({
min: z.number().int().safe().positive(),
max: z.number().int().safe().positive(),
})
.default({ min: 1, max: 1 })
.refine(({ min, max }) => min <= max, {
message: "cardinality min must not exceed max",
}),
}),
z.strictObject({
kind: z.literal("terminal_text"),
literal: z.string().min(1),
occurrence: z.number().int().safe().positive().default(1),
since: frontierSchema.default({ kind: "scenario_start" }),
consume: z.boolean().default(false),
}),
z.strictObject({
kind: z.literal("all"),
triggers: z.array(processReactiveTriggerSchema).min(2),
}),
z.strictObject({
kind: z.literal("any"),
triggers: z.array(processReactiveTriggerSchema).min(2),
}),
z.strictObject({
kind: z.literal("sequence"),
triggers: z.array(processReactiveTriggerSchema).min(1),
}),
z
.strictObject({
kind: z.literal("repeat"),
trigger: processReactiveTriggerSchema,
min: z.number().int().safe().positive(),
max: z.number().int().safe().positive(),
})
.refine(({ min, max }) => min <= max, {
message: "repeat min must not exceed max",
}),
]),
);
const signalTargetSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("root") }),
z.strictObject({ kind: z.literal("process_group") }),
z.strictObject({
kind: z.literal("subject_id"),
subject_id: identifierSchema,
}),
]);
const processReactiveActionSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("send_input"),
data: z.string(),
sensitive: z.boolean().default(false),
}),
z.strictObject({
type: z.literal("resize"),
columns: z.number().int().positive(),
rows: z.number().int().positive(),
}),
z.strictObject({ type: z.literal("close_stdin") }),
z.strictObject({
type: z.literal("send_signal"),
target: signalTargetSchema,
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]),
}),
z.strictObject({ type: z.literal("checkpoint"), name: checkpointNameSchema }),
]);
export type ProcessReactiveAction = z.infer<typeof processReactiveActionSchema>;
const transitionTargetSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("goto"), state: identifierSchema }),
z.strictObject({ kind: z.literal("finish") }),
]);
const transitionSchema = z.strictObject({
id: identifierSchema,
priority: z.number().int().safe().min(0),
max_uses: z.number().int().safe().positive(),
when: processReactiveTriggerSchema,
actions: z.array(processReactiveActionSchema),
target: transitionTargetSchema,
});
const stateSchema = z.strictObject({
id: identifierSchema,
max_visits: z.number().int().safe().positive(),
deadline_ms: positiveRuntime,
on: z.array(transitionSchema).min(1),
});
const scenarioShapeSchema = z.strictObject({
initial_state: identifierSchema,
deadline_ms: positiveRuntime,
states: z.array(stateSchema).min(1),
});
/** Parsed process reactive scenario declaration. */
export type ProcessReactiveScenario = z.infer<typeof scenarioShapeSchema>;
type TriggerMeasurements = {
readonly depth: number;
};
const measureTrigger = (
trigger: ProcessReactiveTrigger,
): TriggerMeasurements => {
if (trigger.kind === "event" || trigger.kind === "terminal_text")
return { depth: 1 };
const children =
trigger.kind === "repeat" ? [trigger.trigger] : trigger.triggers;
const measured = children.map(measureTrigger);
return {
depth:
1 + measured.reduce((maximum, { depth }) => Math.max(maximum, depth), 0),
};
};
const collectCheckpointFrontiers = (
trigger: ProcessReactiveTrigger,
): readonly string[] => {
if (trigger.kind === "event" || trigger.kind === "terminal_text")
return trigger.since.kind === "checkpoint" ? [trigger.since.name] : [];
const children =
trigger.kind === "repeat" ? [trigger.trigger] : trigger.triggers;
return children.flatMap(collectCheckpointFrontiers);
};
const validateTriggerSemantics = (
trigger: ProcessReactiveTrigger,
path: PropertyKey[],
context: z.RefinementCtx,
): void => {
if (trigger.kind === "event") {
const exact = trigger.exact;
if (
trigger.ignore_fields.length > 0 &&
(typeof exact !== "object" || exact === null || Array.isArray(exact))
)
context.addIssue({
code: "custom",
message: "ignored fields require an exact object payload",
path: [...path, "ignore_fields"],
});
if (
typeof exact === "object" &&
exact !== null &&
!Array.isArray(exact) &&
trigger.ignore_fields.some((field) => field in exact)
)
context.addIssue({
code: "custom",
message: "exact payload must omit every ignored field",
path: [...path, "exact"],
});
return;
}
if (trigger.kind === "terminal_text") return;
if (trigger.kind === "repeat") {
validateTriggerSemantics(trigger.trigger, [...path, "trigger"], context);
return;
}
for (const [index, child] of trigger.triggers.entries())
validateTriggerSemantics(child, [...path, "triggers", index], context);
};
type GraphValidation = {
readonly knownStates: ReadonlySet<string>;
readonly transitionIds: Set<string>;
readonly checkpoints: Set<string>;
readonly checkpointReferences: Array<{
readonly name: string;
readonly stateId: string;
readonly path: PropertyKey[];
}>;
readonly adjacency: ReadonlyMap<string, Set<string>>;
};
type ReactiveTransition =
ProcessReactiveScenario["states"][number]["on"][number];
const validateTransition = (input: {
readonly stateId: string;
readonly transition: ReactiveTransition;
readonly path: PropertyKey[];
readonly validation: GraphValidation;
readonly context: z.RefinementCtx;
}): void => {
const { transition, validation, path, context } = input;
const measured = measureTrigger(transition.when);
validateTriggerSemantics(transition.when, [...path, "when"], context);
if (measured.depth > PROCESS_REACTIVE_LIMITS.triggerDepth)
context.addIssue({
code: "custom",
message: "trigger nesting exceeds the configured limit",
path: [...path, "when"],
});
if (validation.transitionIds.has(transition.id))
context.addIssue({
code: "custom",
message: "transition ids must be unique",
path: [...path, "id"],
});
validation.transitionIds.add(transition.id);
for (const action of transition.actions) {
if (action.type !== "checkpoint") continue;
if (validation.checkpoints.has(action.name))
context.addIssue({
code: "custom",
message: "checkpoint action names must be unique",
path: [...path, "actions"],
});
validation.checkpoints.add(action.name);
}
for (const name of collectCheckpointFrontiers(transition.when))
validation.checkpointReferences.push({
name,
stateId: input.stateId,
path: [...path, "when"],
});
if (transition.target.kind !== "goto") return;
if (!validation.knownStates.has(transition.target.state)) {
context.addIssue({
code: "custom",
message: "transition target state is not declared",
path: [...path, "target", "state"],
});
return;
}
validation.adjacency.get(input.stateId)?.add(transition.target.state);
};
const validateTotalsAndReferences = (
scenario: ProcessReactiveScenario,
validation: GraphValidation,
context: z.RefinementCtx,
): void => {
const available = definitelyAvailableCheckpoints(scenario);
for (const reference of validation.checkpointReferences)
if (!available.get(reference.stateId)?.has(reference.name))
context.addIssue({
code: "custom",
message:
"checkpoint frontier is not definitely available before this transition",
path: reference.path,
});
};
const validateReachability = (
scenario: ProcessReactiveScenario,
stateIds: readonly string[],
validation: GraphValidation,
context: z.RefinementCtx,
): void => {
const reachable = new Set<string>();
const pending = validation.knownStates.has(scenario.initial_state)
? [scenario.initial_state]
: [];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || reachable.has(current)) continue;
reachable.add(current);
pending.push(...(validation.adjacency.get(current) ?? []));
}
for (const [index, id] of stateIds.entries())
if (!reachable.has(id))
context.addIssue({
code: "custom",
message: "state is unreachable from the initial state",
path: ["states", index],
});
};
const validateScenarioGraph = (
scenario: ProcessReactiveScenario,
context: z.RefinementCtx,
): void => {
const stateIds = scenario.states.map(({ id }) => id);
const knownStates = new Set(stateIds);
if (knownStates.size !== stateIds.length)
context.addIssue({
code: "custom",
message: "state ids must be unique",
path: ["states"],
});
if (!knownStates.has(scenario.initial_state))
context.addIssue({
code: "custom",
message: "initial state is not declared",
path: ["initial_state"],
});
const validation: GraphValidation = {
knownStates,
transitionIds: new Set(),
checkpoints: new Set(),
checkpointReferences: [],
adjacency: new Map(stateIds.map((id) => [id, new Set<string>()])),
};
for (const [stateIndex, state] of scenario.states.entries()) {
if (state.deadline_ms > scenario.deadline_ms)
context.addIssue({
code: "custom",
message: "state deadline must not exceed scenario deadline",
path: ["states", stateIndex, "deadline_ms"],
});
for (const [transitionIndex, transition] of state.on.entries())
validateTransition({
stateId: state.id,
transition,
path: ["states", stateIndex, "on", transitionIndex],
validation,
context,
});
}
validateTotalsAndReferences(scenario, validation, context);
validateReachability(scenario, stateIds, validation, context);
};
/** Strict boundary schema for a bounded declarative reactive scenario. */
export const processReactiveScenarioSchema = z.preprocess(
(input, context) =>
preflightProcessReactiveScenario(input, context, PROCESS_REACTIVE_LIMITS),
scenarioShapeSchema.superRefine((scenario, context) =>
validateScenarioGraph(scenario, context),
),
);
@@ -1,133 +0,0 @@
import { z } from "zod";
interface ReactivePreflightLimits {
readonly triggerDepth: number;
readonly jsonDepth: number;
}
type PendingTrigger = { readonly value: unknown; readonly depth: number };
interface TriggerTraversal {
readonly pending: PendingTrigger[];
readonly context: z.RefinementCtx;
readonly limits: ReactivePreflightLimits;
}
const isUnknownRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const reject = (context: z.RefinementCtx, message: string): false => {
context.addIssue({ code: "custom", message });
return false;
};
const inspectJsonValue = (
value: unknown,
context: z.RefinementCtx,
limits: ReactivePreflightLimits,
): boolean => {
const pending: PendingTrigger[] = [{ value, depth: 1 }];
const seen = new WeakSet<object>();
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
if (current.depth > limits.jsonDepth)
return reject(
context,
"event exact JSON exceeds the configured depth limit",
);
if (typeof current.value !== "object" || current.value === null) continue;
if (seen.has(current.value))
return reject(context, "event exact JSON must not contain cycles");
seen.add(current.value);
if (Array.isArray(current.value)) {
for (const child of current.value)
pending.push({ value: child, depth: current.depth + 1 });
continue;
}
if (!isUnknownRecord(current.value)) continue;
for (const key in current.value) {
if (!Object.hasOwn(current.value, key)) continue;
pending.push({
value: current.value[key],
depth: current.depth + 1,
});
}
}
return true;
};
const collectTriggerRoots = (states: readonly unknown[]): PendingTrigger[] => {
const pending: PendingTrigger[] = [];
for (const stateValue of states) {
if (!isUnknownRecord(stateValue) || !Array.isArray(stateValue["on"]))
continue;
for (const transitionValue of stateValue["on"])
if (isUnknownRecord(transitionValue))
pending.push({ value: transitionValue["when"], depth: 1 });
}
return pending;
};
const enqueueTriggerChildren = (
trigger: Record<string, unknown>,
depth: number,
traversal: TriggerTraversal,
): boolean => {
if (trigger["kind"] === "repeat") {
traversal.pending.push({ value: trigger["trigger"], depth: depth + 1 });
return true;
}
if (
trigger["kind"] !== "all" &&
trigger["kind"] !== "any" &&
trigger["kind"] !== "sequence"
)
return true;
const children = trigger["triggers"];
if (!Array.isArray(children)) return true;
for (const child of children)
traversal.pending.push({ value: child, depth: depth + 1 });
return true;
};
const inspectTriggerTree = (
pending: PendingTrigger[],
context: z.RefinementCtx,
limits: ReactivePreflightLimits,
): boolean => {
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
if (current.depth > limits.triggerDepth)
return reject(context, "trigger nesting exceeds the configured limit");
if (
isUnknownRecord(current.value) &&
current.value["kind"] === "event" &&
!inspectJsonValue(current.value["exact"], context, limits)
)
return false;
if (
isUnknownRecord(current.value) &&
!enqueueTriggerChildren(current.value, current.depth, {
pending,
context,
limits,
})
)
return false;
}
return true;
};
/** Reject oversized unknown trees before the recursive Zod schema visits them. */
export const preflightProcessReactiveScenario = (
input: unknown,
context: z.RefinementCtx,
limits: ReactivePreflightLimits,
): unknown => {
if (!isUnknownRecord(input) || !Array.isArray(input["states"])) return input;
const pending = collectTriggerRoots(input["states"]);
if (!inspectTriggerTree(pending, context, limits)) return z.NEVER;
return input;
};
-310
View File
@@ -1,310 +0,0 @@
import type { ProcessObservation } from "./processObservation.js";
import type {
ProcessReactiveDecision,
ProcessReactiveEffectResult,
ProcessReactiveEvaluation,
ProcessReactiveSnapshot,
ProcessReactiveTransitionRecord,
} from "./processReactiveRuntime.js";
import type { ProcessReactiveScenario } from "./processReactiveScenario.js";
type ReactiveTransition =
ProcessReactiveScenario["states"][number]["on"][number];
type SuccessfulEffectResult = Extract<
ProcessReactiveEffectResult,
{ readonly status: "succeeded" }
>;
const createTransitionRecord = (input: {
readonly sequence: number;
readonly stateBefore: string;
readonly transition: ReactiveTransition;
readonly triggerEventIds: readonly string[];
readonly effectResults: readonly SuccessfulEffectResult[];
}): ProcessReactiveTransitionRecord => {
const state = {
sequence: input.sequence,
transition_id: input.transition.id,
state_before: input.stateBefore,
trigger_event_ids: input.triggerEventIds,
action_event_ids: input.effectResults.map(
({ observation }) => observation.event_id,
),
action_types: input.transition.actions.map(({ type }) => type),
};
return input.transition.target.kind === "finish"
? {
...state,
state_after: null,
outcome: "passed",
}
: {
...state,
state_after: input.transition.target.state,
outcome: null,
};
};
const counterValue = (
counters: readonly { readonly id: string; readonly count: number }[],
id: string,
): number => counters.find((counter) => counter.id === id)?.count ?? 0;
const incrementCounter = (
counters: readonly { readonly id: string; readonly count: number }[],
id: string,
) => {
let found = false;
const updated = counters.map((counter) => {
if (counter.id !== id) return counter;
found = true;
return { id, count: counter.count + 1 };
});
return found ? updated : [...updated, { id, count: 1 }];
};
/** Commit one uniquely selected transition after its declarative effects succeed. */
const applyProcessReactiveTransition = (input: {
readonly scenario: ProcessReactiveScenario;
readonly snapshot: ProcessReactiveSnapshot;
readonly observation: ProcessObservation;
readonly transition: ReactiveTransition;
readonly triggerEventIds: readonly string[];
readonly consumeEventIds: readonly string[];
readonly effectResults: readonly SuccessfulEffectResult[];
readonly evaluations: readonly ProcessReactiveEvaluation[];
}): ProcessReactiveDecision => {
if (input.effectResults.length !== input.transition.actions.length)
throw new TypeError(
"Reactive transition effects do not match the admitted actions",
);
const record = createTransitionRecord({
sequence: input.snapshot.transitions.length,
stateBefore: input.snapshot.active_state,
transition: input.transition,
triggerEventIds: input.triggerEventIds,
effectResults: input.effectResults,
});
const outcome = record.outcome;
const stateAfter = record.state_after;
const consumed = new Set(input.snapshot.consumed_event_ids);
for (const eventId of input.consumeEventIds) consumed.add(eventId);
const checkpoints = [...input.snapshot.checkpoints];
for (const [index, action] of input.transition.actions.entries()) {
const effect = input.effectResults[index];
if (effect === undefined)
throw new TypeError("Reactive transition effect is missing");
if (action.type === "checkpoint")
checkpoints.push({
name: action.name,
event_id: effect.observation.event_id,
capture_order: effect.observation.capture_order,
});
}
const completedCaptureOrder = Math.max(
input.observation.capture_order,
...input.effectResults.map(({ observation }) => observation.capture_order),
);
const nextState = {
...input.snapshot,
active_state: stateAfter ?? input.snapshot.active_state,
state_entry_capture_order:
stateAfter === null
? input.snapshot.state_entry_capture_order
: completedCaptureOrder + 1,
consumed_event_ids: [...consumed],
transition_uses: incrementCounter(
input.snapshot.transition_uses,
input.transition.id,
),
state_visits:
stateAfter === null
? input.snapshot.state_visits
: incrementCounter(input.snapshot.state_visits, stateAfter),
checkpoints,
transitions: [...input.snapshot.transitions, record],
};
let next: ProcessReactiveSnapshot =
outcome === null
? { ...nextState, status: "running", outcome: null }
: { ...nextState, status: "finished", outcome };
if (stateAfter !== null) {
const nextState = input.scenario.states.find(({ id }) => id === stateAfter);
if (
nextState === undefined ||
counterValue(next.state_visits, stateAfter) > nextState.max_visits
)
next = { ...next, status: "finished", outcome: "capture_incomplete" };
}
return next.outcome === "capture_incomplete"
? {
kind: "finished",
snapshot: next,
evaluations: input.evaluations,
outcome: next.outcome,
}
: {
kind: "transition",
snapshot: next,
evaluations: input.evaluations,
record,
};
};
const terminalControlObservationMatches = (
action: Exclude<
ProcessReactiveScenario["states"][number]["on"][number]["actions"][number],
{ readonly type: "checkpoint" | "send_input" }
>,
payload: Readonly<Record<string, unknown>>,
): boolean => {
if (action.type === "resize")
return (
payload["type"] === "resize" &&
payload["data"] === `${String(action.columns)}x${String(action.rows)}`
);
if (action.type === "close_stdin")
return payload["type"] === "stdin_close" && payload["data"] === "";
return payload["type"] === "signal" && payload["data"] === action.signal;
};
const effectObservationMatchesAction = (
action: ProcessReactiveScenario["states"][number]["on"][number]["actions"][number],
observation: ProcessObservation,
committedSensitiveInputs: boolean,
): boolean => {
const payload =
typeof observation.payload === "object" &&
observation.payload !== null &&
!Array.isArray(observation.payload)
? observation.payload
: null;
const journalIdentityMatches =
observation.source_sequence === observation.location.index &&
observation.capture_order === observation.location.capture_order &&
observation.event_id ===
`obs.${observation.location.collection}.${String(observation.location.index)}`;
if (!journalIdentityMatches || payload === null) return false;
if (action.type === "checkpoint")
return (
observation.source === "filesystem" &&
observation.location.collection === "filesystem_checkpoints" &&
payload["name"] === action.name
);
if (
observation.source !== "interaction" ||
observation.location.collection !== "interaction_events" ||
payload["outcome"] !== "dispatched"
)
return false;
if (action.type === "send_input")
return (
payload["type"] === "input" &&
payload["data"] ===
expectedInputEvidence(
action.data,
action.sensitive,
committedSensitiveInputs,
)
);
return terminalControlObservationMatches(action, payload);
};
const expectedInputEvidence = (
data: string,
sensitive: boolean,
committedSensitiveInput: boolean,
): string =>
!sensitive ||
(committedSensitiveInput && /^<redacted-input:\d+-bytes>$/.test(data))
? data
: `<redacted-input:${String(Buffer.byteLength(data))}-bytes>`;
const failedProposal = (
proposed: Extract<ProcessReactiveDecision, { readonly kind: "proposal" }>,
outcome: "action_rejected" | "target_lost",
): ProcessReactiveDecision => ({
kind: "finished",
outcome,
evaluations: proposed.evaluations,
snapshot: { ...proposed.snapshot, status: "finished", outcome },
});
/** Commit a proposal only after the host reports every effect as successful. */
export const commitProcessReactiveProposal = (
scenario: ProcessReactiveScenario,
proposed: Extract<ProcessReactiveDecision, { readonly kind: "proposal" }>,
results: readonly ProcessReactiveEffectResult[],
options: { readonly committedSensitiveInputs?: boolean } = {},
): ProcessReactiveDecision => {
if (results.some(({ status }) => status === "target_lost"))
return failedProposal(proposed, "target_lost");
const state = scenario.states.find(
({ id }) => id === proposed.snapshot.active_state,
);
const transition = state?.on.find(
({ id }) => id === proposed.proposal.transition_id,
);
const observation = proposed.snapshot.observations.find(
({ event_id }) => event_id === proposed.proposal.observation_event_id,
);
if (
transition === undefined ||
observation === undefined ||
canonicalize(transition) !== proposed.proposal.transition_identity ||
canonicalize(proposed.effects) !== canonicalize(transition.actions)
)
return failedProposal(proposed, "target_lost");
if (
results.length !== transition.actions.length ||
results.some(({ status }) => status === "rejected")
)
return failedProposal(proposed, "action_rejected");
const succeeded = results.filter(
(
result,
): result is Extract<
ProcessReactiveEffectResult,
{ readonly status: "succeeded" }
> => result.status === "succeeded",
);
let previousOrder =
proposed.snapshot.observations.find(
({ event_id }) => event_id === proposed.proposal.observation_event_id,
)?.capture_order ?? -1;
const knownEventIds = new Set([
...proposed.snapshot.observations.map(({ event_id }) => event_id),
...proposed.snapshot.transitions.flatMap(
({ action_event_ids }) => action_event_ids,
),
]);
for (const [index, result] of succeeded.entries()) {
const action = transition.actions[index];
const effectObservation = result.observation;
if (
action === undefined ||
!effectObservationMatchesAction(
action,
effectObservation,
options.committedSensitiveInputs ?? false,
) ||
!Number.isSafeInteger(effectObservation.capture_order) ||
effectObservation.capture_order <= previousOrder ||
knownEventIds.has(effectObservation.event_id)
)
return failedProposal(proposed, "action_rejected");
knownEventIds.add(effectObservation.event_id);
previousOrder = effectObservation.capture_order;
}
return applyProcessReactiveTransition({
scenario,
snapshot: proposed.snapshot,
observation,
transition,
triggerEventIds: proposed.proposal.trigger_event_ids,
consumeEventIds: proposed.proposal.consume_event_ids,
effectResults: succeeded,
evaluations: proposed.evaluations,
});
};
import canonicalize from "canonicalize";
+57 -262
View File
@@ -2,14 +2,33 @@ import { describe, expect, it } from "vitest";
import { processScenarioSchema } from "./processScenario.js";
describe("process scenario collection inputs", () => {
it("accepts OS environment names without imposing shell identifier syntax", () => {
describe("direct process scenarios", () => {
it("defaults to one command with inherited environment and no filesystem scan", () => {
expect(processScenarioSchema.parse({ executable: "node" })).toMatchObject({
executable: "node",
arguments: [],
working_directory: ".",
environment: {},
filesystem_observation_paths: [],
events: [],
});
});
it("accepts caller-selected environment and explicit filesystem observations", () => {
const environment = { "app.setting": "value", "1": "numbered" };
expect(
processScenarioSchema.parse({ executable: "node", environment })
.environment,
).toEqual(environment);
for (const name of ["", "KEY=VALUE", "KEY\0VALUE"])
const scenario = processScenarioSchema.parse({
executable: "node",
arguments: ["./task.mjs"],
working_directory: "./project",
environment,
filesystem_observation_paths: ["state"],
});
expect(scenario.environment).toEqual(environment);
expect(scenario.filesystem_observation_paths).toEqual(["state"]);
});
it("rejects malformed environment names and adapter-reserved identity", () => {
for (const name of ["", "KEY=VALUE", "KEY\0VALUE", "REA_PROCESS_RUN_ID"])
expect(
processScenarioSchema.safeParse({
executable: "node",
@@ -18,263 +37,39 @@ describe("process scenario collection inputs", () => {
).toBe(false);
});
it("accepts more than 64 named filesystem checkpoints", () => {
it("keeps bounded capture controls and ordered scheduled interaction", () => {
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
working_directory: "/tmp",
checkpoints: Array.from({ length: 65 }, (_, index) => ({
name: `state-${index}`,
trigger: { type: "root_exit" as const },
})),
});
expect(scenario.checkpoints).toHaveLength(65);
});
it("allows a zero-depth filesystem observation", () => {
expect(
processScenarioSchema.parse({
executable: "/bin/echo",
working_directory: "/tmp",
limits: { filesystem_depth: 0 },
}).limits.filesystem_depth,
).toBe(0);
});
it("accepts caller budgets above the former tool-side ceilings", () => {
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
working_directory: "/tmp",
timeout_ms: 600_000,
idle_timeout_ms: 900_000,
settle_ms: 20_000,
limits: {
output_bytes: 10_000_001,
files: 100_001,
file_bytes: 100_000_001,
processes: 10_001,
protocol_events: 100_001,
protocol_body_bytes: 10_000_001,
connections: 1_001,
filesystem_depth: 100,
},
checkpoints: [
{
name: "later",
trigger: { type: "time", at_ms: 600_000 },
},
],
});
expect(scenario.limits.output_bytes).toBe(10_000_001);
expect(scenario.limits.files).toBe(100_001);
expect(scenario.limits.file_bytes).toBe(100_000_001);
expect(scenario.limits.processes).toBe(10_001);
expect(scenario.limits.protocol_events).toBe(100_001);
expect(scenario.limits.protocol_body_bytes).toBe(10_000_001);
expect(scenario.limits.connections).toBe(1_001);
expect(scenario.limits.filesystem_depth).toBe(100);
expect(scenario.timeout_ms).toBe(600_000);
expect(scenario.idle_timeout_ms).toBe(900_000);
expect(scenario.settle_ms).toBe(20_000);
});
});
describe("process scenario complete input values", () => {
it("accepts long checkpoint and command names", () => {
const checkpointName = `c${"k".repeat(1_000)}`;
const commandName = `c${"m".repeat(1_000)}`;
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
working_directory: "/tmp",
checkpoints: [{ name: checkpointName, trigger: { type: "root_exit" } }],
command_shims: [
{
name: commandName,
routes: [
{
arguments: [],
termination: { type: "exit", code: 0 },
},
],
},
],
});
expect(scenario.checkpoints[0]?.name).toBe(checkpointName);
expect(scenario.command_shims[0]?.name).toBe(commandName);
});
});
describe("process scenario long delays", () => {
it("accepts delayed actions longer than one operating-system timer", () => {
const beyondOneTimer = 2_147_483_648;
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
working_directory: "/tmp",
timeout_ms: beyondOneTimer + 1,
events: [{ type: "input", at_ms: beyondOneTimer, data: "later" }],
checkpoints: [
{
name: "later",
trigger: { type: "time", at_ms: beyondOneTimer },
},
],
command_shims: [
{
name: "later",
routes: [
{
arguments: [],
outputs: [
{
at_ms: beyondOneTimer,
stream: "stdout",
data: "later",
},
],
termination: { type: "exit", code: 0 },
},
],
},
],
replay: {
http: [
{
method: "GET",
path: "/later",
status: 200,
body: "later",
delay_ms: beyondOneTimer,
},
],
websocket_connections: [
{
messages: [{ data: "later", delay_ms: beyondOneTimer }],
},
],
},
});
expect(scenario.events[0]?.at_ms).toBe(beyondOneTimer);
expect(scenario.checkpoints[0]?.trigger).toMatchObject({
at_ms: beyondOneTimer,
});
expect(scenario.command_shims[0]?.routes[0]?.outputs[0]?.at_ms).toBe(
beyondOneTimer,
);
expect(scenario.replay.http[0]?.delay_ms).toBe(beyondOneTimer);
expect(
scenario.replay.websocket_connections[0]?.messages[0]?.delay_ms,
).toBe(beyondOneTimer);
});
});
describe("process scenario large interaction inputs", () => {
it("accepts large interaction and replay descriptions under the run budgets", () => {
const environment = Object.fromEntries(
Array.from({ length: 65 }, (_, index) => [`APP_VALUE_${index}`, "x"]),
);
const commandShims = Array.from({ length: 33 }, (_, shimIndex) => ({
name: `tool-${shimIndex}`,
routes: Array.from({ length: 101 }, (_, routeIndex) => ({
arguments: [`--route-${routeIndex}`],
outputs: Array.from({ length: routeIndex === 0 ? 1_001 : 0 }, () => ({
at_ms: 0,
stream: "stdout" as const,
data: "x",
})),
termination: { type: "exit" as const, code: 0 },
max_calls: 101,
})),
}));
const scenario = processScenarioSchema.parse({
executable: "/bin/echo",
arguments: Array.from({ length: 257 }, (_, index) => String(index)),
working_directory: "/tmp",
filesystem_observation_paths: Array.from(
{ length: 17 },
(_, index) => `/tmp/root-${index}`,
),
environment,
command_shims: commandShims,
events: Array.from({ length: 1_001 }, () => ({
type: "input" as const,
at_ms: 0,
data: "x",
})),
checkpoints: [
{
name: "many_occurrences",
trigger: {
type: "terminal_literal",
value: "ready",
occurrence: 1_001,
},
},
],
replay: {
http: Array.from({ length: 101 }, (_, index) => ({
method: "GET",
path: `/route-${index}`,
status: 200,
body: "ok",
max_calls: 101,
})),
websocket_messages: Array.from({ length: 101 }, () => "message"),
websocket_connections: Array.from({ length: 101 }, () => ({
messages: Array.from({ length: 101 }, () => ({ data: "message" })),
disconnect_after: false,
})),
},
});
expect(scenario.arguments).toHaveLength(257);
expect(scenario.command_shims).toHaveLength(33);
expect(scenario.command_shims[0]?.routes).toHaveLength(101);
expect(scenario.command_shims[0]?.routes[0]?.outputs).toHaveLength(1_001);
expect(scenario.events).toHaveLength(1_001);
expect(scenario.filesystem_observation_paths).toHaveLength(17);
expect(scenario.checkpoints[0]?.trigger).toMatchObject({
occurrence: 1_001,
});
expect(scenario.replay.http).toHaveLength(101);
expect(scenario.replay.websocket_connections[0]?.messages).toHaveLength(
101,
);
});
});
describe("minimal process scenario inputs", () => {
const scenario = {
arguments: [],
environment: {},
filesystem_observation_paths: [],
};
it("defaults working directory at execution and accepts command names", () => {
const parsed = processScenarioSchema.parse({
...scenario,
executable: "node",
events: [
{ type: "input", at_ms: 10, data: "answer", sensitive: true },
{ type: "resize", at_ms: 20, columns: 100, rows: 30 },
{ type: "signal", at_ms: 30, signal: "SIGTERM" },
],
limits: { output_bytes: 2_000_000, filesystem_depth: 0 },
});
expect(parsed.working_directory).toBe(".");
expect(parsed.executable).toBe("node");
expect(parsed.filesystem_observation_paths).toEqual([]);
expect(scenario.events).toHaveLength(3);
expect(scenario.events[0]).toMatchObject({ sensitive: true });
expect(scenario.limits.output_bytes).toBe(2_000_000);
expect(scenario.limits.filesystem_depth).toBe(0);
});
it("rejects events after timeout and unknown orchestration fields", () => {
expect(
processScenarioSchema.safeParse({
executable: "node",
timeout_ms: 10,
events: [{ type: "input", at_ms: 11, data: "late" }],
}).success,
).toBe(false);
for (const [field, value] of [
["command_shims", []],
["replay", {}],
["reactive", {}],
["checkpoints", []],
] as const)
expect(
processScenarioSchema.safeParse({ executable: "node", [field]: value })
.success,
).toBe(false);
});
});
describe("process scenario path portability", () => {
it.each([
["posix", "/usr/bin/node", "/tmp"],
["windows drive with backslashes", "C:\\tools\\node.exe", "C:\\work"],
["windows drive with forward slashes", "c:/tools/node.exe", "c:/work"],
["unc share", "\\\\server\\share\\node.exe", "\\\\server\\share"],
])(
"preserves a %s scenario on any host",
(_label, executable, working_directory) => {
expect(
processScenarioSchema.parse({ executable, working_directory }),
).toMatchObject({ executable, working_directory });
},
);
});
+1 -173
View File
@@ -1,23 +1,13 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
processReactiveScenarioSchema,
type ProcessReactiveScenario,
} from "./processReactiveScenario.js";
import { replayMachineSchema } from "./replayMachine.js";
const positiveBudget = z.number().int().safe().positive();
const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
const environmentName = z
.string()
.regex(/^[^=\0]+$/u, "Environment names cannot contain '=' or NUL");
const reservedEnvironment = new Set([
"REA_PROCESS_RUN_ID",
"REA_REPLAY_HTTP_URL",
"REA_REPLAY_WEBSOCKET_URL",
"REA_SHIM_LEDGER_URL",
]);
const reservedEnvironment = new Set(["REA_PROCESS_RUN_ID"]);
export const normalizationSchema = z.object({
paths: z.boolean(),
pids: z.boolean(),
@@ -30,13 +20,6 @@ export const normalizationSchema = z.object({
}),
),
});
const checkpointNameSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/u);
const commandNameSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
const outputChunkSchema = z.object({
at_ms: z.number().int().safe().nonnegative(),
stream: z.enum(["stdout", "stderr"]),
data: z.string(),
});
/** Compute a canonical SHA-256 commitment independent of object key order. */
export const digestProcessCommitment = (value: unknown): string => {
@@ -46,29 +29,6 @@ export const digestProcessCommitment = (value: unknown): string => {
return createHash("sha256").update(serialized).digest("hex");
};
const reactiveScenarioCommitment = (
scenario: ProcessReactiveScenario | null,
): Readonly<Record<string, unknown>> | null =>
scenario === null
? null
: {
...scenario,
states: scenario.states.map((state) => ({
...state,
on: state.on.map((transition) => ({
...transition,
actions: transition.actions.map((action) =>
action.type === "send_input" && action.sensitive
? {
...action,
data: `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`,
}
: action,
),
})),
})),
};
const committedScenarioEvents = (
events: ProcessScenario["events"],
includeSensitiveInputLength: boolean,
@@ -91,7 +51,6 @@ export const processScenarioCommitment = (
): Readonly<Record<string, unknown>> => ({
...scenario,
events: committedScenarioEvents(scenario.events, true),
reactive: reactiveScenarioCommitment(scenario.reactive),
executable_sha256: executableSha256 ?? null,
});
@@ -104,7 +63,6 @@ export const processComparisonContract = (
ambient_environment: "unknown",
filesystem_observation_paths: scenario.filesystem_observation_paths,
terminal: scenario.terminal,
checkpoints: scenario.checkpoints,
// Input bytes are intentionally absent from compatibility identity. Their
// redacted observations remain unknown, so equal commitments never imply
// that two secret values were the same.
@@ -114,9 +72,6 @@ export const processComparisonContract = (
settle_ms: scenario.settle_ms,
limits: scenario.limits,
normalization: scenario.normalization,
command_shims: scenario.command_shims,
replay: scenario.replay,
reactive: reactiveScenarioCommitment(scenario.reactive),
});
/**
@@ -137,52 +92,6 @@ export const processScenarioSchema = z
scrollback: z.number().int().min(0).default(1_000),
})
.default({ columns: 80, rows: 24, scrollback: 1_000 }),
checkpoints: z
.array(
z.object({
name: checkpointNameSchema,
trigger: z.discriminatedUnion("type", [
z.object({
type: z.literal("time"),
at_ms: z.number().int().safe().nonnegative(),
}),
z.object({
type: z.literal("terminal_literal"),
value: z.string().min(1),
occurrence: positiveBudget.default(1),
}),
z.object({ type: z.literal("root_exit") }),
z.object({ type: z.literal("settled") }),
]),
}),
)
.default([]),
command_shims: z
.array(
z.object({
name: commandNameSchema,
routes: z
.array(
z.object({
arguments: z.array(z.string()),
outputs: z.array(outputChunkSchema).default([]),
termination: z.discriminatedUnion("type", [
z.object({
type: z.literal("exit"),
code: z.number().int().min(0).max(255),
}),
z.object({
type: z.literal("signal"),
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]),
}),
]),
max_calls: positiveBudget.default(1),
}),
)
.min(1),
}),
)
.default([]),
events: z
.array(
z.discriminatedUnion("type", [
@@ -215,9 +124,6 @@ export const processScenarioSchema = z
files: positiveBudget.default(10_000),
file_bytes: positiveBudget.default(10_000_000),
processes: positiveBudget.default(1_000),
protocol_events: positiveBudget.default(10_000),
protocol_body_bytes: positiveBudget.default(1_000_000),
connections: positiveBudget.default(100),
filesystem_depth: z.number().int().safe().nonnegative().default(16),
})
.strict()
@@ -226,9 +132,6 @@ export const processScenarioSchema = z
files: 10_000,
file_bytes: 10_000_000,
processes: 1_000,
protocol_events: 10_000,
protocol_body_bytes: 1_000_000,
connections: 100,
filesystem_depth: 16,
}),
normalization: z
@@ -253,47 +156,6 @@ export const processScenarioSchema = z
time_bucket_ms: 10,
patterns: [],
}),
replay: z
.object({
machine: replayMachineSchema.nullable().default(null),
http: z
.array(
z.object({
method: z.string(),
path: z.string().startsWith("/"),
status: z.number().int().min(100).max(599),
body: z.string(),
request_headers: z.record(z.string(), z.string()).default({}),
request_body: z.string().optional(),
response_headers: z.record(z.string(), z.string()).default({}),
delay_ms: z.number().int().safe().nonnegative().default(0),
disconnect: z.boolean().default(false),
max_calls: positiveBudget.default(1),
}),
)
.default([]),
websocket_messages: z.array(z.string()).default([]),
websocket_connections: z
.array(
z.object({
messages: z.array(
z.object({
data: z.string(),
delay_ms: z.number().int().safe().nonnegative().default(0),
}),
),
disconnect_after: z.boolean().default(false),
}),
)
.default([]),
})
.default({
machine: null,
http: [],
websocket_messages: [],
websocket_connections: [],
}),
reactive: processReactiveScenarioSchema.nullable().default(null),
})
.strict()
.superRefine((scenario, context) => {
@@ -327,40 +189,6 @@ export const processScenarioSchema = z
});
}
}
const checkpointNames = scenario.checkpoints.map(({ name }) => name);
for (const [index, name] of checkpointNames.entries()) {
if (name === "before" || name === "after_settlement")
context.addIssue({
code: "custom",
message: "checkpoint name is reserved by the capture lifecycle",
path: ["checkpoints", index, "name"],
});
}
if (new Set(checkpointNames).size !== checkpointNames.length)
context.addIssue({
code: "custom",
message: "checkpoint names must be unique",
path: ["checkpoints"],
});
const shimNames = scenario.command_shims.map(({ name }) => name);
if (new Set(shimNames).size !== shimNames.length)
context.addIssue({
code: "custom",
message: "command shim names must be unique",
path: ["command_shims"],
});
if (
scenario.replay.machine !== null &&
(scenario.replay.http.length > 0 ||
scenario.replay.websocket_messages.length > 0 ||
scenario.replay.websocket_connections.length > 0)
)
context.addIssue({
code: "custom",
message:
"a replay machine cannot be combined with static HTTP or WebSocket scripts",
path: ["replay"],
});
});
const eventsOutOfOrder = (
-165
View File
@@ -69,171 +69,6 @@ const traceSpecification: ProcessTraceSpecification = {
},
};
describe("declared trace comparison adapters", () => {
it("treats only explicitly ignored schedule metadata as reorderable", () => {
const httpPayload = {
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocketPayload = {
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const scheduledCapture = (order: "http-first" | "websocket-first") => {
const protocolEvents =
order === "http-first"
? [
{ sequence: 0, at_ms: 1, ...httpPayload },
{ sequence: 1, at_ms: 2, ...websocketPayload },
]
: [
{ sequence: 0, at_ms: 1, ...websocketPayload },
{ sequence: 1, at_ms: 2, ...httpPayload },
];
return parseProcessCapture({
...capture,
protocol_events: protocolEvents,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
};
const specification: ProcessTraceSpecification = {
events: [
{
id: "status",
source: "http",
exact: httpPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocketPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [{ events: ["status", "done"] }],
prefix: [],
suffix: [],
},
};
expect(
compareProcessCaptures(
scheduledCapture("http-first"),
scheduledCapture("websocket-first"),
{ traceSpecification: specification },
),
).toMatchObject({
status: "unchanged",
protocol: "unchanged",
trace: {
verdict: "equivalent",
left: { raw_trace: [{ event_id: "status" }, { event_id: "done" }] },
right: { raw_trace: [{ event_id: "done" }, { event_id: "status" }] },
},
});
});
});
describe("declared trace comparison coverage", () => {
it("does not mask an unselected source in a covered legacy dimension", () => {
const http = {
sequence: 0,
at_ms: 1,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = (data: string) => ({
sequence: 1,
at_ms: 2,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data,
outcome: "matched" as const,
});
const withProtocol = (data: string) =>
parseProcessCapture({
...capture,
protocol_events: [http, websocket(data)],
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
const specification: ProcessTraceSpecification = {
events: [
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "status", trace: ["status"] }],
},
};
expect(
compareProcessCaptures(withProtocol("left"), withProtocol("right"), {
traceSpecification: specification,
}),
).toMatchObject({
status: "changed",
protocol: "changed",
trace: { verdict: "equivalent" },
});
});
});
describe("declared trace comparison nonconformance", () => {
it("does not call identical captures changed when both violate the language", () => {
const parsedCapture = parseProcessCapture(capture);
+28 -82
View File
@@ -3,16 +3,22 @@ import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
import { type ProcessTraceSpecification } from "./processTraceComparison.js";
export const emptyCapture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
export const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
export const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
export const capture = (
values: Pick<
ProcessCapture,
| "frames"
| "process_samples"
| "filesystem_checkpoints"
| "protocol_events"
| "shim_events"
> & {
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
values: Pick<ProcessCapture, "frames" | "process_samples"> & {
readonly event_journal: readonly Pick<
NonNullable<ProcessCapture["event_journal"]>[number],
"collection" | "index"
>[];
},
options: {
readonly truncated?: boolean;
@@ -23,18 +29,11 @@ export const capture = (
...emptyCapture,
frames: values.frames,
process_samples: values.process_samples,
filesystem_checkpoints: emptyCapture.filesystem_checkpoints,
shim_events: values.shim_events,
protocol_events: values.protocol_events,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
...values.event_journal.map((entry) => ({
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
...values.event_journal.map((entry, index) => ({
...entry,
capture_order: entry.capture_order + 1,
capture_order: index + 1,
})),
{
capture_order: values.event_journal.length + 1,
@@ -55,54 +54,18 @@ export const capture = (
truncated: options.truncated ?? false,
residual_unknowns: options.residualUnknowns ?? [],
});
export const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
export const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
export const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
export const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
export const values = (
order: readonly ("terminal" | "process" | "http" | "websocket")[],
order: readonly ("terminal" | "process")[],
): Parameters<typeof capture>[0] => ({
frames: [terminal],
process_samples: [processStarted],
filesystem_checkpoints: [],
protocol_events: [http, websocket],
shim_events: [],
event_journal: order.map((event, captureOrder) => ({
capture_order: captureOrder,
collection:
event === "terminal"
? "frames"
: event === "process"
? "process_samples"
: "protocol_events",
index: event === "websocket" ? 1 : 0,
event_journal: order.map((event) => ({
collection: event === "terminal" ? "frames" : "process_samples",
index: 0,
})),
});
export const partialSpecification = (): ProcessTraceSpecification => ({
events: [
{
@@ -117,30 +80,13 @@ export const partialSpecification = (): ProcessTraceSpecification => ({
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
happens_before: [{ before: "ready", after: "worker" }],
not_before: [],
unordered_groups: [],
prefix: ["ready"],
suffix: ["done"],
suffix: ["worker"],
},
});
+102 -127
View File
@@ -8,125 +8,69 @@ import {
import {
capture,
partialSpecification,
processStarted,
terminal,
values,
websocket,
} from "./processTraceComparison.fixture.js";
describe("process trace comparison: declared schedules", () => {
it("accepts only explicitly declared concurrent schedules without timestamp causality", () => {
const left = capture(values(["terminal", "process", "http", "websocket"]));
const right = capture(values(["terminal", "http", "process", "websocket"]));
const comparison = compareProcessTraces(
left,
right,
partialSpecification(),
);
expect(comparison.verdict).toBe("equivalent");
expect(comparison.left.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"worker",
"status",
"done",
]);
expect(comparison.right.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"status",
"worker",
"done",
]);
expect(comparison.left.satisfied_constraints).toContain(
"unordered:worker:status",
);
});
it("returns the minimal journal slice for a reversed required edge", () => {
const baseline = capture(
values(["terminal", "process", "http", "websocket"]),
);
const reversed = capture(
values(["process", "terminal", "http", "websocket"]),
);
const comparison = compareProcessTraces(
baseline,
reversed,
partialSpecification(),
);
expect(comparison).toMatchObject({
describe("generic capture trace comparison", () => {
it("requires explicit partial ordering and never infers causality from timestamps", () => {
const specification = partialSpecification();
const left = capture(values(["terminal", "process"]));
const right = capture(values(["process", "terminal"]));
expect(compareProcessTraces(left, right, specification)).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["ready", "worker"],
locations: [{ capture_order: 2 }, { capture_order: 1 }],
},
diagnostic: { kind: "edge", side: "right" },
});
expect(
processTraceComparisonResultSchema.safeParse({
...comparison,
right: { ...comparison.right, matched_variant: "invented" },
}).success,
).toBe(false);
});
it("enforces explicit negative not-before constraints", () => {
const specification: ProcessTraceSpecification = {
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
const concurrent: ProcessTraceSpecification = {
...specification,
language: {
kind: "partial_order",
happens_before: [],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [],
not_before: [],
unordered_groups: [{ events: ["ready", "worker"] }],
prefix: [],
suffix: [],
},
};
const normal = capture(
values(["terminal", "process", "http", "websocket"]),
);
const invalid = capture(
values(["websocket", "terminal", "process", "http"]),
);
expect(compareProcessTraces(normal, invalid, specification)).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["done", "ready"],
},
expect(compareProcessTraces(left, right, concurrent)).toMatchObject({
verdict: "equivalent",
});
});
it("rejects malformed result contracts", () => {
const result = compareProcessTraces(
capture(values(["terminal", "process"])),
capture(values(["terminal", "process"])),
partialSpecification(),
);
expect(
processTraceComparisonResultSchema.safeParse({
...result,
right: {
...result.right,
status: "fail",
matched_variant: "invented",
},
}).success,
).toBe(false);
});
it("supports declared optional events and bounded duplicates", () => {
const first = { sequence: 0, at_ms: 1, data: "tick" };
const second = { sequence: 1, at_ms: 2, data: "tick" };
const one = capture({
frames: [first],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [{ capture_order: 0, collection: "frames", index: 0 }],
event_journal: [{ collection: "frames", index: 0 }],
});
const two = capture({
frames: [first, second],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [
{ capture_order: 0, collection: "frames", index: 0 },
{ capture_order: 1, collection: "frames", index: 1 },
{ collection: "frames", index: 0 },
{ collection: "frames", index: 1 },
],
});
const specification: ProcessTraceSpecification = {
@@ -160,8 +104,8 @@ describe("process trace comparison: declared schedules", () => {
});
});
describe("process trace comparison: evidence sufficiency", () => {
it("enforces exact and range cardinality for one repeated predicate", () => {
describe("process trace constraints and evidence sufficiency", () => {
it("enforces exact and range cardinality for a repeated terminal observation", () => {
const repeated = (count: number) =>
capture({
frames: Array.from({ length: count }, (_, sequence) => ({
@@ -170,11 +114,7 @@ describe("process trace comparison: evidence sufficiency", () => {
data: "tick",
})),
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: Array.from({ length: count }, (_, index) => ({
capture_order: index,
collection: "frames" as const,
index,
})),
@@ -214,6 +154,7 @@ describe("process trace comparison: evidence sufficiency", () => {
verdict: "different",
diagnostic: { kind: "cardinality", side: "right" },
});
const exactSpecification: ProcessTraceSpecification = {
events: [{ ...event, cardinality: { kind: "exact", count: 2 } }],
language: {
@@ -231,43 +172,77 @@ describe("process trace comparison: evidence sufficiency", () => {
diagnostic: { kind: "cardinality", side: "left" },
});
});
it("enforces an explicit not-before relation between terminal and process events", () => {
const specification: ProcessTraceSpecification = {
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [{ event: "ready", anchor: "worker" }],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
const readyFirst = capture(values(["terminal", "process"]));
const workerFirst = capture(values(["process", "terminal"]));
expect(
compareProcessTraces(workerFirst, readyFirst, specification),
).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["ready", "worker"],
},
});
expect(
compareProcessTraces(workerFirst, workerFirst, specification),
).toMatchObject({ verdict: "equivalent" });
});
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
const complete = capture(
values(["terminal", "process", "http", "websocket"]),
);
const truncated = capture(
values(["terminal", "process", "http", "websocket"]),
{ truncated: true },
);
const complete = capture(values(["terminal", "process"]));
const truncated = capture(values(["terminal", "process"]), {
truncated: true,
});
expect(
compareProcessTraces(complete, truncated, partialSpecification()).verdict,
).toBe("unknown");
const unknown = capture(
values(["terminal", "process", "http", "websocket"]),
{ residualUnknowns: [{ scope: "protocol", reason: "gap" }] },
);
const unknown = capture(values(["terminal", "process"]), {
residualUnknowns: [{ scope: "process", reason: "sampled" }],
});
expect(
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
).toBe("unknown");
const noJournal = parseProcessCapture({
...complete,
event_journal: [],
});
const comparison = compareProcessTraces(
complete,
noJournal,
partialSpecification(),
);
expect(comparison).toMatchObject({
const noJournal = parseProcessCapture({ ...complete, event_journal: [] });
expect(
compareProcessTraces(complete, noJournal, partialSpecification()),
).toMatchObject({
verdict: "unknown",
diagnostic: { kind: "journal", side: "right" },
});
const incompleteJournal = {
...complete,
event_journal: (complete.event_journal ?? []).slice(1),
};
expect(() => parseProcessCapture(incompleteJournal)).toThrow(
"Invalid process capture: event_journal.0.capture_order",
);
expect(() =>
parseProcessCapture({
...complete,
event_journal: (complete.event_journal ?? []).slice(1),
}),
).toThrow("event_journal");
});
});
+1 -25
View File
@@ -6,9 +6,7 @@ export type ProcessComparisonDimension =
| "interaction"
| "exit"
| "filesystem"
| "protocol"
| "process"
| "shim";
| "process";
/** Map declared trace sources to legacy process-comparison dimensions. */
export const dimensionsForTraceSources = (
@@ -20,14 +18,7 @@ export const dimensionsForTraceSources = (
else if (source === "interaction") dimensions.add("interaction");
else if (source === "lifecycle") dimensions.add("exit");
else if (source === "filesystem") dimensions.add("filesystem");
else if (
source === "http" ||
source === "websocket" ||
source === "replay_transition"
)
dimensions.add("protocol");
else if (source === "process") dimensions.add("process");
else if (source === "shim") dimensions.add("shim");
}
return dimensions;
};
@@ -56,22 +47,7 @@ export const traceCoversObservedDimension = (
return sources.has("lifecycle");
case "filesystem":
return false;
case "protocol":
return (
(![...left.protocol_events, ...right.protocol_events].some(
({ protocol }) => protocol === "http",
) ||
sources.has("http")) &&
(![...left.protocol_events, ...right.protocol_events].some(
({ protocol }) => protocol === "websocket",
) ||
sources.has("websocket")) &&
(!any(left.replay_transitions, right.replay_transitions) ||
sources.has("replay_transition"))
);
case "process":
return sources.has("process");
case "shim":
return sources.has("shim");
}
};
-7
View File
@@ -84,15 +84,8 @@ const scopesFor = (
[...sources].map((source) => {
if (source.startsWith("terminal_")) return "terminal";
if (source === "lifecycle") return "exit";
if (
source === "http" ||
source === "websocket" ||
source === "replay_transition"
)
return "protocol";
if (source === "filesystem") return "filesystem";
if (source === "process") return "process";
if (source === "shim") return "shim";
return "interaction";
}),
);
+18 -145
View File
@@ -3,122 +3,44 @@ import {
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "./processTraceComparison.js";
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
const processStarted = {
at_ms: 1,
const ready = { sequence: 0, at_ms: 10, data: "ready" };
const worker = {
at_ms: 20,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const partialSpecification = (): ProcessTraceSpecification => ({
const specification = (): ProcessTraceSpecification => ({
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
exact: ready,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
exact: worker,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
happens_before: [{ before: "ready", after: "worker" }],
not_before: [],
unordered_groups: [],
prefix: ["ready"],
suffix: ["done"],
suffix: ["worker"],
},
});
describe("process trace specification", () => {
it("accepts event sets and cardinalities beyond the former fixed ceilings", () => {
const ids = Array.from({ length: 257 }, (_, index) => `event-${index}`);
const events = ids.map((id) => ({
id,
source: "terminal_raw" as const,
exact: { id },
cardinality: { kind: "required" as const },
}));
const trace = processTraceSpecificationSchema.safeParse({
events: [
{
id: "repeated",
source: "terminal_raw",
exact: "event",
cardinality: { kind: "exact", count: 10_001 },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "long-trace",
trace: Array.from({ length: 10_001 }, () => "repeated"),
},
],
},
});
expect(trace.success).toBe(true);
const eventSet = processTraceSpecificationSchema.safeParse({
events,
language: {
kind: "partial_order",
happens_before: ids.slice(1).map((after, index) => ({
before: ids[index] ?? "",
after,
})),
prefix: Array.from({ length: 4_097 }, () => ids[0] ?? ""),
},
});
expect(eventSet.success).toBe(true);
});
it("rejects cycles, implicit concurrency, overlap, and unsatisfiable variants", () => {
const base = partialSpecification();
it("rejects cycles, implicit ordering gaps, invalid ignores, and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
@@ -128,26 +50,20 @@ describe("process trace specification", () => {
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
unordered_groups: [{ events: ["status", "done"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: base.events.slice(0, 3),
language: {
kind: "partial_order",
happens_before: [{ before: "ready", after: "status" }],
not_before: [{ event: "worker", anchor: "ready" }],
unordered_groups: [],
},
...base,
language: { kind: "partial_order" },
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [
{
id: "invalid-ignore",
id: "bad",
source: "terminal_raw",
exact: "ready",
ignore_fields: ["at_ms"],
@@ -155,38 +71,7 @@ describe("process trace specification", () => {
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [
{
id: "invalid-ignore",
source: "terminal_raw",
exact: terminal,
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: base.events.slice(0, 2),
language: { kind: "partial_order" },
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [base.events[0], { ...base.events[0], id: "duplicate" }],
language: {
kind: "partial_order",
unordered_groups: [{ events: ["ready", "duplicate"] }],
variants: [{ id: "one", trace: ["bad"] }],
},
}).success,
).toBe(false);
@@ -204,17 +89,5 @@ describe("process trace specification", () => {
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
events: [base.events[0]],
language: {
kind: "finite_traces",
variants: [
{ id: "first", trace: ["ready"] },
{ id: "duplicate", trace: ["ready"] },
],
},
}).success,
).toBe(false);
});
});
+21 -8
View File
@@ -8,6 +8,7 @@ import {
} from "./reconstructionVerification.js";
import type { JsonValue } from "./jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
import { reconstructionSpecificationSchema } from "./reconstructionVerificationSchemas.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../contracts/artifactComparisonExample.js";
import { createResidualUnknown } from "./residualUnknown.js";
@@ -58,9 +59,7 @@ const processResult = (
interaction: "unchanged",
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
shim: "unchanged",
first_divergence:
terminal === "changed"
? {
@@ -176,7 +175,7 @@ const artifactComparison = (
);
describe("reconstruction verification", () => {
it("accepts interaction and shim behavioral claim dimensions", () => {
it("accepts real process dimensions and rejects removed protocol dimensions", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const result = {
@@ -185,9 +184,7 @@ describe("reconstruction verification", () => {
interaction: "changed",
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
shim: "unchanged",
first_divergence: {
status: "found",
dimension: "interaction",
@@ -215,10 +212,10 @@ describe("reconstruction verification", () => {
},
{
kind: "behavioral",
claim_id: "shim",
title: "Shim remains equivalent",
claim_id: "process",
title: "Process behavior remains equivalent",
comparison_evidence_id: comparison.evidence_id,
dimension: "shim",
dimension: "process",
},
],
},
@@ -227,6 +224,22 @@ describe("reconstruction verification", () => {
).toMatchObject({
summary: { total: 2, passed: 1, failed: 1, unknown: 0 },
});
for (const dimension of ["protocol", "shim"] as const) {
expect(
reconstructionSpecificationSchema.safeParse({
name: "Removed process dimension",
claims: [
{
kind: "behavioral",
claim_id: dimension,
title: "Unsupported dimension",
comparison_evidence_id: comparison.evidence_id,
dimension,
},
],
}).success,
).toBe(false);
}
});
it("passes a complete authoritative claim with two-sided citations", () => {
@@ -1,6 +1,7 @@
import { z } from "zod";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { PROCESS_COMPARISON_DIMENSIONS } from "./processComparison.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const unknownIdSchema = prefixedDigestSchema("unk");
@@ -16,16 +17,7 @@ const commonClaim = {
const behavioralClaimSchema = z.object({
...commonClaim,
kind: z.literal("behavioral"),
dimension: z.enum([
"overall",
"terminal",
"interaction",
"exit",
"filesystem",
"protocol",
"process",
"shim",
]),
dimension: z.enum(["overall", ...PROCESS_COMPARISON_DIMENSIONS]),
});
const functionClaimSchema = z.object({
...commonClaim,
-332
View File
@@ -1,332 +0,0 @@
import { describe, expect, it } from "vitest";
import { replayMachineSchema } from "./replayMachine.js";
const loginMachine = () => ({
initial_state: "waiting_for_login",
states: [
{ name: "waiting_for_login" },
{ name: "waiting_for_api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "login",
from: "waiting_for_login",
to: "waiting_for_api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
max_uses: 1,
},
{
id: "api",
from: "waiting_for_api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{
type: "http_response",
status: 200,
headers: {},
body: "done",
},
],
max_uses: 1,
},
],
max_transitions: 2,
});
describe("replay machine", () => {
it("accepts a bounded, reachable, data-only login machine", () => {
expect(replayMachineSchema.parse(loginMachine())).toMatchObject({
initial_state: "waiting_for_login",
max_transitions: 2,
});
});
});
describe("replay machine long identifiers", () => {
it("accepts long state, transition, and variable identifiers", () => {
const initialState = `s${"t".repeat(255)}`;
const terminalState = `s${"f".repeat(255)}`;
const transitionId = `t${"r".repeat(255)}`;
const variable = `v${"a".repeat(255)}`;
const machine = {
initial_state: initialState,
states: [{ name: initialState }, { name: terminalState, terminal: true }],
transitions: [
{
id: transitionId,
from: initialState,
to: terminalState,
trigger: { protocol: "http", method: "GET", path: "/complete" },
captures: [
{
variable,
value: { source: "request_header", name: "x-value" },
sensitive: false,
},
],
actions: [{ type: "http_response", status: 200, body: "done" }],
max_uses: 1,
},
],
max_transitions: 1,
};
expect(replayMachineSchema.parse(machine)).toMatchObject({
initial_state: initialState,
states: [{ name: initialState }, { name: terminalState }],
transitions: [{ id: transitionId, captures: [{ variable }] }],
});
});
});
describe("replay machine long delays", () => {
it("accepts replay delays longer than one operating-system timer", () => {
const machine: unknown = {
...loginMachine(),
transitions: loginMachine().transitions.map((transition, index) =>
index === 0
? {
...transition,
actions: [
{ type: "delay", duration_ms: 2_147_483_648 },
...transition.actions,
],
}
: transition,
),
};
expect(
replayMachineSchema.parse(machine).transitions[0]?.actions[0],
).toEqual({ type: "delay", duration_ms: 2_147_483_648 });
});
});
describe("replay machine validation", () => {
it.each([
[
"unreachable state",
(machine: ReturnType<typeof loginMachine>) =>
machine.states.push({ name: "orphan", terminal: false }),
"unreachable",
],
[
"ambiguous transition",
(machine: ReturnType<typeof loginMachine>) => {
const transition = machine.transitions[0];
if (transition === undefined) throw new TypeError("missing transition");
machine.transitions.push({ ...transition, id: "login_2" });
},
"ambiguous",
],
[
"outgoing terminal transition",
(machine: ReturnType<typeof loginMachine>) => {
const transition = machine.transitions[0];
if (transition === undefined) throw new TypeError("missing transition");
machine.transitions.push({
...transition,
id: "restart",
from: "complete",
to: "waiting_for_login",
trigger: { protocol: "http", method: "POST", path: "/restart" },
});
},
"terminal",
],
[
"unknown guard variable",
(machine: ReturnType<typeof loginMachine>) => {
const guard = machine.transitions[1]?.guards?.[0];
if (guard === undefined) throw new TypeError("missing guard");
guard.variable = "missing";
},
"executable path before use",
],
[
"missing terminal state",
(machine: ReturnType<typeof loginMachine>) => {
const state = machine.states[2];
if (state === undefined) throw new TypeError("missing state");
state.terminal = false;
},
"terminal state",
],
])("rejects %s", (_name, mutate, message) => {
const machine = loginMachine();
mutate(machine);
expect(() => replayMachineSchema.parse(machine)).toThrow(message);
});
it("canonicalizes methods and headers while refusing persisted credential matchers", () => {
const canonical = {
...loginMachine(),
transitions: loginMachine().transitions.map((transition, index) =>
index === 0
? {
...transition,
trigger: {
protocol: "http",
method: "post",
path: "/login",
headers: { "X-Request-ID": "fixture" },
},
}
: transition,
),
};
expect(
replayMachineSchema.parse(canonical).transitions[0]?.trigger,
).toMatchObject({
method: "POST",
headers: { "x-request-id": "fixture" },
});
const credentialMatcher = {
...loginMachine(),
transitions: loginMachine().transitions.map((transition, index) =>
index === 0
? {
...transition,
trigger: {
protocol: "http",
method: "POST",
path: "/login",
headers: { Authorization: "test-auth-token" },
},
}
: transition,
),
};
expect(() => replayMachineSchema.parse(credentialMatcher)).toThrow(
/secret alias/u,
);
});
});
describe("replay machine validation", () => {
it("rejects sensitive captures sourced from persisted action JSON", () => {
const candidate = loginMachine();
const capture = candidate.transitions[0]?.captures?.[0];
if (capture === undefined) throw new TypeError("missing capture");
capture.value = { source: "action_json", path: ["token"] };
expect(() => replayMachineSchema.parse(candidate)).toThrow(
/literal action JSON/u,
);
});
it.each([
["invalid header name", { "bad header": "value" }],
["invalid header value", { "x-test": "value\nsmuggled" }],
])("rejects %s in HTTP responses", (_name, headers) => {
const candidate = loginMachine();
const action = candidate.transitions[0]?.actions[0];
if (action === undefined || action.type !== "http_response")
throw new TypeError("missing HTTP response");
action.headers = headers;
expect(() => replayMachineSchema.parse(candidate)).toThrow();
});
it("rejects unknown fields at nested machine boundaries", () => {
const candidate = loginMachine();
const action = candidate.transitions[0]?.actions[0];
if (action === undefined) throw new TypeError("missing action");
expect(() =>
replayMachineSchema.parse({
...candidate,
transitions: [
{
...candidate.transitions[0],
actions: [{ ...action, unexpected: true }],
},
candidate.transitions[1],
],
}),
).toThrow(/Unrecognized key/u);
});
it("reports duplicate transition IDs as structured validation", () => {
const candidate = loginMachine();
const first = candidate.transitions[0];
const second = candidate.transitions[1];
if (first === undefined || second === undefined)
throw new TypeError("missing transition");
expect(
replayMachineSchema.safeParse({
...candidate,
transitions: [first, { ...second, id: first.id }],
}),
).toMatchObject({ success: false });
});
it("rejects guards whose capture is not available before the transition", () => {
const candidate = loginMachine();
const first = candidate.transitions[0];
if (first === undefined) throw new TypeError("missing transition");
first.guards = [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
];
expect(() => replayMachineSchema.parse(candidate)).toThrow(
/executable path before use/u,
);
});
it("rejects ambiguous header triggers regardless of key order", () => {
const candidate = loginMachine();
const first = candidate.transitions[0];
if (first === undefined) throw new TypeError("missing transition");
const withHeaders = {
...first,
trigger: {
protocol: "http" as const,
method: "POST",
path: "/login",
headers: { accept: "json", "x-mode": "test" },
},
};
expect(() =>
replayMachineSchema.parse({
...candidate,
transitions: [
withHeaders,
{
...withHeaders,
id: "login_duplicate",
trigger: {
...withHeaders.trigger,
headers: { "x-mode": "test", accept: "json" },
},
},
candidate.transitions[1],
],
}),
).toThrow(/ambiguous/u);
});
});
-383
View File
@@ -1,383 +0,0 @@
import { MultiDirectedGraph } from "graphology";
import { singleSource } from "graphology-shortest-path";
import canonicalize from "canonicalize";
import { z } from "zod";
const replayIdentifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/u);
const replayPathSchema = z.array(
z.union([z.string(), z.number().int().nonnegative()]),
);
const sensitiveHeaderNames = new Set([
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
]);
const headerNameSchema = z
.string()
.min(1)
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u);
const headerValueSchema = z.string().regex(/^[\t\x20-\x7e\x80-\xff]*$/u);
const replayHeaderMatchersSchema = z
.record(headerNameSchema, headerValueSchema)
.superRefine((headers, context) => {
const names = Object.keys(headers).map((name) => name.toLowerCase());
if (new Set(names).size !== names.length)
context.addIssue({
code: "custom",
message: "replay header matchers must be unique ignoring case",
input: headers,
});
if (names.some((name) => sensitiveHeaderNames.has(name)))
context.addIssue({
code: "custom",
message:
"replay header matchers cannot persist authorization or cookie values; capture and guard through a secret alias instead",
input: headers,
});
})
.transform((headers) =>
Object.fromEntries(
Object.entries(headers).map(([name, value]) => [
name.toLowerCase(),
value,
]),
),
);
const replayValueSourceSchema = z.discriminatedUnion("source", [
z.strictObject({
source: z.literal("request_header"),
name: z
.string()
.min(1)
.transform((name) => name.toLowerCase()),
}),
z.strictObject({ source: z.literal("request_json"), path: replayPathSchema }),
z.strictObject({
source: z.literal("websocket_json"),
path: replayPathSchema,
}),
z.strictObject({ source: z.literal("action_json"), path: replayPathSchema }),
]);
const replayTriggerSchema = z.discriminatedUnion("protocol", [
z.strictObject({
protocol: z.literal("http"),
method: z
.string()
.min(1)
.transform((method) => method.toUpperCase()),
path: z.string().startsWith("/"),
headers: replayHeaderMatchersSchema.default({}),
body: z.string().nullable().default(null),
}),
z.strictObject({
protocol: z.literal("websocket_connect"),
path: z.string().startsWith("/"),
headers: replayHeaderMatchersSchema.default({}),
}),
z.strictObject({
protocol: z.literal("websocket_message"),
path: z.string().startsWith("/"),
body: z.string().nullable().default(null),
}),
]);
const replayActionSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("http_response"),
status: z.number().int().min(100).max(599),
headers: z.record(headerNameSchema, headerValueSchema).default({}),
body: z.string(),
}),
z.strictObject({
type: z.literal("websocket_send"),
data: z.string(),
}),
z.strictObject({ type: z.literal("disconnect") }),
z.strictObject({
type: z.literal("delay"),
duration_ms: z.number().int().safe().nonnegative(),
}),
]);
const replayTransitionSchema = z.strictObject({
id: replayIdentifierSchema,
from: replayIdentifierSchema,
to: replayIdentifierSchema,
priority: z.number().int().min(0).default(100),
trigger: replayTriggerSchema,
guards: z
.array(
z.strictObject({
variable: replayIdentifierSchema,
value: replayValueSourceSchema,
}),
)
.default([]),
captures: z
.array(
z.strictObject({
variable: replayIdentifierSchema,
value: replayValueSourceSchema,
sensitive: z.boolean().default(false),
}),
)
.default([]),
actions: z.array(replayActionSchema).min(1),
max_uses: z.number().int().min(1),
});
const transitionSignature = (
transition: z.infer<typeof replayTransitionSchema>,
): string => {
const signature = canonicalize({
from: transition.from,
priority: transition.priority,
trigger: transition.trigger,
});
if (signature === undefined)
throw new TypeError("Replay transition signature is not canonical JSON");
return signature;
};
const replayMachineBaseSchema = z.strictObject({
initial_state: replayIdentifierSchema,
states: z
.array(
z.strictObject({
name: replayIdentifierSchema,
terminal: z.boolean().default(false),
max_visits: z.number().int().min(1).default(100_000),
}),
)
.min(1),
transitions: z.array(replayTransitionSchema).min(1),
max_transitions: z.number().int().min(1),
limits: z
.strictObject({
connections: z.number().int().min(1).default(100),
messages: z.number().int().min(1).default(10_000),
bytes: z.number().int().min(1).default(1_000_000),
duration_ms: z.number().int().min(1).default(30_000),
})
.default({
connections: 100,
messages: 10_000,
bytes: 1_000_000,
duration_ms: 30_000,
}),
});
type ReplayMachineInput = z.infer<typeof replayMachineBaseSchema>;
type ReplayMachineContext = z.core.$RefinementCtx<ReplayMachineInput>;
const validateReplayIdentities = (
machine: ReplayMachineInput,
context: ReplayMachineContext,
): ReadonlySet<string> => {
const names = machine.states.map(({ name }) => name);
const nameSet = new Set(names);
if (nameSet.size !== names.length)
context.addIssue({
code: "custom",
message: "replay machine state names must be unique",
path: ["states"],
input: machine,
});
if (!nameSet.has(machine.initial_state))
context.addIssue({
code: "custom",
message: "replay machine initial state is not declared",
path: ["initial_state"],
input: machine,
});
const transitionIds = machine.transitions.map(({ id }) => id);
if (new Set(transitionIds).size !== transitionIds.length)
context.addIssue({
code: "custom",
message: "replay machine transition IDs must be unique",
path: ["transitions"],
input: machine,
});
const signatures = machine.transitions.map(transitionSignature);
if (new Set(signatures).size !== signatures.length)
context.addIssue({
code: "custom",
message:
"replay machine transitions with the same state, trigger, and priority are ambiguous",
path: ["transitions"],
input: machine,
});
return nameSet;
};
const validateReplayVariables = (
machine: ReplayMachineInput,
context: ReplayMachineContext,
): void => {
const capturedVariables = new Map<string, boolean>();
for (const [transitionIndex, transition] of machine.transitions.entries()) {
for (const capture of transition.captures) {
if (capture.sensitive && capture.value.source === "action_json")
context.addIssue({
code: "custom",
message:
"sensitive replay captures cannot read literal action JSON persisted in the replay plan",
path: ["transitions", transitionIndex, "captures"],
input: machine,
});
const sensitivity = capturedVariables.get(capture.variable);
if (sensitivity !== undefined && sensitivity !== capture.sensitive)
context.addIssue({
code: "custom",
message:
"a replay variable cannot change secret classification between captures",
path: ["transitions", transitionIndex, "captures"],
input: machine,
});
capturedVariables.set(capture.variable, capture.sensitive);
}
}
const availableByState = new Map<string, Set<string>>([
[machine.initial_state, new Set()],
]);
let changed = true;
while (changed) {
changed = false;
for (const transition of machine.transitions) {
const available = availableByState.get(transition.from);
if (
available === undefined ||
transition.guards.some(({ variable }) => !available.has(variable))
)
continue;
const nextAvailable = new Set(available);
for (const { variable } of transition.captures)
nextAvailable.add(variable);
const existing = availableByState.get(transition.to);
if (existing === undefined) {
availableByState.set(transition.to, nextAvailable);
changed = true;
continue;
}
for (const variable of nextAvailable)
if (!existing.has(variable)) {
existing.add(variable);
changed = true;
}
}
}
for (const [transitionIndex, transition] of machine.transitions.entries())
for (const [guardIndex, guard] of transition.guards.entries())
if (!availableByState.get(transition.from)?.has(guard.variable))
context.addIssue({
code: "custom",
message:
"replay guard variable is not captured on an executable path before use",
path: ["transitions", transitionIndex, "guards", guardIndex],
input: machine,
});
};
const validateReplayActions = (
machine: ReplayMachineInput,
context: ReplayMachineContext,
): void => {
for (const [index, transition] of machine.transitions.entries()) {
const httpResponses = transition.actions.filter(
({ type }) => type === "http_response",
).length;
const websocketSends = transition.actions.some(
({ type }) => type === "websocket_send",
);
const invalid =
transition.trigger.protocol === "http"
? httpResponses !== 1 || websocketSends
: httpResponses !== 0;
if (invalid)
context.addIssue({
code: "custom",
message:
"replay actions must match the transition protocol and HTTP transitions require exactly one response",
path: ["transitions", index, "actions"],
input: machine,
});
}
};
const validateReplayGraph = (
machine: ReplayMachineInput,
names: ReadonlySet<string>,
context: ReplayMachineContext,
): void => {
const graph = new MultiDirectedGraph();
for (const name of names) graph.addNode(name);
for (const [index, transition] of machine.transitions.entries()) {
if (!names.has(transition.from) || !names.has(transition.to)) {
context.addIssue({
code: "custom",
message: "replay machine transition references an unknown state",
path: ["transitions", index],
input: machine,
});
continue;
}
graph.addDirectedEdgeWithKey(
`${transition.id}:${String(index)}`,
transition.from,
transition.to,
);
}
if (!graph.hasNode(machine.initial_state)) return;
if (!machine.states.some(({ terminal }) => terminal))
context.addIssue({
code: "custom",
message: "replay machine must declare at least one terminal state",
path: ["states"],
input: machine,
});
const reachable = new Set(
Object.keys(singleSource(graph, machine.initial_state)),
);
reachable.add(machine.initial_state);
for (const [index, state] of machine.states.entries()) {
if (!reachable.has(state.name))
context.addIssue({
code: "custom",
message: "replay machine state is unreachable from the initial state",
path: ["states", index],
input: machine,
});
if (state.terminal && graph.outDegree(state.name) > 0)
context.addIssue({
code: "custom",
message:
"terminal replay machine state cannot have outgoing transitions",
path: ["states", index],
input: machine,
});
if (!state.terminal && graph.outDegree(state.name) === 0)
context.addIssue({
code: "custom",
message: "non-terminal replay machine state has no outgoing transition",
path: ["states", index],
input: machine,
});
}
};
/** Portable finite replay machine with no executable callbacks. */
export const replayMachineSchema = z
.object(replayMachineBaseSchema.shape)
.strict()
.superRefine((machine, context) => {
const names = validateReplayIdentities(machine, context);
validateReplayVariables(machine, context);
validateReplayActions(machine, context);
validateReplayGraph(machine, names, context);
});
export type ReplayMachine = z.infer<typeof replayMachineSchema>;
-503
View File
@@ -1,503 +0,0 @@
import { describe, expect, it } from "vitest";
import {
replayMachineRunInputSchema,
runReplayMachine,
} from "./replayMachineRun.js";
const loginRun = () =>
replayMachineRunInputSchema.parse({
machine: {
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "capture_token",
from: "login",
to: "api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [
{
type: "http_response",
status: 204,
headers: { "x-token": "target-secret" },
body: "target-secret",
},
],
max_uses: 1,
},
{
id: "authorize",
from: "api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{
type: "http_response",
status: 200,
headers: {},
body: "done",
},
],
max_uses: 1,
},
],
max_transitions: 2,
limits: {
connections: 2,
messages: 4,
bytes: 1_000,
duration_ms: 100,
},
},
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 1,
method: "post",
path: "/login",
headers: {},
body: '{"token":"target-secret"}',
},
{
protocol: "http",
connection: "not_applicable",
at_ms: 2,
method: "GET",
path: "/api",
headers: { Authorization: "target-secret" },
body: "",
},
],
});
const parseMachineRun = (machine: unknown, events: unknown[]) =>
replayMachineRunInputSchema.parse({ machine, events });
const httpEvent = (path: string, atMs = 0) => ({
protocol: "http" as const,
connection: "not_applicable" as const,
at_ms: atMs,
method: "GET",
path,
headers: {},
body: "",
});
describe("direct replay machine execution", () => {
it("returns actions, aliases, terminal state, and exact limit use", () => {
const result = runReplayMachine(loginRun());
expect(result).toMatchObject({
initial_state: "login",
final_state: "complete",
terminal: true,
decisions: [
{ event_sequence: 0, outcome: "matched", transition_sequence: 0 },
{ event_sequence: 1, outcome: "matched", transition_sequence: 1 },
],
transition_journal: [
{
transition_id: "capture_token",
captured_aliases: [{ name: "token", sensitive: true }],
},
{
transition_id: "authorize",
captured_aliases: [],
},
],
transition_actions: [
{
transition_id: "capture_token",
actions: [
{
type: "http_response",
status: 204,
headers: { "x-token": "<secret:token>" },
body: "<secret:token>",
},
],
},
{
transition_id: "authorize",
actions: [
{
type: "http_response",
status: 200,
headers: {},
body: "done",
},
],
},
],
limits: {
configured: {
transitions: 2,
connections: 2,
messages: 4,
bytes: 1_000,
duration_ms: 100,
},
usage: {
offered_events: 2,
admitted_events: 2,
transitions: 2,
connections: 0,
messages: 0,
bytes: 25,
last_at_ms: 2,
},
},
});
expect(JSON.stringify(result)).not.toContain("target-secret");
});
it("classifies unmatched and guard-failed events without aborting", () => {
const input = loginRun();
const result = runReplayMachine({
...input,
events: [httpEvent("/missing"), input.events[0]!, httpEvent("/api", 2)],
});
expect(result.decisions.map(({ outcome }) => outcome)).toEqual([
"unmatched",
"matched",
"guard_failed",
]);
});
it("classifies exhausted transitions", () => {
const input = parseMachineRun(
{
initial_state: "active",
states: [
{ name: "active", max_visits: 3 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "retry_once",
from: "active",
to: "active",
trigger: { protocol: "http", method: "GET", path: "/retry" },
actions: [{ type: "http_response", status: 200, body: "retry" }],
max_uses: 1,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [{ type: "http_response", status: 200, body: "done" }],
max_uses: 1,
},
],
max_transitions: 3,
},
[httpEvent("/retry"), httpEvent("/retry", 1)],
);
expect(
runReplayMachine(input).decisions.map(({ outcome }) => outcome),
).toEqual(["matched", "transition_exhausted"]);
});
});
describe("direct replay machine protocol and limits", () => {
it("classifies reconnects that arrive in the wrong state", () => {
const input = parseMachineRun(
{
initial_state: "connected",
states: [
{ name: "connected" },
{ name: "reconnecting" },
{ name: "done", terminal: true },
],
transitions: [
{
id: "disconnect",
from: "connected",
to: "reconnecting",
trigger: {
protocol: "websocket_message",
path: "/socket",
body: "disconnect",
},
actions: [{ type: "disconnect" }],
max_uses: 1,
},
{
id: "reconnect",
from: "reconnecting",
to: "done",
trigger: { protocol: "websocket_connect", path: "/socket" },
actions: [{ type: "websocket_send", data: "ready" }],
max_uses: 1,
},
],
max_transitions: 2,
},
[
{
protocol: "websocket_connect",
connection: "reconnect",
at_ms: 0,
method: null,
path: "/socket",
headers: {},
body: "",
},
],
);
expect(runReplayMachine(input).decisions[0]?.outcome).toBe(
"unexpected_reconnect",
);
});
it("rejects protocol-inconsistent events at the boundary", () => {
const input = loginRun();
expect(
replayMachineRunInputSchema.safeParse({
...input,
events: [{ ...httpEvent("/login"), method: null }],
}).success,
).toBe(false);
expect(
replayMachineRunInputSchema.safeParse({
...input,
events: [
{
...httpEvent("/login"),
protocol: "websocket_connect",
connection: "reconnect",
},
],
}).success,
).toBe(false);
expect(
replayMachineRunInputSchema.safeParse({
...input,
events: [
{
...httpEvent("/login"),
headers: { Authorization: "first", authorization: "second" },
},
],
}).success,
).toBe(false);
});
it("reports limit refusals without committing rejected usage", () => {
const input = loginRun();
const result = runReplayMachine({
...input,
machine: {
...input.machine,
limits: { ...input.machine.limits, bytes: 1 },
},
events: [input.events[0]!],
});
expect(result.decisions).toEqual([
{
event_sequence: 0,
outcome: "limit_exhausted",
transition_sequence: null,
},
]);
expect(result.limits.usage).toMatchObject({
offered_events: 1,
admitted_events: 0,
transitions: 0,
bytes: 0,
});
});
});
/**
* Assert every dispatched action is a websocket_send carrying `body` byte for
* byte. Comparing the serialized size instead would let escaping or padding
* satisfy the assertion even if a body were truncated.
*/
const expectActionsRetained = (
actions: readonly { readonly type: string; readonly data?: string }[],
body: string,
): void => {
expect(actions).toHaveLength(5);
for (const action of actions) {
expect(action.type).toBe("websocket_send");
expect(action.data).toBe(body);
}
expect(
actions.reduce((total, action) => total + (action.data?.length ?? 0), 0),
).toBe(5 * body.length);
};
describe("direct replay machine large inputs", () => {
it("records large repeated actions once instead of amplifying each match", () => {
const largeBody = "x".repeat(1_000_000);
const input = parseMachineRun(
{
initial_state: "active",
states: [
{ name: "active", max_visits: 11 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "repeat",
from: "active",
to: "active",
trigger: { protocol: "http", method: "GET", path: "/repeat" },
actions: [{ type: "http_response", status: 200, body: largeBody }],
max_uses: 10,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [{ type: "http_response", status: 204, body: "" }],
max_uses: 1,
},
],
max_transitions: 11,
},
Array.from({ length: 10 }, (_, index) => httpEvent("/repeat", index)),
);
const result = runReplayMachine(input);
expect(result.transition_journal).toHaveLength(10);
expect(result.transition_actions).toHaveLength(1);
expect(JSON.stringify(result).length).toBeLessThan(1_100_000);
});
it("retains actions above the former four MiB aggregate cap", () => {
const largeBody = "x".repeat(1_000_000);
const parsed = replayMachineRunInputSchema.safeParse({
machine: {
initial_state: "waiting",
states: [{ name: "waiting" }, { name: "done", terminal: true }],
transitions: [
{
id: "send",
from: "waiting",
to: "done",
trigger: { protocol: "websocket_connect", path: "/socket" },
actions: Array.from({ length: 5 }, () => ({
type: "websocket_send",
data: largeBody,
})),
max_uses: 1,
},
],
max_transitions: 1,
},
events: [
{
protocol: "websocket_connect",
connection: "initial",
at_ms: 0,
method: null,
path: "/socket",
headers: {},
body: "",
},
],
});
expect(parsed.success).toBe(true);
if (parsed.success) {
const result = runReplayMachine(parsed.data);
expectActionsRetained(
result.transition_actions[0]?.actions ?? [],
largeBody,
);
}
});
it("accepts event counts and action fields beyond former caps", () => {
const input = loginRun();
const largeEventRun = replayMachineRunInputSchema.safeParse({
...input,
events: Array.from({ length: 10_001 }, (_, index) =>
httpEvent("/missing", index),
),
});
expect(largeEventRun.success).toBe(true);
if (largeEventRun.success)
expect(runReplayMachine(largeEventRun.data).decisions).toHaveLength(
10_001,
);
const largeHeaderTable = replayMachineRunInputSchema.safeParse({
machine: {
initial_state: "waiting",
states: [{ name: "waiting" }, { name: "done", terminal: true }],
transitions: [
{
id: "respond",
from: "waiting",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{
type: "http_response",
status: 200,
headers: Object.fromEntries(
Array.from({ length: 1_024 }, (_, index) => [
`x-field-${String(index)}`,
"",
]),
),
body: "",
},
],
max_uses: 1,
},
],
max_transitions: 1,
},
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 0,
method: "GET",
path: "/done",
headers: {},
body: "",
},
],
});
expect(largeHeaderTable.success).toBe(true);
if (largeHeaderTable.success) {
const result = runReplayMachine(largeHeaderTable.data);
const action = result.transition_actions[0]?.actions[0];
expect(action?.type).toBe("http_response");
if (action?.type === "http_response")
expect(Object.keys(action.headers)).toHaveLength(1_024);
}
});
});
-206
View File
@@ -1,206 +0,0 @@
import { z } from "zod";
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
import {
replayMachineEventSchema,
ReplayMachineRuntime,
} from "./replayMachineRuntime.js";
const refusalOutcomeSchema = z.enum([
"unmatched",
"invalid_state",
"guard_failed",
"transition_exhausted",
"invalid_capture",
"unexpected_reconnect",
"limit_exhausted",
]);
/** Complete declarative input for one direct replay-machine run. */
export const replayMachineRunInputSchema = z.strictObject({
machine: replayMachineSchema,
events: z.array(replayMachineEventSchema),
});
const replayMachineRunDecisionSchema = z.strictObject({
event_sequence: z.number().int().nonnegative(),
outcome: z.union([z.literal("matched"), refusalOutcomeSchema]),
transition_sequence: z.number().int().nonnegative().nullable(),
});
const replayRunActionSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("http_response"),
status: z.number().int().min(100).max(599),
headers: z.record(
z
.string()
.min(1)
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u),
z.string(),
),
body: z.string(),
}),
z.strictObject({
type: z.literal("websocket_send"),
data: z.string(),
}),
z.strictObject({ type: z.literal("disconnect") }),
z.strictObject({
type: z.literal("delay"),
duration_ms: z.number().int().nonnegative(),
}),
]);
const replayRunIdentifierSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u);
const replayMachineRunJournalEntrySchema = z.strictObject({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
transition_id: replayRunIdentifierSchema,
state_before: replayRunIdentifierSchema,
state_after: replayRunIdentifierSchema,
captured_aliases: z.array(
z.strictObject({
name: replayRunIdentifierSchema,
sensitive: z.boolean(),
}),
),
});
/** Capture-value-free result of directly evaluating a finite replay machine. */
export const replayMachineRunOutputSchema = z.strictObject({
initial_state: replayRunIdentifierSchema,
final_state: replayRunIdentifierSchema,
terminal: z.boolean(),
decisions: z.array(replayMachineRunDecisionSchema),
transition_journal: z.array(replayMachineRunJournalEntrySchema),
transition_actions: z.array(
z.strictObject({
transition_id: replayRunIdentifierSchema,
actions: z.array(replayRunActionSchema),
}),
),
limits: z.strictObject({
configured: z.strictObject({
transitions: z.number().int().positive(),
connections: z.number().int().positive(),
messages: z.number().int().positive(),
bytes: z.number().int().positive(),
duration_ms: z.number().int().positive(),
}),
usage: z.strictObject({
offered_events: z.number().int().nonnegative(),
admitted_events: z.number().int().nonnegative(),
transitions: z.number().int().nonnegative(),
connections: z.number().int().nonnegative(),
messages: z.number().int().nonnegative(),
bytes: z.number().int().nonnegative(),
last_at_ms: z.number().int().nonnegative(),
}),
}),
});
export type ReplayMachineRunInput = z.infer<typeof replayMachineRunInputSchema>;
export type ReplayMachineRunOutput = z.infer<
typeof replayMachineRunOutputSchema
>;
type ReplayAction = ReplayMachine["transitions"][number]["actions"][number];
const redactAction = (
runtime: ReplayMachineRuntime,
action: ReplayAction,
): ReplayAction => {
switch (action.type) {
case "http_response":
return {
...action,
headers: Object.fromEntries(
Object.entries(action.headers).map(([name, value]) => [
name,
runtime.redactField(value),
]),
),
body: runtime.redactField(action.body),
};
case "websocket_send":
return { ...action, data: runtime.redactField(action.data) };
case "delay":
case "disconnect":
return action;
}
};
/** Evaluate every supplied event in order without opening sockets or processes. */
export const runReplayMachine = (
input: ReplayMachineRunInput,
): ReplayMachineRunOutput => {
const runtime = new ReplayMachineRuntime(input.machine);
const decisions: ReplayMachineRunOutput["decisions"] = [];
const transitionJournal: ReplayMachineRunOutput["transition_journal"] = [];
const usedTransitionIds = new Set<string>();
const transitionById = new Map(
input.machine.transitions.map((transition) => [transition.id, transition]),
);
for (const [eventSequence, event] of input.events.entries()) {
const decision = runtime.dispatch(event);
decisions.push({
event_sequence: eventSequence,
outcome: decision.outcome,
transition_sequence: decision.transition?.sequence ?? null,
});
if (decision.outcome !== "matched") continue;
usedTransitionIds.add(decision.transition.transition_id);
const definition = transitionById.get(decision.transition.transition_id);
if (definition === undefined)
throw new TypeError("Replay runtime selected an unknown transition");
transitionJournal.push({
sequence: decision.transition.sequence,
at_ms: decision.transition.at_ms,
transition_id: decision.transition.transition_id,
state_before: decision.transition.state_before,
state_after: decision.transition.state_after,
captured_aliases: definition.captures.map(({ variable, sensitive }) => ({
name: variable,
sensitive,
})),
});
}
const usage = runtime.usage;
const transitionActions = input.machine.transitions
.filter(({ id }) => usedTransitionIds.has(id))
.map(({ id, actions }) => ({
transition_id: id,
actions: actions.map((action) => redactAction(runtime, action)),
}));
return replayMachineRunOutputSchema.parse({
initial_state: input.machine.initial_state,
final_state: runtime.state,
terminal:
input.machine.states.find(({ name }) => name === runtime.state)
?.terminal ?? false,
decisions,
transition_journal: transitionJournal,
transition_actions: transitionActions,
limits: {
configured: {
transitions: input.machine.max_transitions,
...input.machine.limits,
},
usage: {
offered_events: input.events.length,
admitted_events: usage.events,
transitions: usage.transitions,
connections: usage.connections,
messages: usage.messages,
bytes: usage.bytes,
last_at_ms: usage.last_at_ms,
},
},
});
};
@@ -1,308 +0,0 @@
import { expect, it } from "vitest";
import { replayMachineSchema } from "./replayMachine.js";
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
const machine = replayMachineSchema.parse({
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "capture_token",
from: "login",
to: "api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "session_value",
value: { source: "request_json", path: ["session_value"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
max_uses: 1,
},
{
id: "authorize_api",
from: "api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "session_value",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{ type: "http_response", status: 200, headers: {}, body: "done" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
const event = (
method: string,
path: string,
body = "",
headers: Readonly<Record<string, string>> = {},
) => ({
protocol: "http" as const,
connection: "not_applicable" as const,
at_ms: 0,
method,
path,
body,
headers,
});
it("compares captured JSON values canonically", () => {
const objectMachine = replayMachineSchema.parse({
initial_state: "capture",
states: [
{ name: "capture" },
{ name: "guard" },
{ name: "done", terminal: true },
],
transitions: [
{
id: "capture_profile",
from: "capture",
to: "guard",
trigger: { protocol: "http", method: "POST", path: "/capture" },
captures: [
{
variable: "profile",
value: { source: "request_json", path: ["profile"] },
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
{
id: "guard_profile",
from: "guard",
to: "done",
trigger: { protocol: "http", method: "POST", path: "/guard" },
guards: [
{
variable: "profile",
value: { source: "request_json", path: ["profile"] },
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
const runtime = new ReplayMachineRuntime(objectMachine);
expect(
runtime.dispatch(
event("POST", "/capture", '{"profile":{"name":"A","id":1}}'),
),
).toMatchObject({ outcome: "matched" });
expect(
runtime.dispatch(
event("POST", "/guard", '{"profile":{"id":1,"name":"A"}}'),
),
).toMatchObject({ outcome: "matched" });
});
it("does not traverse inherited properties in JSON capture paths", () => {
const inheritedPathMachine = replayMachineSchema.parse({
...machine,
transitions: machine.transitions.map((transition, index) =>
index === 0
? {
...transition,
captures: [
{
variable: "session_value",
value: {
source: "request_json" as const,
path: ["__proto__", "toString"],
},
sensitive: true,
},
],
}
: transition,
),
});
expect(
new ReplayMachineRuntime(inheritedPathMachine).dispatch(
event("POST", "/login", "{}"),
),
).toMatchObject({ outcome: "invalid_capture" });
});
it("rejects non-string sensitive captures and retains rotated values", () => {
expect(
new ReplayMachineRuntime(machine).dispatch(
event("POST", "/login", '{"session_value":1234}'),
),
).toMatchObject({ outcome: "invalid_capture" });
const rotatingMachine = replayMachineSchema.parse({
initial_state: "active",
states: [
{ name: "active", max_visits: 3 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "rotate",
from: "active",
to: "active",
trigger: { protocol: "http", method: "POST", path: "/rotate" },
captures: [
{
variable: "session_value",
value: { source: "request_json", path: ["value"] },
sensitive: true,
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 2,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
],
max_transitions: 3,
});
const rotating = new ReplayMachineRuntime(rotatingMachine);
rotating.dispatch(event("POST", "/rotate", '{"value":"alpha"}'));
rotating.dispatch(event("POST", "/rotate", '{"value":"beta"}'));
const alias = ["<", "secret", ":session_value>"].join("");
expect(rotating.redact("alpha beta")).toBe(`${alias} ${alias}`);
});
it("falls back to a lower-priority transition after a preferred one is exhausted", () => {
const fallbackMachine = replayMachineSchema.parse({
initial_state: "active",
states: [
{ name: "active", max_visits: 2 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "preferred",
from: "active",
to: "active",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/next" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "again" },
],
max_uses: 1,
},
{
id: "fallback",
from: "active",
to: "done",
priority: 20,
trigger: { protocol: "http", method: "GET", path: "/next" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "done" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
const runtime = new ReplayMachineRuntime(fallbackMachine);
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
outcome: "matched",
transition: { transition_id: "preferred" },
});
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
outcome: "matched",
transition: { transition_id: "fallback" },
});
});
it("rejects non-finite parsed JSON captures and guard values", () => {
const jsonMachine = replayMachineSchema.parse({
initial_state: "capture",
states: [
{ name: "capture" },
{ name: "guard" },
{ name: "done", terminal: true },
],
transitions: [
{
id: "capture_value",
from: "capture",
to: "guard",
trigger: { protocol: "http", method: "POST", path: "/capture" },
captures: [
{
variable: "value",
value: { source: "request_json", path: ["value"] },
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
{
id: "guard_value",
from: "guard",
to: "done",
trigger: { protocol: "http", method: "POST", path: "/guard" },
guards: [
{
variable: "value",
value: { source: "request_json", path: ["value"] },
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
expect(
new ReplayMachineRuntime(jsonMachine).dispatch(
event("POST", "/capture", '{"value":1e400}'),
),
).toMatchObject({ outcome: "invalid_capture" });
const guarded = new ReplayMachineRuntime(jsonMachine);
expect(
guarded.dispatch(event("POST", "/capture", '{"value":null}')),
).toMatchObject({ outcome: "matched" });
expect(
guarded.dispatch(event("POST", "/guard", '{"value":1e400}')),
).toMatchObject({ outcome: "guard_failed" });
});
-333
View File
@@ -1,333 +0,0 @@
import { expect, it } from "vitest";
import { replayMachineSchema } from "./replayMachine.js";
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
const machine = replayMachineSchema.parse({
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "capture_token",
from: "login",
to: "api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "session_value",
value: { source: "request_json", path: ["session_value"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
max_uses: 1,
},
{
id: "authorize_api",
from: "api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "session_value",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{ type: "http_response", status: 200, headers: {}, body: "done" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
const event = (
method: string,
path: string,
body = "",
headers: Readonly<Record<string, string>> = {},
) => ({
protocol: "http" as const,
connection: "not_applicable" as const,
at_ms: 0,
method,
path,
body,
headers,
});
it("captures secret values in memory and journals aliases only", () => {
const runtime = new ReplayMachineRuntime(machine);
expect(
runtime.dispatch(
event("POST", "/login", '{"session_value":"test-auth-token"}'),
),
).toMatchObject({
outcome: "matched",
transition: {
transition_id: "capture_token",
sensitive_aliases: ["session_value"],
},
});
const expectedRedaction = ["Bearer <", "secret", ":session_value>"].join("");
expect(runtime.redact("Bearer test-auth-token")).toBe(expectedRedaction);
expect(
runtime.dispatch(
event("GET", "/api", "", { Authorization: "test-auth-token" }),
),
).toMatchObject({ outcome: "matched" });
expect(JSON.stringify(runtime.timeline)).not.toContain("test-auth-token");
expect(runtime.state).toBe("complete");
});
it("classifies wrong-state, guard, capture, and exhaustion failures", () => {
expect(
new ReplayMachineRuntime(machine).dispatch(event("GET", "/api")),
).toMatchObject({ outcome: "invalid_state" });
expect(
new ReplayMachineRuntime(machine).dispatch(event("POST", "/login", "{}")),
).toMatchObject({ outcome: "invalid_capture" });
const runtime = new ReplayMachineRuntime(machine);
runtime.dispatch(
event("POST", "/login", '{"session_value":"test-auth-token"}'),
);
expect(
runtime.dispatch(
event("GET", "/api", "", {
authorization: "test-token-placeholder",
}),
),
).toMatchObject({
outcome: "guard_failed",
});
const bounded = new ReplayMachineRuntime(
replayMachineSchema.parse({
initial_state: "active",
states: [{ name: "active" }, { name: "done", terminal: true }],
transitions: [
{
id: "once",
from: "active",
to: "active",
trigger: { protocol: "http", method: "GET", path: "/once" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
],
max_transitions: 2,
}),
);
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
outcome: "matched",
});
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
outcome: "transition_exhausted",
});
});
it("matches bounded headers and bodies and distinguishes wrong-state reconnects", () => {
const runtime = new ReplayMachineRuntime(
replayMachineSchema.parse({
initial_state: "connected",
states: [{ name: "connected" }, { name: "done", terminal: true }],
transitions: [
{
id: "finish",
from: "connected",
to: "done",
trigger: {
protocol: "http",
method: "POST",
path: "/finish",
headers: { "content-type": "application/json" },
body: '{"done":true}',
},
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
{
id: "initial_socket",
from: "connected",
to: "connected",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "disconnect" }],
max_uses: 1,
},
],
max_transitions: 2,
}),
);
expect(runtime.dispatch(event("POST", "/finish", "wrong"))).toMatchObject({
outcome: "unmatched",
});
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "initial",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "matched" });
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "reconnect",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "transition_exhausted" });
expect(
runtime.dispatch(
event("POST", "/finish", '{"done":true}', {
"content-type": "application/json",
}),
),
).toMatchObject({ outcome: "matched" });
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "reconnect",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "unexpected_reconnect" });
});
it("enforces state, connection, message, byte, and duration limits", () => {
const limitedMachine = replayMachineSchema.parse({
initial_state: "active",
states: [
{ name: "active", max_visits: 1 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "loop",
from: "active",
to: "active",
trigger: { protocol: "websocket_message", path: "/ws" },
actions: [{ type: "websocket_send", data: "ack" }],
max_uses: 2,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
],
max_transitions: 3,
limits: { connections: 1, messages: 1, bytes: 100, duration_ms: 10 },
});
const stateLimited = new ReplayMachineRuntime(limitedMachine);
expect(
stateLimited.dispatch({
protocol: "websocket_message",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "one",
}),
).toMatchObject({ outcome: "limit_exhausted" });
const messageLimited = new ReplayMachineRuntime(
replayMachineSchema.parse({
...limitedMachine,
states: limitedMachine.states.map((state) =>
state.name === "active" ? { ...state, max_visits: 3 } : state,
),
}),
);
const message = {
protocol: "websocket_message" as const,
connection: "not_applicable" as const,
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "one",
};
expect(messageLimited.dispatch(message)).toMatchObject({
outcome: "matched",
});
expect(messageLimited.dispatch(message)).toMatchObject({
outcome: "limit_exhausted",
});
const durationLimited = new ReplayMachineRuntime(limitedMachine);
expect(
durationLimited.dispatch({ ...event("GET", "/done"), at_ms: 11 }),
).toMatchObject({ outcome: "limit_exhausted" });
expect(
new ReplayMachineRuntime(limitedMachine).dispatch({
...event("GET", "/done"),
at_ms: Number.NaN,
}),
).toMatchObject({ outcome: "limit_exhausted" });
const monotonic = new ReplayMachineRuntime(limitedMachine);
expect(
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 5 }),
).toMatchObject({ outcome: "unmatched" });
expect(
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 4 }),
).toMatchObject({ outcome: "limit_exhausted" });
const byteLimited = new ReplayMachineRuntime(
replayMachineSchema.parse({
...limitedMachine,
limits: { ...limitedMachine.limits, bytes: 4 },
}),
);
expect(byteLimited.dispatch(event("GET", "/missing", "12345"))).toMatchObject(
{ outcome: "limit_exhausted" },
);
const connectionLimited = new ReplayMachineRuntime(limitedMachine);
const connect = {
protocol: "websocket_connect" as const,
connection: "initial" as const,
at_ms: 0,
method: null,
path: "/unknown",
headers: {},
body: "",
};
expect(connectionLimited.dispatch(connect)).toMatchObject({
outcome: "unmatched",
});
expect(
connectionLimited.dispatch({ ...connect, connection: "reconnect" }),
).toMatchObject({ outcome: "limit_exhausted" });
});
-462
View File
@@ -1,462 +0,0 @@
import { z } from "zod";
import type { ReplayMachine } from "./replayMachine.js";
import { isJsonCompatible, replayValuesEqual } from "./replayMachineValues.js";
type ReplayTransition = ReplayMachine["transitions"][number];
type IndexedReplayTransition = {
readonly transition: ReplayTransition;
readonly declarationOrder: number;
};
type ReplayValueSource = ReplayTransition["captures"][number]["value"];
interface TransitionRecordOptions {
readonly sequence: number;
readonly atMs: number;
readonly stateBefore: string;
readonly transition: ReplayTransition;
readonly captures: readonly {
readonly variable: string;
readonly sensitive: boolean;
}[];
}
/** One bounded inbound protocol event offered to a replay machine. */
const replayEventHeadersSchema = z
.record(
z
.string()
.min(1)
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u),
z.string().regex(/^[\t\x20-\x7e\x80-\xff]*$/u),
)
.superRefine((headers, context) => {
const normalized = Object.keys(headers).map((name) => name.toLowerCase());
if (new Set(normalized).size !== normalized.length)
context.addIssue({
code: "custom",
message: "replay event headers must be unique ignoring case",
input: headers,
});
});
const replayEventFields = {
at_ms: z.number().int().safe().nonnegative(),
path: z.string().startsWith("/"),
headers: replayEventHeadersSchema,
body: z.string(),
};
export const replayMachineEventSchema = z.discriminatedUnion("protocol", [
z.strictObject({
protocol: z.literal("http"),
connection: z.literal("not_applicable"),
method: z
.string()
.min(1)
.transform((method) => method.toUpperCase()),
...replayEventFields,
}),
z.strictObject({
protocol: z.literal("websocket_connect"),
connection: z.enum(["initial", "reconnect"]),
method: z.null(),
...replayEventFields,
}),
z.strictObject({
protocol: z.literal("websocket_message"),
connection: z.enum(["initial", "reconnect"]),
method: z.null(),
...replayEventFields,
}),
]);
/** One bounded inbound protocol event offered to a replay machine. */
export interface ReplayMachineEvent {
readonly protocol: "http" | "websocket_connect" | "websocket_message";
readonly connection: "not_applicable" | "initial" | "reconnect";
readonly at_ms: number;
readonly recorded_at_ms?: number;
readonly method: string | null;
readonly path: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: string;
}
/** Runtime counters committed only for events admitted by all machine limits. */
export interface ReplayMachineUsage {
readonly events: number;
readonly transitions: number;
readonly connections: number;
readonly messages: number;
readonly bytes: number;
readonly last_at_ms: number;
}
/** Persistable transition journal entry containing aliases, never secrets. */
export interface ReplayTransitionRecord {
readonly sequence: number;
readonly at_ms: number;
readonly transition_id: string;
readonly state_before: string;
readonly state_after: string;
readonly sensitive_aliases: readonly string[];
}
/** Result of dispatching one event through a replay machine. */
export type ReplayMachineDecision =
| {
readonly outcome: "matched";
readonly actions: ReplayTransition["actions"];
readonly transition: ReplayTransitionRecord;
}
| {
readonly outcome:
| "unmatched"
| "invalid_state"
| "guard_failed"
| "transition_exhausted"
| "invalid_capture"
| "unexpected_reconnect"
| "limit_exhausted";
readonly actions: readonly [];
readonly transition: null;
};
const parseJson = (value: string): unknown => {
try {
const parsed: unknown = JSON.parse(value);
return parsed;
} catch {
return undefined;
}
};
const atPath = (
value: unknown,
path: readonly (string | number)[],
): unknown => {
let current = value;
for (const segment of path) {
if (typeof segment === "number") {
if (!Array.isArray(current)) return undefined;
current = current[segment];
continue;
}
if (
typeof current !== "object" ||
current === null ||
!Object.hasOwn(current, segment)
)
return undefined;
const next: unknown = Reflect.get(current, segment);
current = next;
}
return current;
};
const actionJsonBody = (transition: ReplayTransition): string | undefined => {
for (const action of transition.actions)
if (action.type === "http_response") return action.body;
else if (action.type === "websocket_send") return action.data;
return undefined;
};
const triggerKey = (transition: ReplayTransition): string =>
`${transition.trigger.protocol}\0${transition.trigger.path}`;
const readValue = (
source: ReplayValueSource,
event: ReplayMachineEvent,
transition: ReplayTransition,
): unknown => {
switch (source.source) {
case "request_header":
return event.headers[source.name.toLowerCase()];
case "request_json":
return atPath(parseJson(event.body), source.path);
case "websocket_json":
return atPath(parseJson(event.body), source.path);
case "action_json": {
const body = actionJsonBody(transition);
return body === undefined
? undefined
: atPath(parseJson(body), source.path);
}
}
};
const triggerMatches = (
transition: ReplayTransition,
event: ReplayMachineEvent,
): boolean => {
const trigger = transition.trigger;
if (trigger.protocol !== event.protocol || trigger.path !== event.path)
return false;
if (
"headers" in trigger &&
Object.entries(trigger.headers).some(
([name, value]) => event.headers[name.toLowerCase()] !== value,
)
)
return false;
if (trigger.protocol === "http")
return (
trigger.method === event.method &&
(trigger.body === null || trigger.body === event.body)
);
if (trigger.protocol === "websocket_message")
return trigger.body === null || trigger.body === event.body;
return true;
};
const createTransitionRecord = ({
sequence,
atMs,
stateBefore,
transition,
captures,
}: TransitionRecordOptions): ReplayTransitionRecord => ({
sequence,
at_ms: atMs,
transition_id: transition.id,
state_before: stateBefore,
state_after: transition.to,
sensitive_aliases: captures
.filter(({ sensitive }) => sensitive)
.map(({ variable }) => variable)
.sort(),
});
/** Stateful evaluator for one validated replay-machine instance. */
export class ReplayMachineRuntime {
readonly #transitionsByTrigger = new Map<
string,
readonly IndexedReplayTransition[]
>();
readonly #variables = new Map<string, unknown>();
readonly #sensitiveValues = new Map<string, Set<string>>();
readonly #uses = new Map<string, number>();
readonly #stateVisits = new Map<string, number>();
readonly #timeline: ReplayTransitionRecord[] = [];
#state: string;
#connections = 0;
#messages = 0;
#bytes = 0;
#lastAtMs = 0;
#events = 0;
constructor(readonly machine: ReplayMachine) {
this.#state = machine.initial_state;
this.#stateVisits.set(machine.initial_state, 1);
const byTrigger = new Map<string, IndexedReplayTransition[]>();
for (const [
declarationOrder,
transition,
] of machine.transitions.entries()) {
const key = triggerKey(transition);
const indexed = byTrigger.get(key) ?? [];
indexed.push({ transition, declarationOrder });
byTrigger.set(key, indexed);
}
for (const [key, indexed] of byTrigger)
this.#transitionsByTrigger.set(
key,
indexed.sort(
(left, right) =>
left.transition.priority - right.transition.priority ||
left.declarationOrder - right.declarationOrder,
),
);
}
/** Current machine state after all accepted transitions. */
get state(): string {
return this.#state;
}
/** Ordered, secret-free transition records. */
get timeline(): readonly ReplayTransitionRecord[] {
return this.#timeline;
}
/** Current committed use of the machine's declared limits. */
get usage(): ReplayMachineUsage {
return {
events: this.#events,
transitions: this.#timeline.length,
connections: this.#connections,
messages: this.#messages,
bytes: this.#bytes,
last_at_ms: this.#lastAtMs,
};
}
/** Replace captured secret values with stable aliases before persistence. */
redact(value: string): string {
let redacted = value;
const secrets = [...this.#sensitiveValues]
.flatMap(([variable, values]) =>
[...values].map((secret) => ({ variable, secret })),
)
.sort(
(left, right) =>
right.secret.length - left.secret.length ||
left.variable.localeCompare(right.variable),
);
for (const { variable, secret } of secrets)
redacted = redacted.replaceAll(secret, `<secret:${variable}>`);
return redacted;
}
/** Replace a field containing captured secrets with one stable alias only. */
redactField(value: string): string {
const alias = [...this.#sensitiveValues]
.filter(([, values]) =>
[...values].some((secret) => value.includes(secret)),
)
.map(([variable]) => variable)
.sort()[0];
return alias === undefined ? value : `<secret:${alias}>`;
}
/** Evaluate and, when admitted, commit one protocol event. */
dispatch(event: ReplayMachineEvent): ReplayMachineDecision {
const normalizedEvent = {
...event,
headers: Object.fromEntries(
Object.entries(event.headers).map(([name, value]) => [
name.toLowerCase(),
value,
]),
),
};
if (!this.#admitEvent(normalizedEvent))
return this.#refusal("limit_exhausted");
const matching = this.#matchingTransitions(normalizedEvent);
const eligible = matching.filter(({ transition }) =>
this.#transitionStartsHere(transition),
);
if (eligible.length === 0)
return this.#refusal(this.#noEligibleReason(matching, normalizedEvent));
const guarded = eligible.filter(({ transition }) =>
this.#transitionGuardsMatch(transition, normalizedEvent),
);
if (guarded.length === 0) return this.#refusal("guard_failed");
if (this.#timeline.length >= this.machine.max_transitions)
return this.#refusal("transition_exhausted");
const usable = guarded.find(
({ transition }) =>
(this.#uses.get(transition.id) ?? 0) < transition.max_uses,
);
if (usable === undefined) return this.#refusal("transition_exhausted");
const transition = usable.transition;
const used = this.#uses.get(transition.id) ?? 0;
const nextState = this.machine.states.find(
({ name }) => name === transition.to,
);
const nextVisits = (this.#stateVisits.get(transition.to) ?? 0) + 1;
if (nextState === undefined || nextVisits > nextState.max_visits)
return this.#refusal("limit_exhausted");
const captures = transition.captures.map((capture) => ({
...capture,
captured: readValue(capture.value, normalizedEvent, transition),
}));
if (
captures.some(
({ captured, sensitive }) =>
!isJsonCompatible(captured) ||
(sensitive && typeof captured !== "string"),
)
)
return this.#refusal("invalid_capture");
for (const capture of captures) {
this.#variables.set(capture.variable, capture.captured);
if (capture.sensitive && typeof capture.captured === "string") {
const values = this.#sensitiveValues.get(capture.variable) ?? new Set();
if (capture.captured.length > 0) values.add(capture.captured);
this.#sensitiveValues.set(capture.variable, values);
}
}
const record = createTransitionRecord({
sequence: this.#timeline.length,
atMs: normalizedEvent.recorded_at_ms ?? normalizedEvent.at_ms,
stateBefore: this.#state,
transition,
captures,
});
this.#uses.set(transition.id, used + 1);
this.#stateVisits.set(transition.to, nextVisits);
this.#state = transition.to;
this.#timeline.push(record);
return {
outcome: "matched",
actions: transition.actions,
transition: record,
};
}
#matchingTransitions(
event: ReplayMachineEvent,
): readonly IndexedReplayTransition[] {
return (
this.#transitionsByTrigger.get(`${event.protocol}\0${event.path}`) ?? []
).filter(({ transition }) => triggerMatches(transition, event));
}
#transitionStartsHere(transition: ReplayTransition): boolean {
return transition.from === this.#state;
}
#noEligibleReason(
matching: readonly IndexedReplayTransition[],
event: ReplayMachineEvent,
): "unmatched" | "unexpected_reconnect" | "invalid_state" {
if (matching.length === 0) return "unmatched";
return event.protocol === "websocket_connect" &&
event.connection === "reconnect"
? "unexpected_reconnect"
: "invalid_state";
}
#transitionGuardsMatch(
transition: ReplayTransition,
event: ReplayMachineEvent,
): boolean {
return transition.guards.every((guard) => {
if (!this.#variables.has(guard.variable)) return false;
return replayValuesEqual(
this.#variables.get(guard.variable),
readValue(guard.value, event, transition),
);
});
}
#admitEvent(event: ReplayMachineEvent): boolean {
const connections =
this.#connections + (event.protocol === "websocket_connect" ? 1 : 0);
const messages =
this.#messages + (event.protocol === "websocket_message" ? 1 : 0);
const bytes = this.#bytes + Buffer.byteLength(event.body);
if (
!Number.isSafeInteger(event.at_ms) ||
event.at_ms < this.#lastAtMs ||
event.at_ms > this.machine.limits.duration_ms ||
connections > this.machine.limits.connections ||
messages > this.machine.limits.messages ||
bytes > this.machine.limits.bytes
)
return false;
this.#connections = connections;
this.#messages = messages;
this.#bytes = bytes;
this.#lastAtMs = event.at_ms;
this.#events += 1;
return true;
}
#refusal(
outcome: Exclude<ReplayMachineDecision["outcome"], "matched">,
): ReplayMachineDecision {
return { outcome, actions: [], transition: null };
}
}
-129
View File
@@ -1,129 +0,0 @@
import { describe, expect, it } from "vitest";
import { replayMachineSchema } from "./replayMachine.js";
const websocketActions = (count: number) =>
Array.from({ length: count }, () => ({
type: "websocket_send" as const,
data: "ok",
}));
const websocketMachine = () => ({
initial_state: "start",
states: [
{ name: "start" },
{ name: "active", max_visits: 100_001 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "begin",
from: "start",
to: "active",
trigger: { protocol: "websocket_connect", path: "/begin" },
actions: websocketActions(1),
max_uses: 10_001,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "websocket_message", path: "/finish" },
actions: websocketActions(1),
max_uses: 10_001,
},
],
max_transitions: 100_001,
limits: {
connections: 1_001,
messages: 100_001,
bytes: 10_000_001,
duration_ms: 300_001,
},
});
describe("finite replay machine schema input size", () => {
it("accepts states, transitions, guards, captures, actions, and paths beyond old caps", () => {
const states: { name: string; terminal?: boolean }[] = Array.from(
{ length: 257 },
(_, index) => ({
name: `state-${index}`,
}),
);
states.push({ name: "complete", terminal: true });
const transitions = Array.from({ length: 257 }, (_, index) => ({
id: `chain-${index}`,
from: `state-${index}`,
to: index === 256 ? "complete" : `state-${index + 1}`,
trigger: { protocol: "http", method: "GET", path: `/chain-${index}` },
actions: [{ type: "http_response", status: 200, body: "" }],
max_uses: 10_001,
}));
transitions.push(
...Array.from({ length: 1_745 }, (_, index) => ({
id: `loop-${index}`,
from: "state-0",
to: "state-0",
trigger: { protocol: "http", method: "GET", path: `/loop-${index}` },
actions: [{ type: "http_response", status: 200, body: "" }],
max_uses: 10_001,
})),
);
const parsed = replayMachineSchema.safeParse({
initial_state: "state-0",
states,
transitions,
max_transitions: 100_001,
limits: {
connections: 1_001,
messages: 100_001,
bytes: 10_000_001,
duration_ms: 300_001,
},
});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.states).toHaveLength(258);
expect(parsed.data.transitions).toHaveLength(2_002);
}
});
it("accepts over 32 guards, captures, actions, and path segments", () => {
const path = Array.from({ length: 33 }, (_, index) => `key-${index}`);
const input = websocketMachine();
const machine = {
...input,
transitions: [
{
id: "capture",
from: "start",
to: "active",
trigger: { protocol: "websocket_connect", path: "/begin" },
captures: Array.from({ length: 33 }, () => ({
variable: "value",
value: { source: "request_json", path },
sensitive: false,
})),
actions: websocketActions(33),
max_uses: 10_001,
},
{
id: "guarded-finish",
from: "active",
to: "done",
trigger: { protocol: "websocket_message", path: "/finish" },
guards: Array.from({ length: 33 }, () => ({
variable: "value",
value: { source: "request_json", path },
})),
actions: websocketActions(33),
max_uses: 10_001,
},
],
};
expect(replayMachineSchema.safeParse(machine).success).toBe(true);
});
});
-93
View File
@@ -1,93 +0,0 @@
/** Compare JSON-compatible replay values without recursive stack growth. */
export const replayValuesEqual = (left: unknown, right: unknown): boolean => {
const pending: [unknown, unknown][] = [[left, right]];
while (pending.length > 0) {
const pair = pending.pop();
if (pair === undefined) continue;
const [currentLeft, currentRight] = pair;
const primitive = equalPrimitiveReplayValues(currentLeft, currentRight);
if (primitive !== undefined) {
if (!primitive) return false;
continue;
}
const array = compareReplayArrays(currentLeft, currentRight, pending);
if (array !== undefined) {
if (!array) return false;
continue;
}
if (!compareReplayRecords(currentLeft, currentRight, pending)) return false;
}
return true;
};
/** Check that captured values can be serialized as JSON without recursion. */
export const isJsonCompatible = (value: unknown): boolean => {
const pending: unknown[] = [value];
while (pending.length > 0) {
const candidate = pending.pop();
if (
candidate === null ||
typeof candidate === "string" ||
typeof candidate === "boolean"
)
continue;
if (typeof candidate === "number") {
if (!Number.isFinite(candidate)) return false;
continue;
}
if (Array.isArray(candidate)) {
for (const item of candidate) pending.push(item);
continue;
}
if (typeof candidate !== "object") return false;
for (const item of Object.values(candidate)) pending.push(item);
}
return true;
};
const equalPrimitiveReplayValues = (
left: unknown,
right: unknown,
): boolean | undefined => {
if (left === null || typeof left === "string" || typeof left === "boolean")
return left === right;
if (typeof left !== "number") return undefined;
return (
Number.isFinite(left) &&
left === right &&
typeof right === "number" &&
Number.isFinite(right)
);
};
const compareReplayArrays = (
left: unknown,
right: unknown,
pending: [unknown, unknown][],
): boolean | undefined => {
if (!Array.isArray(left)) return undefined;
if (!Array.isArray(right) || left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1)
pending.push([left[index], right[index]]);
return true;
};
const compareReplayRecords = (
left: unknown,
right: unknown,
pending: [unknown, unknown][],
): boolean | undefined => {
if (typeof left !== "object" || left === null) return undefined;
if (typeof right !== "object" || right === null || Array.isArray(right))
return false;
const leftKeys = Object.keys(left).sort();
const rightKeys = Object.keys(right).sort();
if (
leftKeys.length !== rightKeys.length ||
leftKeys.some((key, index) => key !== rightKeys[index])
)
return false;
for (const key of leftKeys)
pending.push([Reflect.get(left, key), Reflect.get(right, key)]);
return true;
};
@@ -1,63 +0,0 @@
import { describe, expect, it } from "vitest";
import {
createRuntimeCharacterizationPlan,
parseRuntimeCharacterizationPlan,
} from "./runtimeCharacterization.js";
const digest = (character: string): string => character.repeat(64);
describe("provider-neutral runtime characterization plan", () => {
it("commits the selected preparation inputs", () => {
const plan = createRuntimeCharacterizationPlan({
preparation_sha256: digest("5"),
artifact: {
path: "/approved/app.js",
sha256: digest("1"),
byte_length: 100,
},
runtime: {
family: "ecmascript",
provider_id: "node-javascript",
executable_path: "/usr/bin/node",
executable_sha256: digest("2"),
version: "v24.18.0",
profile_sha256: digest("3"),
},
callable: {
callable_id: "bundle.module7.hidden",
module_id: "bundle.module7",
export_name: "selected",
semantic_evidence_id: null,
selector_sha256: digest("4"),
},
working_directory: "/owned/work",
isolated_home: "/owned/home",
expected_effect: "pure",
allowed_boundaries: [],
limits: {
max_calls: 2,
max_processes: 0,
max_files: 0,
max_bytes: 65_536,
max_handles: 32,
timeout_ms: 5_000,
idle_timeout_ms: 1_000,
},
determinism: {
clock: "fixed",
randomness: "seeded",
identifiers: "deterministic",
seed: 7,
},
});
expect(parseRuntimeCharacterizationPlan(plan)).toEqual(plan);
expect(() =>
parseRuntimeCharacterizationPlan({
...plan,
expected_effect: "bounded-effects",
}),
).toThrow(/digest is invalid/u);
});
});
-95
View File
@@ -1,95 +0,0 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { digestSchema } from "./../domain/digests.js";
const stableIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._:/-]*$/u);
const runtimeIdentitySchema = z.strictObject({
family: z.string().trim().min(1),
provider_id: stableIdSchema,
executable_path: z.string().min(1),
executable_sha256: digestSchema,
version: z.string().trim().min(1),
profile_sha256: digestSchema,
});
const artifactIdentitySchema = z.strictObject({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
});
const callableIdentitySchema = z.strictObject({
callable_id: stableIdSchema,
module_id: stableIdSchema,
export_name: z.string().min(1),
semantic_evidence_id: z
.string()
.regex(/^ev_[a-f0-9]{64}$/u)
.nullable(),
selector_sha256: digestSchema,
});
export const runtimeCharacterizationPlanSchema = z.strictObject({
plan_sha256: digestSchema,
preparation_sha256: digestSchema,
artifact: artifactIdentitySchema,
runtime: runtimeIdentitySchema,
callable: callableIdentitySchema,
working_directory: z.string().min(1),
isolated_home: z.string().min(1),
expected_effect: z.enum(["pure", "bounded-effects", "observation-only"]),
allowed_boundaries: z.array(stableIdSchema),
limits: z.strictObject({
max_calls: z.number().int().min(1),
max_processes: z.number().int().min(0),
max_files: z.number().int().min(0),
max_bytes: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
max_handles: z.number().int().min(0),
timeout_ms: z.number().int().min(1),
idle_timeout_ms: z.number().int().min(1),
}),
determinism: z.strictObject({
clock: z.enum(["fixed", "real"]),
randomness: z.enum(["seeded", "system"]),
identifiers: z.enum(["deterministic", "runtime"]),
seed: z.number().int().min(0).max(0xffff_ffff),
}),
});
export type RuntimeCharacterizationPlan = z.infer<
typeof runtimeCharacterizationPlanSchema
>;
/** Commit a provider-neutral preparation plan; execution checks the resulting content identity. */
export const createRuntimeCharacterizationPlan = (
input: Omit<z.input<typeof runtimeCharacterizationPlanSchema>, "plan_sha256">,
): RuntimeCharacterizationPlan => {
const parsed = runtimeCharacterizationPlanSchema
.omit({ plan_sha256: true })
.parse(input);
return runtimeCharacterizationPlanSchema.parse({
...parsed,
plan_sha256: digest(parsed),
});
};
/** Parse a characterization plan and reject altered commitments. */
export const parseRuntimeCharacterizationPlan = (
input: unknown,
): RuntimeCharacterizationPlan => {
const parsed = runtimeCharacterizationPlanSchema.parse(input);
const { plan_sha256: planSha256, ...semantic } = parsed;
if (planSha256 !== digest(semantic))
throw new TypeError("Runtime characterization plan digest is invalid");
return parsed;
};
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Runtime characterization plan is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+9 -7
View File
@@ -5,6 +5,7 @@ import { createEvidence, type Evidence } from "./evidence.js";
import type { JsonValue } from "./jsonValue.js";
import {
correlateStaticAndRuntime,
staticRuntimeCorrelationInputSchema,
staticRuntimeCorrelationResultSchema,
} from "./staticRuntimeCorrelation.js";
@@ -44,9 +45,7 @@ const processComparison = (
interaction: terminal === "truncated" ? "truncated" : "unchanged",
exit: terminal === "truncated" ? "truncated" : "unchanged",
filesystem: terminal === "truncated" ? "truncated" : "unchanged",
protocol: terminal === "truncated" ? "truncated" : "unchanged",
process: terminal === "truncated" ? "truncated" : "unchanged",
shim: terminal === "truncated" ? "truncated" : "unchanged",
first_divergence:
terminal === "changed"
? {
@@ -88,7 +87,7 @@ const processComparison = (
const mapping = (
runtime: Evidence,
expected: "cochanged" | "static_only" | "runtime_only" | "both_unchanged",
dimension: "terminal" | "interaction" | "exit" | "shim" = "terminal",
dimension: string = "terminal",
) => ({
static_comparisons: [staticComparison],
runtime_comparisons: [runtime],
@@ -115,14 +114,17 @@ const mapping = (
});
describe("static/runtime correlation", () => {
it("accepts interaction and shim runtime dimensions", () => {
it("accepts real runtime dimensions and rejects removed protocol dimensions", () => {
const runtime = processComparison("unchanged");
expect(
correlateStaticAndRuntime(mapping(runtime, "static_only", "interaction")),
).toMatchObject({ status: "correlated" });
expect(
correlateStaticAndRuntime(mapping(runtime, "static_only", "shim")),
).toMatchObject({ status: "correlated" });
for (const dimension of ["protocol", "shim"] as const)
expect(
staticRuntimeCorrelationInputSchema.safeParse(
mapping(runtime, "static_only", dimension),
).success,
).toBe(false);
});
it("keeps consistent cochange as a hypothesis with complete citations", () => {
+2 -9
View File
@@ -11,6 +11,7 @@ import {
comparisonStatusSchema,
processCaptureComparisonSchema,
} from "./processCapture.js";
import { PROCESS_COMPARISON_DIMENSIONS } from "./processComparison.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
@@ -24,15 +25,7 @@ const functionDimensionSchema = z.enum([
"strings_names",
"cfg",
]);
const runtimeDimensionSchema = z.enum([
"terminal",
"interaction",
"exit",
"filesystem",
"protocol",
"process",
"shim",
]);
const runtimeDimensionSchema = z.enum(PROCESS_COMPARISON_DIMENSIONS);
const expectedPatternSchema = z.enum([
"cochanged",
"static_only",