refactor(app): split session and CLI workflows
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { runCrossVersionInvestigationValidated } from "../application/CrossVersionInvestigation.js";
|
||||
@@ -14,21 +15,15 @@ import {
|
||||
reconstructionVerificationInputSchema,
|
||||
verifyReconstruction,
|
||||
} from "../domain/reconstructionVerification.js";
|
||||
import { evaluateReconstructionClosure } from "../domain/reconstructionCoverage.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 {
|
||||
AnalysisInputError,
|
||||
EvidenceIntegrityError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { type AnalysisError } from "../domain/errors.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import {
|
||||
CALL_PATH_PROVIDER,
|
||||
CHANGED_BEHAVIOR_PROVIDER,
|
||||
@@ -36,16 +31,26 @@ import {
|
||||
STATIC_RUNTIME_PROVIDER,
|
||||
} from "./sessionToolPolicies.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { runDerivedOperation } from "./runDerivedOperation.js";
|
||||
import {
|
||||
runDerivedOperation,
|
||||
type DerivedOperationContext,
|
||||
} from "./runDerivedOperation.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
authorizeRootPermission,
|
||||
type DeferredFileWriteAuthorization,
|
||||
} from "../application/DeferredFileAuthorization.js";
|
||||
import {
|
||||
comparisonClosure,
|
||||
evidenceClosure,
|
||||
functionEvidenceIds,
|
||||
investigationContext,
|
||||
isIncomplete,
|
||||
recordWorkflowEvidence,
|
||||
verifyCoverageReadiness,
|
||||
} from "./registerInvestigationTools/helpers.js";
|
||||
import type { InvestigationToolPolicies } from "./registerInvestigationTools/types.js";
|
||||
|
||||
/** Register Evidence-composed differential investigation workflows. */
|
||||
export const registerInvestigationTools = (
|
||||
@@ -65,30 +70,6 @@ export const registerInvestigationTools = (
|
||||
registerReconstruction(server, session, contracts[3]);
|
||||
};
|
||||
|
||||
interface InvestigationToolPolicies {
|
||||
readonly evidenceFiles: EvidenceFilePolicy;
|
||||
readonly inputRoots: readonly string[];
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly integrityContinueEnabled?: () => boolean;
|
||||
}
|
||||
|
||||
const investigationExecution = (
|
||||
session: BinarySessionPort,
|
||||
signal: AbortSignal,
|
||||
inputRoots: readonly string[],
|
||||
integrityContinueEnabled: boolean,
|
||||
progress?: ProgressReporter,
|
||||
) => ({
|
||||
session,
|
||||
signal,
|
||||
inputRoots,
|
||||
integrityContinueEnabled,
|
||||
...(progress === undefined ? {} : { progress }),
|
||||
});
|
||||
|
||||
const isIncomplete = (status: string): boolean =>
|
||||
status === "unknown" || status === "truncated";
|
||||
|
||||
const registerChangedBehavior = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
@@ -107,98 +88,16 @@ const registerChangedBehavior = (
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, contract);
|
||||
const parsed = parsedInput.value;
|
||||
const investigationRun = parsed.investigation_run;
|
||||
if (investigationRun !== undefined) {
|
||||
const progress = mcpProgressReporter(context);
|
||||
let workspaceAuthorization: DeferredFileWriteAuthorization | undefined;
|
||||
let authorizeInputRead:
|
||||
| (() => Promise<Result<null, AnalysisError>>)
|
||||
| undefined;
|
||||
if (policies.permissionAuthority !== undefined) {
|
||||
const authority = policies.permissionAuthority;
|
||||
const authorizedWorkspace = await authorizeFileReadWithDeferredWrite(
|
||||
authority,
|
||||
{
|
||||
path: investigationRun.workspace_path,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: contract.name,
|
||||
},
|
||||
);
|
||||
if (!authorizedWorkspace.ok)
|
||||
return toCallToolResult(authorizedWorkspace, contract);
|
||||
workspaceAuthorization = authorizedWorkspace.value;
|
||||
authorizeInputRead = () =>
|
||||
authorizeRootPermission(authority, {
|
||||
capability: "investigation_input",
|
||||
roots: [investigationRun.left_path, investigationRun.right_path],
|
||||
access: "read",
|
||||
operation: contract.name,
|
||||
});
|
||||
}
|
||||
const investigated = await runCrossVersionInvestigationValidated(
|
||||
investigationRun,
|
||||
policies.evidenceFiles,
|
||||
{
|
||||
...investigationExecution(
|
||||
session,
|
||||
context.mcpReq.signal,
|
||||
policies.inputRoots,
|
||||
policies.integrityContinueEnabled?.() ?? false,
|
||||
progress,
|
||||
),
|
||||
...(workspaceAuthorization === undefined
|
||||
? {}
|
||||
: {
|
||||
authorizeWorkspaceWrite:
|
||||
workspaceAuthorization.authorizeWrite,
|
||||
}),
|
||||
...(authorizeInputRead === undefined ? {} : { authorizeInputRead }),
|
||||
},
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const workspace = investigated.value.workspace;
|
||||
if (session.retainInvestigationWorkspace(workspace) === "added")
|
||||
server.sendResourceListChanged();
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
investigated.value.evidence.normalized_result,
|
||||
);
|
||||
const toolResult = toCallToolResult(
|
||||
recordWorkflowEvidence(
|
||||
session,
|
||||
investigated.value.evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
isIncomplete(result.behavior_status),
|
||||
{
|
||||
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.",
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
if (investigationRun !== undefined)
|
||||
return runAutomaticInvestigation({
|
||||
server,
|
||||
session,
|
||||
contract,
|
||||
);
|
||||
return {
|
||||
...toolResult,
|
||||
content: [
|
||||
...toolResult.content,
|
||||
{
|
||||
type: "resource_link" as const,
|
||||
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
|
||||
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
|
||||
description:
|
||||
"Immutable CAS-linked investigation workspace revision",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
policies,
|
||||
investigationRun,
|
||||
unknownRegistryApproved: parsed.unknown_registry_approved,
|
||||
context,
|
||||
});
|
||||
const closure = evidenceClosure(
|
||||
session,
|
||||
comparisonClosure(parsed.comparisons),
|
||||
@@ -251,6 +150,107 @@ const registerChangedBehavior = (
|
||||
);
|
||||
};
|
||||
|
||||
const runAutomaticInvestigation = async (input: {
|
||||
readonly server: McpServer;
|
||||
readonly session: BinarySessionPort;
|
||||
readonly contract: ToolContract<"find_changed_behavior">;
|
||||
readonly policies: InvestigationToolPolicies;
|
||||
readonly investigationRun: NonNullable<
|
||||
z.output<typeof changedBehaviorInputSchema>["investigation_run"]
|
||||
>;
|
||||
readonly unknownRegistryApproved: true | undefined;
|
||||
readonly context: DerivedOperationContext;
|
||||
}) => {
|
||||
const { policies, investigationRun, contract, session } = input;
|
||||
const progress = mcpProgressReporter(input.context);
|
||||
let workspaceAuthorization: DeferredFileWriteAuthorization | undefined;
|
||||
let authorizeInputRead:
|
||||
| (() => Promise<Result<null, AnalysisError>>)
|
||||
| undefined;
|
||||
if (policies.permissionAuthority !== undefined) {
|
||||
const authority = policies.permissionAuthority;
|
||||
const authorizedWorkspace = await authorizeFileReadWithDeferredWrite(
|
||||
authority,
|
||||
{
|
||||
path: investigationRun.workspace_path,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: contract.name,
|
||||
},
|
||||
);
|
||||
if (!authorizedWorkspace.ok)
|
||||
return toCallToolResult(authorizedWorkspace, contract);
|
||||
workspaceAuthorization = authorizedWorkspace.value;
|
||||
authorizeInputRead = () =>
|
||||
authorizeRootPermission(authority, {
|
||||
capability: "investigation_input",
|
||||
roots: [investigationRun.left_path, investigationRun.right_path],
|
||||
access: "read",
|
||||
operation: contract.name,
|
||||
});
|
||||
}
|
||||
const investigated = await runCrossVersionInvestigationValidated(
|
||||
investigationRun,
|
||||
policies.evidenceFiles,
|
||||
{
|
||||
...investigationContext({
|
||||
session,
|
||||
signal: input.context.mcpReq.signal,
|
||||
inputRoots: policies.inputRoots,
|
||||
integrityContinueEnabled:
|
||||
policies.integrityContinueEnabled?.() ?? false,
|
||||
progress,
|
||||
}),
|
||||
...(workspaceAuthorization === undefined
|
||||
? {}
|
||||
: { authorizeWorkspaceWrite: workspaceAuthorization.authorizeWrite }),
|
||||
...(authorizeInputRead === undefined ? {} : { authorizeInputRead }),
|
||||
},
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const workspace = investigated.value.workspace;
|
||||
if (session.retainInvestigationWorkspace(workspace) === "added")
|
||||
input.server.sendResourceListChanged();
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
investigated.value.evidence.normalized_result,
|
||||
);
|
||||
const toolResult = toCallToolResult(
|
||||
recordWorkflowEvidence(
|
||||
session,
|
||||
investigated.value.evidence,
|
||||
input.unknownRegistryApproved,
|
||||
isIncomplete(result.behavior_status),
|
||||
{
|
||||
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,
|
||||
);
|
||||
return {
|
||||
...toolResult,
|
||||
content: [
|
||||
...toolResult.content,
|
||||
{
|
||||
type: "resource_link" as const,
|
||||
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
|
||||
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
|
||||
description: "Immutable CAS-linked investigation workspace revision",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const registerCallPath = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
@@ -407,47 +407,8 @@ const registerReconstruction = (
|
||||
);
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, contract);
|
||||
const parsed = parsedInput.value;
|
||||
const coverage = parsed.coverage;
|
||||
if (coverage !== undefined) {
|
||||
const workspace = session.reconstructionCoverageWorkspace(
|
||||
coverage.workspace_id,
|
||||
coverage.revision,
|
||||
);
|
||||
if (
|
||||
workspace === undefined ||
|
||||
workspace.revision_sha256 !== coverage.revision_sha256
|
||||
)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new EvidenceIntegrityError(
|
||||
"The requested reconstruction coverage revision is not retained by this session",
|
||||
),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
let coverageResult;
|
||||
try {
|
||||
coverageResult = evaluateReconstructionClosure(
|
||||
workspace,
|
||||
coverage.boundary_id,
|
||||
Date.now(),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return toCallToolResult(
|
||||
err(new AnalysisInputError(contract.name, { cause })),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
if (coverageResult.status !== "ready")
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new EvidenceIntegrityError(
|
||||
`Reconstruction coverage boundary is ${coverageResult.status}; readiness requires ready`,
|
||||
),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
const coverage = verifyCoverageReadiness(session, parsed.coverage);
|
||||
if (!coverage.ok) return toCallToolResult(coverage, contract);
|
||||
const owned = session.exportEvidenceBundle();
|
||||
const computed = await runDerivedOperation(context, contract.name, () =>
|
||||
verifyReconstruction(
|
||||
@@ -503,89 +464,3 @@ const registerReconstruction = (
|
||||
};
|
||||
|
||||
const contractOptions = toolRegistrationOptions;
|
||||
|
||||
const comparisonClosure = (comparisons: readonly Evidence[]): string[] =>
|
||||
uniqueIds(
|
||||
comparisons.flatMap((evidence) => [
|
||||
evidence.evidence_id,
|
||||
...evidence.evidence_links,
|
||||
]),
|
||||
);
|
||||
|
||||
const functionEvidenceIds = (
|
||||
groups: readonly (Evidence | readonly Evidence[])[],
|
||||
): string[] =>
|
||||
uniqueIds(
|
||||
groups.flatMap((group) =>
|
||||
(Array.isArray(group) ? group : [group]).map(({ evidence_id: id }) => id),
|
||||
),
|
||||
);
|
||||
|
||||
const uniqueIds = (ids: readonly string[]): string[] =>
|
||||
[...new Set(ids)].sort((left, right) => left.localeCompare(right));
|
||||
|
||||
const evidenceClosure = (
|
||||
session: BinarySessionPort,
|
||||
seedIds: readonly string[],
|
||||
): Result<string[], EvidenceIntegrityError> => {
|
||||
const records = new Map(
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.map((evidence) => [evidence.evidence_id, evidence]),
|
||||
);
|
||||
const visited = new Set<string>();
|
||||
const pending = [...seedIds];
|
||||
while (pending.length > 0) {
|
||||
const evidenceId = pending.pop();
|
||||
if (evidenceId === undefined || visited.has(evidenceId)) continue;
|
||||
const evidence = records.get(evidenceId);
|
||||
if (evidence === undefined)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation input has a dangling Evidence link",
|
||||
),
|
||||
);
|
||||
visited.add(evidenceId);
|
||||
pending.push(...evidence.evidence_links);
|
||||
}
|
||||
return ok(uniqueIds([...visited]));
|
||||
};
|
||||
|
||||
const recordWorkflowEvidence = (
|
||||
...[session, evidence, approved, unresolved, input]: readonly [
|
||||
BinarySessionPort,
|
||||
Evidence,
|
||||
true | undefined,
|
||||
boolean,
|
||||
{
|
||||
readonly question: string;
|
||||
readonly domain: string;
|
||||
readonly requiredAuthority:
|
||||
| "shipped-artifact"
|
||||
| "controlled-replay"
|
||||
| null;
|
||||
readonly requiredConfidence: "observed" | "derived";
|
||||
readonly probes: readonly {
|
||||
readonly operation: string;
|
||||
readonly rationale: string;
|
||||
}[];
|
||||
},
|
||||
]
|
||||
): Result<Evidence, import("../domain/errors.js").AnalysisError> => {
|
||||
if (approved !== true || !unresolved) {
|
||||
return recordDerivedEvidence(session, evidence, undefined);
|
||||
}
|
||||
return recordDerivedEvidence(session, evidence, {
|
||||
approved: true,
|
||||
question: input.question,
|
||||
severity: "high",
|
||||
domain: input.domain,
|
||||
supporting_evidence_ids: [evidence.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: input.requiredAuthority,
|
||||
required_confidence: input.requiredConfidence,
|
||||
required_environment: null,
|
||||
recommended_probes: [...input.probes],
|
||||
relationships: [],
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user