chore: merge main into feat/dylib-resolution

Resolve conflicts against main:
- README.md: take main's simplified English README, which no longer has
  the tool-family table.
- README_ja.md: take main's reworded table and count
  trace_dylib_resolution in the artifact graph row (5 -> 6).
- Skill: the references gain the trace_dylib_resolution paragraph, so
  the version moves to 29 (main already uses 28).
- Regenerate the product catalog, conformance manifest, skill digest and
  package metadata (135 tools). The MCP tool catalog is now built rather
  than committed (#997), so it is removed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-08 04:45:50 +00:00
co-authored by Claude Opus 5.5
581 changed files with 29518 additions and 12109 deletions
+29
View File
@@ -0,0 +1,29 @@
import { expect, it } from "vitest";
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
it.each(["EACCES", "EPERM"] as const)(
"projects %s as host access denial with correction guidance and a valid public schema",
(systemCode) => {
const error = new AnalysisAccessDeniedError(
"inspect_web_network_capture",
"/selected/capture.har",
systemCode,
{ cause: new Error("internal detail") },
);
const projected = projectAnalysisError(error);
expect(analysisErrorProjectionSchema.parse(projected)).toMatchObject({
code: "access_denied",
category: "unavailable",
retryable: false,
details: {
path: "/selected/capture.har",
system_code: systemCode,
boundary: "filesystem-read",
},
});
expect(projected.remediation.action).toContain("read access");
expect(JSON.stringify(projected)).not.toContain("internal detail");
},
);
+10
View File
@@ -2,6 +2,8 @@
const ANALYSIS_ERROR_TAGS = [
"AnalysisProtocolError",
"AnalysisInputError",
"AnalysisAccessDeniedError",
"AnalysisArtifactChangedError",
"AnalysisOutputError",
"AnalysisCapabilityUnavailableError",
"AnalysisCancelledError",
@@ -35,4 +37,12 @@ export abstract class AnalysisError extends Error {
readonly userCategory: "cancelled" | undefined = undefined;
readonly cleanupIncomplete: boolean = false;
readonly cleanupResources: readonly string[] = [];
readonly executionFailure: string | undefined = undefined;
readonly partialObservation: PartialProcessCaptureObservation | undefined =
undefined;
readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined;
}
import type {
PartialProcessCaptureObservation,
ProcessCaptureCleanupReport,
} from "./process/processCapture.js";
+29
View File
@@ -90,3 +90,32 @@ export class AnalysisTimeoutError extends AnalysisError {
);
}
}
/** Host filesystem permissions denied the selected read; this is not malformed caller input. */
export class AnalysisAccessDeniedError extends AnalysisError {
readonly _tag = "AnalysisAccessDeniedError";
constructor(
readonly operation: string,
readonly path: string,
readonly systemCode: "EACCES" | "EPERM",
options?: ErrorOptions,
) {
super(
`Host filesystem read access denied (${systemCode}) for ${path} during ${operation}`,
options,
);
}
}
/** Selected artifact acquisition observed a change, so no stable identity can be reported. */
export class AnalysisArtifactChangedError extends AnalysisError {
readonly _tag = "AnalysisArtifactChangedError";
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: ErrorOptions,
) {
super(`Selected artifact changed during acquisition: ${reason}`, options);
}
}
+17 -1
View File
@@ -1,4 +1,8 @@
import { AnalysisInputError } from "./analysisErrorCore.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import {
BinaryTargetError,
@@ -47,6 +51,10 @@ export const analysisErrorRemediationAction = (
error.constraint === "directory_requires_file"
)
return "For a JavaScript/Electron application directory, call analyze_javascript_application with input_path or run `rea analyze <directory>`. For binary analysis, select its executable file.";
if (error instanceof AnalysisAccessDeniedError)
return "Check the current process's read access to the selected path. Retry with a readable local file.";
if (error instanceof AnalysisArtifactChangedError)
return "Wait until the selected file is stable, then retry this operation.";
if (error instanceof AnalysisInputError)
return "Correct the listed arguments and retry.";
if (error instanceof UnknownRegistryError && error.reason === "not-found")
@@ -107,6 +115,8 @@ const STATIC_ERROR_CATEGORIES: Readonly<
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
> = {
AnalysisInputError: "invalid_input",
AnalysisAccessDeniedError: "unavailable",
AnalysisArtifactChangedError: "integrity_mismatch",
AnalysisCapabilityUnavailableError: "unsupported_provider",
ProviderSelectionError: "unsupported_provider",
EvidenceIntegrityError: "integrity_mismatch",
@@ -119,6 +129,10 @@ const STATIC_ERROR_CATEGORIES: Readonly<
};
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof AnalysisAccessDeniedError)
return "Host filesystem permissions denied read access to the selected path.";
if (error instanceof AnalysisArtifactChangedError)
return "The selected artifact changed during acquisition; no stable snapshot was decoded.";
if (error instanceof AnalysisInputError)
return "Analysis input is invalid. Check the arguments and try again.";
const hopperMessage = hopperErrorUserMessage(error);
@@ -243,6 +257,8 @@ const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
const KNOWN_ERROR_TAGS = {
AnalysisProtocolError: true,
AnalysisInputError: true,
AnalysisAccessDeniedError: true,
AnalysisArtifactChangedError: true,
AnalysisOutputError: true,
AnalysisCapabilityUnavailableError: true,
AnalysisCancelledError: true,
+40 -1
View File
@@ -1,4 +1,4 @@
import type { JsonValue } from "./jsonValue.js";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import {
analysisErrorCategory,
@@ -7,6 +7,8 @@ import {
assertKnownAnalysisErrorTag,
} from "./analysisErrorPresentation.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
@@ -130,6 +132,8 @@ const STATIC_ERROR_CODES = {
AnalysisOutputError: "unreadable_output",
HopperProtocolError: "unreadable_output",
AnalysisInputError: "invalid_request",
AnalysisAccessDeniedError: "access_denied",
AnalysisArtifactChangedError: "artifact_changed",
AnalysisCapabilityUnavailableError: "capability_unavailable",
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
@@ -177,6 +181,20 @@ const errorDetails = (
const requestErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisArtifactChangedError)
return {
operation: error.operation,
path: error.path,
reason: error.reason,
boundary: "stable-artifact-read",
};
if (error instanceof AnalysisAccessDeniedError)
return {
operation: error.operation,
path: error.path,
system_code: error.systemCode,
boundary: "filesystem-read",
};
if (error instanceof AnalysisOutputError)
return { operation: error.operation, reason: error.reason };
if (error instanceof AnalysisInputError && error.issues.length > 0)
@@ -336,12 +354,30 @@ const lifecycleErrorDetails = (
return {
cleanup: "incomplete",
resources: [...error.cleanupResources],
...(error.cleanupReport === undefined
? {}
: { cleanup_report: jsonValueSchema.parse(error.cleanupReport) }),
...(error.executionFailure === undefined
? {}
: { execution_failure: error.executionFailure }),
...(error.partialObservation === undefined
? {}
: {
partial_observation: jsonValueSchema.parse(
error.partialObservation,
),
}),
};
if (
error._tag === "ProcessCaptureError" &&
error.userCategory === "cancelled"
)
return { operation: "process_capture", cleanup: "complete" };
if (
error._tag === "ProcessCaptureError" &&
error.executionFailure !== undefined
)
return { execution_failure: error.executionFailure };
if (error instanceof BinaryTargetError)
return {
path: error.path,
@@ -354,6 +390,7 @@ const lifecycleErrorDetails = (
};
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
"artifact_changed",
"invalid_request",
"provider_timeout",
"cancelled",
@@ -366,6 +403,8 @@ export interface AnalysisErrorProjection extends Readonly<
> {
readonly code:
| "invalid_request"
| "access_denied"
| "artifact_changed"
| "unreadable_output"
| "capability_unavailable"
| "provider_unavailable"
+51 -26
View File
@@ -17,6 +17,55 @@ import {
import { createEvidence } from "./evidence.js";
import { createEvidenceBundle } from "./evidenceBundle.js";
const snapshotWithHistoricalEvidence = () => {
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const parameters = { procedure: "main" };
const makeEvidence = (result: string) =>
createEvidence(ANALYSIS_SNAPSHOT_TARGET, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "analyze_function",
parameters,
result: { summary: result },
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
});
const current = makeEvidence("cached");
const entry = {
query_id: analysisQueryId(target, binding, "analyze_function", parameters),
operation: "analyze_function",
parameters,
execution: {
result: { summary: "cached" },
raw_result: null,
provider: binding.provider,
limitations: [],
locations: [],
subject: {
path: ANALYSIS_SNAPSHOT_TARGET.path,
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
format: ANALYSIS_SNAPSHOT_TARGET.format,
architecture: ANALYSIS_SNAPSHOT_TARGET.architecture ?? null,
},
},
};
return {
current,
snapshot: {
target,
binding,
entries: [entry],
evidence_bundle: createEvidenceBundle([
makeEvidence("older"),
current,
createEvidence(ANALYSIS_SNAPSHOT_TARGET, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "legacy_query",
parameters: {},
result: { summary: "legacy" },
}),
]),
} satisfies AnalysisSnapshot,
};
};
describe("analysis snapshot contract", () => {
it("preserves DOS MZ target and subject formats with the x86 family", () => {
const target = {
@@ -91,31 +140,7 @@ describe("analysis snapshot contract", () => {
describe("analysis snapshot Evidence binding", () => {
it("finds only Evidence committed to the exact binding and profile", () => {
const evidence = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
ANALYSIS_SNAPSHOT_PROVIDER,
{
operation: "analyze_function",
parameters: { procedure: "main" },
result: { summary: "cached" },
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
},
);
const legacy = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
ANALYSIS_SNAPSHOT_PROVIDER,
{
operation: "legacy_query",
parameters: {},
result: { summary: "legacy" },
},
);
const snapshot: AnalysisSnapshot = {
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
entries: [],
evidence_bundle: createEvidenceBundle([evidence, legacy]),
};
const { current, snapshot } = snapshotWithHistoricalEvidence();
expect(
snapshotEvidenceForQuery(snapshot, {
target: ANALYSIS_SNAPSHOT_TARGET,
@@ -125,7 +150,7 @@ describe("analysis snapshot Evidence binding", () => {
provider: ANALYSIS_SNAPSHOT_PROVIDER,
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
}),
).toEqual(evidence);
).toEqual(current);
expect(
snapshotEvidenceForQuery(snapshot, {
target: ANALYSIS_SNAPSHOT_TARGET,
+250 -2
View File
@@ -101,17 +101,33 @@ const entrySchema = z.object({
subject: subjectSchema.nullable(),
}),
});
const workflowEntrySchema = z.object({
query_id: prefixedDigestSchema("query"),
operation: z.string().min(1),
parameters: jsonObjectSchema,
execution: z.object({
result: jsonValueSchema,
raw_result: jsonValueSchema.nullable(),
provider: committedProviderSchema,
analysis_profile: analysisProfileSchema,
limitations: z.array(z.string()),
locations: z.array(evidenceLocationSchema),
subject: subjectSchema.nullable(),
}),
});
/** Provider- and profile-exact cache of successful immutable analysis calls. */
export const analysisSnapshotSchema = z.object({
target: targetSchema,
binding: bindingSchema,
entries: z.array(entrySchema),
workflow_entries: z.array(workflowEntrySchema).optional(),
evidence_bundle: evidenceBundleSchema,
});
export type AnalysisSnapshot = z.infer<typeof analysisSnapshotSchema>;
export type AnalysisSnapshotEntry = z.infer<typeof entrySchema>;
export type AnalysisSnapshotWorkflowEntry = z.infer<typeof workflowEntrySchema>;
export type AnalysisSnapshotTarget = z.infer<typeof targetSchema>;
export type AnalysisSnapshotBinding = z.infer<typeof bindingSchema>;
@@ -208,6 +224,19 @@ export const snapshotEvidenceForQuery = (
if (!snapshotMatchesBinding(snapshot, target, bindingProfile))
return undefined;
const encodedParameters = canonicalJson(parameters);
const queryId = analysisQueryId(
snapshot.target,
snapshot.binding,
operation,
parameters,
);
const entry = snapshot.entries.find(
(candidate) => candidate.query_id === queryId,
);
const workflowEntry = snapshot.workflow_entries?.find(
(candidate) => candidate.query_id === queryId,
);
if (entry === undefined && workflowEntry === undefined) return undefined;
return snapshot.evidence_bundle.records.find(
(record) =>
record.subject?.digest.sha256 === target.sha256 &&
@@ -217,10 +246,77 @@ export const snapshotEvidenceForQuery = (
record.provider.version === provider.version &&
"analysis_profile" in record &&
analysisProfilesEqual(record.analysis_profile, evidenceProfile) &&
canonicalJson(record.parameters) === encodedParameters,
canonicalJson(record.parameters) === encodedParameters &&
((entry !== undefined && evidenceMatchesEntry(record, entry, snapshot)) ||
(workflowEntry !== undefined &&
evidenceMatchesWorkflowEntry(record, workflowEntry, snapshot))),
);
};
/** Create one exact replay record for a derived application workflow result. */
export const createAnalysisSnapshotWorkflowEntry = (input: {
readonly target: AnalysisSnapshotTarget;
readonly binding: AnalysisSnapshotBinding;
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly execution: SnapshotExecution & {
readonly analysisProfile: AnalysisProfileCommitment;
};
}): AnalysisSnapshotWorkflowEntry => {
const { target, binding, operation, parameters, execution } = input;
if (
execution.provider.id !== execution.analysisProfile.provider.id ||
execution.provider.name !== execution.analysisProfile.provider.name ||
execution.provider.version !== execution.analysisProfile.provider.version
)
throw new TypeError(
"Workflow snapshot execution provider does not match its profile",
);
return {
query_id: analysisQueryId(target, binding, operation, parameters),
operation,
parameters: jsonObjectSchema.parse(parameters),
execution: {
result: execution.result,
raw_result: execution.rawResult,
provider: execution.analysisProfile.provider,
analysis_profile: execution.analysisProfile,
limitations: [...execution.limitations],
locations: [...execution.locations],
subject:
execution.subject === null
? null
: {
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
},
};
};
const evidenceMatchesEntry = (
evidence: Evidence,
entry: AnalysisSnapshotEntry,
snapshot: Pick<AnalysisSnapshot, "target" | "binding">,
): boolean =>
isCorrespondingEvidence(evidence, snapshot) &&
canonicalJson({
query: evidenceQueryKey(evidence),
normalized_result: evidence.normalized_result,
raw_result: evidence.raw_result,
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
local_path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
}) === entryEvidenceKey(entry, snapshot.binding);
/** Compute the stable lookup key for one provider/profile-specific query. */
export const analysisQueryId = (
target: AnalysisSnapshotTarget,
@@ -286,7 +382,9 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
);
const ids = new Set<string>();
const boundEntries: AnalysisSnapshotEntry[] = [];
const boundWorkflowEntries: AnalysisSnapshotWorkflowEntry[] = [];
const index = createEvidenceIndex(parsed);
const workflowIndex = createWorkflowEvidenceIndex(parsed);
for (const entry of parsed.entries) {
if (
entry.execution.provider.id !== parsed.binding.provider.id ||
@@ -316,12 +414,60 @@ export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
}
boundEntries.push(entry);
}
for (const entry of parsed.workflow_entries ?? []) {
if (
entry.execution.provider.id !==
entry.execution.analysis_profile.provider.id ||
entry.execution.provider.name !==
entry.execution.analysis_profile.provider.name ||
entry.execution.provider.version !==
entry.execution.analysis_profile.provider.version
)
throw new TypeError(
"Analysis snapshot workflow entry provider does not match its profile",
);
const expected = analysisQueryId(
parsed.target,
parsed.binding,
entry.operation,
entry.parameters,
);
if (entry.query_id !== expected)
throw new TypeError(
"Analysis snapshot workflow query identifier does not match",
);
if (ids.has(entry.query_id))
throw new TypeError("Analysis snapshot contains duplicate queries");
ids.add(entry.query_id);
if (!workflowEntryHasMatchingEvidence(entry, workflowIndex)) {
if (workflowEntryHasCorrespondingEvidence(entry, workflowIndex))
throw new TypeError(
`Analysis snapshot workflow entry ${entry.operation} differs from its Evidence record`,
);
continue;
}
boundWorkflowEntries.push(entry);
}
const sorted = [...parsed.entries].sort((left, right) =>
left.query_id.localeCompare(right.query_id),
);
if (JSON.stringify(parsed.entries) !== JSON.stringify(sorted))
throw new TypeError("Analysis snapshot entries are not canonical");
return { ...parsed, entries: boundEntries };
const sortedWorkflows = [...(parsed.workflow_entries ?? [])].sort(
(left, right) => left.query_id.localeCompare(right.query_id),
);
if (
parsed.workflow_entries !== undefined &&
JSON.stringify(parsed.workflow_entries) !== JSON.stringify(sortedWorkflows)
)
throw new TypeError("Analysis snapshot workflow entries are not canonical");
return {
...parsed,
entries: boundEntries,
...(parsed.workflow_entries === undefined
? {}
: { workflow_entries: boundWorkflowEntries }),
};
};
/** Check that a cached provider execution is represented by bundled Evidence. */
@@ -429,6 +575,108 @@ const entryEvidenceKey = (
},
});
const workflowEntryQueryKey = (entry: AnalysisSnapshotWorkflowEntry): string =>
canonicalJson({
operation: entry.operation,
parameters: entry.parameters,
provider: entry.execution.provider,
analysis_profile: entry.execution.analysis_profile,
});
const workflowEntryEvidenceKey = (
entry: AnalysisSnapshotWorkflowEntry,
): string =>
canonicalJson({
query: workflowEntryQueryKey(entry),
normalized_result: entry.execution.result,
raw_result: entry.execution.raw_result,
limitations: entry.execution.limitations,
locations: entry.execution.locations,
subject:
entry.execution.subject === null
? null
: {
local_path: entry.execution.subject.path,
sha256: entry.execution.subject.sha256,
format: entry.execution.subject.format,
architecture: entry.execution.subject.architecture,
},
});
const isWorkflowEvidence = (
evidence: Evidence,
snapshot: Pick<AnalysisSnapshot, "target">,
entry: AnalysisSnapshotWorkflowEntry,
): boolean =>
evidence.predicate_type === "rea.analysis" &&
evidence.confidence === "derived" &&
evidence.authority === "shipped-artifact" &&
evidence.subject?.digest.sha256 === snapshot.target.sha256 &&
"analysis_profile" in evidence &&
analysisProfilesEqual(
evidence.analysis_profile,
entry.execution.analysis_profile,
) &&
evidence.provider.id === entry.execution.provider.id &&
evidence.provider.name === entry.execution.provider.name &&
evidence.provider.version === entry.execution.provider.version;
const createWorkflowEvidenceIndex = (
snapshot: Pick<AnalysisSnapshot, "target" | "evidence_bundle">,
): EvidenceIndex => {
const matching = new Set<string>();
const corresponding = new Set<string>();
for (const evidence of snapshot.evidence_bundle.records) {
if (
evidence.predicate_type !== "rea.analysis" ||
evidence.confidence !== "derived" ||
evidence.authority !== "shipped-artifact" ||
evidence.subject?.digest.sha256 !== snapshot.target.sha256 ||
!("analysis_profile" in evidence)
)
continue;
corresponding.add(evidenceQueryKey(evidence));
matching.add(canonicalJson(evidenceContentProjection(evidence)));
}
return { matching, corresponding };
};
const workflowEntryHasMatchingEvidence = (
entry: AnalysisSnapshotWorkflowEntry,
index: EvidenceIndex,
): boolean => index.matching.has(workflowEntryEvidenceKey(entry));
const workflowEntryHasCorrespondingEvidence = (
entry: AnalysisSnapshotWorkflowEntry,
index: EvidenceIndex,
): boolean => index.corresponding.has(workflowEntryQueryKey(entry));
const evidenceMatchesWorkflowEntry = (
evidence: Evidence,
entry: AnalysisSnapshotWorkflowEntry,
snapshot: Pick<AnalysisSnapshot, "target">,
): boolean =>
isWorkflowEvidence(evidence, snapshot, entry) &&
canonicalJson(evidenceContentProjection(evidence)) ===
workflowEntryEvidenceKey(entry);
const evidenceContentProjection = (evidence: Evidence) => ({
query: evidenceQueryKey(evidence),
normalized_result: evidence.normalized_result,
raw_result: evidence.raw_result,
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
local_path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
});
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
+9 -2
View File
@@ -118,6 +118,7 @@ export const projectAndroidApplication = (
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.",
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
];
const withoutId = {
@@ -176,11 +177,17 @@ const runtimeFamilies = (all: readonly Component[]) => {
const families = new Set<
AndroidApplicationProjectionResult["runtime_families"][number]
>();
if (all.some(({ path, format }) => format === "dex" || path.endsWith(".dex")))
if (
all.some(
({ path, format }) =>
format === "dex" || path.toLowerCase().endsWith(".dex"),
)
)
families.add("dalvik-art");
if (
all.some(
({ path, format }) => format === "jvm-class" || path.endsWith(".class"),
({ path, format }) =>
format === "jvm-class" || path.toLowerCase().endsWith(".class"),
)
)
families.add("java-kotlin");
+57 -44
View File
@@ -202,53 +202,66 @@ export const buildInterfaceBuilderAnalysis = (input: {
};
let hierarchyCount = 0;
let hierarchyTruncated = false;
const visitHierarchy = (value: unknown, parentId: string): void => {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
return;
}
if (Array.isArray(value)) {
for (const child of value) visitHierarchy(child, parentId);
return;
}
if (typeof value !== "object" || value === null) return;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
const visitHierarchy = (
initial: unknown,
initialParentId: string,
): void => {
const pending: { readonly value: unknown; readonly parentId: string }[] =
[{ value: initial, parentId: initialParentId }];
while (pending.length > 0) {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
return;
}
const entry = pending.pop();
if (entry === undefined) break;
const { value, parentId } = entry;
if (Array.isArray(value)) {
for (let index = value.length - 1; index >= 0; index -= 1) {
const child = value[index];
if (child !== undefined) pending.push({ value: child, parentId });
}
continue;
}
if (typeof value !== "object" || value === null) continue;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
nextParent = childId;
hierarchyCount += 1;
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
);
nextParent = childId;
hierarchyCount += 1;
}
pending.push({ value: item.children, parentId: nextParent });
}
visitHierarchy(item.children, nextParent);
};
for (const hierarchy of parsed.hierarchy) visitHierarchy(hierarchy, rootId);
for (const [index, item] of parsed.connections
@@ -196,39 +196,85 @@ const keyedArchiveTable = (objectTable: readonly unknown[]) => {
};
const hierarchy = (start: unknown): unknown[] => {
const visited = new Set<number>();
const node = (
const root: unknown[] = [];
const pending: { readonly value: unknown; readonly output: unknown[] }[] = [
{ value: start, output: root },
];
const appendNode = (
item: Record<string, unknown>,
uid: number | undefined,
depth: number,
): unknown[] => {
output: unknown[],
): void => {
const objectId = firstString(
authoredId(item),
text(item.id),
uid === undefined ? null : String(uid),
);
const children = Object.entries(item)
.filter(([key]) => HIERARCHY_KEY.test(key))
.flatMap(([, child]) => visit(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
if (objectId === null) {
for (const [key, child] of Object.entries(item).reverse())
if (HIERARCHY_KEY.test(key)) pending.push({ value: child, output });
return;
}
const children: unknown[] = [];
output.push({ objectID: objectId, children });
for (const [key, child] of Object.entries(item).reverse())
if (HIERARCHY_KEY.test(key))
pending.push({ value: child, output: children });
};
const visit = (value: unknown, depth: number): unknown[] => {
if (depth > 32) return [];
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined) break;
const { value, output } = entry;
const uid = archiveUid(value);
if (uid !== undefined) {
if (visited.has(uid)) return [];
if (visited.has(uid)) continue;
visited.add(uid);
const target = objectTable[uid];
if (Array.isArray(target)) return visit(target, depth + 1);
return typeof target === "object" && target !== null
? node(record(target), uid, depth)
: [];
if (Array.isArray(target)) {
for (let index = target.length - 1; index >= 0; index -= 1) {
const child = target[index];
if (child !== undefined) pending.push({ value: child, output });
}
continue;
}
if (typeof target !== "object" || target === null) continue;
const item = record(target);
if (archivedArrayClass(item.$class)) {
const members = item["NS.objects"];
if (Array.isArray(members))
for (let index = members.length - 1; index >= 0; index -= 1) {
const child = members[index];
if (child !== undefined) pending.push({ value: child, output });
}
continue;
}
appendNode(item, uid, output);
continue;
}
if (Array.isArray(value))
return value.flatMap((item) => visit(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
return node(record(value), undefined, depth);
};
return visit(start, 0);
if (Array.isArray(value)) {
for (let index = value.length - 1; index >= 0; index -= 1) {
const child = value[index];
if (child !== undefined) pending.push({ value: child, output });
}
} else if (typeof value === "object" && value !== null) {
appendNode(record(value), undefined, output);
}
}
return root;
};
const archivedArrayClass = (classReference: unknown): boolean => {
const uid = archiveUid(classReference);
const descriptor = record(
uid === undefined ? classReference : objectTable[uid],
);
const classNames = Array.isArray(descriptor.$classes)
? descriptor.$classes.filter(
(name): name is string => typeof name === "string",
)
: [];
return (
classNames.includes("NSArray") || classNames.includes("NSMutableArray")
);
};
return { resolve, hierarchy };
};
+5
View File
@@ -12,6 +12,11 @@ describe("artifact path syntax", () => {
expect(hasScheme("https://example.test/app.js")).toBe(true);
expect(hasScheme("file:///app.js")).toBe(true);
expect(hasScheme("node:fs")).toBe(true);
expect(hasScheme("web3:app.js")).toBe(true);
expect(hasScheme("h323:user@example.test")).toBe(true);
expect(hasScheme("x1+custom.v2-test:asset")).toBe(true);
expect(hasScheme("3web:app.js")).toBe(false);
expect(hasScheme("./web3:app.js")).toBe(false);
expect(hasScheme("./relative.js")).toBe(false);
expect(hasScheme("/absolute.js")).toBe(false);
expect(hasScheme("app.js")).toBe(false);
+1 -1
View File
@@ -17,7 +17,7 @@
/** Whether a reference carries a URI scheme (`https:`, `file:`, …). */
export const hasScheme = (value: string): boolean =>
/^[A-Za-z][A-Za-z+.-]*:/u.test(value);
/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);
/** Whether a reference is scheme-qualified or protocol-relative. */
export const looksExternal = (value: string): boolean =>
+1 -1
View File
@@ -94,7 +94,7 @@ const browserInput = {
};
/** Public input for complete discovery, optionally filtered by exact origin. */
export const listBrowserTargetsInputSchema = z.object({
export const listBrowserTargetsInputSchema = z.strictObject({
...browserInput,
});
+15
View File
@@ -114,6 +114,21 @@ const browserNetworkRequestSchema = z.object({
status: z.number().nullable(),
mime_type: z.string().nullable(),
encoded_data_length: z.number().min(0).nullable(),
redirects: z
.array(
z.object({
url: z.string(),
response_url: z.string(),
method: z.string(),
resource_type: z.string().nullable(),
status: z.number().nullable(),
mime_type: z.string().nullable(),
encoded_data_length: z.number().min(0).nullable(),
request_timestamp: z.number().nullable(),
redirect_event_timestamp: z.number().nullable(),
}),
)
.optional(),
initiator: z.object({
type: z.string(),
url: z.string().nullable(),
+1 -1
View File
@@ -56,7 +56,7 @@ it("does not require duplicate origin scope declarations", () => {
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
executable_path: "chrome",
executable_path: "/opt/chromium/chrome",
},
start_url: { url: "https://app.example.test/" },
actions: [
+12 -2
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { isAbsoluteLocalPath } from "./localPath.js";
import { browserNetworkContentSelectionSchema } from "./browserNetworkEvidence.js";
import {
@@ -11,7 +12,14 @@ export const scenarioIdentifierSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9._-]*$/u);
const browserExecutablePathSchema = z.string().trim().min(1);
const browserExecutablePathSchema = z
.string()
.trim()
.min(1)
.refine(isAbsoluteLocalPath, {
message:
"executable_path must be an absolute local filesystem path (for example /opt/chromium/chrome or C:\\chromium\\chrome.exe)",
});
const browserScenarioBaseUrlSchema = z
.string()
@@ -67,7 +75,9 @@ export type BrowserScenarioUrl = z.infer<typeof browserScenarioUrlSchema>;
export const browserScenarioBrowserSchema = z.discriminatedUnion("mode", [
z.strictObject({
mode: z.literal("launch"),
executable_path: browserExecutablePathSchema,
executable_path: browserExecutablePathSchema.describe(
"Absolute local filesystem path for the browser executable; relative paths are rejected.",
),
headless: z
.boolean()
.default(true)
-160
View File
@@ -1,160 +0,0 @@
import { describe, expect, it } from "vitest";
import {
analyzeBytecodeArtifacts,
bytecodeAnalysisSchema,
classifyProvenance,
detectArtifactFormat,
detectBytecodeFamily,
type BytecodeArtifact,
} from "./bytecodeProvider.js";
describe("bytecode provider", () => {
it("detects JVM family from extensions", () => {
expect(detectBytecodeFamily("App.class")).toBe("jvm");
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
});
it("detects Python family from extensions", () => {
expect(detectBytecodeFamily("module.pyc")).toBe("python");
expect(detectBytecodeFamily("module.pyo")).toBe("python");
expect(detectBytecodeFamily("package.whl")).toBe("python");
expect(detectBytecodeFamily("app.pyz")).toBe("python");
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
});
it("returns null for unknown extensions", () => {
expect(detectBytecodeFamily("readme.txt")).toBeNull();
expect(detectBytecodeFamily("script.js")).toBeNull();
});
it("detects artifact format from path", () => {
expect(detectArtifactFormat("App.class")).toBe("class");
expect(detectArtifactFormat("lib.jar")).toBe("jar");
expect(detectArtifactFormat("web.war")).toBe("war");
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
});
it("classifies standard library provenance", () => {
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
"standard_library",
);
expect(
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
).toBe("standard_library");
});
it("classifies generated provenance", () => {
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
"generated",
);
expect(
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
).toBe("generated");
});
it("classifies vendored provenance", () => {
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
"vendored",
);
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
"vendored",
);
});
it("classifies application provenance", () => {
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
"application",
);
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
});
it("analyzes bytecode artifacts and computes summary", () => {
const artifacts: BytecodeArtifact[] = [
{
path: "src/App.class",
family: "jvm",
format: "class",
size: 1000,
digest: "a".repeat(64),
symbols: [
{
name: "com.example.App",
raw_location: "0x1000",
kind: "class",
bytecode_version: 52,
provenance: "application",
is_public: true,
},
{
name: "java.lang.String",
raw_location: "0x2000",
kind: "class",
bytecode_version: 52,
provenance: "standard_library",
is_public: true,
},
],
is_standard_library: false,
is_generated: false,
is_vendored: false,
},
{
path: "lib/generated/Generated.class",
family: "jvm",
format: "class",
size: 500,
digest: "b".repeat(64),
symbols: [
{
name: "GeneratedClass",
raw_location: "0x3000",
kind: "class",
bytecode_version: 52,
provenance: "generated",
is_public: false,
},
],
is_standard_library: false,
is_generated: true,
is_vendored: false,
},
];
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.family).toBe("jvm");
expect(result.total_symbols).toBe(3);
expect(result.application_symbols).toBe(1);
expect(result.standard_library_symbols).toBe(1);
expect(result.generated_symbols).toBe(1);
expect(result.vendored_symbols).toBe(0);
// Validate schema
const parsed = bytecodeAnalysisSchema.safeParse(result);
expect(parsed.success).toBe(true);
});
it("returns every artifact when the inventory exceeds ten thousand entries", () => {
const artifacts = Array.from({ length: 10_001 }, (_, index) => ({
path: `classes/${index}.class`,
family: "jvm" as const,
format: "class" as const,
size: 1,
digest: "a".repeat(64),
symbols: [],
is_standard_library: false,
is_generated: false,
is_vendored: false,
}));
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
expect(result.artifacts).toHaveLength(artifacts.length);
expect(bytecodeAnalysisSchema.parse(result).artifacts).toHaveLength(
artifacts.length,
);
});
});
-204
View File
@@ -1,204 +0,0 @@
import { z } from "zod";
/** Supported managed-runtime bytecode families. */
export const bytecodeFamilySchema = z.enum(["jvm", "python"]);
export type BytecodeFamily = z.infer<typeof bytecodeFamilySchema>;
/** Classification of bytecode provenance. */
export const bytecodeProvenanceSchema = z.enum([
"application",
"generated",
"vendored",
"bundled",
"standard_library",
]);
export type BytecodeProvenance = z.infer<typeof bytecodeProvenanceSchema>;
/** A bytecode symbol discovered through static analysis. */
export const bytecodeSymbolSchema = z.strictObject({
/** Fully qualified name. */
name: z.string().min(1),
/** Raw bytecode location or offset. */
raw_location: z.string().min(1),
/** Normalized symbol type. */
kind: z.enum([
"class",
"interface",
"method",
"field",
"function",
"module",
"variable",
]),
/** Bytecode version if known. */
bytecode_version: z.number().int().nullable(),
/** Provenance classification. */
provenance: bytecodeProvenanceSchema,
/** Whether the symbol is accessible (public). */
is_public: z.boolean().default(false),
});
/** A discovered bytecode artifact (class file, wheel, etc). */
export const bytecodeArtifactSchema = z.strictObject({
/** Artifact path relative to the analysis root. */
path: z.string().min(1),
/** Bytecode family. */
family: bytecodeFamilySchema,
/** Artifact format. */
format: z.enum(["class", "jar", "war", "ear", "pyc", "pyo", "whl", "zipapp"]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z.string().regex(/^[a-f0-9]{64}$/u),
/** Discovered symbols. */
symbols: z.array(bytecodeSymbolSchema).default([]),
/** Whether this is a standard library artifact. */
is_standard_library: z.boolean().default(false),
/** Whether this is a generated artifact. */
is_generated: z.boolean().default(false),
/** Whether this is a vendored artifact. */
is_vendored: z.boolean().default(false),
});
export type BytecodeArtifact = z.infer<typeof bytecodeArtifactSchema>;
/** Static bytecode analysis result. */
export const bytecodeAnalysisSchema = z.strictObject({
/** Bytecode family. */
family: bytecodeFamilySchema,
/** All discovered artifacts. */
artifacts: z.array(bytecodeArtifactSchema),
/** Total symbols across all artifacts. */
total_symbols: z.number().int().nonnegative(),
/** Symbols classified as application code. */
application_symbols: z.number().int().nonnegative(),
/** Symbols classified as generated code. */
generated_symbols: z.number().int().nonnegative(),
/** Symbols classified as vendored code. */
vendored_symbols: z.number().int().nonnegative(),
/** Symbols classified as standard library. */
standard_library_symbols: z.number().int().nonnegative(),
});
export type BytecodeAnalysis = z.infer<typeof bytecodeAnalysisSchema>;
/** Detect bytecode family from file extension. */
export function detectBytecodeFamily(path: string): BytecodeFamily | null {
const lower = path.toLowerCase();
if (
lower.endsWith(".class") ||
lower.endsWith(".jar") ||
lower.endsWith(".war") ||
lower.endsWith(".ear")
) {
return "jvm";
}
if (
lower.endsWith(".pyc") ||
lower.endsWith(".pyo") ||
lower.endsWith(".whl") ||
lower.endsWith(".pyz") ||
lower.endsWith(".zipapp")
) {
return "python";
}
return null;
}
/** Detect artifact format from file path. */
export function detectArtifactFormat(
path: string,
): `class` | `jar` | `war` | `ear` | `pyc` | `pyo` | `whl` | `zipapp` | null {
const lower = path.toLowerCase();
if (lower.endsWith(".class")) return "class";
if (lower.endsWith(".jar")) return "jar";
if (lower.endsWith(".war")) return "war";
if (lower.endsWith(".ear")) return "ear";
if (lower.endsWith(".pyc")) return "pyc";
if (lower.endsWith(".pyo")) return "pyo";
if (lower.endsWith(".whl")) return "whl";
if (lower.endsWith(".pyz") || lower.endsWith(".zipapp")) return "zipapp";
return null;
}
const STANDARD_LIBRARY_PATH_MARKERS = [
"/stdlib/",
"/site-packages/",
"java/",
"javax/",
"sun/",
];
const STANDARD_LIBRARY_SYMBOL_MARKERS = ["java.", "javax.", "sun.", "__"];
const GENERATED_PATH_MARKERS = [
"/generated/",
"_generated",
"/build/",
"/target/",
"/dist-packages/",
"/__pycache__/",
];
const GENERATED_SYMBOL_MARKERS = ["Generated", "_generated"];
const VENDORED_PATH_MARKERS = [
"/vendor/",
"/vendored/",
"/third_party/",
"/3rdparty/",
"/node_modules/",
];
const BUNDLED_PATH_MARKERS = ["/bundle/", "/bundled/", ".jar!", ".war!"];
const includesAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.includes(marker));
const startsWithAny = (value: string, markers: readonly string[]): boolean =>
markers.some((marker) => value.startsWith(marker));
/** Classify bytecode symbol provenance. */
export function classifyProvenance(
path: string,
symbolName: string,
): BytecodeProvenance {
const lower = path.toLowerCase();
if (
includesAny(lower, STANDARD_LIBRARY_PATH_MARKERS) ||
startsWithAny(symbolName, STANDARD_LIBRARY_SYMBOL_MARKERS)
)
return "standard_library";
if (
includesAny(lower, GENERATED_PATH_MARKERS) ||
includesAny(symbolName, GENERATED_SYMBOL_MARKERS)
)
return "generated";
if (includesAny(lower, VENDORED_PATH_MARKERS)) return "vendored";
if (includesAny(lower, BUNDLED_PATH_MARKERS)) return "bundled";
return "application";
}
/** Analyze a set of bytecode artifacts and produce a summary. */
export function analyzeBytecodeArtifacts(
artifacts: readonly BytecodeArtifact[],
family: BytecodeFamily,
): BytecodeAnalysis {
const totals = artifacts.reduce(
(counts, artifact) => {
counts.total += artifact.symbols.length;
for (const symbol of artifact.symbols) counts[symbol.provenance] += 1;
return counts;
},
{
total: 0,
application: 0,
generated: 0,
vendored: 0,
standard_library: 0,
bundled: 0,
},
);
return {
family,
artifacts: [...artifacts],
total_symbols: totals.total,
application_symbols: totals.application,
generated_symbols: totals.generated,
vendored_symbols: totals.vendored,
standard_library_symbols: totals.standard_library,
};
}
+1 -1
View File
@@ -24,7 +24,7 @@ export const parseCallPathAddress = (input: unknown): string =>
inputAddressSchema.parse(input);
/** Strict input for explicit call-path reconstruction from complete dossiers. */
export const callPathInputSchema = z.object({
export const callPathInputSchema = z.strictObject({
functions: z.array(evidenceSchema).min(1),
start: z.object({ address: inputAddressSchema }).strict(),
goal: z.object({ address: inputAddressSchema }).strict(),
+7
View File
@@ -62,6 +62,13 @@ describe("incremental canonical digest", () => {
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
});
it("keeps digests identical when buffered parts cross flush boundaries", () => {
const manyKeys: Record<string, unknown> = {};
for (let i = 0; i < 2000; i += 1) manyKeys[`k${i}`] = i;
const value = { keys: manyKeys, tail: ["€", "😀", "x".repeat(9000)] };
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
});
it("preserves canonicalize property access and toJSON cycle behavior", () => {
const createAccessor = () => {
let reads = 0;
+12 -1
View File
@@ -6,8 +6,19 @@ export const digestCanonicalValue = (
context = "Comparison",
): string => {
const hash = createHash("sha256");
const encoded = emitCanonical(value, (part) => hash.update(part), new Set());
// Batch small emitted parts to cut hash.update crossings.
// Flush cuts only at part boundaries, so the hashed byte stream is unchanged.
let buffered = "";
const emit = (part: string): void => {
buffered += part;
if (buffered.length >= 8192) {
hash.update(buffered);
buffered = "";
}
};
const encoded = emitCanonical(value, emit, new Set());
if (!encoded) throw new TypeError(`${context} could not canonicalize data`);
if (buffered) hash.update(buffered);
return hash.digest("hex");
};
+3 -3
View File
@@ -7,19 +7,19 @@ import { functionComparisonResultSchema } from "./functionComparison.js";
import {
PROCESS_PROVIDER,
isProcessEvidenceProvider,
} from "./processEvidenceProvider.js";
} from "./process/processEvidenceProvider.js";
import {
comparisonStatusSchema,
deriveProcessComparisonStatus,
PROCESS_COMPARISON_DIMENSIONS,
processCaptureComparisonSchema,
} from "./processCapture.js";
} from "./process/processCapture.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
/** Input for aggregating existing comparison Evidence. */
export const changedBehaviorInputSchema = z.object({
export const changedBehaviorInputSchema = z.strictObject({
comparisons: z.array(evidenceSchema).default([]),
});
+1 -7
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { absenceClaimable, canonicalDigest } from "./comparisonSemantics.js";
import { absenceClaimable } from "./comparisonSemantics.js";
describe("shared comparison semantics", () => {
it("permits absence claims only for complete, non-truncated inventories", () => {
@@ -27,10 +27,4 @@ describe("shared comparison semantics", () => {
).toBe(false);
expect(absenceClaimable({ status: "partial" })).toBe(false);
});
it("produces one stable SHA-256 for equivalent canonical JSON values", () => {
expect(canonicalDigest({ b: 2, a: 1 })).toBe(
canonicalDigest({ a: 1, b: 2 }),
);
});
});
-86
View File
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vitest";
import {
bundleClassificationToCanonical,
comparisonConclusionSchema,
comparisonStatusSchema,
functionStatusToCanonical,
scenarioArtifactStatusToCanonical,
sourceToBundleStatusToCanonical,
} from "./comparisonStatus.js";
describe("comparison status vocabulary", () => {
it("owns the canonical unchanged/changed/unknown triple", () => {
expect(comparisonStatusSchema.options).toEqual([
"unchanged",
"changed",
"unknown",
]);
expect(comparisonConclusionSchema.options).toEqual([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
});
it("projects every bundle classification", () => {
expect(
(
[
"added",
"removed",
"changed",
"unknown",
"history_advanced",
"history_diverged",
] as const
).map(bundleClassificationToCanonical),
).toEqual([
"changed",
"changed",
"changed",
"unknown",
"changed",
"changed",
]);
});
it("projects every source-to-bundle item status", () => {
expect(
(
[
"unchanged",
"modified",
"removed",
"split",
"merged",
"duplicated",
"unknown",
] as const
).map(sourceToBundleStatusToCanonical),
).toEqual([
"unchanged",
"changed",
"changed",
"changed",
"changed",
"changed",
"unknown",
]);
});
it("projects every function dimension status without claiming truncated work", () => {
expect(
(["unchanged", "changed", "truncated", "unknown"] as const).map(
functionStatusToCanonical,
),
).toEqual(["unchanged", "changed", "unknown", "unknown"]);
});
it("projects every scenario artifact status", () => {
expect(
(["changed", "unknown"] as const).map(scenarioArtifactStatusToCanonical),
).toEqual(["changed", "unknown"]);
});
});
+2 -60
View File
@@ -2,69 +2,11 @@ import { z } from "zod";
/**
* Canonical top-level comparison outcome shared by every comparison
* pipeline. Pipeline-native detail enums (bundle classifications,
* source-to-bundle split/merge kinds, scenario alignment states, function
* truncation) keep their wire schemas; the mappers below project each of
* them onto this triple without changing any pipeline result.
* pipeline. Pipeline-native detail enums keep their wire schemas, while
* shared result contracts use this canonical triple.
*/
export const comparisonStatusSchema = z.enum([
"unchanged",
"changed",
"unknown",
]);
export type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
/** Canonical comparison conclusion shared by every comparison pipeline. */
export const comparisonConclusionSchema = z.enum([
"observed_change",
"derived_relationship",
"contradiction",
"unresolved_branch",
]);
/** Project a bundle change classification onto the canonical triple. */
export const bundleClassificationToCanonical = (
classification:
| "added"
| "removed"
| "changed"
| "unknown"
| "history_advanced"
| "history_diverged",
): ComparisonStatus => (classification === "unknown" ? "unknown" : "changed");
/** Project a source-to-bundle item status onto the canonical triple. */
export const sourceToBundleStatusToCanonical = (
status:
| "unchanged"
| "modified"
| "removed"
| "split"
| "merged"
| "duplicated"
| "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "unknown"
? "unknown"
: "changed";
/**
* Project a function dimension status onto the canonical triple. A
* truncated dimension cannot support an unchanged/changed claim.
*/
export const functionStatusToCanonical = (
status: "unchanged" | "changed" | "truncated" | "unknown",
): ComparisonStatus =>
status === "unchanged"
? "unchanged"
: status === "changed"
? "changed"
: "unknown";
/** Project a browser-scenario artifact status onto the canonical triple. */
export const scenarioArtifactStatusToCanonical = (
status: "changed" | "unknown",
): ComparisonStatus => status;
-18
View File
@@ -51,19 +51,6 @@ const VOLATILE_DIMENSIONS = new Set([
"updated_at",
]);
/** Dimension that carries semantic content. */
const SEMANTIC_DIMENSIONS = new Set([
"exit_code",
"stdout",
"stderr",
"filesystem",
"process",
"process_tree",
"shim_events",
"protocol_events",
"event_journal",
]);
type IncompleteStatus = "unknown" | "truncated";
type EvidenceView = {
@@ -214,11 +201,6 @@ export function isVolatileDimension(name: string): boolean {
return VOLATILE_DIMENSIONS.has(name);
}
/** Check if a dimension name carries semantic content. */
export function isSemanticDimension(name: string): boolean {
return SEMANTIC_DIMENSIONS.has(name);
}
/**
* Compare two values for a dimension, classifying semantic diffs
* from timing/normalization noise.
-158
View File
@@ -1,158 +0,0 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
authEventsByProtocol,
authFlowDuration,
customProtocolCaptureSchema,
correlateProcessIdentity,
failedAuthEvents,
framesByTransport,
looksLikeCredentialFrame,
successfulAuthEvents,
type AuthFlowEvent,
type ProtocolFrame,
} from "./customProtocolCapture.js";
const sampleFrames: ProtocolFrame[] = [
{
sequence: 0,
at_ms: 100,
transport: "tcp",
direction: "sent",
source_pid: 100,
dest_pid: 200,
source_endpoint: "127.0.0.1:8080",
dest_endpoint: "127.0.0.1:9090",
raw_data: "hello",
decoded_content: "hello",
size: 5,
truncated: false,
},
{
sequence: 1,
at_ms: 200,
transport: "udp",
direction: "received",
source_pid: 200,
dest_pid: 100,
source_endpoint: "127.0.0.1:9090",
dest_endpoint: "127.0.0.1:8080",
raw_data: "world",
decoded_content: "world",
size: 5,
truncated: false,
},
];
const sampleAuthEvents: AuthFlowEvent[] = [
{
sequence: 0,
at_ms: 100,
stage: "init",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: false,
error: null,
},
{
sequence: 1,
at_ms: 500,
stage: "success",
protocol: "OAuth2",
token_type: "Bearer",
token_lifecycle: "issued",
correlation_id: "abc-123",
credentials_redacted: true,
succeeded: true,
error: null,
},
];
describe("custom protocol capture", () => {
it("rejects a capture with an unknown transport", () => {
const result = customProtocolCaptureSchema.safeParse({
transport: "carrier-pigeon",
frames: sampleFrames,
auth_events: sampleAuthEvents,
has_truncated: false,
credentials_detected: false,
});
expect(result.success).toBe(false);
});
it("retains every captured frame at any size", () => {
fc.assert(
fc.property(
// The bound must sit well above any ceiling a future change would
// plausibly introduce. A generated length of 40 would pass unnoticed
// against a cap at 100, so the generated arrays cross 1,000.
fc.array(fc.constant(sampleFrames[0]!), {
minLength: 300,
maxLength: 1_000,
}),
(frames) => {
const parsed = customProtocolCaptureSchema.parse({
transport: "tcp",
frames: frames.map((frame, sequence) => ({ ...frame, sequence })),
});
expect(parsed.frames).toHaveLength(frames.length);
},
),
{ numRuns: 25 },
);
});
it("correlates process identity", () => {
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
});
it("filters frames by transport", () => {
const tcpFrames = framesByTransport(sampleFrames, "tcp");
expect(tcpFrames).toHaveLength(1);
const udpFrames = framesByTransport(sampleFrames, "udp");
expect(udpFrames).toHaveLength(1);
});
it("detects credential-like frames", () => {
const credFrame: ProtocolFrame = {
...sampleFrames[0]!,
decoded_content: { password: "secret" },
};
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
});
it("filters auth events by protocol", () => {
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
expect(oauthEvents).toHaveLength(2);
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
expect(otherEvents).toHaveLength(0);
});
it("gets successful auth events", () => {
const success = successfulAuthEvents(sampleAuthEvents);
expect(success).toHaveLength(1);
expect(success[0]!.succeeded).toBe(true);
});
it("gets failed auth events", () => {
const failed = failedAuthEvents(sampleAuthEvents);
expect(failed).toHaveLength(1);
expect(failed[0]!.succeeded).toBe(false);
});
it("computes auth flow duration", () => {
const duration = authFlowDuration(sampleAuthEvents);
expect(duration).toBe(400);
});
it("returns null for empty auth events", () => {
expect(authFlowDuration([])).toBeNull();
});
});
-169
View File
@@ -1,169 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Supported transport types for custom protocol capture. */
export const transportTypeSchema = z.enum([
"tcp",
"udp",
"ipc",
"unix-socket",
"named-pipe",
"xpc",
]);
export type TransportType = z.infer<typeof transportTypeSchema>;
/** Direction of a protocol frame. */
export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
/** A captured protocol frame. */
export const protocolFrameSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Transport type. */
transport: transportTypeSchema,
/** Direction of the frame. */
direction: frameDirectionSchema,
/** Source process identity. */
source_pid: z.number().int().nullable(),
/** Destination process identity. */
dest_pid: z.number().int().nullable(),
/** Endpoint address (IP:port, socket path, pipe name). */
source_endpoint: z.string().nullable(),
/** Destination endpoint. */
dest_endpoint: z.string().nullable(),
/** Raw frame data as base64. */
raw_data: z.string().nullable(),
/** Decoded/parsed frame content if known. */
decoded_content: jsonValueSchema.nullable(),
/** Frame size in bytes. */
size: z.number().int().nonnegative(),
/** Whether the frame was truncated. */
truncated: z.boolean().default(false),
});
export type ProtocolFrame = z.infer<typeof protocolFrameSchema>;
/** Authentication flow stage. */
export const authStageSchema = z.enum([
"init",
"challenge",
"response",
"token_exchange",
"renewal",
"revocation",
"failure",
"success",
]);
/** Token lifecycle event. */
export const tokenLifecycleEventSchema = z.enum([
"issued",
"refreshed",
"expired",
"revoked",
"renewed",
]);
/** A captured authentication flow event. */
export const authFlowEventSchema = z.strictObject({
/** Monotonic sequence number. */
sequence: z.number().int().nonnegative(),
/** Timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Authentication stage. */
stage: authStageSchema,
/** Protocol used. */
protocol: z.string().min(1),
/** Token type if applicable. */
token_type: z.string().nullable(),
/** Token lifecycle event. */
token_lifecycle: tokenLifecycleEventSchema.nullable(),
/** Correlation ID linking challenge-response pairs. */
correlation_id: z.string().nullable(),
/** Whether the capture producer marked credentials as redacted. */
credentials_redacted: z.boolean().default(false),
/** Whether the authentication succeeded. */
succeeded: z.boolean().default(false),
/** Error message if authentication failed. */
error: z.string().nullable(),
});
export type AuthFlowEvent = z.infer<typeof authFlowEventSchema>;
/** A captured protocol session. */
export const customProtocolCaptureSchema = z.strictObject({
/** Transport type for this session. */
transport: transportTypeSchema,
/** Captured frames in order. */
frames: z.array(protocolFrameSchema),
/** Authentication flow events. */
auth_events: z.array(authFlowEventSchema).default([]),
/** Whether any frame was truncated. */
has_truncated: z.boolean().default(false),
/** Whether the capture producer detected credential content. */
credentials_detected: z.boolean().default(false),
});
/** Correlate a frame with process identity. */
export function correlateProcessIdentity(
frame: ProtocolFrame,
pid: number,
): boolean {
return frame.source_pid === pid || frame.dest_pid === pid;
}
/** Check if a frame contains credential-like content. */
export function looksLikeCredentialFrame(frame: ProtocolFrame): boolean {
const patterns = [
"password",
"token",
"secret",
"api_key",
"apikey",
"authorization",
"credential",
];
const content = JSON.stringify(frame.decoded_content ?? "").toLowerCase();
return patterns.some((p) => content.includes(p));
}
/** Filter frames by transport type. */
export function framesByTransport(
frames: readonly ProtocolFrame[],
transport: TransportType,
): ProtocolFrame[] {
return frames.filter((f) => f.transport === transport);
}
/** Get all authentication flow events for a specific protocol. */
export function authEventsByProtocol(
events: readonly AuthFlowEvent[],
protocol: string,
): AuthFlowEvent[] {
return events.filter((e) => e.protocol === protocol);
}
/** Get successful authentication events. */
export function successfulAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => e.succeeded);
}
/** Get failed authentication events. */
export function failedAuthEvents(
events: readonly AuthFlowEvent[],
): AuthFlowEvent[] {
return events.filter((e) => !e.succeeded);
}
/** Compute the duration of an authentication flow in milliseconds. */
export function authFlowDuration(
events: readonly AuthFlowEvent[],
): number | null {
const first = events.at(0);
const last = events.at(-1);
if (first === undefined || last === undefined) return null;
return last.at_ms - first.at_ms;
}
-6
View File
@@ -5,7 +5,6 @@ import {
isDigest,
isPrefixedDigest,
prefixedDigestSchema,
SHA256_PATTERN,
} from "./digests.js";
const DIGEST = "a".repeat(64);
@@ -59,9 +58,4 @@ describe("digest shapes", () => {
`jag_${OTHER_DIGEST}`,
);
});
it("exposes the pattern for callers that cannot use zod", () => {
expect(SHA256_PATTERN.test(DIGEST)).toBe(true);
expect(SHA256_PATTERN.test(DIGEST.toUpperCase())).toBe(false);
});
});
-21
View File
@@ -1,21 +0,0 @@
import { describe, expect, it } from "vitest";
import { emptyArraySchema } from "./emptyArraySchema.js";
describe("empty array schema", () => {
it("accepts only an empty array", () => {
expect(emptyArraySchema.parse([])).toEqual([]);
for (const value of [
[null],
["candidate"],
[0],
[false],
[{}],
[[]],
null,
{},
]) {
expect(emptyArraySchema.safeParse(value).success).toBe(false);
}
});
});
-112
View File
@@ -1,112 +0,0 @@
import type { ProcessNode, ProcessTreeEvent } from "./eventProcessTree.js";
/**
* Defaults shared by every fixture event. Tests vary only the fields they are
* actually asserting on, so a tree reads as the sequence of transitions under
* test rather than thirteen repeated literal fields per event.
*/
const eventDefaults: {
arguments: string[];
previous_pid: number | null;
previous_ppid: number | null;
exit_code: number | null;
signal: number | null;
tid: number | null;
} = {
arguments: [],
previous_pid: null,
previous_ppid: null,
exit_code: null,
signal: null,
tid: null,
};
/** One `spawn` event, numbering itself from the sequence given. */
export const spawnEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable?: string | null;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "spawn",
executable: event.executable ?? `/${event.process_name}`,
...event,
});
/** One `exit` event. */
export const exitEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number | null;
process_name: string | null;
exit_code?: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "exit",
executable: null,
exit_code: 0,
...event,
});
/** One `re_exec` event, which keeps the pid and replaces the executable. */
export const reExecEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
executable: string;
arguments?: string[];
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "re_exec",
previous_pid: null,
...event,
});
/** One `reparent` event, which records the pid the process was adopted from. */
export const reparentEvent = (event: {
sequence: number;
at_ms?: number;
pid: number;
ppid: number;
process_name: string;
previous_ppid: number;
}): ProcessTreeEvent => ({
...eventDefaults,
at_ms: event.at_ms ?? event.sequence * 10,
type: "reparent",
executable: null,
...event,
});
/** A reconstructed node, defaulting to a childless process with no lifecycle. */
export const processNode = (node: {
pid: number;
ppid: number | null;
process_name: string;
children?: number[];
}): ProcessNode => ({
executable: null,
arguments: [],
spawn_time_ms: null,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
...node,
children: node.children ?? [],
});
/** The common `spawn` of a root process at pid 1. */
export const rootSpawn = (sequence = 0): ProcessTreeEvent =>
spawnEvent({ sequence, pid: 1, ppid: 0, process_name: "root" });
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
containsProcess,
getDescendants,
maxTreeDepth,
reconstructProcessTree,
type ProcessTreeEvent,
} from "./eventProcessTree.js";
import {
exitEvent,
processNode,
reExecEvent,
reparentEvent,
rootSpawn,
spawnEvent,
} from "./eventProcessTree.fixture.js";
describe("event-backed process tree reconstruction", () => {
it("walks trees larger than ten thousand nodes", () => {
const childPids = Array.from({ length: 10_001 }, (_, index) => index + 2);
const root = processNode({
pid: 1,
ppid: null,
process_name: "root",
children: childPids,
});
const children = childPids.map((pid) =>
processNode({ pid, ppid: 1, process_name: "root" }),
);
expect(maxTreeDepth([root, ...children], 1)).toBe(1);
expect(getDescendants([root, ...children], 1)).toHaveLength(
childPids.length,
);
});
it("reconstructs a simple process tree", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
exitEvent({
sequence: 2,
at_ms: 20,
pid: 2,
ppid: 1,
process_name: "child",
}),
exitEvent({
sequence: 3,
at_ms: 30,
pid: 1,
ppid: 0,
process_name: "root",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.processes).toHaveLength(2);
expect(result.events_consumed).toBe(4);
expect(result.events_unmatched).toBe(0);
expect(result.short_lived_descendants).toBe(2);
});
});
describe("short-lived process descendants", () => {
it("detects short-lived descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "short",
executable: "/short",
}),
exitEvent({
sequence: 2,
at_ms: 11,
pid: 2,
ppid: 1,
process_name: "short",
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.short_lived_descendants).toBe(1);
});
});
describe("event-backed process tree transitions", () => {
it("detects re-exec", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
reExecEvent({
sequence: 1,
pid: 1,
ppid: 0,
process_name: "root",
executable: "/newroot",
arguments: ["--new"],
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_re_exec).toBe(true);
const root = result.processes.find((p) => p.pid === 1);
expect(root?.is_re_exec).toBe(true);
expect(root?.executable).toBe("/newroot");
});
it("detects reparenting", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/child",
}),
reparentEvent({
sequence: 2,
pid: 2,
ppid: 0,
process_name: "child",
previous_ppid: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.has_reparenting).toBe(true);
const child = result.processes.find((p) => p.pid === 2);
expect(child?.is_reparented).toBe(true);
expect(child?.previous_ppid).toBe(1);
expect(child?.ppid).toBe(0);
});
it("reports unmatched events for unknown exits", () => {
const events: ProcessTreeEvent[] = [
exitEvent({
sequence: 0,
at_ms: 0,
pid: 999,
ppid: null,
process_name: null,
exit_code: 1,
}),
];
const result = reconstructProcessTree(events, 1);
expect(result.events_unmatched).toBe(1);
expect(result.processes).toHaveLength(0);
});
});
describe("event-backed process tree queries", () => {
it("gets descendants", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child1",
executable: "/c1",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "grandchild",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
const descendants = getDescendants(result.processes, 1);
expect(descendants).toHaveLength(2);
expect(descendants).toContain(2);
expect(descendants).toContain(3);
});
it("checks process containment", () => {
const events: ProcessTreeEvent[] = [rootSpawn(0)];
const result = reconstructProcessTree(events, 1);
expect(containsProcess(result.processes, 1)).toBe(true);
expect(containsProcess(result.processes, 999)).toBe(false);
});
});
describe("event-backed process tree depth and types", () => {
it("computes max tree depth", () => {
const events: ProcessTreeEvent[] = [
rootSpawn(0),
spawnEvent({
sequence: 1,
pid: 2,
ppid: 1,
process_name: "child",
executable: "/c",
}),
spawnEvent({
sequence: 2,
pid: 3,
ppid: 2,
process_name: "gc",
executable: "/gc",
}),
];
const result = reconstructProcessTree(events, 1);
expect(maxTreeDepth(result.processes, 1)).toBe(2);
});
});
-262
View File
@@ -1,262 +0,0 @@
import { z } from "zod";
/** Event types for event-backed process-tree capture. */
export const processEventTypeSchema = z.enum([
"spawn",
"exit",
"re_exec",
"reparent",
"signal",
"name_change",
"thread_create",
"thread_exit",
]);
/** A single event-backed process-tree event. */
export const processTreeEventSchema = z.strictObject({
/** Monotonic event sequence number. */
sequence: z.number().int().nonnegative(),
/** Event timestamp in milliseconds. */
at_ms: z.number().int().nonnegative(),
/** Event type. */
type: processEventTypeSchema,
/** Process ID. */
pid: z.number().int().positive(),
/** Parent process ID. */
ppid: z.number().int().nullable(),
/** Process name if known. */
process_name: z.string().nullable(),
/** Executable path if known. */
executable: z.string().nullable(),
/** Command line arguments. */
arguments: z.array(z.string()).default([]),
/** Previous PID (for reparent events). */
previous_pid: z.number().int().nullable(),
/** Previous PPID (for reparent events). */
previous_ppid: z.number().int().nullable(),
/** Exit code (for exit events). */
exit_code: z.number().int().nullable(),
/** Signal number (for signal events). */
signal: z.number().int().nullable(),
/** Thread ID (for thread events). */
tid: z.number().int().nullable(),
});
export type ProcessTreeEvent = z.infer<typeof processTreeEventSchema>;
/** Process node in a reconstructed tree. */
export const processNodeSchema = z.strictObject({
pid: z.number().int().positive(),
ppid: z.number().int().nullable(),
process_name: z.string().nullable(),
executable: z.string().nullable(),
arguments: z.array(z.string()).default([]),
children: z.array(z.number().int()).default([]),
spawn_time_ms: z.number().int().nullable(),
exit_time_ms: z.number().int().nullable(),
exit_code: z.number().int().nullable(),
is_re_exec: z.boolean().default(false),
is_reparented: z.boolean().default(false),
previous_ppid: z.number().int().nullable(),
});
export type ProcessNode = z.infer<typeof processNodeSchema>;
/** Result of event-backed process-tree reconstruction. */
export const processTreeReconstructionSchema = z.strictObject({
/** Root PID of the process tree. */
root_pid: z.number().int().positive(),
/** All reconstructed process nodes. */
processes: z.array(processNodeSchema).min(0),
/** Events that were consumed. */
events_consumed: z.number().int().nonnegative(),
/** Events that could not be matched. */
events_unmatched: z.number().int().nonnegative(),
/** Short-lived descendants that were missed by sampling. */
short_lived_descendants: z.number().int().nonnegative(),
/** Whether any re-exec was detected. */
has_re_exec: z.boolean().default(false),
/** Whether any reparenting was detected. */
has_reparenting: z.boolean().default(false),
});
export type ProcessTreeReconstruction = z.infer<
typeof processTreeReconstructionSchema
>;
type ProcessTreeAccumulator = {
readonly nodes: Map<number, ProcessNode>;
readonly children: Map<number, number[]>;
eventsUnmatched: number;
hasReExec: boolean;
hasReparenting: boolean;
shortLivedDescendants: number;
};
const applyProcessTreeEvent = (
event: ProcessTreeEvent,
state: ProcessTreeAccumulator,
): void => {
let node = state.nodes.get(event.pid);
switch (event.type) {
case "spawn": {
if (!node) {
node = {
pid: event.pid,
ppid: event.ppid,
process_name: event.process_name,
executable: event.executable,
arguments: event.arguments,
children: [],
spawn_time_ms: event.at_ms,
exit_time_ms: null,
exit_code: null,
is_re_exec: false,
is_reparented: false,
previous_ppid: null,
};
state.nodes.set(event.pid, node);
}
if (event.ppid !== null) {
const parentChildren = state.children.get(event.ppid) ?? [];
parentChildren.push(event.pid);
state.children.set(event.ppid, parentChildren);
}
break;
}
case "exit":
if (node) {
node.exit_time_ms = event.at_ms;
node.exit_code = event.exit_code;
if (
node.spawn_time_ms !== null &&
event.at_ms - node.spawn_time_ms < 100
)
state.shortLivedDescendants++;
} else state.eventsUnmatched++;
break;
case "re_exec":
if (node) {
node.is_re_exec = true;
node.executable = event.executable ?? node.executable;
node.arguments = event.arguments;
state.hasReExec = true;
} else state.eventsUnmatched++;
break;
case "reparent":
if (node) {
node.previous_ppid = node.ppid;
node.ppid = event.ppid;
node.is_reparented = true;
state.hasReparenting = true;
} else state.eventsUnmatched++;
break;
case "signal":
case "name_change":
case "thread_create":
case "thread_exit":
// These events are recorded but don't modify the tree structure.
break;
}
};
/** Reconstruct a process tree from event-backed capture. */
export function reconstructProcessTree(
events: readonly ProcessTreeEvent[],
rootPid: number,
): ProcessTreeReconstruction {
const nodes = new Map<number, ProcessNode>();
const children = new Map<number, number[]>();
let eventsConsumed = 0;
const state: ProcessTreeAccumulator = {
nodes,
children,
eventsUnmatched: 0,
hasReExec: false,
hasReparenting: false,
shortLivedDescendants: 0,
};
const sorted = [...events].sort((a, b) => a.at_ms - b.at_ms);
for (const event of sorted) {
eventsConsumed++;
applyProcessTreeEvent(event, state);
}
// Attach children to nodes
for (const [pid, childPids] of children) {
const node = nodes.get(pid);
if (node) node.children = childPids;
}
return {
root_pid: rootPid,
processes: [...nodes.values()],
events_consumed: eventsConsumed,
events_unmatched: state.eventsUnmatched,
short_lived_descendants: state.shortLivedDescendants,
has_re_exec: state.hasReExec,
has_reparenting: state.hasReparenting,
};
}
/** Get all descendant PIDs of a given root PID. */
export function getDescendants(
processes: readonly ProcessNode[],
rootPid: number,
): number[] {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const visited = new Set<number>();
const result: number[] = [];
const queue: number[] = [rootPid];
for (let head = 0; head < queue.length; head += 1) {
const pid = queue[head];
if (pid === undefined) continue;
if (visited.has(pid)) continue;
visited.add(pid);
const node = byPid.get(pid);
if (node) {
for (const child of node.children) {
if (!visited.has(child)) {
result.push(child);
queue.push(child);
}
}
}
}
return result;
}
/** Check if a process tree contains a specific PID. */
export function containsProcess(
processes: readonly ProcessNode[],
pid: number,
): boolean {
return processes.some((p) => p.pid === pid);
}
/** Get the maximum tree depth from the root. */
export function maxTreeDepth(
processes: readonly ProcessNode[],
rootPid: number,
): number {
const byPid = new Map(processes.map((p) => [p.pid, p]));
const pending = [{ pid: rootPid, depth: 0 }];
const visited = new Set<number>();
let maximumDepth = 0;
while (pending.length > 0) {
const current = pending.pop();
if (!current || visited.has(current.pid)) continue;
visited.add(current.pid);
const node = byPid.get(current.pid);
if (!node || node.children.length === 0) continue;
const childDepth = current.depth + 1;
maximumDepth = Math.max(maximumDepth, childDepth);
for (const childPid of node.children)
if (!visited.has(childPid))
pending.push({ pid: childPid, depth: childDepth });
}
return maximumDepth;
}
+17
View File
@@ -156,6 +156,23 @@ describe("analysis evidence identity", () => {
});
});
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
const reason = "Caller excluded the observed digest.";
const observation = { operation: "health", parameters: {}, result: true };
const explicit = createEvidence(undefined, PROVIDER, {
...observation,
subjectUnavailableReason: reason,
});
const defaulted = createEvidence(undefined, PROVIDER, observation);
expect(explicit.subject).toBeNull();
expect(explicit.limitations).toEqual([reason]);
expect(defaulted.limitations).toEqual([
"Artifact identity is unavailable for this observation.",
]);
expect(explicit.evidence_id).not.toBe(defaulted.evidence_id);
expect(parseEvidence(explicit)).toEqual(explicit);
});
it("derives byte-stable bundle manifests independent of record order", () => {
const artifactEvidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
+7 -2
View File
@@ -169,6 +169,8 @@ export interface EvidenceObservation {
readonly authority?: EvidenceAuthority;
readonly environment?: ExecutionEnvironment | null;
readonly limitations?: readonly string[];
/** Reason the subject identity is unavailable, when no target identity is supplied. */
readonly subjectUnavailableReason?: string;
readonly locations?: readonly EvidenceLocation[];
readonly evidenceLinks?: readonly string[];
}
@@ -229,7 +231,7 @@ export const createEvidence = (
target === undefined
? null
: {
name: target.path.split("/").at(-1) ?? target.path,
name: target.path.split("/").at(-1) || "artifact",
digest: { sha256: target.sha256 },
format: target.format,
architecture: target.architecture ?? null,
@@ -262,7 +264,10 @@ export const createEvidence = (
environment: observation.environment ?? null,
limitations: [
...(target === undefined
? ["Artifact identity is unavailable for this observation."]
? [
observation.subjectUnavailableReason ??
"Artifact identity is unavailable for this observation.",
]
: []),
...(observation.limitations ?? []),
],
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "./evidence.js";
import {
createEvidenceBundle,
evidenceBundleForTarget,
parseEvidenceBundle,
} from "./evidenceBundle.js";
import {
createResidualUnknown,
recordUnknownInputSchema,
} from "./residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
const targetDigest = "a".repeat(64);
const foreignDigest = "b".repeat(64);
const makeUnknown = (
question: string,
scopeDigest: string,
dependency?: string,
) => {
const input = recordUnknownInputSchema.parse({
question,
severity: "medium",
domain: "bundle-projection",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships:
dependency === undefined
? []
: [{ type: "depends-on", unknown_id: dependency }],
});
const mutation = createEvidence(undefined, provider, {
predicateType: "rea.residual-unknown-mutation",
operation: "record_unknown",
parameters: { domain: input.domain, severity: input.severity },
result: {
action: "record",
question: input.question,
required_authority: input.required_authority,
required_confidence: input.required_confidence,
},
});
return {
evidence: mutation,
unknown: createResidualUnknown(input, mutation.evidence_id, scopeDigest),
};
};
describe("evidenceBundleForTarget", () => {
it("removes dependent unknowns when their foreign-scope root is excluded", () => {
const foreignRoot = makeUnknown("Foreign root", foreignDigest);
const child = makeUnknown(
"Target child",
targetDigest,
foreignRoot.unknown.unknown_id,
);
const grandchild = makeUnknown(
"Target grandchild",
targetDigest,
child.unknown.unknown_id,
);
const retained = makeUnknown("Independent target", targetDigest);
const bundle = createEvidenceBundle(
[
foreignRoot.evidence,
child.evidence,
grandchild.evidence,
retained.evidence,
],
[
foreignRoot.unknown,
child.unknown,
grandchild.unknown,
retained.unknown,
],
);
expect(evidenceBundleForTarget(bundle, targetDigest)).toEqual(
createEvidenceBundle([retained.evidence], [retained.unknown]),
);
});
it("projects a valid graph with more than 125,000 dependents", () => {
const foreignRoot = makeUnknown("Foreign high-fan-out root", foreignDigest);
const middle = makeUnknown(
"Target middle depending on foreign root",
targetDigest,
foreignRoot.unknown.unknown_id,
);
const unknowns = [foreignRoot.unknown, middle.unknown];
for (let index = 0; index < 125_000; index += 1) {
const input = recordUnknownInputSchema.parse({
question: `Target child ${index}`,
severity: "medium",
domain: "bundle-projection",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [
{ type: "depends-on", unknown_id: middle.unknown.unknown_id },
],
});
unknowns.push(
createResidualUnknown(input, middle.evidence.evidence_id, targetDigest),
);
}
const bundle = parseEvidenceBundle(
createEvidenceBundle([foreignRoot.evidence, middle.evidence], unknowns),
);
expect(evidenceBundleForTarget(bundle, targetDigest)).toEqual(
createEvidenceBundle([], []),
);
});
});
+108 -41
View File
@@ -111,28 +111,57 @@ export const evidenceBundleForTarget = (
const recordsById = new Map(
bundle.records.map((record) => [record.evidence_id, record]),
);
let unknowns = bundle.unknowns.filter(
const candidates = bundle.unknowns.filter(
({ scope_digest: scopeDigest }) => scopeDigest === sha256,
);
let changed = true;
while (changed) {
const ids = new Set(unknowns.map(({ unknown_id: id }) => id));
const retained = unknowns.filter(
(unknown) =>
unknown.relationships.every(({ unknown_id: id }) => ids.has(id)) &&
referencedEvidenceIds(unknown).every((id) => {
const record = recordsById.get(id);
return (
record?.subject?.digest.sha256 === sha256 ||
(unknown.mutation_evidence_ids.includes(id) &&
record?.subject === null &&
record.predicate_type === "rea.residual-unknown-mutation")
);
}),
const retained = new Set<ResidualUnknown>();
const revisionsById = new Map<string, number>();
const dependents = new Map<string, Set<ResidualUnknown>>();
for (const unknown of candidates) {
const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids);
const evidenceAvailable = referencedEvidenceIds(unknown).every((id) => {
const record = recordsById.get(id);
return (
record?.subject?.digest.sha256 === sha256 ||
(mutationEvidenceIds.has(id) &&
record?.subject === null &&
record.predicate_type === "rea.residual-unknown-mutation")
);
});
if (!evidenceAvailable) continue;
retained.add(unknown);
revisionsById.set(
unknown.unknown_id,
(revisionsById.get(unknown.unknown_id) ?? 0) + 1,
);
changed = retained.length !== unknowns.length;
unknowns = retained;
for (const relatedId of new Set(
unknown.relationships.map(({ unknown_id: id }) => id),
)) {
const references =
dependents.get(relatedId) ?? new Set<ResidualUnknown>();
references.add(unknown);
dependents.set(relatedId, references);
}
}
const pending: ResidualUnknown[] = [];
for (const unknown of retained)
if (
unknown.relationships.some(({ unknown_id: id }) => !revisionsById.has(id))
)
pending.push(unknown);
for (let index = 0; index < pending.length; index += 1) {
const unknown = pending[index];
if (unknown === undefined || !retained.delete(unknown)) continue;
const remaining = (revisionsById.get(unknown.unknown_id) ?? 1) - 1;
if (remaining > 0) {
revisionsById.set(unknown.unknown_id, remaining);
continue;
}
revisionsById.delete(unknown.unknown_id);
for (const dependent of dependents.get(unknown.unknown_id) ?? [])
pending.push(dependent);
}
const unknowns = candidates.filter((unknown) => retained.has(unknown));
const mutationIds = new Set(
unknowns.flatMap(({ mutation_evidence_ids: ids }) => ids),
);
@@ -285,26 +314,28 @@ export const validateResidualUnknownAddition = (
);
if (unknown.resolution?.disposition === "verified")
validateVerifiedResolution(unknown, evidenceById);
for (const relationship of unknown.relationships)
// In a valid graph, no existing node can point to an absent ID. Since the
// schema rejects self-relations, a new node's outgoing edges cannot close a
// cycle; keep graph traversal for revisions of existing nodes only.
if (current !== undefined) {
const dependencies = unknown.relationships
.filter((relationship) => relationship.type === "depends-on")
.map(({ unknown_id }) => unknown_id);
if (
relationship.type === "depends-on" &&
reachesUnknown(
relationship.unknown_id,
unknown.unknown_id,
currentHeads,
unknown,
)
dependencies.length > 0 &&
reachesUnknown(dependencies, unknown.unknown_id, currentHeads, unknown)
)
throw new TypeError("Residual unknown dependency graph contains a cycle");
}
};
const reachesUnknown = (
start: string,
starts: readonly string[],
goal: string,
currentHeads: ReadonlyMap<string, ResidualUnknown>,
candidate: ResidualUnknown,
): boolean => {
const pending = [start];
const pending = [...starts];
const visited = new Set<string>();
while (pending.length > 0) {
const id = pending.pop();
@@ -356,20 +387,56 @@ const rejectDependencyCycles = (
): void => {
const visited = new Set<string>();
const active = new Set<string>();
const visit = (id: string): void => {
if (active.has(id))
throw new TypeError("Residual unknown dependency graph contains a cycle");
if (visited.has(id)) return;
active.add(id);
const unknown = unknownById.get(id);
if (unknown === undefined)
const pending: {
readonly id: string;
readonly relationships: ResidualUnknown["relationships"];
nextRelationship: number;
}[] = [];
for (const root of unknownById.keys()) {
if (visited.has(root)) continue;
const rootUnknown = unknownById.get(root);
if (rootUnknown === undefined)
throw new TypeError("Residual unknown dependency graph is inconsistent");
for (const relationship of unknown.relationships)
if (relationship.type === "depends-on") visit(relationship.unknown_id);
active.delete(id);
visited.add(id);
};
for (const id of unknownById.keys()) visit(id);
active.add(root);
pending.push({
id: root,
relationships: rootUnknown.relationships,
nextRelationship: 0,
});
while (pending.length > 0) {
const frame = pending[pending.length - 1];
if (frame === undefined) break;
let descended = false;
while (frame.nextRelationship < frame.relationships.length) {
const relationship = frame.relationships[frame.nextRelationship];
frame.nextRelationship += 1;
if (relationship?.type !== "depends-on") continue;
const dependency = relationship.unknown_id;
if (active.has(dependency))
throw new TypeError(
"Residual unknown dependency graph contains a cycle",
);
if (visited.has(dependency)) continue;
const unknown = unknownById.get(dependency);
if (unknown === undefined)
throw new TypeError(
"Residual unknown dependency graph is inconsistent",
);
active.add(dependency);
pending.push({
id: dependency,
relationships: unknown.relationships,
nextRelationship: 0,
});
descended = true;
break;
}
if (descended) continue;
pending.pop();
active.delete(frame.id);
visited.add(frame.id);
}
}
};
/** Encode a validated bundle as byte-stable RFC 8785 canonical JSON. */
+126
View File
@@ -0,0 +1,126 @@
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
import { expect, it } from "vitest";
import {
AnalysisInputError,
AnalysisCapabilityUnavailableError,
} from "./analysisErrorCore.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
import {
redactExplicitFailure,
redactExplicitPointer,
} from "./explicitSensitiveFailure.js";
it.each([
["/metadata/private~1~0/numeric", ["private/~"], "/metadata"],
["/metadata/private/child", ["private"], "/metadata"],
["/ordinary/path", [], "/ordinary/path"],
])(
"preserves a real parent for excluded pointer identities: %s",
(pointer, values, expected) => {
expect(redactExplicitPointer(pointer, values)).toBe(expected);
},
);
it("preserves cleanup failure authority and resources while excluding diagnostics", () => {
const error = new ProviderCleanupError(
"har",
["/root/private/capture", "pid:123"],
{
capture_path: "/root/private/capture",
nested: { "private-key": 5, ordinary: "private ordinary" },
exit_code: 2,
},
{ operation: "inspect_web_network_capture" },
);
const projected = projectAnalysisError(
redactExplicitFailure(error, ["private", "REDACTED"]),
);
expect(projected.code).toBe("cleanup_incomplete");
expect(JSON.stringify(projected)).not.toContain("private");
expect(JSON.stringify(projected)).not.toContain("REDACTED");
expect(JSON.stringify(projected)).toContain("pid:123");
expect(JSON.stringify(projected)).toContain('"exit_code":2');
});
it("keeps unsupported profile reasons distinct from malformed input", () => {
const error = new AnalysisCapabilityUnavailableError(
"mitmproxy",
"inspect_web_network_capture",
"Unsupported private profile",
{ userMessage: "Select private-compatible profile" },
);
const result = redactExplicitFailure(error, ["private"]);
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
expect(projectAnalysisError(result).code).toBe("capability_unavailable");
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("coarsens format issue pointers without creating replacement coordinates", () => {
const error = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[
{
path: ["capture_path", "/metadata/private~1~0/nested"],
reason: "invalid_format",
message: "Malformed private field",
},
],
);
const result = redactExplicitFailure(error, ["private/~", "private"]);
expect(result).toBeInstanceOf(AnalysisInputError);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual(["capture_path", "/metadata"]);
});
it("excludes a marked permission-denied path without losing its host error code", () => {
const error = redactExplicitFailure(
new AnalysisAccessDeniedError(
"inspect_web_network_capture",
"/declared-path-value/capture.har",
"EACCES",
),
["declared-path-value"],
);
expect(error._tag).toBe("AnalysisAccessDeniedError");
const projected = projectAnalysisError(error);
expect(projected).toMatchObject({
code: "access_denied",
category: "unavailable",
details: { system_code: "EACCES" },
});
expect(JSON.stringify(projected)).not.toContain("declared-path-value");
});
it("coarsens ordinary sensitive issue-path segments to their real parent", () => {
const input = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[
{
path: ["input", "mysecret", "child"],
reason: "unknown_argument",
message: "Unrecognized mysecret",
},
],
);
const result = redactExplicitFailure(input, ["secret"]);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual(["input"]);
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("secret");
});
it("does not reinterpret an unknown argument name as a JSON pointer", () => {
const input = new AnalysisInputError(
"inspect_web_network_capture",
undefined,
[{ path: ["/ordinary/secret"], reason: "unknown_argument" }],
);
const result = redactExplicitFailure(input, ["secret"]);
if (!(result instanceof AnalysisInputError))
throw new Error("Input error required");
expect(result.issues[0]?.path).toEqual([]);
});
+136
View File
@@ -0,0 +1,136 @@
import type { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCapabilityUnavailableError,
} from "./analysisErrorCore.js";
import { redactExplicitText } from "./explicitSensitiveValues.js";
import type { JsonValue } from "./jsonValue.js";
import { ProviderAdapterError } from "./providerAdapterError.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
/** Keep a real JSON-pointer ancestor when a property identity is explicitly excluded. */
export const redactExplicitPointer = (
pointer: string,
values: readonly string[],
): string => {
let parent = "";
for (const segment of pointer.split("/").slice(1)) {
const decoded = segment.replaceAll("~1", "/").replaceAll("~0", "~");
const child = `${parent}/${segment}`;
if (
values.some(
(literal) => decoded.includes(literal) || child.includes(literal),
)
)
return parent;
parent = child;
}
return parent;
};
/** Exclude explicit literals from common acquisition/decoder failures, preserving typed diagnostics. */
export const redactExplicitFailure = (
error: AnalysisError,
values: readonly string[],
): AnalysisError => {
if (values.length === 0) return error;
const text = (value: string): string => redactExplicitText(value, values);
const path = (
parts: readonly (string | number)[],
ordinaryNames: boolean,
): (string | number)[] => {
const retained: (string | number)[] = [];
for (const part of parts) {
if (typeof part !== "string") {
retained.push(part);
} else if (!ordinaryNames && part.startsWith("/")) {
const pointer = redactExplicitPointer(part, values);
retained.push(pointer);
if (pointer !== part) break;
} else {
if (values.some((literal) => part.includes(literal))) break;
retained.push(part);
}
}
return retained;
};
const diagnostics = (
value: Readonly<Record<string, JsonValue>>,
): Record<string, JsonValue> =>
Object.fromEntries(
Object.entries(value)
.filter(([key]) => !values.some((literal) => key.includes(literal)))
.map(([key, item]) => [key, visit(item)]),
);
const visit = (value: JsonValue): JsonValue => {
if (typeof value === "string") return text(value);
if (Array.isArray(value)) return value.map(visit);
if (typeof value === "object" && value !== null) return diagnostics(value);
return value;
};
if (error instanceof AnalysisAccessDeniedError)
return new AnalysisAccessDeniedError(
error.operation,
text(error.path),
error.systemCode,
{ cause: error },
);
if (error instanceof AnalysisArtifactChangedError)
return new AnalysisArtifactChangedError(
error.operation,
text(error.path),
text(error.reason),
{ cause: error },
);
if (error instanceof AnalysisInputError)
return new AnalysisInputError(
error.operation,
{ cause: error },
error.issues.map((issue) => ({
...issue,
// Unknown-argument paths contain literal field names, including names
// beginning with '/'; they are not producer JSON-pointer coordinates.
path: path(issue.path, issue.reason === "unknown_argument"),
...(issue.message === undefined
? {}
: { message: text(issue.message) }),
...(issue.expected === undefined
? {}
: { expected: visit(issue.expected) }),
})),
);
if (error instanceof AnalysisOutputError)
return new AnalysisOutputError(error.operation, text(error.reason), {
cause: error,
});
if (error instanceof AnalysisCapabilityUnavailableError)
return new AnalysisCapabilityUnavailableError(
error.providerId,
error.operation,
text(error.reason),
{
cause: error,
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
},
);
if (error instanceof ProviderCleanupError)
return new ProviderCleanupError(
error.providerId,
error.cleanupResources.map(text),
diagnostics(error.diagnostics ?? {}),
{ operation: error.operation, cause: error },
);
if (error instanceof ProviderAdapterError)
return new ProviderAdapterError(error.providerId, error.operation, {
cause: error,
...(error.diagnostics === undefined
? {}
: { diagnostics: diagnostics(error.diagnostics) }),
});
return error;
};
@@ -0,0 +1,22 @@
import { expect, it } from "vitest";
import { redactExplicitText } from "./explicitSensitiveValues.js";
it.each([
["secret context", ["secret"]],
["secret context", ["secret", "REDACTED"]],
["secret context", ["secret", "[", "…"]],
["secretable context", ["secret", "able", "table"]],
["secretsecret context", ["secret", "…", "REDACTED"]],
] as const)(
"keeps declared literals out of replacement text: %s",
(input, values) => {
const result = redactExplicitText(input, values);
for (const value of values) expect(result).not.toContain(value);
},
);
it("does not guess sensitivity or treat empty declarations as matches", () => {
expect(redactExplicitText("API_SECRET ordinary evidence", [""])).toBe(
"API_SECRET ordinary evidence",
);
});
+20
View File
@@ -0,0 +1,20 @@
/** Replace caller-declared literal text values without guessing sensitivity from names. */
export const redactExplicitText = (
value: string,
sensitiveValues: readonly string[],
): string => {
const literals = [...new Set(sensitiveValues)].filter(
(literal) => literal !== "",
);
const replacement =
["[REDACTED]", "…", ""].find((candidate) =>
literals.every((literal) => !candidate.includes(literal)),
) ?? "";
let result = value;
for (const literal of literals.sort(
(left, right) => right.length - left.length,
))
result = result.replaceAll(literal, replacement);
// Replacement boundaries can form another declaration; exclude that text.
return literals.some((literal) => result.includes(literal)) ? "" : result;
};
+11 -1
View File
@@ -1,11 +1,21 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { jsonValueSchema } from "../jsonValue.js";
import { isAbsoluteLocalPath } from "../localPath.js";
const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const range = z.strictObject({ offset: bytes, length: bytes.positive() });
const target = {
path: z.string().min(1).describe("Local firmware file; never executed"),
path: z
.string()
.min(1)
.refine(isAbsoluteLocalPath, {
message:
"path must be an absolute local filesystem path (for example /tmp/firmware.bin or C:\\firmware\\firmware.bin)",
})
.describe(
"Absolute local firmware file; never executed. Relative paths are rejected.",
),
};
/** Explicit firmware inspection and extraction intent, independent of engines. */
+106
View File
@@ -246,6 +246,112 @@ describe("function collection collation ties", () => {
});
});
describe("function comparison ordering controls", () => {
const composed = { address: "0x2000", name: "caf\u00e9" };
const decomposed = { address: "0x3000", name: "cafe\u0301" };
it("preserves duplicate Unicode collections and nullable endpoints", () => {
const controlled = (base: "0x1000" | "0x2000", reverse: boolean) => {
const endpoint = base === "0x1000" ? "0x1010" : "0x2010";
const edges = [
{
source_address: base,
target_address: endpoint,
source_procedure: null,
target_procedure: { address: endpoint, name: "caf\u00e9" },
kind: {
available: true,
provenance: "provider-reference-manager",
type: "UNCONDITIONAL_CALL",
flow: true,
call: true,
jump: false,
data: false,
read: false,
write: false,
indirect: false,
computed: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 0,
external: false,
},
},
{
source_address: base,
target_address: endpoint,
source_procedure: { address: base, name: "dispatch" },
target_procedure: null,
kind: {
available: true,
provenance: "provider-reference-manager",
type: "READ",
flow: false,
call: false,
jump: false,
data: true,
read: true,
write: false,
indirect: false,
computed: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 1,
external: false,
},
},
];
const strings = [
{ address: endpoint, source_address: base, value: "caf\u00e9" },
{ address: endpoint, source_address: base, value: "cafe\u0301" },
{ address: endpoint, source_address: base, value: "cafe\u0301" },
];
return functionDossierSchema.parse({
...dossier("return 0;", base),
callees: [composed, decomposed, composed],
incoming_references: reverse ? [...edges].reverse() : edges,
outgoing_references: reverse ? [...edges].reverse() : edges,
referenced_strings: reverse ? [...strings].reverse() : strings,
referenced_names: reverse ? [...strings].reverse() : strings,
});
};
const makeEvidence = (digit: string, result: unknown): Evidence =>
createEvidence(
{
path: `/tmp/function-${digit}`,
sha256: digit.repeat(64),
format: "mach-o",
},
{ id: "rea-workflow", name: "REA workflow", version: "1" },
{
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: "dispatch",
}),
result: jsonValueSchema.parse(result),
confidence: "derived",
authority: "shipped-artifact",
},
);
const left = controlled("0x1000", false);
const right = controlled("0x2000", true);
const { native_api: _nativeApi, ...rightWithoutNativeApi } = right;
const comparison = compareFunctions(
makeEvidence("d", left),
makeEvidence("e", rightWithoutNativeApi),
);
expect(comparison.status).toBe("unchanged");
for (const dimension of ["calls", "references", "strings_names"] as const)
expect(
comparison.dimensions.find((item) => item.dimension === dimension),
).toMatchObject({ status: "unchanged" });
});
});
describe("function comparison CFG address normalization", () => {
it("matches CFG successors by numeric address", () => {
const make = (base: "0x1000" | "0x2000") =>
+13 -9
View File
@@ -177,15 +177,19 @@ export const stringAndNameProjection = (
};
export const sorted = (values: readonly unknown[]): readonly unknown[] =>
[...values].sort((left, right) => {
const leftJson = canonicalJson(left, "Function normalization");
const rightJson = canonicalJson(right, "Function normalization");
// Preserve existing collation while ordering distinct values within a tie.
return (
leftJson.localeCompare(rightJson) ||
compareCodePoints(leftJson, rightJson)
);
});
values
.map((value) => ({
value,
json: canonicalJson(value, "Function normalization"),
}))
.sort((left, right) => {
// Preserve existing collation while ordering distinct values within a tie.
return (
left.json.localeCompare(right.json) ||
compareCodePoints(left.json, right.json)
);
})
.map(({ value }) => value);
export const combineCoverage = <Item>(
left: FunctionCollection<Item>,
+37
View File
@@ -2,8 +2,45 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { projectInputIssues } from "./inputIssueProjection.js";
import { processScenarioSchema } from "./process/processScenario.js";
describe("input issue projection", () => {
it("preserves static regex guidance without echoing the rejected value", () => {
const schema = z.object({
value: z.string().regex(/^[^\0]*$/u, "Values cannot contain NUL"),
});
const input = { value: "private\0value" };
const parsed = schema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["value"],
reason: "invalid_format",
expected: "regex",
message: "Values cannot contain NUL",
},
]);
});
it("projects reserved process environment key constraints at the key path", () => {
const input = {
executable: "/usr/bin/true",
environment: { REA_PROCESS_RUN_ID: "caller-value" },
};
const parsed = processScenarioSchema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["environment", "REA_PROCESS_RUN_ID"],
reason: "invalid_format",
expected: "regex",
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
},
]);
});
it("preserves schema-authored custom correction guidance", () => {
const schema = z
.object({ left: z.string().optional(), right: z.string().optional() })
+17 -1
View File
@@ -27,6 +27,13 @@ const projectIssue = (
),
),
);
if (issue.code === "invalid_key")
return issue.issues.flatMap((keyIssue) =>
projectIssue(
{ ...keyIssue, path: [...issue.path, ...keyIssue.path] },
input,
),
);
if (issue.code === "unrecognized_keys")
return issue.keys.map((key) => ({
path: [...path, key],
@@ -48,7 +55,16 @@ const projectIssue = (
if (issue.code === "too_big")
return [boundedIssue(path, "maximum", numericBound(issue.maximum))];
if (issue.code === "invalid_format")
return [{ path, reason: "invalid_format", expected: issue.format }];
return [
{
path,
reason: "invalid_format",
expected: issue.format,
...(issue.format === "regex" && issue.message.length > 0
? { message: issue.message }
: {}),
},
];
if (issue.code === "invalid_value")
return [
{
@@ -1,6 +1,11 @@
import { z } from "zod";
const pathInputSchema = z.string().trim().min(1);
import { isAbsoluteLocalPath } from "../localPath.js";
const pathInputSchema = z.string().trim().min(1).refine(isAbsoluteLocalPath, {
message:
"Electron executable, application, and root paths must be absolute local filesystem paths (for example /Applications/Electron.app/Contents/MacOS/Electron)",
});
const absolutePathSchema = z
.string()
.min(1)
@@ -60,9 +65,17 @@ const actionSchema = z.discriminatedUnion("kind", [
/** Input for one explicit, provider-owned Electron runtime experiment. */
export const electronActiveObservationInputSchema = z.strictObject({
executable_path: pathInputSchema,
application_path: pathInputSchema,
application_root: pathInputSchema.optional(),
executable_path: pathInputSchema.describe(
"Absolute local filesystem path for the Electron executable; relative paths are rejected.",
),
application_path: pathInputSchema.describe(
"Absolute local filesystem path for the Electron application; relative paths are rejected.",
),
application_root: pathInputSchema
.optional()
.describe(
"Absolute local filesystem root for application-relative paths; omit to derive it from the application path. Relative paths are rejected.",
),
args: z.array(z.string()).default([]),
actions: z.array(actionSchema).default([]),
});
@@ -2,156 +2,46 @@ import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
describe.each(["webPreferences", "serviceName"] as const)(
"Electron %s option lookup",
(name) => {
const value =
name === "webPreferences"
? '{ preload: "./kept.js", sandbox: true }'
: '"kept"';
const explicit = `${name}: ${value}`;
const method = `${name}() { return ${value}; }`;
const getter = `get ${name}() { return ${value}; }`;
const setter = `set ${name}(value) {}`;
describe("Electron option evidence", () => {
it("keeps the final explicit preload and service name with unrelated keys", () => {
const analysis = analyzeJavaScriptStaticSource(`
new BrowserWindow({ webPreferences: { preload: "./kept.js", sandbox: true }, title: "App" });
utilityProcess.fork("./worker.js", [], { serviceName: "kept", cwd: "/app" });
`);
const explicitCases = [
["plain key", explicit],
["quoted key", `"${name}": ${value}`],
["computed string key", `["${name}"]: ${value}`],
["duplicate key", `${name}: null, ${explicit}`],
["computed duplicate key", `${name}: null, ["${name}"]: ${value}`],
["earlier spread", `...options, ${explicit}`],
["earlier computed identifier", `[key]: null, ${explicit}`],
["earlier computed expression", `[getKey()]: null, ${explicit}`],
["earlier getter", `${getter}, ${explicit}`],
["earlier method", `${method}, ${explicit}`],
["unrelated later key", `${explicit}, title: "title"`],
["unrelated computed literal", `${explicit}, ["title"]: null`],
["unrelated numeric key", `${explicit}, [1]: null`],
["unrelated empty key", `${explicit}, [""]: null`],
["unrelated getter", `${explicit}, get title() { return "title"; }`],
];
it.each(explicitCases)(
"retains the explicit value with %s",
(_, members) => {
const analysis = analyzeOption(name, `{ ${members} }`);
expect(analysis.parse_status).toBe("complete");
if (name === "webPreferences") {
expect(analysis.electron.browser_windows).toEqual([
expect.objectContaining({
options_status: "object-literal",
web_preferences_status: "object-literal",
preload_path: "./kept.js",
preload_resolution_context: "module-specifier",
web_preferences: [
{ name: "preload", value: literal("./kept.js") },
{ name: "sandbox", value: literal(true) },
],
}),
]);
} else {
expect(analysis.electron.utility_processes).toEqual([
expect.objectContaining({ service_name: "kept" }),
]);
}
},
);
const dynamicCases = [
["same-spelled computed binding", `[${name}]: ${value}`],
["different computed binding", `[key]: ${value}`],
["computed expression", `[getKey()]: ${value}`],
["unevaluated template key", `[\`${name}\`]: ${value}`],
["spread only", "...options"],
["later spread", `${explicit}, ...options`],
["later computed binding", `${explicit}, [key]: null`],
["later computed expression", `${explicit}, [getKey()]: null`],
["exact getter", getter],
["exact setter", setter],
["exact method", method],
["computed string method", `["${name}"]() { return ${value}; }`],
["overriding getter", `${explicit}, ${getter}`],
["overriding setter", `${explicit}, ${setter}`],
["overriding method", `${explicit}, ${method}`],
["dynamic explicit value", `${name}: dynamicValue`],
["null explicit value", `${name}: null`],
["duplicate null value", `${explicit}, ${name}: null`],
];
it.each(dynamicCases)("preserves uncertainty for %s", (_, members) => {
expectUnknownOption(name, `{ ${members} }`, "object-literal");
});
it.each(["null", "options"])(
"preserves nonliteral options %s",
(options) => {
expectUnknownOption(name, options, "dynamic");
},
);
it.each(["", "{}", '{ title: "title", ["other"]: null }'])(
"reports an omitted option in %s without inventing a default",
(options) => {
const analysis = analyzeOption(name, options);
expect(analysis.parse_status).toBe("complete");
if (name === "webPreferences")
expect(analysis.electron.browser_windows[0]).toMatchObject({
options_status: options === "" ? "missing" : "object-literal",
web_preferences_status: "missing",
web_preferences: [],
preload_path: null,
preload_resolution_context: null,
});
else
expect(
analysis.electron.utility_processes[0]?.service_name,
).toBeNull();
},
);
},
);
type OptionName = "webPreferences" | "serviceName";
const analyzeOption = (name: OptionName, options: string) =>
analyzeJavaScriptStaticSource(`
const webPreferences = "title";
const serviceName = "env";
${
name === "webPreferences"
? `new BrowserWindow(${options});`
: `utilityProcess.fork("./worker.js", []${options === "" ? "" : `, ${options}`});`
}
`);
const literal = (value: string | boolean) => ({
status: "literal",
value,
expression: null,
});
const expectUnknownOption = (
name: OptionName,
options: string,
optionsStatus: "object-literal" | "dynamic",
): void => {
const analysis = analyzeOption(name, options);
expect(analysis.parse_status).toBe("partial");
expect(analysis.parse_error_count).toBe(0);
expect(analysis.limitations.join(" ")).toContain("remain unknown");
if (name === "webPreferences")
expect(analysis.parse_status).toBe("complete");
expect(analysis.electron.browser_windows[0]).toMatchObject({
options_status: optionsStatus,
web_preferences_status: "dynamic",
web_preferences: [],
preload_path: null,
preload_resolution_context: null,
preload_path: "./kept.js",
preload_resolution_context: "module-specifier",
web_preferences: [
{ name: "preload", value: { status: "literal", value: "./kept.js" } },
{ name: "sandbox", value: { status: "literal", value: true } },
],
});
expect(analysis.electron.utility_processes[0]).toMatchObject({
module_path: "./worker.js",
service_name: "kept",
});
});
it("keeps values unknown when a later computed key can override them", () => {
const analysis = analyzeJavaScriptStaticSource(`
new BrowserWindow({ webPreferences: { preload: "./maybe.js" }, [key]: null });
utilityProcess.fork("./worker.js", [], { serviceName: "maybe", [key]: null });
`);
expect(analysis.parse_status).toBe("partial");
expect(analysis.parse_error_count).toBe(0);
expect(analysis.limitations.join(" ")).toContain("remain unknown");
expect(analysis.electron.browser_windows[0]).toMatchObject({
preload_path: null,
preload_resolution_context: null,
web_preferences_status: "dynamic",
web_preferences: [],
});
else
expect(analysis.electron.utility_processes[0]).toMatchObject({
module_path: "./worker.js",
module_expression: null,
service_name: null,
});
};
});
});
@@ -1,5 +1,8 @@
import { uniqueSorted } from "../canonicalOrdering.js";
import { digestExportShapeValue } from "./javascriptExportShapeComparisonIdentity.js";
import { compareCodePoints, uniqueSorted } from "../canonicalOrdering.js";
import {
canonicalExportShapeValue,
digestExportShapeValue,
} from "./javascriptExportShapeComparisonIdentity.js";
import {
javaScriptExportShapeComparisonResultSchema,
type JavaScriptExportShapeComparisonChange,
@@ -14,7 +17,6 @@ import {
} from "./javascriptExportShapeSelection.js";
import {
buildJavaScriptExportShapeChanges,
compareJavaScriptExportShapeChanges,
hasPartialJavaScriptExportPropertyCoverage,
pairJavaScriptExportShapeVariants,
type JavaScriptExportShapePairing,
@@ -42,14 +44,16 @@ export const compareJavaScriptExportShapes = (
input.left.evidenceId,
input.right.evidenceId,
);
const allChanges = buildJavaScriptExportShapeChanges({
leftSelection: left,
rightSelection: right,
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
evidenceLinks,
}).sort(compareJavaScriptExportShapeChanges);
const allChanges = sortChanges(
buildJavaScriptExportShapeChanges({
leftSelection: left,
rightSelection: right,
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
evidenceLinks,
}),
);
const changes = allChanges;
const omittedChanges = 0;
const coverage = comparisonCoverage({
@@ -78,6 +82,29 @@ export const compareJavaScriptExportShapes = (
});
};
const sortChanges = (
changes: readonly JavaScriptExportShapeComparisonChange[],
): JavaScriptExportShapeComparisonChange[] =>
changes
.map((change, index) => ({
change,
index,
sortKey: canonicalExportShapeValue({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
}),
}))
.sort(
(left, right) =>
compareCodePoints(left.sortKey, right.sortKey) ||
left.index - right.index,
)
.map(({ change }) => change);
interface CoverageInput {
readonly input: JavaScriptExportShapeComparisonProjectionInput;
readonly left: SelectedJavaScriptExport;
@@ -1,9 +1,6 @@
import { expect, it } from "vitest";
import {
javaScriptExportShapeComparisonResultSchema,
projectedExportReturnShapesSchema,
} from "./javascriptExportShapeComparisonSchemas.js";
import { projectedExportReturnShapesSchema } from "./javascriptExportShapeComparisonSchemas.js";
const projectionWithField = (field: unknown) => ({
semantic_role: "export-return-shapes",
@@ -54,104 +51,3 @@ it("parses projected fields into literal, union, or unknown values", () => {
).success,
).toBe(true);
});
it("accepts every projected return site and field without presentation caps", () => {
const fields = Array.from({ length: 65 }, (_, index) => ({
path: `/field-${String(index)}`,
state: "literal",
value: index,
reason: null,
}));
const propertyCoverage = fields.map(({ path }) => ({
path,
status: "complete",
omitted: 0,
}));
const shapes = Array.from({ length: 33 }, () => ({
source_range: {
start: { line: 1, column: 0 },
end: { line: 1, column: 10 },
},
value_status: "object",
fields,
property_coverage: propertyCoverage,
}));
expect(
projectedExportReturnShapesSchema.parse({
...projectionWithField(fields[0]),
static_return_shapes: shapes,
return_shape_coverage: {
status: "complete",
retained_return_sites: shapes.length,
omitted_return_sites: 0,
omitted_fields: 0,
omitted_property_coverage: 0,
projection_complete: true,
},
}).static_return_shapes,
).toHaveLength(33);
});
it("accepts complete candidate and change inventories without page ceilings", () => {
const evidenceId = `ev_${"a".repeat(64)}`;
const graphId = `jag_${"b".repeat(64)}`;
const selector = {
evidence_id: evidenceId,
graph_id: graphId,
requested_module_path: "index.js",
requested_export_name: "render",
candidates: Array.from({ length: 1_001 }, (_, index) => ({
node_id: `jag_node_${index.toString(16).padStart(64, "0")}`,
module_path: "index.js",
export_name: "render",
matches_requested_module: true,
matches_requested_export: true,
})),
omitted_candidates: 0,
status: "missing",
selected_node_id: null,
};
const changes = Array.from({ length: 10_001 }, (_, index) => ({
change_id: `jesc_change_${index.toString(16).padStart(64, "0")}`,
status: "unknown",
path: `/field-${String(index)}`,
discriminant: null,
left: { availability: "absent" },
right: { availability: "absent" },
left_source_range: null,
right_source_range: null,
evidence_links: [evidenceId, `ev_${"c".repeat(64)}`],
limitations: [],
}));
expect(
javaScriptExportShapeComparisonResultSchema.parse({
comparison_id: `jesc_${"d".repeat(64)}`,
left: selector,
right: { ...selector, graph_id: `jag_${"e".repeat(64)}` },
summary: { added: 0, removed: 0, changed: 0, unknown: changes.length },
changes,
coverage: {
status: "complete-within-inputs",
left_graph_status: "complete",
right_graph_status: "complete",
paired_variants: 0,
unpaired_left_variants: 0,
unpaired_right_variants: 0,
omitted_left_variants: 0,
omitted_right_variants: 0,
left_source_omitted_variants: 0,
right_source_omitted_variants: 0,
left_omitted_fields: 0,
right_omitted_fields: 0,
left_omitted_property_coverage: 0,
right_omitted_property_coverage: 0,
omitted_candidates: 0,
omitted_changes: 0,
},
evidence_links: [evidenceId, `ev_${"c".repeat(64)}`],
limitations: [],
}).changes,
).toHaveLength(10_001);
});
@@ -112,16 +112,6 @@ export const buildJavaScriptExportShapeChanges = (
return [...paired, ...unpairedLeft, ...unpairedRight];
};
/** Sort changes by semantic content rather than traversal order. */
export const compareJavaScriptExportShapeChanges = (
left: JavaScriptExportShapeComparisonChange,
right: JavaScriptExportShapeComparisonChange,
): number =>
compareCodePoints(
canonicalExportShapeValue(changeSortKey(left)),
canonicalExportShapeValue(changeSortKey(right)),
);
/** Report whether any retained shape lacks complete property coverage. */
export const hasPartialJavaScriptExportPropertyCoverage = (
shapes: readonly Shape[],
@@ -429,15 +419,6 @@ const changeWithId = (
change_id: `jesc_change_${digestExportShapeValue(semantic)}`,
});
const changeSortKey = (change: JavaScriptExportShapeComparisonChange) => ({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
});
const literalValue = (
field: Field,
):
@@ -253,56 +253,58 @@ describe("feature seed selection controls", () => {
});
describe("public feature trace from contextBridge source members", () => {
it.each(matchingModes)(
"traces $match / $value / case-sensitive $case_sensitive",
(mode) => {
const graph = contextBridgeGraph();
const before = structuredClone(graph);
const input = {
sourceEvidenceId,
graph,
nativeEvidence: [],
direction: "both" as const,
};
const generic = traceApplicationFeature({
...input,
seed: { kind: "string", ...mode },
});
const typed = traceApplicationFeature({
...input,
seed: { kind: "api", ...mode },
});
it("traces one exact member seed through the public feature workflow", () => {
const mode = {
value: "openProject",
match: "exact" as const,
case_sensitive: true,
};
const graph = contextBridgeGraph();
const before = structuredClone(graph);
const input = {
sourceEvidenceId,
graph,
nativeEvidence: [],
direction: "both" as const,
};
const generic = traceApplicationFeature({
...input,
seed: { kind: "string", ...mode },
});
const typed = traceApplicationFeature({
...input,
seed: { kind: "api", ...mode },
});
expect(typed.coverage).toEqual({
status: "complete-within-source",
source_graph_status: "complete",
total_seed_matches: 1,
});
expect(typed.seed_matches).toEqual(generic.seed_matches);
expect(typed.seed_matches).toEqual([
{
node_id: graph.nodes[0]?.node_id,
kind: "context-bridge-api",
basis: "property",
field: "observations[0].properties.members[1]",
},
]);
expect(typed.graph?.nodes).toEqual(graph.nodes);
expect(typed.graph?.edges).toEqual([]);
expect(typed.evidence_links).toEqual([sourceEvidenceId]);
expect(typed.summary).toMatchObject({
matched_seeds: 1,
traced_nodes: 1,
traced_edges: 0,
observed_facts: 1,
inferred_facts: 0,
unknown_facts: 0,
unavailable_facts: 0,
});
expect(typed.native_handoffs).toEqual([]);
expect(graph).toEqual(before);
},
);
expect(typed.coverage).toEqual({
status: "complete-within-source",
source_graph_status: "complete",
total_seed_matches: 1,
});
expect(typed.seed_matches).toEqual(generic.seed_matches);
expect(typed.seed_matches).toEqual([
{
node_id: graph.nodes[0]?.node_id,
kind: "context-bridge-api",
basis: "property",
field: "observations[0].properties.members[1]",
},
]);
expect(typed.graph?.nodes).toEqual(graph.nodes);
expect(typed.graph?.edges).toEqual([]);
expect(typed.evidence_links).toEqual([sourceEvidenceId]);
expect(typed.summary).toMatchObject({
matched_seeds: 1,
traced_nodes: 1,
traced_edges: 0,
observed_facts: 1,
inferred_facts: 0,
unknown_facts: 0,
unavailable_facts: 0,
});
expect(typed.native_handoffs).toEqual([]);
expect(graph).toEqual(before);
});
it("keeps a missing member explicit without changing source coverage", () => {
const graph = contextBridgeGraph();
@@ -2,19 +2,6 @@ import { describe, expect, it } from "vitest";
import { javascriptRecoveryInputSchema } from "./javascriptRecovery.js";
describe("JavaScript recovery requests", () => {
it("defaults omitted transform metadata without requiring engine confirmations", () => {
expect(
javascriptRecoveryInputSchema.parse({
path: "/tmp/bundle.js",
output_directory: "/tmp/recovered",
}),
).toEqual({
path: "/tmp/bundle.js",
output_directory: "/tmp/recovered",
extraction_mode: "structural",
rewrite_level: "standard",
});
});
it.each([
{ path: "", output_directory: "/tmp/recovered" },
{ path: "/tmp/bundle.js" },
@@ -1,39 +1,15 @@
import { expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
it.each(["namespace", "default", "named-default"])(
"retains Node built-in effects from %s imports",
(mode) => {
const imports = ["fs", "child_process", "timers", "http"]
.map((name, index) => {
const declaration =
mode === "namespace"
? `* as m${String(index)}`
: mode === "default"
? `m${String(index)}`
: `{default as m${String(index)}}`;
return `import ${declaration} from 'node:${name}';`;
})
.join("\n");
const ir = analyzeJavaScriptSemantics(`${imports}
const text = m0.readFileSync('config.json','utf8');
const stream = m0.createReadStream('config.json'); stream.destroy();
const child = m1.spawn('/usr/bin/tool', ['--version']);
const timer = m2.setTimeout(work,1000); m2.clearTimeout(timer);
const request = m3.get('http://localhost/');
it("does not assign built-in APIs to unrelated or shadowed bindings", () => {
const ir = analyzeJavaScriptSemantics(`
import fs from "./fs.js";
import { constants as constantsFs } from "node:fs";
fs.createReadStream("config.json");
constantsFs.createReadStream("config.json");
function run(fs) { fs.createReadStream("config.json"); }
`);
expect(ir.configurationOperations).toHaveLength(1);
expect(ir.resourceOperations).toHaveLength(2);
expect(ir.childProcessSpawns).toHaveLength(1);
expect(ir.timerOperations).toHaveLength(2);
expect(ir.requestOperations).toHaveLength(1);
},
);
it.each([
"import fs from './fs.js'; fs.createReadStream('config.json');",
"import {constants as fs} from 'node:fs'; fs.createReadStream('config.json');",
"function run(fs) { fs.createReadStream('config.json'); }",
])("does not invent a built-in namespace for %s", (source) => {
expect(analyzeJavaScriptSemantics(source).resourceOperations).toEqual([]);
expect(ir.resourceOperations).toEqual([]);
});
@@ -155,19 +155,6 @@ describe("JavaScript semantic analysis: calls 2", () => {
]);
});
it("retains every promise operation found in the finite source", () => {
const ir = analyzeJavaScriptSemantics(
`
Promise.resolve(1);
Promise.resolve(2);
Promise.resolve(3);
`,
);
expect(ir.promiseOperations).toHaveLength(3);
expect(ir.coverage.status).toBe("complete");
});
it("fingerprints formatting and local-name changes identically", () => {
const left = analyzeJavaScriptSemantics(`
function calculate(value) {
@@ -1,67 +1,43 @@
import * as t from "@babel/types";
import { expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import {
analyzeJavaScriptSemantics,
analyzeParsedJavaScriptSemantics,
} from "./javascriptSemanticAnalysis.js";
import { onlyBinding, origin } from "./javascriptSemanticAnalysis.fixture.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { calleeName } from "./javascriptStaticAnalysisHelpers.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import { analyzeParsedJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const memberChain = ".next".repeat(12_000);
const ordinaryMemberChain = ".next".repeat(64);
it("retains native addon observations through a deep member initializer", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = require("./addon.node")${memberChain}.last[""];`,
it("preserves a 12,000-member native import through both analyzers", () => {
const parsed = parseJavaScriptSource(
`const value = require("./addon.node")${memberChain}.last; const ordinary = root.next.last;`,
);
expect(analysis.electron.native_addon_bindings).toEqual([
if (parsed === null) throw new Error("Expected valid JavaScript");
const staticAnalysis = analyzeParsedJavaScriptStaticSource("", parsed);
const ir = analyzeParsedJavaScriptSemantics(parsed);
expect(staticAnalysis.parse_status).toBe("complete");
expect(staticAnalysis.electron.native_addon_bindings).toEqual([
expect.objectContaining({ specifier: "./addon.node", members: ["last"] }),
]);
expect(analysis.parse_error_count).toBe(0);
});
it("keeps a deep non-native initializer outside native addon observations", () => {
const analysis = analyzeJavaScriptStaticSource(
`const value = root${memberChain}.last;`,
);
expect(analysis.electron.native_addon_bindings).toEqual([]);
expect(analysis.parse_status).toBe("complete");
});
it("retains unknown value diagnostics and references after a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`const value = root${memberChain}.last;`,
);
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
expect(onlyBinding(ir, "value")).toMatchObject({
value: { status: "unknown", reason: "Cannot project last from unknown." },
provenance: { status: "unknown", reason: "Unbound identifier root." },
});
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
]);
});
it.each([
`const value = require("./dependency.js")${memberChain}[""].last;`,
`const dependency = require("./dependency.js"); const value = dependency${memberChain}[""].last;`,
`const value = require("./dependency.js")?.next${memberChain}[""].last;`,
])("preserves the full literal module path (case %#)", (source) => {
const ir = analyzeJavaScriptSemantics(source);
const path = origin(onlyBinding(ir, "value"));
expect(path.specifier).toBe("./dependency.js");
expect(path.specifier).toBe("./addon.node");
expect(path.importedPath).toEqual([
...(source.includes("?.next") ? ["next"] : []),
...Array.from({ length: 12_000 }, () => "next"),
"",
"last",
]);
expect(ir.coverage.status).toBe("complete");
});
it("retains a deep CommonJS re-export path without inventing dynamic module links", () => {
const ir = analyzeJavaScriptSemantics(`
module.exports.result = require("./dependency.js")${memberChain}.last;
const dynamic = require("./other.js")${memberChain}[key].last;
module.exports.result = require("./dependency.js")${ordinaryMemberChain}.last;
const dynamic = require("./other.js")${ordinaryMemberChain}[key].last;
`);
expect(ir.moduleLinks).toEqual([
expect.objectContaining({
@@ -80,7 +56,7 @@ it("retains a deep CommonJS re-export path without inventing dynamic module link
it("invalidates a deep mutation while retaining unrelated literal properties", () => {
const ir = analyzeJavaScriptSemantics(`
const root = { untouched: "retained" };
root${memberChain}.last = 1;
root${ordinaryMemberChain}.last = 1;
const value = root.untouched;
`);
expect(onlyBinding(ir, "root").value).toEqual({
@@ -98,7 +74,7 @@ it("invalidates a deep mutation while retaining unrelated literal properties", (
});
it("retains the complete location and unresolved target of a deep call", () => {
const callee = `root${memberChain}.last`;
const callee = `root${ordinaryMemberChain}.last`;
const ir = analyzeJavaScriptSemantics(`${callee}();`);
expect(ir.callSites).toEqual([
expect.objectContaining({
@@ -115,7 +91,7 @@ it("retains the complete location and unresolved target of a deep call", () => {
it("retains deep default values without confusing their reads with parameter bindings", () => {
const ir = analyzeJavaScriptSemantics(
`export function inspect(value = root${memberChain}.last) { return value; }`,
`export function inspect(value = root${ordinaryMemberChain}.last) { return value; }`,
);
expect(ir.references.map(({ name, role }) => ({ name, role }))).toEqual([
{ name: "root", role: "read" },
@@ -126,7 +102,7 @@ it("retains deep default values without confusing their reads with parameter bin
it("keeps a shadowed require local through a deep member initializer", () => {
const ir = analyzeJavaScriptSemantics(
`function inspect(require) { const value = require("./dependency.js")${memberChain}.last; return value; }`,
`function inspect(require) { const value = require("./dependency.js")${ordinaryMemberChain}.last; return value; }`,
);
expect(ir.moduleLinks).toEqual([]);
expect(onlyBinding(ir, "value").provenance.origins).toEqual([]);
@@ -140,7 +116,7 @@ it.each([
["root[0].last()", "root.0.last"],
["root[key].last()", "root.[computed@5].last"],
["root?.first.last()", "root.first.last"],
[`root${memberChain}.last()`, `root${memberChain}.last`],
[`root${ordinaryMemberChain}.last()`, `root${ordinaryMemberChain}.last`],
])("preserves exact callee syntax (case %#)", (source, expected) => {
const file = parseJavaScriptSource(source);
const statement = file?.program.body[0];
@@ -147,3 +147,54 @@ it("keeps an explicit return statement's full range and the producer's location"
});
expect(site.location.start.column).toBe(source.indexOf("return"));
});
it("links returned promises to the exact return site in each callable", () => {
const ir = analyzeJavaScriptSemantics(
[
"function first() { return Promise.resolve(1); }",
"function second() { return Promise.resolve(2); }",
].join("\n"),
);
const callables = new Map(
ir.callables.map((callable) => [callable.name, callable]),
);
const promises = ir.promiseOperations.filter(
({ method }) => method === "resolve",
);
expect(promises).toHaveLength(2);
for (const name of ["first", "second"] as const) {
const callable = callables.get(name);
const promise = promises.find(
({ ownerCallableId }) => ownerCallableId === callable?.callableId,
);
expect(callable?.returnSites).toHaveLength(1);
expect(promise).toMatchObject({
ownership: "returned",
ownerCallableId: callable?.callableId,
returnSiteId: callable?.returnSites[0]?.returnSiteId,
});
}
});
it("does not assign a return site to a Promise owned by a binding", () => {
const ir = analyzeJavaScriptSemantics(
"function unrelated() { return Promise.resolve(2); }\nconst pending = Promise.resolve(1);",
);
const owned = ir.promiseOperations.find(
({ ownerCallableId }) => ownerCallableId !== null,
);
const assigned = ir.promiseOperations.find(
({ ownerCallableId }) => ownerCallableId === null,
);
expect(owned).toMatchObject({
ownership: "returned",
returnSiteId: ir.callables.find(({ name }) => name === "unrelated")
?.returnSites[0]?.returnSiteId,
});
expect(assigned).toMatchObject({
ownership: "assigned",
returnSiteId: null,
});
});
@@ -18,6 +18,19 @@ const valueOf = (expression: string) =>
analyzeJavaScriptSemantics(`const answer = ${expression};`),
"answer",
).value;
const valuesOf = (expressions: readonly string[]) => {
const ir = analyzeJavaScriptSemantics(
expressions
.map(
(expression, index) =>
`const candidate${String(index)} = ${expression};`,
)
.join("\n"),
);
return expressions.map(
(_, index) => topLevelBinding(ir, `candidate${String(index)}`).value,
);
};
describe("conditional primitive unions", () => {
const cases = conditionalCandidates.flatMap((known) =>
@@ -35,11 +48,11 @@ describe("conditional primitive unions", () => {
]),
);
it.each(cases)("preserves incompatible alternatives in %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
it("preserves incompatible alternatives across conditional expressions", () => {
expect(valuesOf(cases)).toEqual(cases.map(() => incompatibleValue));
});
it.each([
const exactCases = [
[
'condition ? (choice ? "two" : "one") : "three"',
{ status: "union", values: ["one", "three", "two"] },
@@ -69,8 +82,12 @@ describe("conditional primitive unions", () => {
{ status: "union", values: [null, "one", "two"] },
],
["condition ? null : null", { status: "literal", value: null }],
])("retains exact primitive candidates in %s", (expression, expected) => {
expect(valueOf(expression)).toEqual(expected);
] as const;
it("retains exact primitive candidates across conditional expressions", () => {
expect(valuesOf(exactCases.map(([expression]) => expression))).toEqual(
exactCases.map(([, expected]) => expected),
);
});
it("propagates an incompatible nested branch through an outer union", () => {
@@ -119,11 +136,11 @@ describe("logical primitive unions", () => {
),
);
it.each(cases)("preserves unresolved alternatives in %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
it("preserves unresolved alternatives across logical expressions", () => {
expect(valuesOf(cases)).toEqual(cases.map(() => incompatibleValue));
});
it.each([
const exactCases = [
[
'(choice ? "" : "one") || "two"',
{ status: "union", values: ["", "one", "two"] },
@@ -138,19 +155,24 @@ describe("logical primitive unions", () => {
],
['"one" || "one"', { status: "literal", value: "one" }],
["null ?? null", { status: "literal", value: null }],
])(
"retains the conservative primitive union in %s",
(expression, expected) => {
expect(valueOf(expression)).toEqual(expected);
},
);
] as const;
it.each([
it("retains conservative primitive unions across logical expressions", () => {
expect(valuesOf(exactCases.map(([expression]) => expression))).toEqual(
exactCases.map(([, expected]) => expected),
);
});
const unevaluatedCases = [
'true ? "one" : missing',
'"one" || missing',
"false && missing",
'"one" ?? missing',
])("does not introduce short-circuit evaluation for %s", (expression) => {
expect(valueOf(expression)).toEqual(incompatibleValue);
];
it("does not introduce short-circuit evaluation", () => {
expect(valuesOf(unevaluatedCases)).toEqual(
unevaluatedCases.map(() => incompatibleValue),
);
});
});
@@ -15,7 +15,7 @@ import {
} from "./javascriptSemanticState.js";
import { compareCodePoints } from "../canonicalOrdering.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { range, sourceRangesEqual } from "./javascriptStaticAnalysisHelpers.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
assignedSemanticResultBindings,
dataEffectMemberCallee,
@@ -56,7 +56,10 @@ interface PromiseOwnershipContext {
readonly candidate: PromiseCandidate;
readonly candidateByNode: WeakMap<t.Node, PromiseCandidate>;
readonly state: JavaScriptSemanticAnalysisState;
readonly callables: readonly JavaScriptSemanticCallable[];
readonly returnSiteIdFor: (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
) => string | null;
}
/** Recover explicit Promise construction, chaining, aggregation, and ownership. */
@@ -66,6 +69,7 @@ export const collectJavaScriptSemanticPromises = (
callables: readonly JavaScriptSemanticCallable[],
): JavaScriptSemanticPromiseOperation[] => {
const candidates = collectCandidates(program, state, callables);
const returnSiteIdFor = createReturnSiteLookup(callables);
const candidateByNode = new WeakMap<t.Node, PromiseCandidate>();
for (const candidate of candidates)
candidateByNode.set(candidate.node, candidate);
@@ -74,7 +78,7 @@ export const collectJavaScriptSemanticPromises = (
candidate,
candidateByNode,
state,
callables,
returnSiteIdFor,
);
const sources = promiseSources(candidate, candidateByNode, state);
return {
@@ -180,14 +184,14 @@ const promiseOwnership = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => {
if (candidate.kind === "awaited-expression") return emptyOwnership("awaited");
const context: PromiseOwnershipContext = {
candidate,
candidateByNode,
state,
callables,
returnSiteIdFor,
};
for (let index = candidate.ancestors.length - 1; index >= 0; index -= 1) {
const ancestor = candidate.ancestors[index];
@@ -203,7 +207,7 @@ const ownershipAtAncestor = (
ancestor: t.Node,
context: PromiseOwnershipContext,
): PromiseOwnership | "boundary" | null => {
const { candidate, candidateByNode, state, callables } = context;
const { candidate, candidateByNode, state, returnSiteIdFor } = context;
if (t.isAwaitExpression(ancestor))
return unwrapExpression(ancestor.argument) === candidate.node
? emptyOwnership("awaited")
@@ -234,7 +238,7 @@ const ownershipAtAncestor = (
return returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor),
callables,
returnSiteIdFor,
);
}
if (t.isExpressionStatement(ancestor))
@@ -249,7 +253,7 @@ const ownershipAtAncestor = (
? returnedPromiseOwnership(
candidate.ownerCallableId,
range(ancestor.body),
callables,
returnSiteIdFor,
)
: "boundary";
};
@@ -283,11 +287,11 @@ const assignedPromiseBinding = (
const returnedPromiseOwnership = (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
callables: readonly JavaScriptSemanticCallable[],
returnSiteIdFor: PromiseOwnershipContext["returnSiteIdFor"],
): PromiseOwnership => ({
ownership: "returned",
ownerBindingId: null,
returnSiteId: matchingReturnSite(callableId, location, callables),
returnSiteId: returnSiteIdFor(callableId, location),
});
const outerConsumesCandidate = (
@@ -329,16 +333,56 @@ const emptyOwnership = (
returnSiteId: null,
});
const matchingReturnSite = (
callableId: string | null,
location: JavaScriptSemanticPromiseOperation["location"],
const indexReturnSites = (
callable: JavaScriptSemanticCallable,
): ReadonlyMap<string, string> => {
const output = new Map<string, string>();
for (const site of callable.returnSites) {
const key = returnSiteKey(site.location);
if (!output.has(key)) output.set(key, site.returnSiteId);
}
return output;
};
const createReturnSiteLookup = (
callables: readonly JavaScriptSemanticCallable[],
): string | null =>
callables
.find(({ callableId: candidate }) => candidate === callableId)
?.returnSites.find(({ location: candidate }) =>
sourceRangesEqual(candidate, location),
)?.returnSiteId ?? null;
): PromiseOwnershipContext["returnSiteIdFor"] => {
let callablesById:
| ReadonlyMap<string, JavaScriptSemanticCallable>
| undefined;
let returnSiteIdsByCallable:
| Map<string, ReadonlyMap<string, string>>
| undefined;
return (callableId, location) => {
if (callableId === null) return null;
callablesById ??= indexCallablesById(callables);
const callable = callablesById.get(callableId);
if (callable === undefined) return null;
returnSiteIdsByCallable ??= new Map();
let returnSiteIds = returnSiteIdsByCallable.get(callableId);
if (returnSiteIds === undefined) {
returnSiteIds = indexReturnSites(callable);
returnSiteIdsByCallable.set(callableId, returnSiteIds);
}
return returnSiteIds.get(returnSiteKey(location)) ?? null;
};
};
const indexCallablesById = (
callables: readonly JavaScriptSemanticCallable[],
): ReadonlyMap<string, JavaScriptSemanticCallable> => {
const output = new Map<string, JavaScriptSemanticCallable>();
for (const callable of callables) {
if (output.has(callable.callableId)) continue;
output.set(callable.callableId, callable);
}
return output;
};
const returnSiteKey = (
location: JavaScriptSemanticPromiseOperation["location"],
): string =>
`${location.start.line}:${location.start.column}:${location.end.line}:${location.end.column}`;
const promiseSources = (
candidate: PromiseCandidate,
@@ -1,28 +1,8 @@
import { expect, it } from "vitest";
import {
javaScriptSemanticQueryInputSchema,
javaScriptSemanticQueryResultSchema,
} from "./javascriptSemanticQuerySchemas.js";
import { javaScriptSemanticQueryInputSchema } from "./javascriptSemanticQuerySchemas.js";
it("accepts long selectors and complete relation and class selections", () => {
const longText = "x".repeat(16_385);
const result = javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "endpoint", value: longText },
direction: "forward-influence",
allowed_relations: Array(2).fill("calls"),
expected: {
role: "sink",
classes: Array(25).fill("module"),
},
});
expect(result.seed).toEqual({ kind: "endpoint", value: longText });
expect(result.allowed_relations).toHaveLength(2);
expect(result.expected?.classes).toHaveLength(25);
});
it("rejects the inert source-map authority setting", () => {
it("rejects a source-map authority setting that the query does not consume", () => {
expect(
javaScriptSemanticQueryInputSchema.safeParse({
seed: { kind: "endpoint", value: "/api" },
@@ -31,36 +11,3 @@ it("rejects the inert source-map authority setting", () => {
}).success,
).toBe(false);
});
it("accepts every reported limitation without a count ceiling", () => {
const limitations = Array.from(
{ length: 1_001 },
(_, index) => `gap-${index}`,
);
const id = "a".repeat(64);
const result = javaScriptSemanticQueryResultSchema.parse({
query_id: `jsrq_${id}`,
source_graph_id: `jsrg_${id}`,
seed: { kind: "literal", value: null },
direction: "forward-influence",
status: "no-match",
seed_node_ids: [],
nodes: [],
relations: [],
unknowns: [],
expected_match_node_ids: [],
summary: {
total_seed_matches: 0,
traversed_nodes: 0,
traversed_relations: 0,
traversed_functions: 0,
traversed_modules: 0,
relevant_unknowns: 0,
},
coverage: { status: "complete" },
limitations,
});
expect(result.limitations).toHaveLength(1_001);
});
@@ -1,66 +0,0 @@
import * as t from "@babel/types";
import { expect, it } from "vitest";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
it("preserves source-tree enter/exit order and detached ancestor snapshots", () => {
const parsed = parseJavaScriptSource("const answer = first + second;");
if (parsed === null)
throw new TypeError("Expected a parsed JavaScript fixture");
const visits: string[] = [];
const snapshots: (readonly t.Node[])[] = [];
traverseJavaScriptAst(parsed.program, {
enter: (node, parent, readAncestors) => {
visits.push(`enter:${node.type}`);
const ancestors = readAncestors();
expect(ancestors.at(-1) ?? null).toBe(parent);
if (t.isIdentifier(node)) snapshots.push(ancestors);
},
exit: (node) => visits.push(`exit:${node.type}`),
});
expect(visits).toEqual([
"enter:Program",
"enter:VariableDeclaration",
"enter:VariableDeclarator",
"enter:Identifier",
"exit:Identifier",
"enter:BinaryExpression",
"enter:Identifier",
"exit:Identifier",
"enter:Identifier",
"exit:Identifier",
"exit:BinaryExpression",
"exit:VariableDeclarator",
"exit:VariableDeclaration",
"exit:Program",
]);
expect(snapshots.map((nodes) => nodes.map(({ type }) => type))).toEqual([
["Program", "VariableDeclaration", "VariableDeclarator"],
[
"Program",
"VariableDeclaration",
"VariableDeclarator",
"BinaryExpression",
],
[
"Program",
"VariableDeclaration",
"VariableDeclarator",
"BinaryExpression",
],
]);
});
it("skips sparse child slots without disturbing sibling visit order", () => {
const parsed = parseJavaScriptSource("const values = [first, , second];");
if (parsed === null)
throw new TypeError("Expected a parsed JavaScript fixture");
const identifiers: string[] = [];
traverseJavaScriptAst(parsed.program, {
enter: (node) => {
if (t.isIdentifier(node)) identifiers.push(node.name);
},
});
expect(identifiers).toEqual(["values", "first", "second"]);
});
@@ -5,6 +5,7 @@ import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
const memberChain = ".next".repeat(12_000);
const ordinaryMemberChain = ".next".repeat(64);
it("collects a 12,000-member CommonJS export path without recursion", () => {
const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`);
@@ -48,8 +49,8 @@ it("keeps left-first and outer-member-first bundler runtime matches", () => {
).toBe("webpackChunkInner");
});
it("analyzes a 12,000-member bundler runtime chain without recursion", () => {
const source = `globalThis.webpackChunkApp${memberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
it("recognizes a bundler runtime through nested member names", () => {
const source = `globalThis.webpackChunkApp${ordinaryMemberChain}.push([[1], { 1: function(module) { module.exports.ok = 42; } }]);`;
const analysis = analyzeJavaScriptStaticSource(source);
expect(analysis.parse_status).toBe("complete");
expect(analysis.parse_error_count).toBe(0);
@@ -22,12 +22,6 @@ describe("source map directives", () => {
expect(sourceMapUrls(source)).toEqual([expected]);
});
it("keeps the comment terminator out of the declared url", () => {
expect(sourceMapUrls("/*# sourceMappingURL=app.js.map */")).toEqual([
"app.js.map",
]);
});
it("retains every directive in a source", () => {
expect(
sourceMapUrls(
@@ -84,30 +78,6 @@ describe("source map comment boundaries", () => {
});
describe("source map comment locations and recovery", () => {
it("keeps exact locations and the first occurrence of duplicate URLs", () => {
const line = "//# sourceMappingURL=first.map";
const block = "/*# sourceMappingURL=second.map";
const result = analyzeJavaScriptStaticSource(
['const marker = "😀";', line, `${block} */`, line].join("\r\n"),
);
expect(result.source_map_urls).toEqual([
{
declared_url: "first.map",
location: {
start: { line: 2, column: 0 },
end: { line: 2, column: line.length },
},
},
{
declared_url: "second.map",
location: {
start: { line: 3, column: 0 },
end: { line: 3, column: block.length },
},
},
]);
});
it("keeps real comments when the parser recovers and reports partial syntax", () => {
const result = analyzeJavaScriptStaticSource(
"let value; let value;\n//# sourceMappingURL=recovered.map",
+37
View File
@@ -0,0 +1,37 @@
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { jsonObjectSchema, jsonValueSchema } from "./jsonValue.js";
const values = [
"text",
0,
false,
null,
[],
{},
{ nested: [{ deeper: [1, "two", null, { three: true }] }] },
];
it("projects JSON values without recursive definitions", () => {
for (const io of ["input", "output"] as const) {
const schema = z.toJSONSchema(
z.object({ value: jsonValueSchema, map: jsonObjectSchema }),
{ io },
);
expect(JSON.stringify(schema)).not.toContain("$ref");
expect(schema).not.toHaveProperty("$defs");
const validate = new Ajv2020({ strict: false }).compile(schema);
for (const value of values)
expect(validate({ value, map: { value } })).toBe(true);
expect(validate({ value: 1, map: [] })).toBe(false);
}
});
it("still parses only JSON values at runtime", () => {
for (const value of values)
expect(jsonValueSchema.safeParse(value).success).toBe(true);
for (const value of [undefined, Number.NaN, Infinity, () => 0, [undefined]])
expect(jsonValueSchema.safeParse(value).success).toBe(false);
});
+4
View File
@@ -2,6 +2,10 @@ import { z } from "zod";
/** JSON-safe value shared by domain, application, and adapter boundaries. */
export const jsonValueSchema = z.json();
// Every JSON value satisfies `{}`. Advertise that instead of Zod's
// self-referential `$defs` projection, which MCP clients and model APIs that
// reject recursive JSON Schemas refuse. Runtime parsing still admits only JSON.
jsonValueSchema._zod.toJSONSchema = () => ({});
/** JSON object boundary for caller-visible parameter maps. */
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
+4
View File
@@ -1,5 +1,9 @@
import { isAbsolute, relative, sep } from "node:path";
/** True when the value is an absolute filesystem path on the host platform. */
export const isAbsoluteLocalPath = (value: string): boolean =>
isAbsolute(value);
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
export const isPathWithinRoot = (root: string, path: string): boolean => {
const value = relative(root, path);
@@ -199,7 +199,10 @@ export const managedNativeVerificationResultSchema = z
path: ["summary", "native_body_unresolved"],
message: "Native body summary must match unresolved implementations",
});
});
})
.describe(
"Counts must agree across the result: native accepted plus unsupported equals total; each P/Invoke summary count equals the number of items with that status; and native_body_unresolved equals native_implementations.unresolved. REA checks these cross-field invariants after constructing the result.",
);
export type ManagedNativeVerificationResult = z.infer<
typeof managedNativeVerificationResultSchema
@@ -1,131 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyMobileResource,
detectMobileFormat,
detectPlatform,
getAllArchitectures,
hasInternetPermission,
mobileArtifactManifestSchema,
nativeLibsByArchitecture,
type MobileArtifactManifest,
type AndroidManifest,
type SigningInfo,
type NativeLibrary,
type MobileResource,
} from "./mobileApplicationInvestigation.js";
describe("mobile application investigation", () => {
it("detects mobile format from extension", () => {
expect(detectMobileFormat("app.apk")).toBe("apk");
expect(detectMobileFormat("app.aab")).toBe("aab");
expect(detectMobileFormat("app.ipa")).toBe("ipa");
expect(detectMobileFormat("classes.dex")).toBe("dex");
expect(detectMobileFormat("lib.so")).toBe("native_lib");
expect(detectMobileFormat("readme.txt")).toBeNull();
});
it("detects platform from format", () => {
expect(detectPlatform("apk")).toBe("android");
expect(detectPlatform("aab")).toBe("android");
expect(detectPlatform("dex")).toBe("android");
expect(detectPlatform("ipa")).toBe("ios");
expect(detectPlatform("native_lib")).toBe("cross_platform");
});
it("classifies resources by path", () => {
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
expect(classifyMobileResource("assets/data.json")).toBe("asset");
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
"native_lib",
);
expect(classifyMobileResource("unknown.xyz")).toBe("other");
});
const androidManifest: AndroidManifest = {
package_name: "com.example.app",
version_name: "1.0.0",
version_code: 1,
min_sdk: 21,
target_sdk: 34,
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
activities: ["MainActivity"],
services: ["BackgroundService"],
receivers: [],
providers: [],
};
const signing: SigningInfo = {
is_signed: true,
signer_identity: "CN=TestSigner",
certificate_fingerprint: "abc123",
signature_scheme: "v2",
is_debuggable: false,
};
const nativeLibs: NativeLibrary[] = [
{
path: "lib/arm64-v8a/libnative.so",
architecture: "arm64-v8a",
size: 100000,
digest: "a".repeat(64),
},
{
path: "lib/armeabi-v7a/libnative.so",
architecture: "armeabi-v7a",
size: 90000,
digest: "b".repeat(64),
},
];
const resources: MobileResource[] = [
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
];
const validManifest: MobileArtifactManifest = {
format: "apk",
platform: "android",
app_name: "TestApp",
android_manifest: androidManifest,
ios_manifest: null,
signing,
resources,
native_libraries: nativeLibs,
total_size: 5000000,
architectures: ["arm64-v8a", "armeabi-v7a"],
};
it("rejects a manifest with a negative total size", () => {
const result = mobileArtifactManifestSchema.safeParse({
...validManifest,
total_size: -1,
});
expect(result.success).toBe(false);
});
it("filters native libs by architecture", () => {
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
expect(arm64).toHaveLength(1);
expect(arm64[0]!.architecture).toBe("arm64-v8a");
});
it("checks internet permission", () => {
expect(hasInternetPermission(validManifest)).toBe(true);
const noInternet: MobileArtifactManifest = {
...validManifest,
android_manifest: { ...androidManifest, permissions: [] },
};
expect(hasInternetPermission(noInternet)).toBe(false);
});
it("gets all architectures", () => {
const archs = getAllArchitectures(validManifest);
expect(archs).toHaveLength(2);
expect(archs).toContain("arm64-v8a");
expect(archs).toContain("armeabi-v7a");
});
});
@@ -1,177 +0,0 @@
import { z } from "zod";
/** Supported mobile artifact formats. */
export const mobileArtifactFormatSchema = z.enum([
"apk",
"aab",
"ipa",
"dex",
"native_lib",
]);
export type MobileArtifactFormat = z.infer<typeof mobileArtifactFormatSchema>;
/** Mobile platform. */
export const mobilePlatformSchema = z.enum([
"android",
"ios",
"cross_platform",
]);
export type MobilePlatform = z.infer<typeof mobilePlatformSchema>;
/** Android manifest entry. */
export const androidManifestSchema = z.strictObject({
package_name: z.string().min(1),
version_name: z.string().nullable(),
version_code: z.number().int().nullable(),
min_sdk: z.number().int().nullable(),
target_sdk: z.number().int().nullable(),
permissions: z.array(z.string()).default([]),
activities: z.array(z.string()).default([]),
services: z.array(z.string()).default([]),
receivers: z.array(z.string()).default([]),
providers: z.array(z.string()).default([]),
});
export type AndroidManifest = z.infer<typeof androidManifestSchema>;
/** iOS app manifest (Info.plist). */
export const iosManifestSchema = z.strictObject({
bundle_identifier: z.string().min(1),
bundle_version: z.string().nullable(),
short_version: z.string().nullable(),
minimum_os_version: z.string().nullable(),
supported_platforms: z.array(z.string()).default([]),
ui_required_device_capabilities: z.array(z.string()).default([]),
app_permissions: z.array(z.string()).default([]),
});
/** Signing information. */
export const signingInfoSchema = z.strictObject({
is_signed: z.boolean().default(false),
signer_identity: z.string().nullable(),
certificate_fingerprint: z.string().nullable(),
signature_scheme: z.string().nullable(),
is_debuggable: z.boolean().default(false),
});
export type SigningInfo = z.infer<typeof signingInfoSchema>;
/** Native library entry. */
export const nativeLibrarySchema = z.strictObject({
path: z.string().min(1),
architecture: z.string().nullable(),
size: z.number().int().nonnegative(),
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type NativeLibrary = z.infer<typeof nativeLibrarySchema>;
/** Resource entry within a mobile artifact. */
export const mobileResourceSchema = z.strictObject({
path: z.string().min(1),
type: z.enum([
"layout",
"drawable",
"string",
"asset",
"raw",
"native_lib",
"manifest",
"entitlements",
"provisioning",
"other",
]),
size: z.number().int().nonnegative(),
});
export type MobileResource = z.infer<typeof mobileResourceSchema>;
/** Static analysis result for a mobile artifact. */
export const mobileArtifactManifestSchema = z.strictObject({
format: mobileArtifactFormatSchema,
platform: mobilePlatformSchema,
app_name: z.string().nullable(),
android_manifest: androidManifestSchema.nullable(),
ios_manifest: iosManifestSchema.nullable(),
signing: signingInfoSchema,
resources: z.array(mobileResourceSchema).default([]),
native_libraries: z.array(nativeLibrarySchema).default([]),
total_size: z.number().int().nonnegative(),
architectures: z.array(z.string()).default([]),
});
export type MobileArtifactManifest = z.infer<
typeof mobileArtifactManifestSchema
>;
/** Detect mobile artifact format from file extension. */
export function detectMobileFormat(path: string): MobileArtifactFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".apk")) return "apk";
if (lower.endsWith(".aab")) return "aab";
if (lower.endsWith(".ipa")) return "ipa";
if (lower.endsWith(".dex")) return "dex";
if (lower.endsWith(".so") || lower.endsWith(".dylib") || lower.endsWith(".a"))
return "native_lib";
return null;
}
/** Detect platform from format. */
export function detectPlatform(format: MobileArtifactFormat): MobilePlatform {
switch (format) {
case "apk":
case "aab":
case "dex":
return "android";
case "ipa":
return "ios";
case "native_lib":
return "cross_platform";
}
}
/** Classify a resource by its path. */
export function classifyMobileResource(path: string): MobileResource["type"] {
const lower = path.toLowerCase();
if (lower.includes("androidmanifest.xml")) return "manifest";
if (lower.includes(".entitlements")) return "entitlements";
if (lower.includes("provisioning") || lower.includes(".mobileprovision"))
return "provisioning";
if (lower.includes("/layout/")) return "layout";
if (lower.includes("/drawable/") || lower.includes("/mipmap/"))
return "drawable";
if (lower.includes("/values/")) return "string";
if (lower.includes("assets/") || lower.includes("raw/")) return "asset";
if (lower.endsWith(".so") || lower.endsWith(".dylib")) return "native_lib";
if (lower.endsWith(".xml")) return "layout";
return "other";
}
/** Get all native libraries for a specific architecture. */
export function nativeLibsByArchitecture(
manifest: MobileArtifactManifest,
arch: string,
): NativeLibrary[] {
return manifest.native_libraries.filter((l) => l.architecture === arch);
}
/** Check if an Android artifact has internet permission. */
export function hasInternetPermission(
manifest: MobileArtifactManifest,
): boolean {
if (!manifest.android_manifest) return false;
return manifest.android_manifest.permissions.some(
(p) => p.includes("INTERNET") || p.includes("android.permission.INTERNET"),
);
}
/** Get all unique architectures across native libraries. */
export function getAllArchitectures(
manifest: MobileArtifactManifest,
): string[] {
const archs = new Set<string>();
for (const lib of manifest.native_libraries) {
if (lib.architecture) archs.add(lib.architecture);
}
for (const arch of manifest.architectures) {
archs.add(arch);
}
return [...archs];
}
+21 -5
View File
@@ -60,10 +60,26 @@ export const nativeUiScenarioInputSchema = z.strictObject({
const nativeUiScreenshotSchema = z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string().min(4),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
width: z.number().int().positive(),
height: z.number().int().positive(),
base64: z
.string()
.min(4)
.describe(
"Canonical base64 encoding of PNG bytes; the decoded bytes must have a PNG signature and IHDR chunk.",
),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.describe("SHA-256 digest of the decoded PNG bytes."),
width: z
.number()
.int()
.positive()
.describe("Must equal the width encoded in the PNG IHDR chunk."),
height: z
.number()
.int()
.positive()
.describe("Must equal the height encoded in the PNG IHDR chunk."),
})
.superRefine((screenshot, context) => {
const bytes = decodeCanonicalBase64(screenshot.base64);
@@ -117,7 +133,7 @@ export const nativeUiSnapshotSchema = z.strictObject({
title: z.string().nullable(),
value: z.string().nullable(),
actions: z.array(z.string()),
children_count: z.number().int().nonnegative(),
children_count: z.number().int().nonnegative().nullable(),
}),
),
truncated: z.boolean(),
+1 -143
View File
@@ -1,150 +1,8 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
countMethodsByType,
isDbSaveComplete,
isGetterSelector,
isSetterSelector,
inspectNativeDispatchMetadata,
propertyNameFromSelector,
swiftDeclsByKind,
type ObjcMethod,
type SwiftDecl,
type DbSaveResult,
} from "./objcSwiftMetadata.js";
import { inspectNativeDispatchMetadata } from "./objcSwiftMetadata.js";
describe("ObjC/Swift metadata", () => {
it("identifies getter selectors", () => {
expect(isGetterSelector("name")).toBe(true);
expect(isGetterSelector("setName:")).toBe(false);
expect(isGetterSelector("set")).toBe(true);
});
it("identifies setter selectors", () => {
expect(isSetterSelector("setName:")).toBe(true);
expect(isSetterSelector("name")).toBe(false);
});
it("extracts property name from selector", () => {
expect(propertyNameFromSelector("name")).toBe("name");
expect(propertyNameFromSelector("setName:")).toBe("name");
expect(propertyNameFromSelector("set")).toBe("set");
});
it("counts methods by type", () => {
const methods: ObjcMethod[] = [
{
selector: "init",
method_type: "instance",
address: 0x1000,
is_required: false,
is_optional: false,
},
{
selector: "alloc",
method_type: "class",
address: 0x2000,
is_required: false,
is_optional: false,
},
];
const counts = countMethodsByType(methods);
expect(counts.instance).toBe(1);
expect(counts.class).toBe(1);
expect(counts.ivar_getter).toBe(0);
expect(counts.ivar_setter).toBe(0);
});
it("filters Swift declarations by kind", () => {
const decls: SwiftDecl[] = [
{
kind: "class",
name: "Foo",
module: null,
access_level: "public",
super_class: null,
protocols: [],
is_final: false,
is_required: false,
is_convenience_init: false,
is_override: false,
},
];
const classes = swiftDeclsByKind(decls, "class");
expect(classes).toHaveLength(1);
expect(classes[0]!.name).toBe("Foo");
});
it("checks database save completeness", () => {
const result: DbSaveResult = {
operation: "save",
succeeded: true,
preserved_names: 10,
preserved_comments: 5,
preserved_bookmarks: 3,
database_path: "/tmp/db.hop",
error: null,
};
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
});
it("is monotone in every expected count and total at the observed count", () => {
fc.assert(
fc.property(
fc.record({
operation: fc.constantFrom(
"save",
"readback",
"open_database",
"close_database",
"export",
"import",
),
succeeded: fc.boolean(),
preserved_names: fc.nat({ max: 50 }),
preserved_comments: fc.nat({ max: 50 }),
preserved_bookmarks: fc.nat({ max: 50 }),
database_path: fc.option(fc.string(), { nil: null }),
error: fc.option(fc.string(), { nil: null }),
}),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
(result, names, comments, bookmarks) => {
// Completeness is downward closed: if demanding more was met,
// demanding less must also be met.
if (isDbSaveComplete(result, names + 1, comments, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments + 1, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments, bookmarks + 1)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
// Expecting exactly what was preserved is complete iff the save worked.
expect(
isDbSaveComplete(
result,
result.preserved_names,
result.preserved_comments,
result.preserved_bookmarks,
),
).toBe(result.succeeded);
},
),
{ numRuns: 200 },
);
});
it("bounds symbol projections and labels symbol-only metadata as partial", () => {
const result = inspectNativeDispatchMetadata(
[
+4 -65
View File
@@ -7,7 +7,6 @@ export const objcMethodTypeSchema = z.enum([
"ivar_getter",
"ivar_setter",
]);
export type ObjcMethodType = z.infer<typeof objcMethodTypeSchema>;
/** Objective-C property attribute. */
export const objcPropertyAttributeSchema = z.strictObject({
@@ -27,7 +26,7 @@ export const objcMethodSchema = z.strictObject({
is_required: z.boolean().default(false),
is_optional: z.boolean().default(false),
});
export type ObjcMethod = z.infer<typeof objcMethodSchema>;
type ObjcMethod = z.infer<typeof objcMethodSchema>;
/** Objective-C property metadata. */
export const objcPropertySchema = z.strictObject({
@@ -87,7 +86,7 @@ export const objcClassSchema = z.strictObject({
)
.optional(),
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
type ObjcClass = z.infer<typeof objcClassSchema>;
/** Exact location of a decoded native metadata value when the provider knows it. */
export const nativeMetadataLocationSchema = z.strictObject({
@@ -162,7 +161,7 @@ export const objcDispatchImplementationSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcDispatchImplementation = z.infer<
type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
@@ -224,7 +223,7 @@ export const swiftSymbolSchema = z.strictObject({
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
/** Per-facet coverage; empty arrays are meaningful only with this record. */
export const nativeMetadataCoverageSchema = z.strictObject({
@@ -246,7 +245,6 @@ export const swiftDeclKindSchema = z.enum([
"global_var",
"global_func",
]);
export type SwiftDeclKind = z.infer<typeof swiftDeclKindSchema>;
/** Swift access level. */
export const swiftAccessLevelSchema = z.enum([
@@ -269,7 +267,6 @@ export const swiftDeclSchema = z.strictObject({
is_convenience_init: z.boolean().default(false),
is_override: z.boolean().default(false),
});
export type SwiftDecl = z.infer<typeof swiftDeclSchema>;
/** Database save/read operation type. */
export const dbOperationSchema = z.enum([
@@ -290,7 +287,6 @@ export const dbSaveResultSchema = z.strictObject({
database_path: z.string().nullable(),
error: z.string().nullable(),
});
export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
/** Result of deeper ObjC/Swift metadata extraction. */
export const objcSwiftMetadataSchema = z.strictObject({
@@ -479,60 +475,3 @@ const parseMetadataAddress = (address: string | null): number | null => {
const value = Number.parseInt(match[1], 16);
return Number.isSafeInteger(value) ? value : null;
};
/** Check if a selector name looks like a getter. */
export function isGetterSelector(selector: string): boolean {
return /^[a-z][a-zA-Z0-9_]*$/u.test(selector) && !selector.includes(":");
}
/** Check if a selector name looks like a setter. */
export function isSetterSelector(selector: string): boolean {
return selector.startsWith("set") && selector.endsWith(":");
}
/** Extract property name from a getter/setter selector. */
export function propertyNameFromSelector(selector: string): string | null {
if (isSetterSelector(selector)) {
const inner = selector.slice(3, -1);
return inner.charAt(0).toLowerCase() + inner.slice(1);
}
if (isGetterSelector(selector)) {
return selector;
}
return null;
}
/** Count ObjC methods by type. */
export function countMethodsByType(
methods: readonly ObjcMethod[],
): Record<ObjcMethodType, number> {
return {
instance: methods.filter((m) => m.method_type === "instance").length,
class: methods.filter((m) => m.method_type === "class").length,
ivar_getter: methods.filter((m) => m.method_type === "ivar_getter").length,
ivar_setter: methods.filter((m) => m.method_type === "ivar_setter").length,
};
}
/** Get all Swift declarations of a specific kind. */
export function swiftDeclsByKind(
decls: readonly SwiftDecl[],
kind: SwiftDeclKind,
): SwiftDecl[] {
return decls.filter((d) => d.kind === kind);
}
/** Check if a database save preserved all expected items. */
export function isDbSaveComplete(
result: DbSaveResult,
expectedNames: number,
expectedComments: number,
expectedBookmarks: number,
): boolean {
return (
result.succeeded &&
result.preserved_names >= expectedNames &&
result.preserved_comments >= expectedComments &&
result.preserved_bookmarks >= expectedBookmarks
);
}
-95
View File
@@ -1,95 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyResource,
detectPackageFormat,
hasValidSignature,
isConfigurationResource,
isManifestResource,
resourcesByType,
totalResourceSize,
type PackageManifest,
} from "./packageAnalysis.js";
describe("package analysis", () => {
it("detects package format from extension", () => {
expect(detectPackageFormat("app.msix")).toBe("msix");
expect(detectPackageFormat("installer.msi")).toBe("msi");
expect(detectPackageFormat("app.appx")).toBe("appx");
expect(detectPackageFormat("app.zip")).toBeNull();
});
it("identifies manifest resources", () => {
expect(isManifestResource("AppXManifest.xml")).toBe(true);
expect(isManifestResource("resources.pri")).toBe(false);
});
it("identifies configuration resources", () => {
expect(isConfigurationResource("settings.xml")).toBe(true);
expect(isConfigurationResource("config.json")).toBe(true);
expect(isConfigurationResource("app.exe")).toBe(false);
});
it("classifies resources by path", () => {
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
expect(classifyResource("icon.png")).toBe("icon");
expect(classifyResource("settings.xml")).toBe("configuration");
expect(classifyResource("cert.cer")).toBe("certificate");
expect(classifyResource("app.exe")).toBe("executable");
expect(classifyResource("lib.dll")).toBe("library");
expect(classifyResource("data.bin")).toBe("other");
});
const validManifest: PackageManifest = {
format: "msix",
name: "TestApp",
publisher: "CN=TestPublisher",
version: "1.0.0.0",
architecture: "x64",
resources: [
{
path: "AppXManifest.xml",
type: "manifest",
size: 1000,
digest: "a".repeat(64),
},
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
{
path: "app.exe",
type: "executable",
size: 50000,
digest: "c".repeat(64),
},
],
signature: {
is_signed: true,
signer_subject: "CN=TestPublisher",
certificate_thumbprint: "abc123",
is_valid: true,
is_timestamped: true,
timestamp_signer: "CN=Timestamp",
},
is_framework: false,
dependencies: ["Microsoft.VCLibs.14.00"],
capabilities: ["internetClient", "localNetwork"],
};
it("filters resources by type", () => {
const icons = resourcesByType(validManifest, "icon");
expect(icons).toHaveLength(1);
expect(icons[0]!.path).toBe("icon.png");
});
it("computes total resource size", () => {
expect(totalResourceSize(validManifest)).toBe(56000);
});
it("checks valid signature", () => {
expect(hasValidSignature(validManifest)).toBe(true);
const unsigned: PackageManifest = {
...validManifest,
signature: { ...validManifest.signature, is_valid: false },
};
expect(hasValidSignature(unsigned)).toBe(false);
});
});
-143
View File
@@ -1,143 +0,0 @@
import { z } from "zod";
/** Supported Windows package formats. */
export const packageFormatSchema = z.enum(["msix", "msi", "appx"]);
export type PackageFormat = z.infer<typeof packageFormatSchema>;
/** A resource entry within a package. */
export const packageResourceSchema = z.strictObject({
/** Resource path within the package. */
path: z.string().min(1),
/** Resource type. */
type: z.enum([
"manifest",
"icon",
"configuration",
"certificate",
"executable",
"library",
"data",
"other",
]),
/** Size in bytes. */
size: z.number().int().nonnegative(),
/** SHA-256 digest. */
digest: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
});
export type PackageResource = z.infer<typeof packageResourceSchema>;
/** Digital signature information. */
export const digitalSignatureSchema = z.strictObject({
/** Whether the package is signed. */
is_signed: z.boolean(),
/** Signer subject name. */
signer_subject: z.string().nullable(),
/** Certificate thumbprint. */
certificate_thumbprint: z.string().nullable(),
/** Whether the signature is valid. */
is_valid: z.boolean().default(false),
/** Whether the signature is timestamped. */
is_timestamped: z.boolean().default(false),
/** Timestamp signer if present. */
timestamp_signer: z.string().nullable(),
});
/** A Windows package manifest for static analysis. */
export const packageManifestSchema = z.strictObject({
/** Package format. */
format: packageFormatSchema,
/** Package identity name. */
name: z.string().min(1),
/** Package publisher. */
publisher: z.string().nullable(),
/** Package version. */
version: z.string().nullable(),
/** Architecture. */
architecture: z.enum(["x86", "x64", "arm", "arm64", "neutral", "unknown"]),
/** Package resources. */
resources: z.array(packageResourceSchema).default([]),
/** Digital signature. */
signature: digitalSignatureSchema,
/** Whether the package is a framework. */
is_framework: z.boolean().default(false),
/** Package dependencies. */
dependencies: z.array(z.string()).default([]),
/** Capabilities declared in the manifest. */
capabilities: z.array(z.string()).default([]),
});
export type PackageManifest = z.infer<typeof packageManifestSchema>;
/** Detect package format from file extension. */
export function detectPackageFormat(path: string): PackageFormat | null {
const lower = path.toLowerCase();
if (lower.endsWith(".msix")) return "msix";
if (lower.endsWith(".msi")) return "msi";
if (lower.endsWith(".appx")) return "appx";
return null;
}
/** Check if a resource path looks like a manifest. */
export function isManifestResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.includes("appxmanifest.xml") ||
lower.includes("appxmanifest") ||
lower.includes("manifest.xml") ||
lower.endsWith("_manifest.xml")
);
}
/** Check if a resource path looks like a configuration file. */
export function isConfigurationResource(path: string): boolean {
const lower = path.toLowerCase();
return (
lower.endsWith(".xml") ||
lower.endsWith(".json") ||
lower.endsWith(".ini") ||
lower.endsWith(".config")
);
}
/** Classify a resource by its path. */
export function classifyResource(path: string): PackageResource["type"] {
if (isManifestResource(path)) return "manifest";
const lower = path.toLowerCase();
if (
lower.endsWith(".ico") ||
lower.endsWith(".png") ||
lower.endsWith(".jpg") ||
lower.endsWith(".jpeg")
)
return "icon";
if (isConfigurationResource(path)) return "configuration";
if (
lower.endsWith(".cer") ||
lower.endsWith(".pfx") ||
lower.endsWith(".p12")
)
return "certificate";
if (lower.endsWith(".exe") || lower.endsWith(".dll"))
return lower.endsWith(".exe") ? "executable" : "library";
return "other";
}
/** Get all resources of a specific type. */
export function resourcesByType(
manifest: PackageManifest,
type: PackageResource["type"],
): PackageResource[] {
return manifest.resources.filter((r) => r.type === type);
}
/** Get the total size of all resources. */
export function totalResourceSize(manifest: PackageManifest): number {
return manifest.resources.reduce((sum, r) => sum + r.size, 0);
}
/** Check if a package has a valid signature. */
export function hasValidSignature(manifest: PackageManifest): boolean {
return manifest.signature.is_signed && manifest.signature.is_valid;
}
-214
View File
@@ -1,214 +0,0 @@
import { describe, expect, it } from "vitest";
import {
countExecutableSections,
getExportedFunctions,
getImportedDlls,
hasPdbInfo,
parseDebugType,
parseImageCharacteristics,
parseMachineType,
parseSectionCharacteristics,
peManifestSchema,
type PeManifest,
} from "./peInspection.js";
const validManifest: PeManifest = {
dos_magic: 0x5a4d,
pe_signature: 0x00004550,
machine: "x64",
number_of_sections: 3,
timestamp: 0x12345678,
is_dll: false,
is_executable: true,
is_console: true,
entry_point: 0x1000,
image_base: 0x400000,
section_alignment: 0x1000,
subsystem_version: "10.0",
sections: [
{
name: ".text",
virtual_size: 0x1000,
virtual_address: 0x1000,
raw_size: 0x1000,
raw_offset: 0x400,
characteristics: {
has_code: true,
has_initialized_data: false,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: true,
},
},
{
name: ".data",
virtual_size: 0x500,
virtual_address: 0x2000,
raw_size: 0x500,
raw_offset: 0x1400,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: true,
executable: false,
},
},
{
name: ".rdata",
virtual_size: 0x200,
virtual_address: 0x3000,
raw_size: 0x200,
raw_offset: 0x1900,
characteristics: {
has_code: false,
has_initialized_data: true,
has_uninitialized_data: false,
readable: true,
writable: false,
executable: false,
},
},
],
imports: [
{
dll: "KERNEL32.DLL",
function_name: "CreateFileW",
ordinal: null,
is_delay_import: false,
},
{
dll: "KERNEL32.DLL",
function_name: "WriteFile",
ordinal: null,
is_delay_import: false,
},
{
dll: "USER32.DLL",
function_name: "MessageBoxW",
ordinal: 100,
is_delay_import: false,
},
],
exports: [
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
],
resources: [
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
],
debug_entries: [
{
type: "CODEVIEW",
rva: 0x5000,
size: 100,
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
pdb_age: 1,
pdb_path: "C:\\src\\app.pdb",
},
],
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
relocations_count: 50,
image_characteristics: ["Executable", "Console"],
};
describe("PE/COFF static inspection", () => {
it("parses machine types", () => {
expect(parseMachineType(0x014c)).toBe("x86");
expect(parseMachineType(0x8664)).toBe("x64");
expect(parseMachineType(0x01c0)).toBe("arm");
expect(parseMachineType(0xaa64)).toBe("arm64");
expect(parseMachineType(0x0200)).toBe("ia64");
expect(parseMachineType(0xffff)).toBe("unknown");
});
it("parses section characteristics", () => {
const CODE = 0x00000020;
const READ = 0x40000000;
const EXECUTE = 0x20000000;
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
expect(result.has_code).toBe(true);
expect(result.readable).toBe(true);
expect(result.executable).toBe(true);
expect(result.writable).toBe(false);
});
it("parses image characteristics", () => {
const DLL = 0x2000;
const EXEC = 0x0002;
const flags = parseImageCharacteristics(DLL | EXEC);
expect(flags).toContain("DLL");
expect(flags).toContain("Executable");
});
it("parses debug types", () => {
expect(parseDebugType(2)).toBe("CODEVIEW");
expect(parseDebugType(1)).toBe("COFF");
expect(parseDebugType(99)).toBe("UNKNOWN");
});
it("rejects a manifest whose section table is malformed", () => {
const malformed = {
...validManifest,
sections: [{ ...validManifest.sections[0]!, name: 7 }],
};
const result = peManifestSchema.safeParse(malformed);
expect(result.success).toBe(false);
});
it("accepts static manifests with more than 96 PE sections", () => {
const section = validManifest.sections[0];
if (section === undefined) throw new Error("Expected PE section fixture");
const sections = Array.from({ length: 97 }, (_, index) => ({
...section,
name: `section-${String(index)}`,
}));
expect(
peManifestSchema.parse({
...validManifest,
number_of_sections: sections.length,
sections,
}).sections,
).toHaveLength(97);
});
it("detects PDB info", () => {
expect(hasPdbInfo(validManifest)).toBe(true);
const withoutPdb: PeManifest = {
...validManifest,
debug_entries: [
{
type: "COFF",
rva: 0x5000,
size: 100,
pdb_guid: null,
pdb_age: null,
pdb_path: null,
},
],
};
expect(hasPdbInfo(withoutPdb)).toBe(false);
});
it("gets imported DLLs", () => {
const dlls = getImportedDlls(validManifest);
expect(dlls).toHaveLength(2);
expect(dlls).toContain("KERNEL32.DLL");
expect(dlls).toContain("USER32.DLL");
});
it("gets exported functions", () => {
const exports = getExportedFunctions(validManifest);
expect(exports).toHaveLength(2);
expect(exports).toContain("DllMain");
expect(exports).toContain("MyFunction");
});
it("counts executable sections", () => {
expect(countExecutableSections(validManifest)).toBe(1);
});
});
-220
View File
@@ -1,220 +0,0 @@
import { z } from "zod";
/** PE/COFF section characteristics flags. */
export const sectionCharacteristicsSchema = z.object({
/** Section contains executable code. */
has_code: z.boolean().default(false),
/** Section contains initialized data. */
has_initialized_data: z.boolean().default(false),
/** Section contains uninitialized data. */
has_uninitialized_data: z.boolean().default(false),
/** Section can be read. */
readable: z.boolean().default(false),
/** Section can be written. */
writable: z.boolean().default(false),
/** Section can be executed. */
executable: z.boolean().default(false),
});
/** PE/COFF section header. */
export const peSectionSchema = z.strictObject({
name: z.string().min(1),
virtual_size: z.number().int().nonnegative(),
virtual_address: z.number().int().nonnegative(),
raw_size: z.number().int().nonnegative(),
raw_offset: z.number().int().nonnegative(),
characteristics: sectionCharacteristicsSchema,
});
/** PE import entry. */
export const peImportSchema = z.strictObject({
dll: z.string().min(1),
function_name: z.string().min(1),
ordinal: z.number().int().nullable(),
is_delay_import: z.boolean().default(false),
});
/** PE export entry. */
export const peExportSchema = z.strictObject({
name: z.string().min(1),
ordinal: z.number().int().nonnegative(),
rva: z.number().int().nonnegative(),
forwarder: z.string().nullable(),
});
/** PE/COFF resource entry. */
export const peResourceSchema = z.strictObject({
type: z.string().min(1),
name: z.string().nullable(),
language: z.number().int().nullable(),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
});
/** PE debug directory entry. */
export const peDebugEntrySchema = z.strictObject({
type: z.string().min(1),
rva: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
/** PDB GUID if this is a CodeView entry. */
pdb_guid: z.string().nullable(),
/** PDB age if this is a CodeView entry. */
pdb_age: z.number().int().nullable(),
/** PDB path if this is a CodeView entry. */
pdb_path: z.string().nullable(),
});
/** TLS callback entry. */
export const peTlsCallbackSchema = z.strictObject({
callback_rva: z.number().int().nonnegative(),
index: z.number().int().nonnegative(),
});
/** Architecture/machine type. */
export const peMachineTypeSchema = z.enum([
"x86",
"x64",
"arm",
"arm64",
"ia64",
"unknown",
]);
export type PeMachineType = z.infer<typeof peMachineTypeSchema>;
/** PE/COFF manifest for static inspection. */
export const peManifestSchema = z.strictObject({
/** DOS header magic. */
dos_magic: z.literal(0x5a4d),
/** PE signature. */
pe_signature: z.literal(0x00004550),
/** Machine type. */
machine: peMachineTypeSchema,
/** Number of sections. */
number_of_sections: z.number().int().positive(),
/** Timestamp from the COFF header. */
timestamp: z.number().int().nullable(),
/** PE characteristics flags. */
is_dll: z.boolean().default(false),
is_executable: z.boolean().default(false),
is_console: z.boolean().default(true),
/** Entry point RVA. */
entry_point: z.number().int().nonnegative(),
/** Image base. */
image_base: z.number().int().nonnegative(),
/** Section alignment. */
section_alignment: z.number().int().positive(),
/** Subsystem version. */
subsystem_version: z.string().nullable(),
/** Sections. */
sections: z.array(peSectionSchema),
/** Imports. */
imports: z.array(peImportSchema).default([]),
/** Exports. */
exports: z.array(peExportSchema).default([]),
/** Resources. */
resources: z.array(peResourceSchema).default([]),
/** Debug directory entries. */
debug_entries: z.array(peDebugEntrySchema).default([]),
/** TLS callbacks. */
tls_callbacks: z.array(peTlsCallbackSchema).default([]),
/** Relocations count (not all entries). */
relocations_count: z.number().int().nonnegative().default(0),
/** Image file characteristics. */
image_characteristics: z.array(z.string()).default([]),
});
export type PeManifest = z.infer<typeof peManifestSchema>;
/** Parse machine type from COFF machine field. */
export function parseMachineType(machine: number): PeMachineType {
switch (machine) {
case 0x014c:
return "x86";
case 0x8664:
return "x64";
case 0x01c0:
case 0x01c2:
case 0x01c4:
return "arm";
case 0xaa64:
return "arm64";
case 0x0200:
return "ia64";
default:
return "unknown";
}
}
/** Parse section characteristics flags. */
export function parseSectionCharacteristics(
characteristics: number,
): z.infer<typeof sectionCharacteristicsSchema> {
const IMAGE_SCN_CNT_CODE = 0x00000020;
const IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040;
const IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080;
const IMAGE_SCN_MEM_READ = 0x40000000;
const IMAGE_SCN_MEM_WRITE = 0x80000000;
const IMAGE_SCN_MEM_EXECUTE = 0x20000000;
return {
has_code: (characteristics & IMAGE_SCN_CNT_CODE) !== 0,
has_initialized_data:
(characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) !== 0,
has_uninitialized_data:
(characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) !== 0,
readable: (characteristics & IMAGE_SCN_MEM_READ) !== 0,
writable: (characteristics & IMAGE_SCN_MEM_WRITE) !== 0,
executable: (characteristics & IMAGE_SCN_MEM_EXECUTE) !== 0,
};
}
/** Parse image characteristics flags. */
export function parseImageCharacteristics(characteristics: number): string[] {
const IMAGE_DLL = 0x2000;
const IMAGE_EXECUTABLE = 0x0002;
const IMAGE_CONSOLE = 0x0003;
const flags: string[] = [];
if (characteristics & IMAGE_DLL) flags.push("DLL");
if (characteristics & IMAGE_EXECUTABLE) flags.push("Executable");
if ((characteristics & 0x0000000f) === IMAGE_CONSOLE) flags.push("Console");
return flags;
}
/** Parse a PE debug directory type. */
export function parseDebugType(type: number): string {
switch (type) {
case 0:
return "UNKNOWN";
case 1:
return "COFF";
case 2:
return "CODEVIEW";
case 3:
return "POGO";
case 4:
return "MISC";
default:
return "UNKNOWN";
}
}
/** Check if a PE manifest has PDB debug info. */
export function hasPdbInfo(manifest: PeManifest): boolean {
return manifest.debug_entries.some(
(e) => e.pdb_guid !== null && e.pdb_path !== null,
);
}
/** Get all imported DLLs from a PE manifest. */
export function getImportedDlls(manifest: PeManifest): string[] {
return [...new Set(manifest.imports.map((i) => i.dll))];
}
/** Get all exported function names from a PE manifest. */
export function getExportedFunctions(manifest: PeManifest): string[] {
return manifest.exports.map((e) => e.name);
}
/** Count executable sections. */
export function countExecutableSections(manifest: PeManifest): number {
return manifest.sections.filter((s) => s.characteristics.executable).length;
}
@@ -0,0 +1,160 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("distinguishes added evidence from unknown observations", () => {
const capture = emptyCapture();
const added = compareProcessCaptures(capture, {
...capture,
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
rendered_frames: [
{
sequence: 0,
at_ms: 0,
columns: 3,
rows: 1,
cursor_x: 3,
cursor_y: 0,
active_buffer: "normal",
lines: ["new"],
serialized_state: "new",
},
],
});
expect(added).toMatchObject({ terminal: "added", status: "changed" });
for (const [scope, dimension] of [
["process", "process"],
["interaction", "interaction"],
] as const) {
expect(
compareProcessCaptures(
{
...capture,
residual_unknowns: [{ scope, reason: "observation was partial" }],
},
capture,
),
).toMatchObject({
status: "unknown",
[dimension]: "unknown",
terminal: "unchanged",
});
}
});
it("compares raw terminal and process observations while honoring normalization shape", () => {
const capture = emptyCapture();
expect(
compareProcessCaptures(capture, {
...capture,
normalization: {
patterns: [],
time_bucket_ms: 10,
ports: true,
pids: true,
paths: true,
},
}),
).toMatchObject({
status: "unchanged",
first_divergence: { status: "none" },
});
const terminal = compareProcessCaptures(
{ ...capture, frames: [{ sequence: 0, at_ms: 0, data: "bar" }] },
{ ...capture, frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }] },
);
expect(terminal).toMatchObject({
terminal: "changed",
first_divergence: { status: "found", dimension: "terminal" },
});
expect(
compareProcessCaptures(
{
...capture,
process_samples: [
{
at_ms: 10,
pid: 1,
parent_pid: 0,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
},
{
...capture,
process_samples: [
{
at_ms: 20,
pid: 1,
parent_pid: 2,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
},
),
).toMatchObject({ process: "changed", status: "changed" });
});
it("keeps filesystem comparison unknown without coverage and reports observed changes", () => {
const capture = emptyCapture();
const incomplete = {
...capture,
residual_unknowns: [
{ scope: "filesystem" as const, reason: "watcher unavailable" },
],
};
expect(compareProcessCaptures(incomplete, incomplete)).toMatchObject({
filesystem: "unknown",
status: "unknown",
});
const finalFile = {
path: "root_0:created.txt",
type: "file" as const,
mode: 0o644,
size: 4,
sha256: "a".repeat(64),
symlink_target: null,
};
expect(
compareProcessCaptures(capture, {
...capture,
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
name: "after_settlement",
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,
},
],
}),
).toMatchObject({ filesystem: "changed", status: "changed" });
});
+661
View File
@@ -0,0 +1,661 @@
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { normalizationSchema } from "./processScenario.js";
import { collectProcessCaptureIssues } from "./processCaptureValidation.js";
export * from "./processScenario.js";
/** Normalized raw PTY chunk, preserving transport-level output differences. */
export interface TerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly data: string;
}
/** Serialized terminal state after interpreting control and resize sequences. */
export interface RenderedTerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly columns: number;
readonly rows: number;
readonly cursor_x: number;
readonly cursor_y: number;
readonly active_buffer: "normal" | "alternate";
readonly lines: readonly string[];
readonly serialized_state: string;
}
/** Scheduled terminal interaction with its observed dispatch outcome. */
export interface InteractionEvent {
readonly sequence: number;
readonly scheduled_at_ms: number;
readonly dispatched_at_ms: number;
readonly type: "input" | "resize" | "signal";
readonly data: string;
readonly outcome: "dispatched" | "target_exited" | "failed";
}
/** One filesystem state used for before/after comparison. */
interface FileStateIdentity {
readonly path: string;
readonly mode: number;
readonly size: number;
}
export type FileState = FileStateIdentity &
(
| {
readonly type: "file";
readonly sha256: string | null;
readonly symlink_target: null;
}
| {
readonly type: "symlink";
readonly sha256: null;
readonly symlink_target: string;
}
| {
readonly type: "directory" | "other";
readonly sha256: null;
readonly symlink_target: null;
}
);
interface FileEffectIdentity {
readonly path: string;
}
type FileEffect = FileEffectIdentity &
(
| {
readonly status: "created";
readonly before: null;
readonly after: FileState;
}
| {
readonly status: "deleted";
readonly before: FileState;
readonly after: null;
}
| {
readonly status: "modified" | "unchanged";
readonly before: FileState;
readonly after: FileState;
}
);
/** A sampled owned-process observation; sampling cannot prove syscall completeness. */
export interface ProcessSample {
readonly at_ms: number;
readonly pid: number;
readonly parent_pid: number;
readonly command: string;
readonly process_group_id: number | null;
readonly session_id: number | null;
}
/** Initial or final filesystem snapshot selected for observation. */
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
readonly files: readonly FileState[];
readonly effects: readonly FileEffect[];
readonly truncated: boolean;
}
/** Capture collection whose members participate in global observation order. */
export const PROCESS_CAPTURE_EVENT_COLLECTIONS = [
"frames",
"rendered_frames",
"interaction_events",
"lifecycle",
"process_samples",
"filesystem_checkpoints",
] as const;
export type ProcessCaptureEventCollection =
(typeof PROCESS_CAPTURE_EVENT_COLLECTIONS)[number];
/** One reference from global observation order into a capture collection. */
export interface ProcessCaptureEventJournalEntry {
readonly capture_order: number;
readonly collection: ProcessCaptureEventCollection;
readonly index: number;
}
/** Shared observation callback used by every process-capture producer. */
export type RecordProcessCaptureEvent = (
collection: ProcessCaptureEventCollection,
index: number,
) => void;
/** Observed process-tree settlement and the cleanup required by that state. */
export type ProcessSettlement =
| VerifiedProcessSettlement
| {
readonly state: "quiesced";
readonly elapsed_ms: number;
readonly cleanup_outcome: "failed";
};
export type VerifiedProcessSettlement =
| {
readonly state: "quiesced";
readonly elapsed_ms: number;
readonly cleanup_outcome: "not_required";
}
| {
readonly state: "alive_at_deadline" | "unverifiable";
readonly elapsed_ms: number;
readonly cleanup_outcome: "cleaned" | "failed";
};
/**
* Process capture observation set.
*
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
* infer equivalence from matching bounded observations when either is present.
*/
export interface UnverifiedProcessCapture {
readonly manifest: {
readonly rea_version: string;
readonly provider_version: string;
readonly platform: string;
readonly architecture: string;
readonly pty_backend: "node-pty";
readonly started_at: string;
readonly completed_at: string;
readonly scenario: Readonly<Record<string, unknown>>;
readonly comparison_contract: Readonly<Record<string, unknown>>;
readonly full_scenario_sha256: string;
readonly comparison_contract_sha256: string;
/** Digest of the selected file sampled before spawn, when readable. */
readonly selected_executable_sha256: string | null;
/** Digest associated with the launch only when path metadata stayed stable across spawn. */
readonly executable_sha256: string | null;
/**
* Digest recorded by the original v3 format before selected and launch
* executable digests were distinguished. Kept only on migrated captures.
*/
readonly legacy_executable_sha256?: string | undefined;
readonly executable_identity: {
readonly state: "path_metadata_unchanged" | "unknown";
readonly reason: string | null;
};
readonly normalization_sha256: string;
};
readonly normalization: z.infer<typeof normalizationSchema>;
readonly frames: readonly TerminalFrame[];
readonly rendered_frames: readonly RenderedTerminalFrame[];
readonly interaction_events: readonly InteractionEvent[];
readonly exit: {
readonly code: number | null;
readonly signal: number | null;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly settlement: VerifiedProcessSettlement;
readonly process_samples: readonly ProcessSample[];
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
/**
* Global observation order across independently recorded collections.
*
* Absence is accepted for captures written before this journal existed.
*/
readonly event_journal?: readonly ProcessCaptureEventJournalEntry[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
readonly filesystem_effects: readonly FileEffect[];
readonly truncated: boolean;
readonly limitations: readonly string[];
readonly residual_unknowns: readonly {
readonly scope:
| "terminal"
| "interaction"
| "exit"
| "process"
| "filesystem"
| "cleanup"
| "network"
| "environment";
readonly reason: string;
}[];
readonly cleanup: {
readonly owned_process_group: "verified";
readonly temporary_root: "removed";
};
}
const fileStateShape = {
path: z.string(),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
};
/** A resource cleanup result retained when observations cannot be verified. */
export interface ProcessCaptureResourceCleanup {
readonly state: "cleaned" | "failed" | "unverified" | "not_required";
readonly reason: string | null;
}
export interface ProcessCaptureCleanupReport {
readonly owned_process_group: ProcessCaptureResourceCleanup;
readonly terminal_renderer: ProcessCaptureResourceCleanup;
readonly temporary_root: ProcessCaptureResourceCleanup;
}
/** One observation field that may be unavailable when capture completion fails. */
export type PartialProcessObservationField<T> =
| { readonly state: "available"; readonly value: T }
| { readonly state: "unavailable"; readonly reason: string };
/** Snapshot facts available before filesystem comparison can be completed. */
/** Snapshot facts available before filesystem comparison can be completed. */
export interface PartialFilesystemSnapshot {
readonly files: readonly FileState[];
readonly truncated: boolean;
}
/** Available and unavailable fields when a run never becomes a full capture. */
/** Available and unavailable fields when a run never becomes a full capture. */
export interface IncompleteProcessCaptureObservations {
readonly target_pid: PartialProcessObservationField<number>;
readonly frames: PartialProcessObservationField<readonly TerminalFrame[]>;
readonly rendered_frames: PartialProcessObservationField<
readonly RenderedTerminalFrame[]
>;
readonly interaction_events: PartialProcessObservationField<
readonly InteractionEvent[]
>;
readonly exit: PartialProcessObservationField<{
readonly code: number | null;
readonly signal: number | null;
readonly reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
}>;
readonly settlement: PartialProcessObservationField<{
readonly state: "quiesced" | "alive_at_deadline" | "unverifiable";
readonly elapsed_ms: number;
}>;
readonly process_samples: PartialProcessObservationField<
readonly ProcessSample[]
>;
readonly filesystem_snapshots: {
readonly before: PartialProcessObservationField<PartialFilesystemSnapshot>;
readonly after: PartialProcessObservationField<PartialFilesystemSnapshot>;
};
readonly event_journal: PartialProcessObservationField<
readonly ProcessCaptureEventJournalEntry[]
>;
readonly manifest: PartialProcessObservationField<
UnverifiedProcessCapture["manifest"]
>;
}
const fileStateSchema = z.discriminatedUnion("type", [
z.object({
...fileStateShape,
type: z.literal("file"),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.null(),
}),
z.object({
...fileStateShape,
type: z.literal("symlink"),
sha256: z.null(),
symlink_target: z.string(),
}),
z.object({
...fileStateShape,
type: z.enum(["directory", "other"]),
sha256: z.null(),
symlink_target: z.null(),
}),
]);
const fileEffectSchema = z.discriminatedUnion("status", [
z.object({
path: z.string(),
status: z.literal("created"),
before: z.null(),
after: fileStateSchema,
}),
z.object({
path: z.string(),
status: z.literal("deleted"),
before: fileStateSchema,
after: z.null(),
}),
z.object({
path: z.string(),
status: z.enum(["modified", "unchanged"]),
before: fileStateSchema,
after: fileStateSchema,
}),
]);
/** Exact serialized shape of a process capture. */
const processSettlementSchema = z.discriminatedUnion("state", [
z.object({
state: z.literal("quiesced"),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.enum(["not_required", "failed"]),
}),
z.object({
state: z.enum(["alive_at_deadline", "unverifiable"]),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.enum(["cleaned", "failed"]),
}),
]);
const processCaptureShapeSchema = z.strictObject({
manifest: z.strictObject({
rea_version: z.string().min(1),
provider_version: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
pty_backend: z.literal("node-pty"),
started_at: z.iso.datetime(),
completed_at: z.iso.datetime(),
scenario: z.record(z.string(), jsonValueSchema),
comparison_contract: 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),
selected_executable_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
executable_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
legacy_executable_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.optional(),
executable_identity: z.strictObject({
state: z.enum(["path_metadata_unchanged", "unknown"]),
reason: z.string().nullable(),
}),
normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
}),
normalization: normalizationSchema,
frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
data: z.string(),
}),
),
rendered_frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
columns: z.number().int().positive(),
rows: z.number().int().positive(),
cursor_x: z.number().int().nonnegative(),
cursor_y: z.number().int().nonnegative(),
active_buffer: z.enum(["normal", "alternate"]),
lines: z.array(z.string()),
serialized_state: z.string(),
}),
),
interaction_events: z.array(
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", "signal"]),
data: z.string(),
outcome: z.enum(["dispatched", "target_exited", "failed"]),
}),
),
exit: z.object({
code: z.number().int().nullable(),
signal: z.number().int().nullable(),
reason: z.enum(["exited", "timeout", "idle_timeout"]),
}),
settlement: z.discriminatedUnion("state", [
z.object({
state: z.literal("quiesced"),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.literal("not_required"),
}),
z.object({
state: z.enum(["alive_at_deadline", "unverifiable"]),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.enum(["cleaned", "failed"]),
}),
]),
process_samples: z.array(
z.object({
at_ms: z.number().int().nonnegative(),
pid: z.number().int().positive(),
parent_pid: z.number().int().nonnegative(),
command: z.string(),
process_group_id: z.number().int().positive().nullable(),
session_id: z.number().int().nonnegative().nullable(),
}),
),
filesystem_checkpoints: z.array(
z.object({
name: z.enum(["before", "after_settlement"]),
at_ms: z.number().int().nonnegative(),
files: z.array(fileStateSchema),
effects: z.array(fileEffectSchema),
truncated: z.boolean(),
}),
),
event_journal: z
.array(
z.object({
capture_order: z.number().int().nonnegative(),
collection: z.enum(PROCESS_CAPTURE_EVENT_COLLECTIONS),
index: z.number().int().nonnegative(),
}),
)
.default([]),
files_before: z.array(fileStateSchema),
files_after: z.array(fileStateSchema),
filesystem_effects: z.array(fileEffectSchema),
truncated: z.boolean(),
limitations: z.array(z.string()),
residual_unknowns: z.array(
z.object({
scope: z.enum([
"terminal",
"interaction",
"exit",
"process",
"filesystem",
"cleanup",
"network",
"environment",
]),
reason: z.string(),
}),
),
cleanup: z.object({
owned_process_group: z.literal("verified"),
temporary_root: z.literal("removed"),
}),
});
const processCleanupResourceSchema = z.strictObject({
state: z.enum(["cleaned", "failed", "unverified", "not_required"]),
reason: z.string().nullable(),
});
const partialObservationFieldSchema = <Schema extends z.ZodType>(
value: Schema,
) =>
z.discriminatedUnion("state", [
z.strictObject({ state: z.literal("available"), value }),
z.strictObject({ state: z.literal("unavailable"), reason: z.string() }),
]);
const incompleteProcessCaptureObservationsSchema = z.strictObject({
target_pid: partialObservationFieldSchema(z.number().int().positive()),
frames: partialObservationFieldSchema(processCaptureShapeSchema.shape.frames),
rendered_frames: partialObservationFieldSchema(
processCaptureShapeSchema.shape.rendered_frames,
),
interaction_events: partialObservationFieldSchema(
processCaptureShapeSchema.shape.interaction_events,
),
exit: partialObservationFieldSchema(
z.strictObject({
code: z.number().int().nullable(),
signal: z.number().int().nullable(),
reason: z.enum(["exited", "timeout", "idle_timeout", "cancelled"]),
}),
),
settlement: partialObservationFieldSchema(
z.strictObject({
state: z.enum(["quiesced", "alive_at_deadline", "unverifiable"]),
elapsed_ms: z.number().int().nonnegative(),
}),
),
process_samples: partialObservationFieldSchema(
processCaptureShapeSchema.shape.process_samples,
),
filesystem_snapshots: z.strictObject({
before: partialObservationFieldSchema(
z.strictObject({
files: z.array(fileStateSchema),
truncated: z.boolean(),
}),
),
after: partialObservationFieldSchema(
z.strictObject({
files: z.array(fileStateSchema),
truncated: z.boolean(),
}),
),
}),
event_journal: partialObservationFieldSchema(
processCaptureShapeSchema.shape.event_journal,
),
manifest: partialObservationFieldSchema(
processCaptureShapeSchema.shape.manifest,
),
});
const partialCleanupReportSchema = z.strictObject({
owned_process_group: processCleanupResourceSchema,
terminal_renderer: processCleanupResourceSchema,
temporary_root: processCleanupResourceSchema,
});
const partialObservationMetadataSchema = z.strictObject({
cleanup: partialCleanupReportSchema,
execution_failure: z.string().nullable(),
});
const completedCaptureObservationSchema = z.strictObject({
capture: processCaptureShapeSchema
.omit({ cleanup: true })
.extend({ settlement: processSettlementSchema }),
});
const incompleteCaptureObservationSchema = z.strictObject({
observations: incompleteProcessCaptureObservationsSchema,
});
/** Validated, non-comparable process observations attached to cleanup errors. */
export const partialProcessCaptureObservationSchema = z
.union([
completedCaptureObservationSchema.extend(
partialObservationMetadataSchema.shape,
),
incompleteCaptureObservationSchema.extend(
partialObservationMetadataSchema.shape,
),
])
.superRefine((partial, context) => {
if (
!Object.values(partial.cleanup).some(
({ state }) => state === "failed" || state === "unverified",
)
)
context.addIssue({
code: "custom",
path: ["cleanup"],
message: "partial observations require incomplete resource cleanup",
});
if ("observations" in partial) {
const { observations } = partial;
if (
![
observations.frames,
observations.interaction_events,
observations.process_samples,
observations.filesystem_snapshots.before,
observations.event_journal,
].some(({ state }) => state === "available")
)
context.addIssue({
code: "custom",
path: ["observations"],
message: "incomplete observations contain no collected evidence",
});
return;
}
const { capture } = partial;
const settlement =
capture.settlement.state === "quiesced"
? {
...capture.settlement,
cleanup_outcome: "not_required" as const,
}
: { ...capture.settlement, cleanup_outcome: "cleaned" as const };
const validationCapture: UnverifiedProcessCapture = {
...capture,
settlement,
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
};
for (const issue of collectProcessCaptureIssues(validationCapture))
context.addIssue({
code: "custom",
path: ["capture", ...issue.path.split(".")],
message: issue.message,
});
});
/** One collected payload: completed capture data or explicit unavailable fields. */
export type PartialProcessCaptureObservation = z.infer<
typeof partialProcessCaptureObservationSchema
>;
/** Exact serialized shape plus all process-capture semantic invariants. */
export const processCaptureSchema = processCaptureShapeSchema
.superRefine((capture, context) => {
if (capture.settlement.cleanup_outcome === "failed")
context.addIssue({
code: "custom",
path: ["settlement", "cleanup_outcome"],
message: "verified captures cannot contain failed cleanup",
});
for (const issue of collectProcessCaptureIssues(capture))
context.addIssue({
code: "custom",
path: issue.path.split("."),
message: issue.message,
});
})
.describe(
"The capture must preserve its canonical scenario, comparison, and normalization SHA-256 commitments; ordered capture timestamps and contiguous sequence numbers; before and final filesystem snapshots with truncation propagated; and exit-code consistency with deadline termination. When parsing older input without an event journal, REA supplies an empty journal; empty journals are valid. A non-empty journal must reference every captured observation exactly once with unique in-range references. These cross-field invariants are checked by REA after capture.",
);
export { parseProcessCapture } from "./processCaptureParsing.js";
export type { ProcessCapture } from "./processCaptureParsing.js";
export {
compareProcessCaptures,
comparisonStatusSchema,
deriveProcessComparisonStatus,
PROCESS_COMPARISON_DIMENSIONS,
processCaptureComparisonSchema,
} from "./processComparison.js";
@@ -65,7 +65,7 @@ it("rejects altered v4 commitments and accepts canonical key reordering", () =>
executable_sha256: "f".repeat(64),
},
}),
).toThrow("executable_sha256");
).toThrow("executable_identity");
});
it("rejects settlement and cleanup combinations that cannot occur", () => {
@@ -142,6 +142,92 @@ it("accepts old captures without a journal and validates complete journals", ()
}
});
it("migrates persisted v3 executable digests without claiming a selected digest", () => {
const capture = emptyCapture();
const {
selected_executable_sha256: _selectedExecutableSha256,
executable_identity: _executableIdentity,
executable_sha256,
...legacyManifest
} = capture.manifest;
const legacyCapture = {
...capture,
manifest: { ...legacyManifest, executable_sha256 },
};
const migrated = parseProcessCapture(legacyCapture);
expect(migrated.manifest).toMatchObject({
selected_executable_sha256: null,
executable_sha256: null,
executable_identity: {
state: "unknown",
reason: expect.stringContaining("did not distinguish"),
},
legacy_executable_sha256: executable_sha256,
scenario: capture.manifest.scenario,
full_scenario_sha256: capture.manifest.full_scenario_sha256,
});
expect(compareProcessCaptures(migrated, migrated)).toMatchObject({
status: "unchanged",
});
const exported = JSON.stringify(migrated);
expect(parseProcessCapture(JSON.parse(exported))).toEqual(migrated);
expect(() =>
parseProcessCapture({
...legacyCapture,
manifest: {
...legacyCapture.manifest,
executable_sha256: "f".repeat(64),
},
}),
).toThrow("legacy_executable_sha256");
const nullDigestScenario = {
...legacyCapture.manifest.scenario,
executable_sha256: null,
};
const malformedLegacyBase = {
...legacyCapture,
manifest: {
...legacyCapture.manifest,
executable_sha256: null,
scenario: nullDigestScenario,
full_scenario_sha256: digestProcessCommitment(nullDigestScenario),
},
};
expect(() => parseProcessCapture(malformedLegacyBase)).toThrow();
expect(() =>
parseProcessCapture({
...malformedLegacyBase,
manifest: {
...malformedLegacyBase.manifest,
executable_sha256: "not-a-digest",
},
}),
).toThrow();
const {
executable_sha256: _missingLegacyDigest,
...manifestWithoutLegacyDigest
} = malformedLegacyBase.manifest;
expect(() =>
parseProcessCapture({
...malformedLegacyBase,
manifest: manifestWithoutLegacyDigest,
}),
).toThrow();
const { executable_identity: _missingIdentity, ...incompleteModernManifest } =
capture.manifest;
expect(() =>
parseProcessCapture({
...capture,
manifest: incompleteModernManifest,
}),
).toThrow();
});
it("requires compatible contracts and enforces capture age through a clock seam", () => {
const capture = emptyCapture();
expect(() =>
@@ -1,4 +1,4 @@
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
import { digestProcessCommitment } from "./processCapture.js";
const normalization = {
@@ -25,7 +25,12 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
comparison_contract: comparisonContract,
full_scenario_sha256: digestProcessCommitment(scenario),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
selected_executable_sha256: "0".repeat(64),
executable_sha256: "0".repeat(64),
executable_identity: {
state: "path_metadata_unchanged",
reason: null,
},
normalization_sha256: digestProcessCommitment(normalization),
},
normalization,
@@ -2,6 +2,7 @@ import {
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import { z } from "zod";
declare class ProcessCaptureProof {
private readonly verified: never;
@@ -22,9 +23,47 @@ const attachProof = (capture: UnverifiedProcessCapture): ProcessCapture => {
throw new TypeError("Process Capture proof ownership failed");
};
const recordSchema = z.record(z.string(), z.unknown());
const LEGACY_EXECUTABLE_IDENTITY_REASON =
"Legacy v3 capture did not distinguish selected and launch executable digests";
const migrateLegacyV3Capture = (input: unknown): unknown => {
const capture = recordSchema.safeParse(input);
if (!capture.success) return input;
const manifest = recordSchema.safeParse(capture.data.manifest);
if (!manifest.success) return input;
if (
manifest.data.provider_version !== "3" ||
"selected_executable_sha256" in manifest.data ||
"executable_identity" in manifest.data ||
"legacy_executable_sha256" in manifest.data
)
return input;
const { executable_sha256 } = manifest.data;
if (
typeof executable_sha256 !== "string" ||
!/^[a-f0-9]{64}$/u.test(executable_sha256)
)
return input;
return {
...capture.data,
manifest: {
...manifest.data,
selected_executable_sha256: null,
executable_sha256: null,
executable_identity: {
state: "unknown",
reason: LEGACY_EXECUTABLE_IDENTITY_REASON,
},
legacy_executable_sha256: executable_sha256,
},
};
};
/** Parse unknown input and reject invalid commitments or semantics. */
export const parseProcessCapture = (input: unknown): ProcessCapture => {
const parsed = processCaptureSchema.safeParse(input);
const parsed = processCaptureSchema.safeParse(migrateLegacyV3Capture(input));
if (parsed.success) return attachProof(parsed.data);
const issues = parsed.error.issues.flatMap((issue) =>
issue.code === "custom"
@@ -26,8 +26,23 @@ const validateCommitments = (
require: RequireInvariant,
): void => {
const { manifest } = capture;
require(manifest.scenario.executable_sha256 ===
manifest.executable_sha256, "manifest.executable_sha256", "executable commitment does not match the scenario projection");
if (manifest.legacy_executable_sha256 !== undefined) {
require(manifest.selected_executable_sha256 === null &&
manifest.executable_sha256 === null &&
manifest.executable_identity.state === "unknown" &&
manifest.executable_identity.reason !== null &&
manifest.scenario.executable_sha256 ===
manifest.legacy_executable_sha256, "manifest.legacy_executable_sha256", "legacy executable digest must remain distinct from unknown selected and launch digests");
} else {
require(manifest.scenario.executable_sha256 ===
manifest.selected_executable_sha256, "manifest.selected_executable_sha256", "selected executable commitment does not match the scenario projection");
}
require(manifest.executable_identity.state === "path_metadata_unchanged"
? manifest.executable_sha256 === manifest.selected_executable_sha256 &&
manifest.executable_identity.reason === null
: manifest.executable_sha256 === null &&
manifest.executable_identity.reason !==
null, "manifest.executable_identity", "launch identity and executable digest do not agree");
for (const [field, value] of [
["full_scenario_sha256", manifest.scenario],
["comparison_contract_sha256", manifest.comparison_contract],
@@ -2,7 +2,7 @@ import canonicalize from "canonicalize";
import { z } from "zod";
import type { ProcessCapture } from "./processCapture.js";
import { jsonValueSchema } from "./jsonValue.js";
import { jsonValueSchema } from "../jsonValue.js";
import {
compareProcessTraces,
processTraceOutcomesDiffer,
@@ -1,4 +1,4 @@
import type { EvidenceProvider } from "./evidence.js";
import type { EvidenceProvider } from "../evidence.js";
/** Canonical provider identity for controlled process capture Evidence. */
export const PROCESS_PROVIDER = {
@@ -5,10 +5,7 @@ import {
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import {
createProcessObservation,
projectProcessObservation,
} from "./processObservation.js";
import { projectProcessObservation } from "./processObservation.js";
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
@@ -86,25 +83,7 @@ describe("process observation vocabulary", () => {
expect(observations[4]?.captured_at_ms).toBeNull();
});
it("uses the same constructor for live and post-hoc observations", () => {
const location = {
collection: "frames" as const,
index: 0,
capture_order: 4,
};
const projected = projectProcessObservation(capture, location);
const live = createProcessObservation({
source: "terminal_raw",
source_sequence: 0,
captured_at_ms: 1,
subject_id: null,
location,
payload: capture.frames[0],
});
expect(live).toEqual(projected);
});
it("returns no observation for a missing raw record", () => {
it("returns no observation for a missing collection record", () => {
expect(
projectProcessObservation(capture, {
collection: "frames",
@@ -1,6 +1,6 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
import type { UnverifiedProcessCapture } from "./processCapture.js";
/** Process-capture observation families shared by live drivers and trace assertions. */
@@ -61,6 +61,24 @@ describe("direct process scenarios", () => {
).toBe(true);
});
it("rejects NUL in strings passed to child-process APIs", () => {
const nul = "\0";
for (const input of [
{ executable: `node${nul}` },
{ executable: "node", arguments: [nul] },
{ executable: "node", working_directory: `.${nul}` },
{ executable: "node", environment: { KEY: nul } },
{ executable: "node", filesystem_observation_paths: [nul] },
])
expect(processScenarioSchema.safeParse(input).success).toBe(false);
expect(
processScenarioSchema.safeParse({
executable: "node",
events: [{ type: "input", at_ms: 0, data: nul }],
}).success,
).toBe(true);
});
it("keeps bounded capture controls and ordered scheduled interaction", () => {
const scenario = processScenarioSchema.parse({
executable: "node",
@@ -14,6 +14,12 @@ const environmentName = z
? `${reservedRunIdEnvironmentName} is reserved by the process adapter`
: "Environment names cannot contain '=' or NUL",
});
const childProcessString = z
.string()
.regex(
/^[^\0]*$/u,
"Values passed to operating-system APIs cannot contain NUL",
);
export const normalizationSchema = z.object({
paths: z.boolean(),
pids: z.boolean(),
@@ -86,11 +92,13 @@ export const processComparisonContract = (
*/
export const processScenarioSchema = z
.object({
executable: z.string().min(1),
arguments: z.array(z.string()).default([]),
working_directory: z.string().default("."),
environment: z.record(environmentName, z.string()).default({}),
filesystem_observation_paths: z.array(z.string().min(1)).default([]),
executable: childProcessString.min(1),
arguments: z.array(childProcessString).default([]),
working_directory: childProcessString.default("."),
environment: z.record(environmentName, childProcessString).default({}),
filesystem_observation_paths: z
.array(childProcessString.min(1))
.default([]),
terminal: z
.object({
columns: z.number().int().min(1).max(65_535).default(80),
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { JsonValue } from "./jsonValue.js";
import type { JsonValue } from "../jsonValue.js";
import type { ProcessCapture } from "./processCapture.js";
import {
processObservationLocationSchema,
@@ -1,7 +1,7 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { jsonValueSchema } from "../jsonValue.js";
import {
comparableProcessObservationPayload,
processObservationSourceSchema,
@@ -1,198 +0,0 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("classifies missing observations as unknown and one-sided evidence as added", () => {
const base = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const added = compareProcessCaptures(base, {
...base,
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
rendered_frames: [
{
sequence: 0,
at_ms: 0,
columns: 3,
rows: 1,
cursor_x: 3,
cursor_y: 0,
active_buffer: "normal",
lines: ["new"],
serialized_state: "new",
},
],
});
expect(added.terminal).toBe("added");
expect(added.status).toBe("changed");
const unknown = compareProcessCaptures(
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
base,
);
expect(unknown.process).toBe("unknown");
expect(unknown.status).toBe("unknown");
});
it("treats equivalent normalization records as equal regardless of member order", () => {
const capture = emptyCapture();
expect(
compareProcessCaptures(capture, {
...capture,
normalization: {
patterns: [],
time_bucket_ms: 10,
ports: true,
pids: true,
paths: true,
},
}),
).toMatchObject({
status: "unchanged",
first_divergence: { status: "none" },
});
});
it("compares raw terminal chunks even when rendered states agree", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const comparison = compareProcessCaptures(capture, {
...capture,
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
});
expect(comparison.terminal).toBe("changed");
expect(comparison.first_divergence).toMatchObject({
status: "found",
dimension: "terminal",
});
});
it("keeps filesystem evidence unknown when stable snapshots match", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [
{ scope: "filesystem" as const, reason: "watcher unavailable" },
],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const comparison = compareProcessCaptures(capture, capture);
expect(comparison.filesystem).toBe("unknown");
expect(comparison.status).toBe("unknown");
const complete = { ...capture, residual_unknowns: [] };
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: "after_settlement",
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(changed.filesystem).toBe("changed");
expect(changed.status).toBe("changed");
});
@@ -1,62 +0,0 @@
import { expect, it } from "vitest";
import {
compareUnverifiedProcessCaptures as compareProcessCaptures,
emptyProcessCapture as emptyCapture,
} from "./processCapture.fixture.js";
it("detects changes in normalized process sample metadata", () => {
const capture = {
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [
{
at_ms: 10,
pid: 1,
parent_pid: 0,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const changed = {
...capture,
process_samples: [
{
at_ms: 20,
pid: 1,
parent_pid: 2,
process_group_id: 1,
session_id: 1,
command: "worker",
},
],
};
const comparison = compareProcessCaptures(capture, changed);
expect(comparison.process).toBe("changed");
expect(comparison.status).toBe("changed");
});
-398
View File
@@ -1,398 +0,0 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { normalizationSchema } from "./processScenario.js";
import { collectProcessCaptureIssues } from "./processCaptureValidation.js";
export * from "./processScenario.js";
/** Normalized raw PTY chunk, preserving transport-level output differences. */
export interface TerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly data: string;
}
/** Serialized terminal state after interpreting control and resize sequences. */
export interface RenderedTerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly columns: number;
readonly rows: number;
readonly cursor_x: number;
readonly cursor_y: number;
readonly active_buffer: "normal" | "alternate";
readonly lines: readonly string[];
readonly serialized_state: string;
}
/** Scheduled terminal interaction with its observed dispatch outcome. */
export interface InteractionEvent {
readonly sequence: number;
readonly scheduled_at_ms: number;
readonly dispatched_at_ms: number;
readonly type: "input" | "resize" | "signal";
readonly data: string;
readonly outcome: "dispatched" | "target_exited" | "failed";
}
/** One filesystem state used for before/after comparison. */
interface FileStateIdentity {
readonly path: string;
readonly mode: number;
readonly size: number;
}
export type FileState = FileStateIdentity &
(
| {
readonly type: "file";
readonly sha256: string | null;
readonly symlink_target: null;
}
| {
readonly type: "symlink";
readonly sha256: null;
readonly symlink_target: string;
}
| {
readonly type: "directory" | "other";
readonly sha256: null;
readonly symlink_target: null;
}
);
interface FileEffectIdentity {
readonly path: string;
}
type FileEffect = FileEffectIdentity &
(
| {
readonly status: "created";
readonly before: null;
readonly after: FileState;
}
| {
readonly status: "deleted";
readonly before: FileState;
readonly after: null;
}
| {
readonly status: "modified" | "unchanged";
readonly before: FileState;
readonly after: FileState;
}
);
/** A sampled owned-process observation; sampling cannot prove syscall completeness. */
export interface ProcessSample {
readonly at_ms: number;
readonly pid: number;
readonly parent_pid: number;
readonly command: string;
readonly process_group_id: number | null;
readonly session_id: number | null;
}
/** Initial or final filesystem snapshot selected for observation. */
export interface FilesystemCheckpoint {
readonly name: string;
readonly at_ms: number;
readonly files: readonly FileState[];
readonly effects: readonly FileEffect[];
readonly truncated: boolean;
}
/** Capture collection whose members participate in global observation order. */
export const PROCESS_CAPTURE_EVENT_COLLECTIONS = [
"frames",
"rendered_frames",
"interaction_events",
"lifecycle",
"process_samples",
"filesystem_checkpoints",
] as const;
export type ProcessCaptureEventCollection =
(typeof PROCESS_CAPTURE_EVENT_COLLECTIONS)[number];
/** One reference from global observation order into a capture collection. */
export interface ProcessCaptureEventJournalEntry {
readonly capture_order: number;
readonly collection: ProcessCaptureEventCollection;
readonly index: number;
}
/** Shared observation callback used by every process-capture producer. */
export type RecordProcessCaptureEvent = (
collection: ProcessCaptureEventCollection,
index: number,
) => void;
/** Observed process-tree settlement and the cleanup required by that state. */
export type ProcessSettlement =
| {
readonly state: "quiesced";
readonly elapsed_ms: number;
readonly cleanup_outcome: "not_required";
}
| {
readonly state: "alive_at_deadline" | "unverifiable";
readonly elapsed_ms: number;
readonly cleanup_outcome: "cleaned" | "failed";
};
/**
* Process capture observation set.
*
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
* infer equivalence from matching bounded observations when either is present.
*/
export interface UnverifiedProcessCapture {
readonly manifest: {
readonly rea_version: string;
readonly provider_version: string;
readonly platform: string;
readonly architecture: string;
readonly pty_backend: "node-pty";
readonly started_at: string;
readonly completed_at: string;
readonly scenario: Readonly<Record<string, unknown>>;
readonly comparison_contract: Readonly<Record<string, unknown>>;
readonly full_scenario_sha256: string;
readonly comparison_contract_sha256: string;
readonly executable_sha256: string;
readonly normalization_sha256: string;
};
readonly normalization: z.infer<typeof normalizationSchema>;
readonly frames: readonly TerminalFrame[];
readonly rendered_frames: readonly RenderedTerminalFrame[];
readonly interaction_events: readonly InteractionEvent[];
readonly exit: {
readonly code: number | null;
readonly signal: number | null;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly settlement: ProcessSettlement;
readonly process_samples: readonly ProcessSample[];
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
/**
* Global observation order across independently recorded collections.
*
* Absence is accepted for captures written before this journal existed.
*/
readonly event_journal?: readonly ProcessCaptureEventJournalEntry[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
readonly filesystem_effects: readonly FileEffect[];
readonly truncated: boolean;
readonly limitations: readonly string[];
readonly residual_unknowns: readonly {
readonly scope:
| "terminal"
| "interaction"
| "exit"
| "process"
| "filesystem"
| "cleanup"
| "network"
| "environment";
readonly reason: string;
}[];
readonly cleanup: {
readonly owned_process_group: "verified";
readonly temporary_root: "removed";
};
}
const fileStateShape = {
path: z.string(),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
};
const fileStateSchema = z.discriminatedUnion("type", [
z.object({
...fileStateShape,
type: z.literal("file"),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.null(),
}),
z.object({
...fileStateShape,
type: z.literal("symlink"),
sha256: z.null(),
symlink_target: z.string(),
}),
z.object({
...fileStateShape,
type: z.enum(["directory", "other"]),
sha256: z.null(),
symlink_target: z.null(),
}),
]);
const fileEffectSchema = z.discriminatedUnion("status", [
z.object({
path: z.string(),
status: z.literal("created"),
before: z.null(),
after: fileStateSchema,
}),
z.object({
path: z.string(),
status: z.literal("deleted"),
before: fileStateSchema,
after: z.null(),
}),
z.object({
path: z.string(),
status: z.enum(["modified", "unchanged"]),
before: fileStateSchema,
after: fileStateSchema,
}),
]);
/** Exact serialized shape of a process capture. */
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),
architecture: z.string().min(1),
pty_backend: z.literal("node-pty"),
started_at: z.iso.datetime(),
completed_at: z.iso.datetime(),
scenario: z.record(z.string(), jsonValueSchema),
comparison_contract: 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),
}),
normalization: normalizationSchema,
frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
data: z.string(),
}),
),
rendered_frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
columns: z.number().int().positive(),
rows: z.number().int().positive(),
cursor_x: z.number().int().nonnegative(),
cursor_y: z.number().int().nonnegative(),
active_buffer: z.enum(["normal", "alternate"]),
lines: z.array(z.string()),
serialized_state: z.string(),
}),
),
interaction_events: z.array(
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", "signal"]),
data: z.string(),
outcome: z.enum(["dispatched", "target_exited", "failed"]),
}),
),
exit: z.object({
code: z.number().int().nullable(),
signal: z.number().int().nullable(),
reason: z.enum(["exited", "timeout", "idle_timeout"]),
}),
settlement: z.discriminatedUnion("state", [
z.object({
state: z.literal("quiesced"),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.literal("not_required"),
}),
z.object({
state: z.enum(["alive_at_deadline", "unverifiable"]),
elapsed_ms: z.number().int().nonnegative(),
cleanup_outcome: z.enum(["cleaned", "failed"]),
}),
]),
process_samples: z.array(
z.object({
at_ms: z.number().int().nonnegative(),
pid: z.number().int().positive(),
parent_pid: z.number().int().nonnegative(),
command: z.string(),
process_group_id: z.number().int().positive().nullable(),
session_id: z.number().int().nonnegative().nullable(),
}),
),
filesystem_checkpoints: z.array(
z.object({
name: z.enum(["before", "after_settlement"]),
at_ms: z.number().int().nonnegative(),
files: z.array(fileStateSchema),
effects: z.array(fileEffectSchema),
truncated: z.boolean(),
}),
),
event_journal: z
.array(
z.object({
capture_order: z.number().int().nonnegative(),
collection: z.enum(PROCESS_CAPTURE_EVENT_COLLECTIONS),
index: z.number().int().nonnegative(),
}),
)
.default([]),
files_before: z.array(fileStateSchema),
files_after: z.array(fileStateSchema),
filesystem_effects: z.array(fileEffectSchema),
truncated: z.boolean(),
limitations: z.array(z.string()),
residual_unknowns: z.array(
z.object({
scope: z.enum([
"terminal",
"interaction",
"exit",
"process",
"filesystem",
"cleanup",
"network",
"environment",
]),
reason: z.string(),
}),
),
cleanup: 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(
(capture, context) => {
for (const issue of collectProcessCaptureIssues(capture))
context.addIssue({
code: "custom",
path: issue.path.split("."),
message: issue.message,
});
},
);
export { parseProcessCapture } from "./processCaptureParsing.js";
export type { ProcessCapture } from "./processCaptureParsing.js";
export {
compareProcessCaptures,
comparisonStatusSchema,
deriveProcessComparisonStatus,
PROCESS_COMPARISON_DIMENSIONS,
processCaptureComparisonSchema,
} from "./processComparison.js";

Some files were not shown because too many files have changed in this diff Show More