feat: add persistent cross-version investigation workspaces
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
ArtifactOperationError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type {
|
||||
CrossVersionInvestigationInput,
|
||||
InvestigationRunOptions,
|
||||
InvestigationRunTarget,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
paginateArtifactInventory,
|
||||
scanArtifactInventory,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "./InvestigationProviders.js";
|
||||
|
||||
export const AUTOMATIC_RUN_LIMITATION =
|
||||
"Automatic cross-version runs compare shipped artifact structure only; they do not execute either version.";
|
||||
|
||||
export interface VersionSnapshots {
|
||||
readonly left: ArtifactInventorySnapshot;
|
||||
readonly right: ArtifactInventorySnapshot;
|
||||
}
|
||||
|
||||
export interface InventoryEvidencePages {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
}
|
||||
|
||||
/** Scan both inputs once under the same bounded traversal policy. */
|
||||
export const scanVersions = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<VersionSnapshots, AnalysisError>> => {
|
||||
try {
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError("find_changed_behavior"));
|
||||
const limits = artifactLimits(input.options);
|
||||
const left = await scanArtifactInventory(input.left_path, limits, signal);
|
||||
const right = await scanArtifactInventory(input.right_path, limits, signal);
|
||||
return ok({ left, right });
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure)
|
||||
return err(
|
||||
new ArtifactOperationError(
|
||||
"inventory_artifact",
|
||||
cause.reason,
|
||||
cause.details,
|
||||
),
|
||||
);
|
||||
return err(new ArtifactOperationError("inventory_artifact", "io"));
|
||||
}
|
||||
};
|
||||
|
||||
/** Project complete snapshots into bounded, comparable Evidence page sets. */
|
||||
export const createInventoryEvidencePages = (
|
||||
input: CrossVersionInvestigationInput,
|
||||
snapshots: VersionSnapshots,
|
||||
): Result<InventoryEvidencePages, AnalysisError> => {
|
||||
const left = inventoryPages(input.left_path, snapshots.left, input.options);
|
||||
const right = inventoryPages(
|
||||
input.right_path,
|
||||
snapshots.right,
|
||||
input.options,
|
||||
);
|
||||
if (left.length > 100 || right.length > 100)
|
||||
return err(new ArtifactOperationError("inventory_artifact", "limit"));
|
||||
return ok({ left, right });
|
||||
};
|
||||
|
||||
/** Reduce a snapshot to the content commitments used by run identity. */
|
||||
export const targetFor = (
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
): InvestigationRunTarget => ({
|
||||
root_sha256: snapshot.manifest.root_sha256,
|
||||
graph_sha256: snapshot.manifest.graph_sha256,
|
||||
manifest_id: snapshot.manifest.manifest_id,
|
||||
format: snapshot.manifest.root_format,
|
||||
});
|
||||
|
||||
/** Preserve scan and execution limitations in stable order. */
|
||||
export const runLimitations = (snapshots: VersionSnapshots): string[] =>
|
||||
[
|
||||
...new Set([
|
||||
...snapshots.left.limitations.map((item) => `Left: ${item}`),
|
||||
...snapshots.right.limitations.map((item) => `Right: ${item}`),
|
||||
AUTOMATIC_RUN_LIMITATION,
|
||||
]),
|
||||
].sort((left, right) => left.localeCompare(right));
|
||||
|
||||
const inventoryPages = (
|
||||
path: string,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
options: InvestigationRunOptions,
|
||||
): Evidence[] => {
|
||||
const count = Math.max(
|
||||
1,
|
||||
Math.ceil(snapshot.nodes.length / options.page_size),
|
||||
Math.ceil(snapshot.occurrences.length / options.page_size),
|
||||
Math.ceil(snapshot.edges.length / options.page_size),
|
||||
);
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
inventoryPage(path, snapshot, options, index * options.page_size),
|
||||
);
|
||||
};
|
||||
|
||||
const inventoryPage = (
|
||||
path: string,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
options: InvestigationRunOptions,
|
||||
offset: number,
|
||||
): Evidence => {
|
||||
const result = paginateArtifactInventory(snapshot, {
|
||||
nodeOffset: offset,
|
||||
nodeLimit: options.page_size,
|
||||
occurrenceOffset: offset,
|
||||
occurrenceLimit: options.page_size,
|
||||
edgeOffset: offset,
|
||||
edgeLimit: options.page_size,
|
||||
});
|
||||
return createEvidence(
|
||||
{
|
||||
path,
|
||||
sha256: snapshot.manifest.root_sha256,
|
||||
format: snapshot.manifest.root_format,
|
||||
},
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {
|
||||
node_offset: offset,
|
||||
node_limit: options.page_size,
|
||||
occurrence_offset: offset,
|
||||
occurrence_limit: options.page_size,
|
||||
edge_offset: offset,
|
||||
edge_limit: options.page_size,
|
||||
max_entries: options.max_entries,
|
||||
max_total_bytes: options.max_total_bytes,
|
||||
max_entry_bytes: options.max_entry_bytes,
|
||||
max_compression_ratio: options.max_compression_ratio,
|
||||
max_depth: options.max_depth,
|
||||
max_path_bytes: options.max_path_bytes,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult: null,
|
||||
limitations: result.limitations,
|
||||
locations: result.occurrences.items.map(
|
||||
({ logical_path: logicalPath }) => ({
|
||||
kind: "artifact-path" as const,
|
||||
path: logicalPath,
|
||||
}),
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const artifactLimits = (options: InvestigationRunOptions): ArtifactLimits => ({
|
||||
maxEntries: options.max_entries,
|
||||
maxTotalBytes: options.max_total_bytes,
|
||||
maxEntryBytes: options.max_entry_bytes,
|
||||
maxCompressionRatio: options.max_compression_ratio,
|
||||
maxDepth: options.max_depth,
|
||||
maxPathBytes: options.max_path_bytes,
|
||||
});
|
||||
@@ -0,0 +1,492 @@
|
||||
import { compareArtifacts } from "../domain/artifactComparison.js";
|
||||
import { findChangedBehavior } from "../domain/changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
type EvidenceFilePolicy,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
EvidenceIntegrityError,
|
||||
InvestigationWorkspaceError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
createInvestigationRunIdentity,
|
||||
createInvestigationWorkspace,
|
||||
crossVersionInvestigationInputSchema,
|
||||
investigationRunSchema,
|
||||
investigationRunSummarySchema,
|
||||
reviseInvestigationWorkspace,
|
||||
type CrossVersionInvestigationInput,
|
||||
type InvestigationRun,
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { BinarySessionPort } from "./BinarySession.js";
|
||||
import {
|
||||
AUTOMATIC_RUN_LIMITATION,
|
||||
createInventoryEvidencePages,
|
||||
runLimitations,
|
||||
scanVersions,
|
||||
targetFor,
|
||||
type InventoryEvidencePages,
|
||||
type VersionSnapshots,
|
||||
} from "./CrossVersionInventory.js";
|
||||
import {
|
||||
readInvestigationWorkspace,
|
||||
writeInvestigationWorkspace,
|
||||
} from "./InvestigationWorkspaceStore.js";
|
||||
import {
|
||||
ARTIFACT_COMPARISON_PROVIDER,
|
||||
CHANGED_BEHAVIOR_PROVIDER,
|
||||
} from "./InvestigationProviders.js";
|
||||
|
||||
export interface CrossVersionInvestigationOutcome {
|
||||
readonly evidence: Evidence;
|
||||
readonly workspace: InvestigationWorkspace;
|
||||
readonly reused: boolean;
|
||||
}
|
||||
|
||||
/** Run or resume a deterministic cross-version artifact investigation. */
|
||||
export const runCrossVersionInvestigation = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
policy: EvidenceFilePolicy,
|
||||
session?: BinarySessionPort,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const parsed = crossVersionInvestigationInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError("find_changed_behavior", {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
const initial = await readInvestigationWorkspace(
|
||||
parsed.data.workspace_path,
|
||||
policy,
|
||||
);
|
||||
if (!initial.ok) return initial;
|
||||
const preflight = validateWorkspaceRequest(initial.value, parsed.data);
|
||||
if (!preflight.ok) return preflight;
|
||||
|
||||
const snapshots = await scanVersions(parsed.data, signal);
|
||||
if (!snapshots.ok) return snapshots;
|
||||
return continueInvestigation({
|
||||
input: parsed.data,
|
||||
initial: initial.value,
|
||||
snapshots: snapshots.value,
|
||||
policy,
|
||||
session,
|
||||
});
|
||||
};
|
||||
|
||||
interface RunState {
|
||||
readonly workspace: InvestigationWorkspace;
|
||||
readonly run: InvestigationRun;
|
||||
}
|
||||
|
||||
const continueInvestigation = async (context: {
|
||||
readonly input: CrossVersionInvestigationInput;
|
||||
readonly initial: InvestigationWorkspace | null;
|
||||
readonly snapshots: VersionSnapshots;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
}): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const left = targetFor(context.snapshots.left);
|
||||
const right = targetFor(context.snapshots.right);
|
||||
const identity = createInvestigationRunIdentity({
|
||||
left,
|
||||
right,
|
||||
options: context.input.options,
|
||||
});
|
||||
const existing = context.initial?.runs.find(
|
||||
({ run_id: id }) => id === identity.runId,
|
||||
);
|
||||
if (context.initial !== null && existing?.status === "complete")
|
||||
return completeOutcome(context.initial, existing, true, context.session);
|
||||
const pages = createInventoryEvidencePages(context.input, context.snapshots);
|
||||
if (!pages.ok) return pages;
|
||||
const inventoried = await ensureInventoryCheckpoint({
|
||||
input: context.input,
|
||||
current: context.initial,
|
||||
existing,
|
||||
pages: pages.value,
|
||||
snapshots: context.snapshots,
|
||||
policy: context.policy,
|
||||
});
|
||||
if (!inventoried.ok) return inventoried;
|
||||
const compared = await ensureComparisonCheckpoint(
|
||||
context.input,
|
||||
inventoried.value,
|
||||
context.policy,
|
||||
);
|
||||
if (!compared.ok) return compared;
|
||||
return finalizeInvestigation(
|
||||
context.input,
|
||||
compared.value,
|
||||
context.policy,
|
||||
context.session,
|
||||
);
|
||||
};
|
||||
|
||||
const ensureInventoryCheckpoint = async (input: {
|
||||
readonly input: CrossVersionInvestigationInput;
|
||||
readonly current: InvestigationWorkspace | null;
|
||||
readonly existing: InvestigationRun | undefined;
|
||||
readonly pages: InventoryEvidencePages;
|
||||
readonly snapshots: VersionSnapshots;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
}): Promise<Result<RunState, AnalysisError>> => {
|
||||
if (input.existing !== undefined) {
|
||||
const consistent = validateInventoryCheckpoint(input.existing, input.pages);
|
||||
if (!consistent.ok) return consistent;
|
||||
return input.current === null
|
||||
? err(new EvidenceIntegrityError("Investigation workspace is missing"))
|
||||
: ok({ workspace: input.current, run: input.existing });
|
||||
}
|
||||
const left = targetFor(input.snapshots.left);
|
||||
const right = targetFor(input.snapshots.right);
|
||||
const identity = createInvestigationRunIdentity({
|
||||
left,
|
||||
right,
|
||||
options: input.input.options,
|
||||
});
|
||||
const run = investigationRunSchema.parse({
|
||||
schema_version: 1,
|
||||
run_id: identity.runId,
|
||||
request_sha256: identity.requestSha256,
|
||||
left,
|
||||
right,
|
||||
options: input.input.options,
|
||||
status: "running",
|
||||
completed_stages: ["inventory_left", "inventory_right"],
|
||||
left_inventory_evidence_ids: evidenceIds(input.pages.left),
|
||||
right_inventory_evidence_ids: evidenceIds(input.pages.right),
|
||||
comparison_evidence_id: null,
|
||||
result_evidence_id: null,
|
||||
limitations: runLimitations(input.snapshots),
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.input.workspace_path,
|
||||
name: input.input.workspace_name,
|
||||
current: input.current,
|
||||
records: [...input.pages.left, ...input.pages.right],
|
||||
run,
|
||||
policy: input.policy,
|
||||
});
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const ensureComparisonCheckpoint = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
state: RunState,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<RunState, AnalysisError>> => {
|
||||
if (state.run.comparison_evidence_id !== null) return ok(state);
|
||||
const inventory = inventoryEvidence(state.workspace, state.run);
|
||||
if (!inventory.ok) return inventory;
|
||||
const evidence = createArtifactComparisonEvidence(
|
||||
inventory.value,
|
||||
input.options.change_limit,
|
||||
);
|
||||
const run = investigationRunSchema.parse({
|
||||
...state.run,
|
||||
completed_stages: [
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
"compare_artifacts",
|
||||
],
|
||||
comparison_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
records: [evidence],
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const createArtifactComparisonEvidence = (
|
||||
inventory: {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
},
|
||||
limit: number,
|
||||
): Evidence => {
|
||||
const comparison = compareArtifacts(
|
||||
inventory.left,
|
||||
inventory.right,
|
||||
0,
|
||||
limit,
|
||||
);
|
||||
const leftIds = evidenceIds(inventory.left);
|
||||
const rightIds = evidenceIds(inventory.right);
|
||||
return createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
|
||||
predicateType: "rea.artifact-comparison/v1",
|
||||
operation: "compare_artifacts",
|
||||
parameters: {
|
||||
left_evidence_ids: leftIds,
|
||||
right_evidence_ids: rightIds,
|
||||
offset: 0,
|
||||
limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [...leftIds, ...rightIds],
|
||||
});
|
||||
};
|
||||
|
||||
const finalizeInvestigation = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
state: RunState,
|
||||
policy: EvidenceFilePolicy,
|
||||
session?: BinarySessionPort,
|
||||
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const comparison = comparisonEvidenceFor(state.workspace, state.run);
|
||||
if (!comparison.ok) return comparison;
|
||||
const evidence = createChangedBehaviorEvidence(state, comparison.value);
|
||||
const run = investigationRunSchema.parse({
|
||||
...state.run,
|
||||
status: "complete",
|
||||
completed_stages: [
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
"compare_artifacts",
|
||||
"find_changed_behavior",
|
||||
],
|
||||
result_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
records: [evidence],
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? completeOutcome(saved.value, run, false, session) : saved;
|
||||
};
|
||||
|
||||
const createChangedBehaviorEvidence = (
|
||||
state: RunState,
|
||||
comparison: Evidence,
|
||||
): Evidence => {
|
||||
const limit = Math.min(state.run.options.change_limit, 100);
|
||||
const changed = findChangedBehavior([comparison], 0, limit);
|
||||
const summary = investigationRunSummarySchema.parse({
|
||||
schema_version: 1,
|
||||
workspace_id: state.workspace.workspace_id,
|
||||
run_id: state.run.run_id,
|
||||
left_manifest_id: state.run.left.manifest_id,
|
||||
right_manifest_id: state.run.right.manifest_id,
|
||||
inventory_evidence_count:
|
||||
state.run.left_inventory_evidence_ids.length +
|
||||
state.run.right_inventory_evidence_ids.length,
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
limitations: state.run.limitations,
|
||||
});
|
||||
return createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: "find_changed_behavior",
|
||||
parameters: {
|
||||
workspace_id: state.workspace.workspace_id,
|
||||
run_id: state.run.run_id,
|
||||
comparison_evidence_ids: [comparison.evidence_id],
|
||||
offset: 0,
|
||||
limit,
|
||||
},
|
||||
result: jsonValueSchema.parse({
|
||||
...changed,
|
||||
investigation_run: summary,
|
||||
}),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: [...changed.limitations, AUTOMATIC_RUN_LIMITATION],
|
||||
evidenceLinks: changed.evidence_links,
|
||||
});
|
||||
};
|
||||
|
||||
const comparisonEvidenceFor = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
): Result<Evidence, EvidenceIntegrityError> => {
|
||||
const evidence = workspace.bundle.records.find(
|
||||
({ evidence_id: id }) => id === run.comparison_evidence_id,
|
||||
);
|
||||
return evidence === undefined
|
||||
? err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation comparison checkpoint is missing Evidence",
|
||||
),
|
||||
)
|
||||
: ok(evidence);
|
||||
};
|
||||
|
||||
const checkpoint = async (input: {
|
||||
readonly path: string;
|
||||
readonly name: string;
|
||||
readonly current: InvestigationWorkspace | null;
|
||||
readonly records: readonly Evidence[];
|
||||
readonly run: InvestigationRun;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
}): Promise<Result<InvestigationWorkspace, AnalysisError>> => {
|
||||
const records = mergeEvidence(
|
||||
input.current?.bundle.records ?? [],
|
||||
input.records,
|
||||
);
|
||||
const bundle = createEvidenceBundle(
|
||||
records,
|
||||
input.current?.bundle.unknowns ?? [],
|
||||
);
|
||||
const runs = replaceRun(input.current?.runs ?? [], input.run);
|
||||
const next =
|
||||
input.current === null
|
||||
? createInvestigationWorkspace(input.name, bundle, runs)
|
||||
: reviseInvestigationWorkspace(input.current, bundle, runs);
|
||||
const written = await writeInvestigationWorkspace(
|
||||
next,
|
||||
input.path,
|
||||
input.current?.revision ?? null,
|
||||
input.policy,
|
||||
);
|
||||
return written.ok ? ok(next) : written;
|
||||
};
|
||||
|
||||
const completeOutcome = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
reused: boolean,
|
||||
session?: BinarySessionPort,
|
||||
): Result<CrossVersionInvestigationOutcome, AnalysisError> => {
|
||||
if (run.result_evidence_id === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError("Completed investigation has no result"),
|
||||
);
|
||||
const evidence = workspace.bundle.records.find(
|
||||
({ evidence_id: id }) => id === run.result_evidence_id,
|
||||
);
|
||||
if (evidence === undefined)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Completed investigation result Evidence is missing",
|
||||
),
|
||||
);
|
||||
if (session !== undefined) {
|
||||
const records = recordsForRun(workspace, run);
|
||||
const imported = session.importEvidenceBundle(
|
||||
createEvidenceBundle(records),
|
||||
);
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
return ok({ evidence, workspace, reused });
|
||||
};
|
||||
|
||||
const validateWorkspaceRequest = (
|
||||
workspace: InvestigationWorkspace | null,
|
||||
input: CrossVersionInvestigationInput,
|
||||
): Result<null, InvestigationWorkspaceError> => {
|
||||
if (workspace !== null && workspace.name !== input.workspace_name)
|
||||
return err(new InvestigationWorkspaceError("update", "name-conflict"));
|
||||
if (
|
||||
input.expected_workspace_revision !== undefined &&
|
||||
workspace?.revision !== input.expected_workspace_revision
|
||||
)
|
||||
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const validateInventoryCheckpoint = (
|
||||
run: InvestigationRun,
|
||||
pages: {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
},
|
||||
): Result<null, EvidenceIntegrityError> =>
|
||||
JSON.stringify(run.left_inventory_evidence_ids) ===
|
||||
JSON.stringify(evidenceIds(pages.left)) &&
|
||||
JSON.stringify(run.right_inventory_evidence_ids) ===
|
||||
JSON.stringify(evidenceIds(pages.right))
|
||||
? ok(null)
|
||||
: err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation inventory checkpoint disagrees with current content",
|
||||
),
|
||||
);
|
||||
|
||||
const inventoryEvidence = (
|
||||
workspace: InvestigationWorkspace | null,
|
||||
run: InvestigationRun,
|
||||
): Result<
|
||||
{ readonly left: readonly Evidence[]; readonly right: readonly Evidence[] },
|
||||
EvidenceIntegrityError
|
||||
> => {
|
||||
if (workspace === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError("Investigation workspace is missing"),
|
||||
);
|
||||
const byId = new Map(
|
||||
workspace.bundle.records.map((record) => [record.evidence_id, record]),
|
||||
);
|
||||
const left = run.left_inventory_evidence_ids.flatMap((id) => {
|
||||
const evidence = byId.get(id);
|
||||
return evidence === undefined ? [] : [evidence];
|
||||
});
|
||||
const right = run.right_inventory_evidence_ids.flatMap((id) => {
|
||||
const evidence = byId.get(id);
|
||||
return evidence === undefined ? [] : [evidence];
|
||||
});
|
||||
return left.length === run.left_inventory_evidence_ids.length &&
|
||||
right.length === run.right_inventory_evidence_ids.length
|
||||
? ok({ left, right })
|
||||
: err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation inventory checkpoint is incomplete",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const recordsForRun = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
): Evidence[] => {
|
||||
const ids = new Set([
|
||||
...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]),
|
||||
]);
|
||||
return workspace.bundle.records.filter(({ evidence_id: id }) => ids.has(id));
|
||||
};
|
||||
|
||||
const mergeEvidence = (
|
||||
current: readonly Evidence[],
|
||||
additions: readonly Evidence[],
|
||||
): Evidence[] => {
|
||||
const records = new Map(
|
||||
current.map((record) => [record.evidence_id, record]),
|
||||
);
|
||||
for (const record of additions)
|
||||
if (!records.has(record.evidence_id))
|
||||
records.set(record.evidence_id, record);
|
||||
return [...records.values()];
|
||||
};
|
||||
|
||||
const replaceRun = (
|
||||
runs: readonly InvestigationRun[],
|
||||
replacement: InvestigationRun,
|
||||
): InvestigationRun[] => [
|
||||
...runs.filter(({ run_id: id }) => id !== replacement.run_id),
|
||||
replacement,
|
||||
];
|
||||
|
||||
const evidenceIds = (records: readonly Evidence[]): string[] =>
|
||||
records.map(({ evidence_id: id }) => id);
|
||||
@@ -1,3 +1,5 @@
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
parseEvidenceBundle,
|
||||
@@ -388,8 +390,8 @@ const unknownRevisionKey = (unknown: ResidualUnknown): string =>
|
||||
`${unknown.unknown_id}:${String(unknown.revision)}`;
|
||||
|
||||
const recordsAgree = (left: Evidence, right: Evidence): boolean =>
|
||||
JSON.stringify(withoutLocalPath(left)) ===
|
||||
JSON.stringify(withoutLocalPath(right));
|
||||
canonicalize(withoutLocalPath(left)) ===
|
||||
canonicalize(withoutLocalPath(right));
|
||||
|
||||
const withoutLocalPath = (evidence: Evidence): Evidence => ({
|
||||
...evidence,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Provider identity for deterministic artifact inventories. */
|
||||
export const ARTIFACT_GRAPH_PROVIDER = {
|
||||
id: "rea-artifact-graph",
|
||||
name: "REA safe artifact graph provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-artifact comparisons. */
|
||||
export const ARTIFACT_COMPARISON_PROVIDER = {
|
||||
id: "rea-artifact-comparison",
|
||||
name: "REA artifact comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-function comparisons. */
|
||||
export const FUNCTION_COMPARISON_PROVIDER = {
|
||||
id: "rea-function-comparison",
|
||||
name: "REA function comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Evidence bundle comparisons. */
|
||||
export const BUNDLE_COMPARISON_PROVIDER = {
|
||||
id: "rea-bundle-comparison",
|
||||
name: "REA Evidence bundle comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for comparison-Evidence behavior aggregation. */
|
||||
export const CHANGED_BEHAVIOR_PROVIDER = {
|
||||
id: "rea-changed-behavior",
|
||||
name: "REA changed behavior investigation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for Evidence-backed call-path reconstruction. */
|
||||
export const CALL_PATH_PROVIDER = {
|
||||
id: "rea-call-path",
|
||||
name: "REA call path reconstruction",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for explicit static/runtime hypothesis correlation. */
|
||||
export const STATIC_RUNTIME_PROVIDER = {
|
||||
id: "rea-static-runtime-correlation",
|
||||
name: "REA static/runtime correlation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for finite reconstruction specification verification. */
|
||||
export const RECONSTRUCTION_PROVIDER = {
|
||||
id: "rea-reconstruction-verifier",
|
||||
name: "REA reconstruction verifier",
|
||||
version: "1",
|
||||
} as const;
|
||||
@@ -0,0 +1,281 @@
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { InvestigationWorkspaceError } from "../domain/errors.js";
|
||||
import {
|
||||
parseInvestigationWorkspace,
|
||||
serializeInvestigationWorkspace,
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type WorkspaceResult<Value> = Result<Value, InvestigationWorkspaceError>;
|
||||
|
||||
/** Read a validated workspace, returning null only when it does not exist. */
|
||||
export const readInvestigationWorkspace = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("read", "disabled"));
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new InvestigationWorkspaceError("read", "outside-root"));
|
||||
return await readWorkspaceFile(destination, policy);
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically append one CAS-linked workspace revision under an exclusive lock. */
|
||||
export const writeInvestigationWorkspace = async (
|
||||
workspace: InvestigationWorkspace,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("update", "disabled"));
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = serializeInvestigationWorkspace(workspace);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError("update", "integrity", { cause }),
|
||||
);
|
||||
}
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("update", "too-large"));
|
||||
let lock: { readonly path: string; readonly handle: FileHandle } | undefined;
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new InvestigationWorkspaceError("update", "outside-root"));
|
||||
const acquired = await acquireLock(destination);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readWorkspaceFile(destination, policy);
|
||||
if (!current.ok) return current;
|
||||
const checked = validateNextRevision(
|
||||
current.value,
|
||||
workspace,
|
||||
expectedRevision,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: resolve(path), bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("update", "io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releaseLock(lock);
|
||||
}
|
||||
};
|
||||
|
||||
const resolveDestination = async (
|
||||
path: string,
|
||||
roots: readonly string[],
|
||||
): Promise<string | null> => {
|
||||
const requested = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requested));
|
||||
const destination = resolve(canonicalParent, basename(requested));
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, destination);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return destination;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const readWorkspaceFile = async (
|
||||
destination: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
const stats = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (stats === undefined) return ok(null);
|
||||
if (!stats.isFile() || stats.isSymbolicLink())
|
||||
return err(new InvestigationWorkspaceError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
const encoded = await readFile(destination);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError("read", "invalid-json", { cause }),
|
||||
);
|
||||
}
|
||||
if (!withinJsonLimits(decoded, policy))
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
try {
|
||||
return ok(parseInvestigationWorkspace(decoded));
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "integrity", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const acquireLock = async (
|
||||
destination: string,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly handle: FileHandle }>
|
||||
> => {
|
||||
const path = `${destination}.lock`;
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (isAlreadyExists(cause) && (await removeStaleLock(path))) {
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
} catch (retryCause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError(
|
||||
"update",
|
||||
isAlreadyExists(retryCause) ? "locked" : "io",
|
||||
{ cause: retryCause },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return err(
|
||||
new InvestigationWorkspaceError(
|
||||
"update",
|
||||
isAlreadyExists(cause) ? "locked" : "io",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const createLock = async (
|
||||
path: string,
|
||||
): Promise<{ readonly path: string; readonly handle: FileHandle }> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStaleLock = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (!stats.isFile() || stats.isSymbolicLink() || stats.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
const pid = Number(encoded);
|
||||
if (processIsAlive(pid)) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releaseLock = async (lock: {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const validateNextRevision = (
|
||||
current: InvestigationWorkspace | null,
|
||||
next: InvestigationWorkspace,
|
||||
expectedRevision: number | null,
|
||||
): WorkspaceResult<null> => {
|
||||
if ((current?.revision ?? null) !== expectedRevision)
|
||||
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
if (current === null) {
|
||||
return next.revision === 1 && next.previous_revision_digest === null
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
}
|
||||
if (current.name !== next.name || current.workspace_id !== next.workspace_id)
|
||||
return err(new InvestigationWorkspaceError("update", "name-conflict"));
|
||||
return next.revision === current.revision + 1 &&
|
||||
next.previous_revision_digest === current.revision_digest
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
};
|
||||
|
||||
const withinJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): boolean => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return false;
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return false;
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength) return false;
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
@@ -26,12 +26,9 @@ import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactLimits,
|
||||
} from "./ArtifactReader.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "rea-artifact-graph",
|
||||
name: "REA safe artifact graph provider",
|
||||
version: "1",
|
||||
});
|
||||
const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
|
||||
|
||||
/** Read-only inventory and exclusively owned extraction provider. */
|
||||
export class ArtifactProvider implements AnalysisProvider {
|
||||
|
||||
+21
-4
@@ -18,6 +18,7 @@ import { parseConfig } from "./config.js";
|
||||
import { importReferenceSource } from "./application/ReferenceSourceImport.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cliProcessCommands.js";
|
||||
import { registerInvestigationCommands } from "./cliInvestigationCommands.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -59,6 +60,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
registerCapabilityCommands(cli, logger);
|
||||
registerNativeCommands(cli, logger);
|
||||
registerArtifactCommands(cli, logger);
|
||||
registerInvestigationCommands(cli, logger);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerReferenceSourceCommand(cli, logger);
|
||||
registerProcessCommands(cli, logger);
|
||||
@@ -69,10 +71,14 @@ const registerCoreCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
const overviewOptions = z.object({
|
||||
detail: z.enum(["concise", "detailed"]).default("concise"),
|
||||
limit: z.number().int().min(1).max(50).default(10),
|
||||
});
|
||||
registerManagementCommands(cli, logger);
|
||||
registerOverviewCommands(cli, logger);
|
||||
};
|
||||
|
||||
const registerManagementCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("setup", {
|
||||
description: "Install requirements and configure coding agents",
|
||||
options: z.object({
|
||||
@@ -132,6 +138,17 @@ const registerCoreCommands = (
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const overviewOptions = z.object({
|
||||
detail: z.enum(["concise", "detailed"]).default("concise"),
|
||||
limit: z.number().int().min(1).max(50).default(10),
|
||||
});
|
||||
|
||||
const registerOverviewCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("analyze", {
|
||||
description: "Get an overview of an app",
|
||||
args: z.object({
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import { runCrossVersionInvestigation } from "./application/CrossVersionInvestigation.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const investigationOptionsSchema = z.object({
|
||||
yes: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Approve persistent workspace writes"),
|
||||
workspaceName: z.string().trim().min(1).max(200).default("default"),
|
||||
expectedRevision: z.number().int().min(1).optional(),
|
||||
maxEntries: z.number().int().min(1).max(50_000).default(10_000),
|
||||
maxTotalBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(1_073_741_824),
|
||||
maxEntryBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(268_435_456),
|
||||
pageSize: z.number().int().min(1).max(500).default(500),
|
||||
changeLimit: z.number().int().min(1).max(500).default(500),
|
||||
});
|
||||
|
||||
/** Register the persistent cross-version CLI workflow. */
|
||||
export const registerInvestigationCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("investigate-versions", {
|
||||
description:
|
||||
"Run or resume a persistent cross-version artifact investigation",
|
||||
args: z.object({
|
||||
leftPath: z.string().describe("Earlier artifact or directory path"),
|
||||
rightPath: z.string().describe("Later artifact or directory path"),
|
||||
workspacePath: z.string().describe("Persistent workspace JSON path"),
|
||||
}),
|
||||
options: investigationOptionsSchema,
|
||||
alias: {
|
||||
workspaceName: "workspace-name",
|
||||
expectedRevision: "expected-revision",
|
||||
maxEntries: "max-entries",
|
||||
maxTotalBytes: "max-total-bytes",
|
||||
maxEntryBytes: "max-entry-bytes",
|
||||
pageSize: "page-size",
|
||||
changeLimit: "change-limit",
|
||||
yes: "y",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "investigate-versions", () =>
|
||||
runInvestigation(args, options),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const runInvestigation = async (
|
||||
args: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
readonly workspacePath: string;
|
||||
},
|
||||
options: z.infer<typeof investigationOptionsSchema>,
|
||||
) => {
|
||||
if (!options.yes)
|
||||
return {
|
||||
error: "ApprovalRequired",
|
||||
message: "Persistent workspace writes require explicit --yes approval.",
|
||||
};
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
{
|
||||
approved: true,
|
||||
workspace_path: args.workspacePath,
|
||||
workspace_name: options.workspaceName,
|
||||
...(options.expectedRevision === undefined
|
||||
? {}
|
||||
: { expected_workspace_revision: options.expectedRevision }),
|
||||
left_path: args.leftPath,
|
||||
right_path: args.rightPath,
|
||||
options: {
|
||||
max_entries: options.maxEntries,
|
||||
max_total_bytes: options.maxTotalBytes,
|
||||
max_entry_bytes: options.maxEntryBytes,
|
||||
max_compression_ratio: 1_000,
|
||||
max_depth: 20,
|
||||
max_path_bytes: 4_096,
|
||||
page_size: options.pageSize,
|
||||
change_limit: options.changeLimit,
|
||||
},
|
||||
},
|
||||
config.value.evidenceFilePolicy,
|
||||
);
|
||||
return investigated.ok
|
||||
? investigated.value.evidence
|
||||
: {
|
||||
error: investigated.error._tag,
|
||||
message: investigated.error.message,
|
||||
};
|
||||
};
|
||||
@@ -466,7 +466,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"find_changed_behavior",
|
||||
"Aggregate validated process, artifact, and function comparison Evidence into a deterministic change report. Runtime observations remain distinct from static behavior candidates; missing or incomplete comparisons produce unresolved findings, never causal claims.",
|
||||
"Aggregate validated comparison Evidence, or automatically run and resume a persistent cross-version artifact investigation beneath an approved evidence root. Runtime observations remain distinct from static behavior candidates; missing or incomplete comparisons produce unresolved findings, never causal claims.",
|
||||
changedBehaviorInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}`);
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { runCrossVersionInvestigation } from "../application/CrossVersionInvestigation.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { buildCallPath, callPathInputSchema } from "../domain/callPath.js";
|
||||
import {
|
||||
@@ -12,10 +13,12 @@ import {
|
||||
verifyReconstruction,
|
||||
} from "../domain/reconstructionVerification.js";
|
||||
import {
|
||||
changedBehaviorResultSchema,
|
||||
changedBehaviorInputSchema,
|
||||
findChangedBehavior,
|
||||
} from "../domain/changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceIntegrityError } from "../domain/errors.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -38,8 +41,9 @@ export const registerInvestigationTools = (
|
||||
ToolContract<"correlate_static_and_runtime">,
|
||||
ToolContract<"verify_reconstruction">,
|
||||
],
|
||||
evidenceFilePolicy: EvidenceFilePolicy,
|
||||
): void => {
|
||||
registerChangedBehavior(server, session, contracts[0]);
|
||||
registerChangedBehavior(server, session, contracts[0], evidenceFilePolicy);
|
||||
registerCallPath(server, session, contracts[1]);
|
||||
registerStaticRuntime(server, session, contracts[2]);
|
||||
registerReconstruction(server, session, contracts[3]);
|
||||
@@ -49,58 +53,98 @@ const registerChangedBehavior = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
contract: ToolContract<"find_changed_behavior">,
|
||||
evidenceFilePolicy: EvidenceFilePolicy,
|
||||
): void => {
|
||||
server.registerTool(contract.name, contractOptions(contract), (input) => {
|
||||
const parsed = changedBehaviorInputSchema.parse(input);
|
||||
const closure = evidenceClosure(
|
||||
session,
|
||||
comparisonClosure(parsed.comparisons),
|
||||
);
|
||||
if (!closure.ok) return toCallToolResult(closure, contract);
|
||||
const links = closure.value;
|
||||
const result = findChangedBehavior(
|
||||
parsed.comparisons,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
);
|
||||
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: contract.name,
|
||||
parameters: {
|
||||
comparison_evidence_ids: parsed.comparisons.map(
|
||||
({ evidence_id: id }) => id,
|
||||
),
|
||||
offset: parsed.offset,
|
||||
limit: parsed.limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: links,
|
||||
});
|
||||
const recorded = recordWorkflowEvidence(
|
||||
session,
|
||||
evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
result.behavior_status === "unknown" ||
|
||||
result.behavior_status === "truncated",
|
||||
{
|
||||
question: `Changed behavior result ${evidence.evidence_id} remains ${result.behavior_status}`,
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
return toCallToolResult(recorded, contract);
|
||||
});
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
contractOptions(contract),
|
||||
async (input, context) => {
|
||||
const parsed = changedBehaviorInputSchema.parse(input);
|
||||
if (parsed.investigation_run !== undefined) {
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
parsed.investigation_run,
|
||||
evidenceFilePolicy,
|
||||
session,
|
||||
context.mcpReq.signal,
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
investigated.value.evidence.normalized_result,
|
||||
);
|
||||
return toCallToolResult(
|
||||
recordWorkflowEvidence(
|
||||
session,
|
||||
investigated.value.evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
result.behavior_status === "unknown" ||
|
||||
result.behavior_status === "truncated",
|
||||
{
|
||||
question: `Automatic changed behavior run ${result.investigation_run?.run_id ?? "unknown"} remains ${result.behavior_status}`,
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
const closure = evidenceClosure(
|
||||
session,
|
||||
comparisonClosure(parsed.comparisons),
|
||||
);
|
||||
if (!closure.ok) return toCallToolResult(closure, contract);
|
||||
const links = closure.value;
|
||||
const result = findChangedBehavior(
|
||||
parsed.comparisons,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
);
|
||||
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: contract.name,
|
||||
parameters: {
|
||||
comparison_evidence_ids: parsed.comparisons.map(
|
||||
({ evidence_id: id }) => id,
|
||||
),
|
||||
offset: parsed.offset,
|
||||
limit: parsed.limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: links,
|
||||
});
|
||||
const recorded = recordWorkflowEvidence(
|
||||
session,
|
||||
evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
result.behavior_status === "unknown" ||
|
||||
result.behavior_status === "truncated",
|
||||
{
|
||||
question: `Changed behavior result ${evidence.evidence_id} remains ${result.behavior_status}`,
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
return toCallToolResult(recorded, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerCallPath = (
|
||||
|
||||
@@ -434,12 +434,17 @@ export const registerSessionTools = (
|
||||
registerArtifactComparisonTool(server, session, compareArtifactsContract);
|
||||
registerFunctionComparisonTool(server, session, compareFunctionsContract);
|
||||
registerBundleComparisonTool(server, session, compareBundlesContract);
|
||||
registerInvestigationTools(server, session, [
|
||||
changedBehaviorContract,
|
||||
callPathContract,
|
||||
staticRuntimeContract,
|
||||
reconstructionContract,
|
||||
]);
|
||||
registerInvestigationTools(
|
||||
server,
|
||||
session,
|
||||
[
|
||||
changedBehaviorContract,
|
||||
callPathContract,
|
||||
staticRuntimeContract,
|
||||
reconstructionContract,
|
||||
],
|
||||
evidenceFilePolicy,
|
||||
);
|
||||
registerUnknownTools({
|
||||
server,
|
||||
session,
|
||||
|
||||
@@ -20,52 +20,12 @@ export const DENY_EVIDENCE_FILE_POLICY: EvidenceFilePolicy = {
|
||||
};
|
||||
|
||||
export { PROCESS_PROVIDER } from "../application/ProcessEvidence.js";
|
||||
|
||||
/** Provider identity for deterministic cross-artifact comparisons. */
|
||||
export const ARTIFACT_COMPARISON_PROVIDER = {
|
||||
id: "rea-artifact-comparison",
|
||||
name: "REA artifact comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-function comparisons. */
|
||||
export const FUNCTION_COMPARISON_PROVIDER = {
|
||||
id: "rea-function-comparison",
|
||||
name: "REA function comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Evidence bundle comparisons. */
|
||||
export const BUNDLE_COMPARISON_PROVIDER = {
|
||||
id: "rea-bundle-comparison",
|
||||
name: "REA Evidence bundle comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for comparison-Evidence behavior aggregation. */
|
||||
export const CHANGED_BEHAVIOR_PROVIDER = {
|
||||
id: "rea-changed-behavior",
|
||||
name: "REA changed behavior investigation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for Evidence-backed call-path reconstruction. */
|
||||
export const CALL_PATH_PROVIDER = {
|
||||
id: "rea-call-path",
|
||||
name: "REA call path reconstruction",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for explicit static/runtime hypothesis correlation. */
|
||||
export const STATIC_RUNTIME_PROVIDER = {
|
||||
id: "rea-static-runtime-correlation",
|
||||
name: "REA static/runtime correlation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for finite reconstruction specification verification. */
|
||||
export const RECONSTRUCTION_PROVIDER = {
|
||||
id: "rea-reconstruction-verifier",
|
||||
name: "REA reconstruction verifier",
|
||||
version: "1",
|
||||
} as const;
|
||||
export {
|
||||
ARTIFACT_COMPARISON_PROVIDER,
|
||||
BUNDLE_COMPARISON_PROVIDER,
|
||||
CALL_PATH_PROVIDER,
|
||||
CHANGED_BEHAVIOR_PROVIDER,
|
||||
FUNCTION_COMPARISON_PROVIDER,
|
||||
RECONSTRUCTION_PROVIDER,
|
||||
STATIC_RUNTIME_PROVIDER,
|
||||
} from "../application/InvestigationProviders.js";
|
||||
|
||||
Reference in New Issue
Block a user