feat: add persistent cross-version investigation workspaces

This commit is contained in:
N0zoM1z0
2026-07-13 19:37:54 +08:00
parent d0e21f9231
commit 41366edd56
113 changed files with 3828 additions and 371 deletions
+42 -13
View File
@@ -7,16 +7,33 @@ import {
comparisonStatusSchema,
processCaptureComparisonSchema,
} from "./processCapture.js";
import {
crossVersionInvestigationInputSchema,
investigationRunSummarySchema,
} from "./investigationWorkspace.js";
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
/** Strict bounded input for aggregating existing comparison Evidence. */
export const changedBehaviorInputSchema = z.object({
comparisons: z.array(evidenceSchema).min(1).max(100),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
unknown_registry_approved: z.literal(true).optional(),
});
export const changedBehaviorInputSchema = z
.object({
comparisons: z.array(evidenceSchema).max(100).default([]),
investigation_run: crossVersionInvestigationInputSchema.optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine((input, context) => {
if (
input.comparisons.length > 0 ===
(input.investigation_run !== undefined)
)
context.addIssue({
code: "custom",
message:
"Supply either existing comparisons or one investigation_run, but not both",
});
});
const findingSchema = z.object({
scope: z.enum(["runtime", "protocol", "resource", "static_candidate"]),
@@ -56,6 +73,7 @@ export const changedBehaviorResultSchema = z.object({
}),
evidence_links: z.array(evidenceIdSchema).min(3).max(20_100),
limitations: z.array(z.string()),
investigation_run: investigationRunSummarySchema.optional(),
});
export type ChangedBehaviorResult = z.infer<typeof changedBehaviorResultSchema>;
@@ -142,6 +160,7 @@ export const findChangedBehavior = (
...(runtimeStatuses.length === 0
? ["No process comparison Evidence was supplied."]
: []),
...evidence.flatMap(artifactPaginationLimitations),
]),
});
};
@@ -219,13 +238,9 @@ const parseResult = (evidence: Evidence): void => {
const result = artifactComparisonResultSchema.parse(
evidence.normalized_result,
);
if (
result.changes.offset !== 0 ||
result.changes.next_offset !== null ||
result.changes.items.length !== result.changes.total
)
if (result.changes.offset !== 0)
throw new TypeError(
"Changed-behavior analysis requires complete artifact comparison pagination",
"Changed-behavior analysis requires artifact comparison pagination from offset zero",
);
assertNestedLinks(
evidence,
@@ -323,7 +338,9 @@ const artifactFindings = (evidence: Evidence): Finding[] => {
links: change.evidence_links,
}),
);
return (result.status === "unknown" || result.status === "truncated") &&
return (result.status === "unknown" ||
result.status === "truncated" ||
result.changes.next_offset !== null) &&
!changes.some(
({ classification }) => classification === "unresolved_branch",
)
@@ -341,6 +358,18 @@ const artifactFindings = (evidence: Evidence): Finding[] => {
: changes;
};
const artifactPaginationLimitations = (evidence: Evidence): string[] => {
if (evidence.operation !== "compare_artifacts") return [];
const result = artifactComparisonResultSchema.parse(
evidence.normalized_result,
);
return result.changes.next_offset === null
? []
: [
`Artifact comparison reports ${String(result.changes.items.length)} of ${String(result.changes.total)} changes.`,
];
};
const makeFinding = (input: {
readonly evidence: Evidence;
readonly dimension: string;
+27
View File
@@ -15,6 +15,7 @@ export const ANALYSIS_ERROR_TAGS = [
"EvidenceIntegrityError",
"EvidenceLimitError",
"EvidenceFileError",
"InvestigationWorkspaceError",
"UnknownRegistryError",
"HopperTimeoutError",
"HopperCancelledError",
@@ -192,6 +193,29 @@ export class EvidenceFileError extends AnalysisError {
}
}
/** Persistent investigation workspace access or CAS validation failed. */
export class InvestigationWorkspaceError extends AnalysisError {
readonly _tag = "InvestigationWorkspaceError";
constructor(
readonly operation: "read" | "update",
readonly reason:
| "disabled"
| "outside-root"
| "not-file"
| "too-large"
| "invalid-json"
| "integrity"
| "locked"
| "revision-conflict"
| "name-conflict"
| "io",
options?: ErrorOptions,
) {
super(`Investigation workspace ${operation} failed: ${reason}`, options);
}
}
/** Residual-unknown mutation failed a lifecycle, reference, or CAS invariant. */
export class UnknownRegistryError extends AnalysisError {
readonly _tag = "UnknownRegistryError";
@@ -347,6 +371,8 @@ const safeDetails = (
return { limit: error.limit, maximum: error.maximum };
if (error instanceof EvidenceFileError)
return { operation: error.operation, reason: error.reason };
if (error instanceof InvestigationWorkspaceError)
return { operation: error.operation, reason: error.reason };
if (error instanceof UnknownRegistryError) return { reason: error.reason };
if (error instanceof HopperTimeoutError)
return { timeoutMs: error.timeoutMs };
@@ -374,6 +400,7 @@ const KNOWN_ERROR_TAGS = {
EvidenceIntegrityError: true,
EvidenceLimitError: true,
EvidenceFileError: true,
InvestigationWorkspaceError: true,
UnknownRegistryError: true,
HopperTimeoutError: true,
HopperCancelledError: true,
+295
View File
@@ -0,0 +1,295 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
evidenceBundleSchema,
parseEvidenceBundle,
type EvidenceBundle,
} from "./evidenceBundle.js";
import type { JsonValue } from "./jsonValue.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const artifactFormatSchema =
evidenceBundleSchema.shape.artifacts.element.shape.format;
/** Bounded controls for one automatic, provider-neutral artifact comparison. */
const investigationRunOptionsSchema = z.object({
max_entries: z.number().int().min(1).max(50_000).default(10_000),
max_total_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(1_073_741_824),
max_entry_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(268_435_456),
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
max_depth: z.number().int().min(0).max(100).default(20),
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
page_size: z.number().int().min(1).max(500).default(500),
change_limit: z.number().int().min(1).max(500).default(500),
});
const DEFAULT_INVESTIGATION_RUN_OPTIONS = {
max_entries: 10_000,
max_total_bytes: 1_073_741_824,
max_entry_bytes: 268_435_456,
max_compression_ratio: 1_000,
max_depth: 20,
max_path_bytes: 4_096,
page_size: 500,
change_limit: 500,
} as const;
export type InvestigationRunOptions = z.infer<
typeof investigationRunOptionsSchema
>;
/** Explicit write approval and two local versions for an automatic run. */
export const crossVersionInvestigationInputSchema = z.object({
approved: z.literal(true),
workspace_path: z.string().min(1).max(4_096),
workspace_name: z.string().trim().min(1).max(200).default("default"),
expected_workspace_revision: z.number().int().min(1).optional(),
left_path: z.string().min(1).max(4_096),
right_path: z.string().min(1).max(4_096),
options: investigationRunOptionsSchema.default(
DEFAULT_INVESTIGATION_RUN_OPTIONS,
),
});
export type CrossVersionInvestigationInput = z.infer<
typeof crossVersionInvestigationInputSchema
>;
const targetSchema = z.object({
root_sha256: digestSchema,
graph_sha256: digestSchema,
manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
format: artifactFormatSchema,
});
export type InvestigationRunTarget = z.infer<typeof targetSchema>;
const stageSchema = z.enum([
"inventory_left",
"inventory_right",
"compare_artifacts",
"find_changed_behavior",
]);
export const investigationRunSchema = z.object({
schema_version: z.literal(1),
run_id: z.string().regex(/^run_[a-f0-9]{64}$/u),
request_sha256: digestSchema,
left: targetSchema,
right: targetSchema,
options: investigationRunOptionsSchema,
status: z.enum(["running", "complete"]),
completed_stages: z.array(stageSchema).max(4),
left_inventory_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
right_inventory_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
comparison_evidence_id: evidenceIdSchema.nullable(),
result_evidence_id: evidenceIdSchema.nullable(),
limitations: z.array(z.string().max(4_096)).max(100),
});
export type InvestigationRun = z.infer<typeof investigationRunSchema>;
export const investigationRunSummarySchema = z.object({
schema_version: z.literal(1),
workspace_id: z.string().regex(/^ws_[a-f0-9]{64}$/u),
run_id: z.string().regex(/^run_[a-f0-9]{64}$/u),
left_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
right_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
inventory_evidence_count: z.number().int().min(2).max(200),
comparison_evidence_id: evidenceIdSchema,
limitations: z.array(z.string().max(4_096)).max(100),
});
const investigationWorkspaceSchema = z.object({
workspace_version: z.literal(1),
workspace_id: z.string().regex(/^ws_[a-f0-9]{64}$/u),
name: z.string().trim().min(1).max(200),
revision: z.number().int().min(1),
previous_revision_digest: z
.string()
.regex(/^wrev_[a-f0-9]{64}$/u)
.nullable(),
revision_digest: z.string().regex(/^wrev_[a-f0-9]{64}$/u),
bundle: evidenceBundleSchema,
runs: z.array(investigationRunSchema).max(1_000),
});
export type InvestigationWorkspace = z.infer<
typeof investigationWorkspaceSchema
>;
/** Derive a stable run identity from content commitments and bounded controls. */
export const createInvestigationRunIdentity = (input: {
readonly left: InvestigationRunTarget;
readonly right: InvestigationRunTarget;
readonly options: InvestigationRunOptions;
}): { readonly runId: string; readonly requestSha256: string } => {
const requestSha256 = digestCanonical({
schema: "rea.cross-version-investigation-request/v1",
left: input.left,
right: input.right,
options: input.options,
});
return { runId: `run_${requestSha256}`, requestSha256 };
};
/** Build the first canonical workspace revision. */
export const createInvestigationWorkspace = (
name: string,
bundle: EvidenceBundle,
runs: readonly InvestigationRun[],
): InvestigationWorkspace =>
buildWorkspace({
workspaceId: `ws_${digestCanonical({ schema: "rea.workspace/v1", name })}`,
name,
revision: 1,
previousRevisionDigest: null,
bundle,
runs,
});
/** Create the next immutable workspace revision. */
export const reviseInvestigationWorkspace = (
current: InvestigationWorkspace,
bundle: EvidenceBundle,
runs: readonly InvestigationRun[],
): InvestigationWorkspace =>
buildWorkspace({
workspaceId: current.workspace_id,
name: current.name,
revision: current.revision + 1,
previousRevisionDigest: current.revision_digest,
bundle,
runs,
});
/** Parse a workspace and verify identities, revision digest, and references. */
export const parseInvestigationWorkspace = (
input: unknown,
): InvestigationWorkspace => {
const parsed = investigationWorkspaceSchema.parse(input);
const bundle = parseEvidenceBundle(parsed.bundle);
const canonical = buildWorkspace({
workspaceId: parsed.workspace_id,
name: parsed.name,
revision: parsed.revision,
previousRevisionDigest: parsed.previous_revision_digest,
bundle,
runs: parsed.runs,
});
if (parsed.workspace_id !== workspaceIdFor(parsed.name))
throw new TypeError("Investigation workspace ID does not match its name");
if (parsed.revision_digest !== canonical.revision_digest)
throw new TypeError("Investigation workspace revision digest is invalid");
if (JSON.stringify(parsed) !== JSON.stringify(canonical))
throw new TypeError("Investigation workspace is not canonical");
validateRunReferences(canonical);
return canonical;
};
/** Encode a validated workspace as byte-stable canonical JSON. */
export const serializeInvestigationWorkspace = (
workspace: InvestigationWorkspace,
): string => canonicalJson(parseInvestigationWorkspace(workspace));
const buildWorkspace = (input: {
readonly workspaceId: string;
readonly name: string;
readonly revision: number;
readonly previousRevisionDigest: string | null;
readonly bundle: EvidenceBundle;
readonly runs: readonly InvestigationRun[];
}): InvestigationWorkspace => {
const runs = [...input.runs]
.map((run) => investigationRunSchema.parse(run))
.sort((left, right) => left.run_id.localeCompare(right.run_id));
assertUnique(
runs.map(({ run_id: id }) => id),
"investigation run ID",
);
const semantic = {
workspace_version: 1,
workspace_id: input.workspaceId,
name: input.name,
revision: input.revision,
previous_revision_digest: input.previousRevisionDigest,
bundle: parseEvidenceBundle(input.bundle),
runs,
} satisfies JsonValue;
return investigationWorkspaceSchema.parse({
...semantic,
revision_digest: `wrev_${digestCanonical(semantic)}`,
});
};
const validateRunReferences = (workspace: InvestigationWorkspace): void => {
const evidenceIds = new Set(
workspace.bundle.records.map(({ evidence_id: id }) => id),
);
for (const run of workspace.runs) {
const expectedIdentity = createInvestigationRunIdentity(run);
if (
run.run_id !== expectedIdentity.runId ||
run.request_sha256 !== expectedIdentity.requestSha256
)
throw new TypeError("Investigation run identity is invalid");
validateRunStages(run);
const references = [
...run.left_inventory_evidence_ids,
...run.right_inventory_evidence_ids,
...(run.comparison_evidence_id === null
? []
: [run.comparison_evidence_id]),
...(run.result_evidence_id === null ? [] : [run.result_evidence_id]),
];
if (references.some((evidenceId) => !evidenceIds.has(evidenceId)))
throw new TypeError("Investigation run references missing Evidence");
}
};
const validateRunStages = (run: InvestigationRun): void => {
const expected = [
"inventory_left",
"inventory_right",
...(run.comparison_evidence_id === null ? [] : ["compare_artifacts"]),
...(run.result_evidence_id === null ? [] : ["find_changed_behavior"]),
];
if (JSON.stringify(run.completed_stages) !== JSON.stringify(expected))
throw new TypeError("Investigation run stages are inconsistent");
if (run.status === "complete" && run.result_evidence_id === null)
throw new TypeError("Completed investigation run has no result Evidence");
if (run.status === "running" && run.result_evidence_id !== null)
throw new TypeError("Running investigation run has final result Evidence");
};
const workspaceIdFor = (name: string): string =>
`ws_${digestCanonical({ schema: "rea.workspace/v1", name })}`;
const digestCanonical = (value: JsonValue): string =>
createHash("sha256").update(canonicalJson(value)).digest("hex");
const canonicalJson = (value: JsonValue): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Investigation workspace could not canonicalize data");
return encoded;
};
const assertUnique = (values: readonly string[], description: string): void => {
if (new Set(values).size !== values.length)
throw new TypeError(`Duplicate ${description}`);
};