feat(analysis-view): project rich captures from Evidence files and template path pairs (#5293)

Project large local Evidence captures through the authenticated file-source boundary and add guarded opt-in sibling-pair path inference. Preserve request cancellation, resource ownership and file-relative validation diagnostics.

Validated relevant source and compiled CLI/MCP/environment boundaries, static/build/docs/catalog gates, and a real isolated Gitea 28.2.0 capture through CLI, default stdio MCP and HTTP replay. Current-head automated review passed; unrelated long-running platform jobs may still be pending.

Co-authored-by: Edgar Arakelyan <[email protected]>
Co-authored-by: Kaoru0822 <[email protected]>
Co-authored-by: gensokyo-dev <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-20 10:33:52 +08:00
1 parent 5fa4defcbc
commit f93a0335a8
28 files changed
+1227 -66

No files matched your search

@@ -1,10 +1,13 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
analysisViewCaptureFixture,
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
environmentManifestCaptureFixture,
} from "../../../tests/fixtures/analysisView.js";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
@@ -19,6 +22,7 @@ import {
import {
inspectAnalysisView,
inspectAnalysisViewValidated,
inspectAnalysisViewWithFiles,
summarizeRetainedAnalysis,
} from "./AnalysisViewService.js";
import type { Evidence } from "../../domain/evidence.js";
@@ -27,6 +31,16 @@ import { err, ok } from "../../domain/result.js";
import { EvidenceLedger } from "../investigation/EvidenceLedger.js";
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
import { isImmutableJsonSnapshot } from "../../domain/immutableJson.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import {
SCENARIO_EXCHANGES,
scenarioCaptureEvidence,
scenarioCaptureFixture,
} from "../../../tests/fixtures/browserScenarioCapture.js";
import { readEvidenceFileSource } from "./evidenceFileSource.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
vi.mock("./evidenceFileSource.js", { spy: true });
it.each(["layout", "javascript"])(
"carries the retained %s source snapshot into repeatable shared views",
@@ -860,3 +874,221 @@ it("admits raw_result and parameters before authenticating a portable capture",
});
}
});
const manifestView = { kind: "environment-manifest" } as const;
const writeEvidenceFile = async (value: unknown): Promise<string> => {
const root = await createTestTempDirectory("rea-analysis-view-file-");
const path = join(root, "capture.json");
await writeFile(path, JSON.stringify(value));
return path;
};
describe("inspectAnalysisViewWithFiles", () => {
const view = manifestView;
it("projects an Evidence file exactly as the same Evidence inline", async () => {
const parent = analysisViewCaptureEvidence(
environmentManifestCaptureFixture(),
);
const fromFile = await inspectAnalysisViewWithFiles({
source: { kind: "evidence-file", path: await writeEvidenceFile(parent) },
view,
});
const inline = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view,
});
if (!fromFile.ok) throw fromFile.error;
if (!inline.ok) throw inline.error;
expect(fromFile.value.normalized_result).toEqual(
inline.value.normalized_result,
);
expect(fromFile.value.parameters).toEqual(inline.value.parameters);
});
it("accepts from a file a capture whose response text exceeds the inline budget", async () => {
const capture = environmentManifestCaptureFixture();
const reported = capture.records[0]!.reported as {
response: { content: { text: string } };
};
// Inline admission charges about 14 bytes per character; this body alone overruns it.
reported.response.content.text = "a".repeat(
Math.ceil(WEB_NETWORK_CAPTURE_LIMITS.outputBytes / 14) + 1024,
);
const parent = analysisViewCaptureEvidence(capture);
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view,
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
});
const fromFile = await inspectAnalysisViewWithFiles({
source: { kind: "evidence-file", path: await writeEvidenceFile(parent) },
view,
});
if (!fromFile.ok) throw fromFile.error;
expect(fromFile.value.parameters).toMatchObject({
parent_evidence_id: parent.evidence_id,
});
});
it("refuses a relative path, a missing file and JSON that is not Evidence", async () => {
expect(
await inspectAnalysisViewWithFiles({
source: { kind: "evidence-file", path: "capture.json" },
view,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const missing = join(
await createTestTempDirectory("rea-analysis-view-missing-"),
"absent.json",
);
expect(
await inspectAnalysisViewWithFiles({
source: { kind: "evidence-file", path: missing },
view,
}),
).toMatchObject({ ok: false, error: { _tag: "EvidenceFileError" } });
const notEvidence = await inspectAnalysisViewWithFiles({
source: {
kind: "evidence-file",
path: await writeEvidenceFile({ hello: 1 }),
},
view,
});
expect(notEvidence).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "wrong-kind" },
});
if (notEvidence.ok) throw new Error("Expected invalid Evidence file");
expect(projectAnalysisError(notEvidence.error)).toMatchObject({
details: {
content_issues: expect.arrayContaining([
{
path: ["evidence_id"],
reason: "missing_argument",
expected: "string",
},
]),
},
});
});
it("returns typed cancellation for a cancelled file request", async () => {
const controller = new AbortController();
controller.abort();
const parent = analysisViewCaptureEvidence(
environmentManifestCaptureFixture(),
);
expect(
await inspectAnalysisViewWithFiles(
{
source: {
kind: "evidence-file",
path: await writeEvidenceFile(parent),
},
view,
},
undefined,
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
});
it("returns typed cancellation when a running file request is aborted", async () => {
const controller = new AbortController();
const parent = analysisViewCaptureEvidence(
environmentManifestCaptureFixture(),
);
const path = await writeEvidenceFile(parent);
const running = inspectAnalysisViewWithFiles(
{ source: { kind: "evidence-file", path }, view },
undefined,
{ signal: controller.signal },
);
// Queued before the request yields after its synchronous work, so it is seen even if the read already finished.
setImmediate(() => controller.abort());
expect(await running).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it("leaves file sources to the file-aware entry point", () => {
expect(
inspectAnalysisView({
source: { kind: "evidence-file", path: "/tmp/capture.json" },
view,
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
});
describe("inspectAnalysisViewWithFiles scenario parents and cancellation", () => {
const view = manifestView;
it("accepts from a file a scenario capture whose response bodies exceed the inline budget", async () => {
const blob = "a".repeat(
Math.ceil(WEB_NETWORK_CAPTURE_LIMITS.outputBytes / 14) + 1024,
);
const parent = scenarioCaptureEvidence(
scenarioCaptureFixture(
SCENARIO_EXCHANGES.map((exchange, index) =>
index === 1 ? { ...exchange, body: `{"blob":"${blob}"}` } : exchange,
),
),
);
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view,
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
});
const fromFile = await inspectAnalysisViewWithFiles({
source: { kind: "evidence-file", path: await writeEvidenceFile(parent) },
view,
});
if (!fromFile.ok) throw fromFile.error;
expect(fromFile.value.parameters).toMatchObject({
parent_evidence_id: parent.evidence_id,
});
});
it("reports cancellation rather than the authentication failure of a file aborted while it is authenticated", async () => {
const controller = new AbortController();
const parent = analysisViewCaptureEvidence(
environmentManifestCaptureFixture(),
);
const path = await writeEvidenceFile({
...parent,
evidence_id: `ev_${"0".repeat(64)}`,
});
const { readEvidenceFileSource: read } = await vi.importActual<
typeof import("./evidenceFileSource.js")
>("./evidenceFileSource.js");
// The abort arrives once the read has finished, while the stale ID is being authenticated.
vi.mocked(readEvidenceFileSource).mockImplementationOnce(
async (...args) => {
const loaded = await read(...args);
controller.abort();
return loaded;
},
);
expect(
await inspectAnalysisViewWithFiles(
{ source: { kind: "evidence-file", path }, view },
undefined,
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
});
});
@@ -1,3 +1,4 @@
import { setImmediate } from "node:timers/promises";
import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../../domain/analysisView/analysisViewErrors.js";
import { z } from "zod";
@@ -6,7 +7,10 @@ import type { EvidenceLookup } from "../EvidenceInputResolver.js";
import { resolveEvidenceInput } from "../EvidenceInputResolver.js";
import type { EvidenceWriter } from "../investigation/InvestigationRecordPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../../domain/analysisErrorCore.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import {
@@ -29,6 +33,10 @@ import { err, ok, type Result } from "../../domain/result.js";
import { WebNetworkApiSurfaceAccumulator } from "../../domain/analysisView/WebNetworkApiSurfaceAccumulator.js";
import { EnvironmentManifestAccumulator } from "../../domain/analysisView/EnvironmentManifestAccumulator.js";
import { admitAnalysisViewData } from "../../domain/analysisView/analysisViewDataAdmission.js";
import {
readEvidenceFileSource,
type EvidenceFileReadOptions,
} from "./evidenceFileSource.js";
/** Authenticate a selected-view request and project already completed Evidence. */
export const inspectAnalysisView = (
@@ -48,6 +56,58 @@ export const inspectAnalysisView = (
return inspectAnalysisViewValidated(parsed.data, lookup);
};
/** Validate a request whose source may be an Evidence file, then project it. */
export const inspectAnalysisViewWithFiles = async (
rawInput: unknown,
lookup?: EvidenceLookup,
options: EvidenceFileReadOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const parsed = inspectAnalysisViewInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
INSPECT_ANALYSIS_VIEW_OPERATION,
parsed.error.issues,
rawInput,
{ cause: parsed.error },
),
);
return inspectAnalysisViewValidatedWithFiles(parsed.data, lookup, options);
};
/**
* Read and authenticate an Evidence-file source, then project it as retained
* Evidence: its strings are bounded by the file reader rather than charged as
* inline input. Other sources project unchanged.
*/
export const inspectAnalysisViewValidatedWithFiles = async (
input: InspectAnalysisViewInput,
lookup?: EvidenceLookup,
options: EvidenceFileReadOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
if (input.source.kind !== "evidence-file")
return inspectAnalysisViewValidated(input, lookup);
const loaded = await readEvidenceFileSource(input.source.path, options);
// Authentication and projection are synchronous; yield so a pending abort is dispatched before each check.
const cancelled = async (): Promise<boolean> => {
await setImmediate();
return options.signal?.aborted === true;
};
// A request cancelled during authentication reports cancellation, even when authentication failed.
if (await cancelled())
return err(new AnalysisCancelledError(INSPECT_ANALYSIS_VIEW_OPERATION));
if (!loaded.ok) return loaded;
const id = loaded.value.evidence_id;
const projected = inspectAnalysisViewValidated(
{ ...input, source: { kind: "retained-evidence", evidence_id: id } },
(evidenceId) => (evidenceId === id ? loaded.value : lookup?.(evidenceId)),
);
// A request cancelled during projection delivers and records nothing.
return (await cancelled())
? err(new AnalysisCancelledError(INSPECT_ANALYSIS_VIEW_OPERATION))
: projected;
};
/** Authenticate borrowed inline Evidence after adapter envelope validation. */
export const inspectAnalysisViewValidated = (
input: InspectAnalysisViewInput,
@@ -182,8 +242,28 @@ const resolveAnalysisViewSource = (
): Result<Evidence, AnalysisError> => {
if (source.kind === "retained-evidence")
return resolveEvidenceInput(source, lookup);
// Files are read by inspectAnalysisViewValidatedWithFiles, which the CLI and MCP adapters call.
if (source.kind === "evidence-file")
return err(
new AnalysisCapabilityUnavailableError(
ANALYSIS_VIEW_PROVIDER.id,
INSPECT_ANALYSIS_VIEW_OPERATION,
"evidence-file sources are read before projection",
),
);
return authenticateEvidence(source.evidence, ["source", "evidence"], {
source,
});
};
/** Parse complete Evidence, reporting schema issues under the given request path. */
const authenticateEvidence = (
value: unknown,
path: readonly (string | number)[],
input: unknown,
): Result<Evidence, AnalysisError> => {
try {
return ok(parseEvidence(source.evidence));
return ok(parseEvidence(value));
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
return err(
@@ -191,9 +271,9 @@ const resolveAnalysisViewSource = (
INSPECT_ANALYSIS_VIEW_OPERATION,
cause.issues.map((issue) => ({
...issue,
path: ["source", "evidence", ...issue.path],
path: [...path, ...issue.path],
})),
{ source },
input,
{ cause },
),
);
@@ -0,0 +1,64 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { analysisViewCaptureEvidence } from "../../../tests/fixtures/analysisView.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
estimateJsonValueBytes,
readEvidenceFileSource,
requireAuthenticationHeadroom,
} from "./evidenceFileSource.js";
describe("evidence-file source", () => {
it("estimates parsed JSON at no less than its UTF-16 text", () => {
const text = "x".repeat(1000);
expect(estimateJsonValueBytes(text)).toBeGreaterThanOrEqual(2000);
expect(
estimateJsonValueBytes({ outer: [text, { inner: text }] }),
).toBeGreaterThan(2 * estimateJsonValueBytes(text));
});
it("refuses authentication when live heap headroom cannot hold its copies", () => {
const value = { normalized_result: "y".repeat(10_000) };
expect(
requireAuthenticationHeadroom(value, "/tmp/capture.json", 1024),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
resource: "memory",
reportedLimits: {
input_path: "/tmp/capture.json",
available_heap_bytes: 1024,
},
},
});
expect(
requireAuthenticationHeadroom(value, "/tmp/capture.json", 1 << 30),
).toEqual({ ok: true, value: undefined });
});
it("refuses a cancelled request before reading and reads within the caller's resource scope", async () => {
const controller = new AbortController();
controller.abort();
expect(
await readEvidenceFileSource("/nonexistent/capture.json", {
signal: controller.signal,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
const path = join(
await createTestTempDirectory("rea-evidence-file-source-"),
"capture.json",
);
const parent = analysisViewCaptureEvidence();
await writeFile(path, JSON.stringify(parent));
const resources = new ArtifactResourceScope();
const read = await readEvidenceFileSource(path, { resources });
await resources.close();
if (!read.ok) throw read.error;
expect(read.value).toEqual(JSON.parse(JSON.stringify(parent)));
});
});
@@ -0,0 +1,125 @@
import { getHeapStatistics } from "node:v8";
import { z } from "zod";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../../domain/analysisView/analysisViewErrors.js";
import { err, ok, type Result } from "../../domain/result.js";
import { parseEvidence, type Evidence } from "../../domain/evidence.js";
import {
EvidenceFileError,
EvidenceIntegrityError,
} from "../../domain/evidenceErrors.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { readJsonFile } from "../JsonFiles.js";
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
/** The request's cancellation and the scope that owns descriptors whose close failed. */
export interface EvidenceFileReadOptions {
readonly signal?: AbortSignal;
readonly resources?: ArtifactResourceScope;
}
/** Authentication clones the parsed Evidence and hashes its canonical JSON. */
const AUTHENTICATION_COPIES = 2;
/** Conservative bytes a parsed JSON value occupies: UTF-16 text plus container and slot overhead. */
export const estimateJsonValueBytes = (value: unknown): number => {
let bytes = 0;
const stack: unknown[] = [value];
while (stack.length > 0) {
const item = stack.pop();
if (typeof item === "string") bytes += 64 + item.length * 2;
else if (Array.isArray(item)) {
bytes += 128 + item.length * 16;
for (const entry of item) stack.push(entry);
} else if (typeof item === "object" && item !== null) {
bytes += 128;
for (const [key, entry] of Object.entries(item)) {
bytes += 64 + key.length * 2;
stack.push(entry);
}
} else bytes += 16;
}
return bytes;
};
/** Refuse before authentication when live heap headroom cannot hold its copies of the parsed value. */
export const requireAuthenticationHeadroom = (
value: unknown,
path: string,
availableBytes: number = getHeapStatistics().total_available_size,
): Result<void, AnalysisError> => {
const valueBytes = estimateJsonValueBytes(value);
const requiredBytes = valueBytes * AUTHENTICATION_COPIES;
if (requiredBytes <= availableBytes) return ok(undefined);
return err(
new AnalysisResourceConstraintError(
INSPECT_ANALYSIS_VIEW_OPERATION,
"memory",
"Insufficient heap headroom to authenticate the Evidence file",
{
input_path: path,
projected_value_bytes: valueBytes,
authentication_bytes: requiredBytes,
available_heap_bytes: availableBytes,
},
),
);
};
/** Read and authenticate one Evidence file under the request's cancellation and resource scope. */
export const readEvidenceFileSource = async (
path: string,
options: EvidenceFileReadOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const { signal, resources } = options;
if (signal?.aborted)
return err(new AnalysisCancelledError(INSPECT_ANALYSIS_VIEW_OPERATION));
const loaded = await readJsonFile(path, signal, resources).catch(
(cause: unknown) => {
// A failed close transfers a live handle owner; preserve that failure.
if (
signal?.aborted === true &&
!(cause instanceof RegularFileCleanupFailure)
)
return err(
new AnalysisCancelledError(INSPECT_ANALYSIS_VIEW_OPERATION, {
cause,
}),
);
throw cause;
},
);
if (!loaded.ok) return loaded;
if (signal?.aborted)
return err(new AnalysisCancelledError(INSPECT_ANALYSIS_VIEW_OPERATION));
const headroom = requireAuthenticationHeadroom(loaded.value, path);
if (!headroom.ok) return headroom;
try {
return ok(parseEvidence(loaded.value));
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
return err(
new EvidenceFileError("read", "wrong-kind", {
path,
cause,
contentIssues: projectInputIssues(cause.issues, loaded.value),
userMessage:
"The selected file does not contain valid Evidence. Repair or recreate the file and try again.",
}),
);
if (cause instanceof TypeError)
return err(
new EvidenceIntegrityError(cause.message, {
cause,
userMessage: cause.message,
}),
);
throw cause;
}
};