mirror of
https://github.com/morluto/rea.git
synced 2026-10-28 02:15:44 +00:00
* feat: add FreeBuff agent support for REA setup Register FreeBuff as a supported setup client using the shared user agents directory (~/.agents/mcp.json with mcpServers, skills in ~/.agents/skills), which matches what FreeBuff Desktop loads. Adds the client definition, boundary tests, supported-agent docs, and the skill reference client list. * fix(freebuff): detect FreeBuff from its profile directory, not shared .agents The ~/.agents marker made FreeBuff appear installed for any home where REA had installed shared skills (the default skill destination, also Gemini CLI's), producing false doctor failures. Detect FreeBuff from its own fixed profile directory ~/.config/freebuff-desktop instead, and add a regression test covering a home with only the shared agents skill directory. * fix(setup): require product evidence for FreeBuff discovery Address review findings at their producing boundaries and preserve directly affected consumers. Source inspection and git diff --check completed. Tests and automated checks were not run at the user’s explicit request. * fix(uninstall): retain unverified shared client configuration * fix(clients): preserve scoped removal evidence * fix(doctor): omit undefined selectedClientIds under exactOptionalPropertyTypes Passing selectedClientIds explicitly as undefined fails typecheck on this branch (TS2379), which blocks the focused test workflow before any test can run. Spread the option only when defined. * fix(update): separate ownership evidence from product applicability rea update's maintenance scope inspected only product applicability evidence, so when a FreeBuff profile was absent but REA already owned a version-pinned row in the shared ~/.agents/mcp.json, the plan omitted freebuff and left the integration stale. FreeBuff now declares its registration storage as shared, which proves ownership of an owned row but never product applicability, and maintenance requests ownership evidence through that declaration instead of reinterpreting the shared paths. Doctor and setup keep readiness evidence, foreign rows stay out of maintenance, and the Doctor exactOptionalPropertyTypes fix makes the focused test workflow runnable. * test(dotnet): split oversized operand extent diagnostics describe The describe callback reached 162 lines (max 150), failing max-lines-per-function and blocking the pre-push check for this branch. Move the single-case extent scenarios into their own describe; no test content or order changes. * fix(update): preserve ZCode's disabled shared registration during maintenance The shared user agents file doubles as ZCode's fallback, where `enable: false` disables the registration. Ownership-based maintenance read that row as a FreeBuff registration, whose format does not recognize the flag, so the row was selected and the emitted setup command rewrote it, dropping the flag and silently re-enabling a registration the user had disabled. registrationActivation now honors `enable: false` for any client whose registration storage is shared, because the activation fact binds every reader of that storage. Maintenance leaves such rows out; doctor reports them as stale, matching ZCode's own treatment. * fix(doctor): let explicit client selection authorize the config read When an ACL or an inaccessible shared parent made every access probe fail, a client selected by name was omitted before the configuration read could return its unreadable-config detail, so doctor reported it as not detected with installation remediation: an unresolved selected path collapsed to absence. An explicit selection now authorizes the read outright and the probes serve automatic discovery only. A selected client with an unreadable config reports invalid with the read failure; one with no config reports missing; automatic discovery still probes before inspecting. * fix(uninstall): share shared-storage checks between ZCode and FreeBuff clients() queued ~/.agents/mcp.json twice: once as zcode_fallback and once as freebuff. ZCode has no discoveryPaths, so its strict read still blocked uninstall on malformed shared text, despite FreeBuff's new retain-and-continue behavior. For a valid owned entry, ZCode removed it first, so FreeBuff reported skipped rather than removed. Make the shared file's checks and removal one shared decision: - Add zcodeDiscoveryPaths to ZCode so it has its own applicability evidence. - Gate zcode_fallback push on applicable, not just zcodeFallbackPath presence. - Report shared storage ownership as one decision for both clients: FreeBuff and ZCode now use clientOwnershipEvidencePaths together, so a recognizable REA-owned row proves ownership once for the shared storage, and both clients report the same result consistently. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(uninstall): merge duplicated host and prove shared ownership from owned rows Uninstall.ts declared systemUninstallHost twice, preventing module load, with the exported copy returning only clients and the second copy missing clientWriteBlocker. Merge into one exported host carrying both blockers. hasOwnershipEvidence used access() existence, so an unrelated malformed ~/.agents/mcp.json established ownership and blocked every removal. Ownership now requires a readable, recognizable REA-owned row via the injected filesystem, so unrelated shared data stays retained. Also cover ZCode discoveryPaths in its path test. * fix(uninstall): keep denied product-local configurations fail-closed Unproven product applicability marked every configuration path of that client unverified, so a denied ZCode profile turned an unreadable product-local config into a retained item: uninstall continued and could report complete with REA still registered. The retain-and-continue exception now applies only to storage REA does not own, classified once by clientSharedRegistrationPaths (shared configuration plus another product's same-scope fallback). Covers the Greptile P1 on Uninstall.ts. Validation: the new test fails on the pre-fix Uninstall and passes after it; freebuff/zcode/updateMaintenance/bom/dsh suites green; clientLifecycle, clientRegistrationStatus and claudeDesktop keep the same 8 host failures as the pre-merge baseline (symlink EPERM, stale-vs-aligned on Windows). * fix(update): retain FreeBuff when ZCode reads the shared fallback Maintenance deduplicated clients on the path each inspection read, so ZCode's fallback view of ~/.agents/mcp.json marked that file "covered" and dropped FreeBuff from the scope. ZCode setup writes ~/.zcode/cli/config.json and deliberately leaves the fallback untouched (docs/client-configuration.md), so the emitted command refreshed only ZCode while the shared row both products load stayed pinned to the old package version. Each setup action rewrites only its own configuration path and no other action rewrites the shared row, so every selected client keeps its own maintenance action; the read-path covered/deduped filter is removed. Covers the Codex P2 on UpdateMaintenance.ts:104. Validation: the new regression fails one2fdec384with {clients:["zcode"]} and passes with {clients:["freebuff","zcode"]}; updateMaintenance 31/31, setupClientConfigCleanupOwnership, cliUpdateAlias, updateOutput, cliStartupImports green; tsc --noEmit, oxlint (0 errors) and oxfmt --check clean; clientRegistrationStatus keeps the same 4 symlink/stale-vs-aligned failures this Windows host has on basee2fdec384(verified by stashing the change). 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): preserve completed reads as shared ownership evidence hasOwnershipEvidence caught every read failure and kept scanning, so a handle-close failure after a successful read — a RegularFileCleanupFailure whose completed outcome still contains the exact shared-file text — was discarded as "no proof". FreeBuff's applicability-unverified storage therefore never got its ownership fact, and once the retained handle blocked later reads, readClientConfiguration downgraded them to retained: inspection passed, removals soft-failed, and runUninstall(true) could purge REA data while the active shared registration remained. The catch now parses the completed outcome for the ownership text while missing or unreadable storage and malformed data keep their proves-nothing semantics, so ownership holds and every later read failure stays blocking. Covers the Codex P2 on Uninstall.ts:252. Validation: the new regression fails on4dbfdf1a9(freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 25/25; the other 21 Uninstall-consumer suites are byte-identical to base4dbfdf1a9(61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): keep owned-row proof through removal refusals hasOwnershipEvidence treated any clientRegistrationRemoval refusal as no ownership: an effective REA-owned rea member shadowed by an earlier foreign duplicate (shadowed_unowned_member), or an owned native row beside a foreign V1 fallback (foreign_legacy_fallback), discarded the already-parsed positive row fact. With FreeBuff unverified and close failures recurring on the preflight/removal rereads, those failures were then downgraded to retained, so runUninstall(true) removed the skill and purged REA data while the active owned row remained. The refusal now carries the owned rows that motivated it — the refusal only refuses the edit — and hasOwnershipEvidence evaluates that fact on both paths; preflight and removal keep refusing the unsafe edit exactly as before. Covers the Codex P2 on Uninstall.ts:269. Validation: the new regression fails on225cb214a(freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 26/26; the 21 Uninstall-consumer suites are byte-identical to the recorded225cb214abaseline (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): keep unresolved discovery probes from softening shared failures The discovery probe swallowed every stat failure, so a FreeBuff profile denied with EACCES/EIO was indistinguishable from an absent profile: shared storage was marked applicability-unverified and, when ~/.agents/mcp.json also remained unreadable, the ownership and removal reads softened to retained. runUninstall(true) then removed the skill and purged REA data while an installed FreeBuff could still hold an active registration — the regression even reports complete. Absence (ENOENT) is now the only state that leaves shared paths unverified; any other probe failure leaves applicability unresolved, and shared-config failures stay blocking. Covers the Codex P2 on Uninstall.ts:318. Validation: the new regression fails on7572a7082with status complete and purged data and passes after; freebuffClientConfiguration 13/13; the Uninstall-consumer batches are byte-identical to the recorded baselines (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same warning rules) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): retain completed configuration reads as removal evidence A close failure after a completed read discarded the text that read produced, so an owned registration row the text proves softened to retained. The completed text now drives removal, keeping shared-config failures blocking when ownership evidence exists. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(uninstall): stop removal when a cleanup retry leaves a handle unreleased A completed reread whose handle the cleanup retry cannot release now fails blockingly instead of serving the text: with no owned row, the soft path let removeAll purge managed data before close() reported the incomplete cleanup. The completed text is served only after the retry releases the handle; an unreleased handle is REA's own failure, never applicability uncertainty, so it bypasses the retained softening. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(uninstall): keep the ZCode fallback when its profile probe is unresolved A denied or failed profile probe leaves ZCode's applicability unresolved, never absent, but the fallback branch dropped the shared row on applicability alone: with the native config and FreeBuff's profile both absent, an installed ZCode kept its uninspected registration while uninstall purged skill and data. Unresolved probes now keep the fallback in scope with the same fail-closed treatment as other unresolved shared paths; definitive absence still keeps ZCode out of another product's primary storage. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(setup): preserve a shared row's enable:false during FreeBuff repair The shared agents file doubles as ZCode's fallback, so its `enable: false` binds every reader: doctor now reports the disabled row as stale for FreeBuff, but following that remediation rebuilt the generic JSON entry without the flag and silently re-enabled a registration ZCode disabled. Repairs of shared storage now carry the activation fact forward, while a client's own native storage keeps its established single-reader repair contract; the denied-profile uninstall regression also pins the fallback's new fail-closed inspection beside the denied read. Co-Authored-By: Anthropic <noreply@anthropic.com> * test(uninstall): retarget the completed-reread regression to a released retry The concurrent-writer regression held the reread handle open forever, which the fail-closed path now serves: it duplicated the unreleased-handle regression while documenting the opposite contract. The fixture's close spy gains a failure limit so the cleanup retry releases the handle, and the test again proves the completed text drives removal of the concurrently added owned row, with purge verified against the cache layout purge actually removes. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(doctor): report a preserved shared disable as a manual conflict Preserving a shared row's enable:false left doctor recommending a setup run that registrationCurrent correctly treats as already current, so the scoped doctor returned needs_human forever. The shared-enable interpretation now has one owner, sharedEnableFlagBinds, used by both the activation rule and the remediation: a row disabled through the shared flag reports the manual conflict and states that rea setup will not change it, instead of an endlessly ineffective repair. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(doctor): keep a native ZCode disable on the setup repair path The manual-conflict remediation matched a native zcode row through sharedEnableFlagBinds, but setup drops enable:false on single-reader storage, so a native disabled registration was told setup would not change it. The remediation now reads setup's own writer rule, exported as setupPreservesDisabledActivation: shared storage and the zcode fallback view keep the manual-conflict message, while a native row keeps the working rea setup instruction. Regressions pin both remediations. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * revert: drop the unrelated managed-CIL describe split The split does not belong to FreeBuff client support and only widens this PR's diff. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): remove the shared agent registration once for both clients ZCode's ~/.agents/mcp.json fallback and FreeBuff's own configuration queued the same physical file twice, so ZCode removed the row and FreeBuff then reported it absent, losing the outcome for the client that owns the file. Resolve every configuration path to one owner -- the client whose configuration it is -- and project that single inspection and removal to each client that loads it. A fallback reader still contributes its discovery probe, so an installed or unresolved reader keeps the shared file fail-closed. Discovery also accepted a dangling ~/.config/freebuff-desktop link, which setup and doctor reject because they follow the target, so an unrelated malformed shared file blocked every other removal. Resolve the link before treating the profile as installation evidence, keeping lstat for removal safety. Also date the FreeBuff release wording against the published 6.7.0 package. * fix(uninstall): keep a row per client when two clients own one file OPENCODE_CONFIG can point OpenCode at FreeBuff's configuration file, where OpenCode writes `mcp.rea` and FreeBuff writes `mcpServers.rea`. Grouping by filename gave that path a single owner, so uninstall removed only OpenCode's row, reported that removal for FreeBuff, and could purge managed data with FreeBuff's registration still active. Share the decision only through a fallback view of another client's row: every client that declares the path as its own configuration keeps its own inspection and removal, and the fallback reader reports each of them. * fix(clients): preserve discovery and fallback registration identity Follow product discovery link targets without losing configuration entry presence or explicitly selected inspections. Associate fallback readers with the format owner's registration table and project outcomes by owner and path, so OpenCode removal cannot be reported as a ZCode fallback removal. All three new boundary regressions fail against the previous source and pass with the fixes. Validation: check:fast; 217 focused tests passed; the two changed test files were rerun with 50 passing tests. No installed FreeBuff client was launched. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Codebuff <noreply@codebuff.com>
1221 lines
40 KiB
TypeScript
1221 lines
40 KiB
TypeScript
import { writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
|
|
import {
|
|
analysisViewCaptureFixture,
|
|
analysisViewCaptureEvidence,
|
|
analysisViewObjectDenseCapture,
|
|
environmentManifestCaptureFixture,
|
|
environmentStateCaptureFixture,
|
|
analysisViewJavaScriptAnalysisWithSource,
|
|
analysisViewJavaScriptEvidence,
|
|
analysisViewLayoutEvidence,
|
|
} from "../../../tests/fixtures/analysisView.js";
|
|
import { describe, expect, it } from "vitest";
|
|
|
|
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
|
|
import {
|
|
createEvidence,
|
|
parseEvidence,
|
|
rebindEvidenceToTargetPath,
|
|
} from "../../domain/evidence.js";
|
|
import { inspectAnalysisViewInputSchema } from "../../domain/analysisView/analysisView.js";
|
|
import { functionDossierSchema } from "../../domain/hopperValues.js";
|
|
import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
|
|
import {
|
|
inspectAnalysisView,
|
|
inspectAnalysisViewValidated,
|
|
summarizeRetainedAnalysis,
|
|
projectRetainedAnalysis,
|
|
} from "./AnalysisViewService.js";
|
|
import type { Evidence } from "../../domain/evidence.js";
|
|
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
|
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 { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
|
|
|
it.each([false, true])(
|
|
"summarizes the selected observation path rather than older retained display metadata (history=%s)",
|
|
(history) => {
|
|
const makeParent = (path: string) =>
|
|
createEvidence(
|
|
{ path, format: "pe", sha256: "c".repeat(64) },
|
|
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
|
{
|
|
operation: "analyze_function",
|
|
parameters: {},
|
|
result: functionDossierSchema.parse(ghidraFunctionDossier()),
|
|
},
|
|
);
|
|
const previous = makeParent("/old/fixture.exe");
|
|
const selected = makeParent("/selected/fixture.exe");
|
|
expect(selected.evidence_id).toBe(previous.evidence_id);
|
|
const ledger = new EvidenceLedger();
|
|
if (history) expect(ledger.record(previous).ok).toBe(true);
|
|
const summary = summarizeRetainedAnalysis(selected, {
|
|
recordEvidence: (evidence) => ledger.record(evidence),
|
|
evidenceById: (id) => ledger.forAnalysis(id),
|
|
});
|
|
if (!summary.ok) throw summary.error;
|
|
expect(summary.value.evidence_links).toEqual([selected.evidence_id]);
|
|
expect(summary.value.subject?.local_path).toBe(
|
|
selected.subject?.local_path,
|
|
);
|
|
expect(ledger.get(selected.evidence_id)?.subject?.local_path).toBe(
|
|
history ? previous.subject?.local_path : selected.subject?.local_path,
|
|
);
|
|
},
|
|
);
|
|
|
|
it("keeps retained admission and payload ownership for a large capture when only its display path changes", async () => {
|
|
const parent = analysisViewCaptureEvidence(
|
|
analysisViewObjectDenseCapture(40_000),
|
|
);
|
|
const ledger = new EvidenceLedger();
|
|
expect(ledger.record(parent).ok).toBe(true);
|
|
const retained = ledger.forAnalysis(parent.evidence_id)!;
|
|
const payload = retained.normalized_result;
|
|
const subject = retained.subject!;
|
|
const selected = rebindEvidenceToTargetPath(retained, {
|
|
path: "/selected/capture.har",
|
|
sha256: subject.digest.sha256,
|
|
format: subject.format,
|
|
...(subject.architecture === null
|
|
? {}
|
|
: { architecture: subject.architecture }),
|
|
});
|
|
const retention = {
|
|
recordEvidence: (evidence: Evidence) => ledger.record(evidence),
|
|
evidenceById: (id: string) => ledger.forAnalysis(id),
|
|
};
|
|
const view = inspectAnalysisViewInputSchema.parse({
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view: { kind: "api-surface" },
|
|
}).view;
|
|
for (const evidence of [retained, selected]) {
|
|
const result = projectRetainedAnalysis(evidence, retention, view);
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.subject?.local_path).toBe(evidence.subject?.local_path);
|
|
expect(result.value.evidence_links).toEqual([parent.evidence_id]);
|
|
}
|
|
expect(ledger.forAnalysis(parent.evidence_id)).toBe(retained);
|
|
expect(retained.normalized_result).toBe(payload);
|
|
expect(retained.subject?.local_path).toBe(parent.subject?.local_path);
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: selected },
|
|
view: { kind: "api-surface" },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
|
|
});
|
|
});
|
|
|
|
it.each(["layout", "javascript"])(
|
|
"carries the retained %s source snapshot into repeatable shared views",
|
|
async (kind) => {
|
|
const parent =
|
|
kind === "layout"
|
|
? analysisViewLayoutEvidence()
|
|
: analysisViewJavaScriptEvidence();
|
|
const ledger = new EvidenceLedger();
|
|
const recorded = ledger.record(parent);
|
|
if (!recorded.ok) throw recorded.error;
|
|
const borrowed = ledger.forAnalysis(parent.evidence_id)!;
|
|
const original = JSON.stringify(borrowed);
|
|
const input = {
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view: { kind: "summary" },
|
|
} as const;
|
|
const first = await inspectAnalysisView(input, (id) =>
|
|
ledger.forAnalysis(id),
|
|
);
|
|
if (!first.ok) throw first.error;
|
|
const repeated = await inspectAnalysisView(input, (id) =>
|
|
ledger.forAnalysis(id),
|
|
);
|
|
if (!repeated.ok) throw repeated.error;
|
|
expect(repeated.value.normalized_result).toEqual(
|
|
first.value.normalized_result,
|
|
);
|
|
expect(isImmutableJsonSnapshot(borrowed.normalized_result)).toBe(true);
|
|
expect(JSON.stringify(borrowed)).toBe(original);
|
|
expect(ledger.forAnalysis(parent.evidence_id)).toBe(borrowed);
|
|
},
|
|
);
|
|
|
|
it.each(["/fixtures/unknown.exe", ""])(
|
|
"preserves recorded empty native identity fields: path=%j",
|
|
async (path) => {
|
|
const original = functionDossierSchema.parse(ghidraFunctionDossier());
|
|
const parent = createEvidence(
|
|
{ path, format: "pe", sha256: "c".repeat(64) },
|
|
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
|
{
|
|
operation: "analyze_function",
|
|
parameters: {},
|
|
result: {
|
|
...original,
|
|
procedure: {
|
|
...original.procedure,
|
|
address: "",
|
|
body: { available: false, reason: "Not recorded" },
|
|
},
|
|
},
|
|
},
|
|
);
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: {
|
|
kind: "native",
|
|
facet: "procedure",
|
|
offset: 0,
|
|
limit: 64,
|
|
},
|
|
});
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.normalized_result).toMatchObject({
|
|
procedure_address: "",
|
|
artifact: { path },
|
|
item: { address: "" },
|
|
});
|
|
expect(result.value.locations).toEqual(
|
|
path.length > 0 ? [{ kind: "artifact-path", path }] : [],
|
|
);
|
|
},
|
|
);
|
|
|
|
it("reports inline Evidence identity failures at the complete source path", async () => {
|
|
const parent = analysisViewLayoutEvidence();
|
|
const input = {
|
|
source: {
|
|
kind: "inline",
|
|
evidence: { ...parent, evidence_id: `ev_${"0".repeat(64)}` },
|
|
},
|
|
view: { kind: "summary" },
|
|
} as const;
|
|
|
|
for (const result of [
|
|
await inspectAnalysisView(input),
|
|
inspectAnalysisViewValidated(input),
|
|
])
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisInputError",
|
|
issues: [
|
|
{
|
|
path: ["source", "evidence", "evidence_id"],
|
|
reason: "invalid_value",
|
|
message: "Evidence semantic identifier does not match its record",
|
|
},
|
|
],
|
|
},
|
|
});
|
|
});
|
|
|
|
it("projects a small native view from an authenticated >10 MiB retained dossier", async () => {
|
|
const original = functionDossierSchema.parse(ghidraFunctionDossier());
|
|
const parent = createEvidence(
|
|
{ path: "/fixtures/large.exe", format: "pe", sha256: "c".repeat(64) },
|
|
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
|
{
|
|
operation: "analyze_function",
|
|
parameters: { address: "0x401000" },
|
|
result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) },
|
|
limitations: ["Synthetic fixture"],
|
|
},
|
|
);
|
|
const input = {
|
|
source: {
|
|
kind: "retained-evidence" as const,
|
|
evidence_id: parent.evidence_id,
|
|
},
|
|
view: {
|
|
kind: "native" as const,
|
|
facet: "pseudocode" as const,
|
|
offset: 0,
|
|
limit: 128,
|
|
},
|
|
};
|
|
const view = await inspectAnalysisView(input, (id) =>
|
|
id === parent.evidence_id ? parent : undefined,
|
|
);
|
|
if (!view.ok) throw view.error;
|
|
expect(view.value.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(view.value.normalized_result).toMatchObject({
|
|
kind: "native",
|
|
parent_operation: "analyze_function",
|
|
parent_evidence_id: parent.evidence_id,
|
|
procedure_address: "0x401000",
|
|
artifact: { path: "/fixtures/large.exe", sha256: "c".repeat(64) },
|
|
coverage: { total: 11 * 1024 * 1024, examined: 128, next_offset: 128 },
|
|
});
|
|
expect(view.value.locations).toEqual([
|
|
{ kind: "artifact-path", path: "/fixtures/large.exe" },
|
|
{ kind: "address", address: "0x401000" },
|
|
]);
|
|
// The summary describes the same function, so its envelope keeps the address.
|
|
const summary = await inspectAnalysisView(
|
|
{ source: input.source, view: { kind: "summary" } },
|
|
(id) => (id === parent.evidence_id ? parent : undefined),
|
|
);
|
|
if (!summary.ok) throw summary.error;
|
|
expect(summary.value.normalized_result).toMatchObject({
|
|
kind: "summary",
|
|
procedure_address: "0x401000",
|
|
});
|
|
expect(summary.value.locations).toEqual(view.value.locations);
|
|
expect(JSON.stringify(view.value).length).toBeLessThan(12000);
|
|
expect(JSON.stringify(parent).length).toBeGreaterThan(10 * 1024 * 1024);
|
|
expect(await inspectAnalysisView(input, () => undefined)).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "EvidenceIntegrityError" },
|
|
});
|
|
});
|
|
|
|
it("projects inline layout Evidence and retains a derived view record", async () => {
|
|
const parent = analysisViewLayoutEvidence();
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: {
|
|
kind: "item",
|
|
collection: "sections",
|
|
selector: { index: 2 },
|
|
},
|
|
});
|
|
if (!result.ok) throw result.error;
|
|
const evidence = parseEvidence(result.value);
|
|
expect(evidence.operation).toBe("inspect_analysis_view");
|
|
expect(evidence.predicate_type).toBe("rea.analysis-view");
|
|
expect(evidence.confidence).toBe("derived");
|
|
expect(evidence.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(evidence.normalized_result).toMatchObject({
|
|
kind: "item",
|
|
parent_evidence_id: parent.evidence_id,
|
|
item: { name: { display: ".data" } },
|
|
});
|
|
});
|
|
|
|
it("resolves same-session retained JavaScript Evidence without re-running analysis", async () => {
|
|
const parent = analysisViewJavaScriptEvidence(
|
|
analysisViewJavaScriptAnalysisWithSource(),
|
|
);
|
|
const lookup = (evidenceId: string) =>
|
|
evidenceId === parent.evidence_id ? parent : undefined;
|
|
const summary = await inspectAnalysisView(
|
|
{
|
|
source: {
|
|
kind: "retained-evidence",
|
|
evidence_id: parent.evidence_id,
|
|
},
|
|
view: { kind: "summary" },
|
|
},
|
|
lookup,
|
|
);
|
|
if (!summary.ok) throw summary.error;
|
|
expect(summary.value.normalized_result).toMatchObject({
|
|
kind: "summary",
|
|
parent_evidence_id: parent.evidence_id,
|
|
parent_operation: "analyze_javascript_application",
|
|
});
|
|
expect(summary.value.normalized_result).not.toHaveProperty(
|
|
"summary.semantic_graph",
|
|
);
|
|
const item = await inspectAnalysisView(
|
|
{
|
|
source: {
|
|
kind: "retained-evidence",
|
|
evidence_id: parent.evidence_id,
|
|
},
|
|
view: {
|
|
kind: "item",
|
|
collection: "modules",
|
|
selector: { path: "renderer.js" },
|
|
},
|
|
},
|
|
lookup,
|
|
);
|
|
if (!item.ok) throw item.error;
|
|
expect(JSON.stringify(item.value.normalized_result)).toContain(
|
|
"export const secret = 1;",
|
|
);
|
|
});
|
|
|
|
it("rejects stale retained IDs and unsupported parent operations", async () => {
|
|
const missing = await inspectAnalysisView(
|
|
{
|
|
source: {
|
|
kind: "retained-evidence",
|
|
evidence_id: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE.evidence_id,
|
|
},
|
|
view: { kind: "summary" },
|
|
},
|
|
() => undefined,
|
|
);
|
|
expect(missing).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "EvidenceIntegrityError",
|
|
evidenceId: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE.evidence_id,
|
|
},
|
|
});
|
|
const unsupported = createEvidence(
|
|
undefined,
|
|
{ id: "fixture", name: "Fixture", version: "1" },
|
|
{
|
|
operation: "inspect_recorded_crash",
|
|
parameters: {},
|
|
result: { path: "/artifacts/crash.core" },
|
|
},
|
|
);
|
|
const rejected = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: unsupported },
|
|
view: { kind: "summary" },
|
|
});
|
|
expect(rejected).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisUnsupportedTargetError" },
|
|
});
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
|
|
view: { kind: "summary", approval: true },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisInputError" },
|
|
});
|
|
});
|
|
|
|
it("preserves an absent parent subject instead of guessing its format", async () => {
|
|
const analysis = analysisViewJavaScriptAnalysisWithSource();
|
|
const original = analysisViewJavaScriptEvidence(analysis);
|
|
const parent = createEvidence(undefined, original.provider, {
|
|
operation: original.operation,
|
|
parameters: {},
|
|
result: original.normalized_result,
|
|
limitations: original.limitations,
|
|
});
|
|
const result = await inspectAnalysisView(
|
|
{
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view: { kind: "summary" },
|
|
},
|
|
() => parent,
|
|
);
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.subject).toBeNull();
|
|
expect(result.value.locations).toEqual([
|
|
{ kind: "artifact-path", path: analysis.input_path },
|
|
]);
|
|
});
|
|
|
|
it("rejects contradictory subject and analysis artifact digests", async () => {
|
|
const analysis = analysisViewJavaScriptAnalysisWithSource();
|
|
const original = analysisViewJavaScriptEvidence(analysis);
|
|
const parent = createEvidence(
|
|
{
|
|
path: analysis.input_path,
|
|
format: analysis.format,
|
|
sha256: "d".repeat(64),
|
|
},
|
|
original.provider,
|
|
{
|
|
operation: original.operation,
|
|
parameters: {},
|
|
result: original.normalized_result,
|
|
},
|
|
);
|
|
const result = await inspectAnalysisView(
|
|
{
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view: { kind: "summary" },
|
|
},
|
|
() => parent,
|
|
);
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "EvidenceIntegrityError" },
|
|
});
|
|
});
|
|
|
|
describe("summarizeRetainedAnalysis", () => {
|
|
const parent = analysisViewJavaScriptEvidence(
|
|
analysisViewJavaScriptAnalysisWithSource(),
|
|
);
|
|
|
|
it("retains the complete Evidence before projecting its summary", () => {
|
|
const retained = new Map<string, Evidence>();
|
|
const summary = summarizeRetainedAnalysis(parent, {
|
|
recordEvidence: (evidence) => {
|
|
retained.set(evidence.evidence_id, evidence);
|
|
return ok("added");
|
|
},
|
|
evidenceById: (evidenceId) => retained.get(evidenceId),
|
|
});
|
|
if (!summary.ok) throw summary.error;
|
|
expect(retained.get(parent.evidence_id)).toBe(parent);
|
|
expect(summary.value.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(summary.value.normalized_result).toMatchObject({
|
|
kind: "summary",
|
|
parent_evidence_id: parent.evidence_id,
|
|
parent_operation: "analyze_javascript_application",
|
|
});
|
|
});
|
|
|
|
it("refuses a summary whose complete Evidence cannot be retained", () => {
|
|
const unavailable = summarizeRetainedAnalysis(parent, {
|
|
recordEvidence: undefined,
|
|
evidenceById: undefined,
|
|
});
|
|
expect(unavailable.ok).toBe(false);
|
|
if (unavailable.ok) return;
|
|
expect(unavailable.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
|
expect(unavailable.error.userMessage).toContain("detail complete");
|
|
|
|
const conflict = new EvidenceIntegrityError("ledger conflict");
|
|
expect(
|
|
summarizeRetainedAnalysis(parent, {
|
|
recordEvidence: () => err(conflict),
|
|
evidenceById: () => parent,
|
|
}),
|
|
).toEqual(err(conflict));
|
|
});
|
|
|
|
it("still rejects missing or mismatched retained identities after a successful writer reply", () => {
|
|
for (const [retained, reason] of [
|
|
[undefined, "missing"],
|
|
[analysisViewLayoutEvidence(), "identity_mismatch"],
|
|
] as const) {
|
|
expect(
|
|
summarizeRetainedAnalysis(parent, {
|
|
recordEvidence: () => ok("added"),
|
|
evidenceById: () => retained,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "EvidenceIntegrityError", reason },
|
|
});
|
|
}
|
|
});
|
|
});
|
|
|
|
it("seals inferred and literal HAR pages, including a null artifact digest", async () => {
|
|
const capture = analysisViewCaptureFixture();
|
|
capture.artifact.sha256 = null;
|
|
const parent = analysisViewCaptureEvidence(capture);
|
|
// Any templated group in the full grouping makes every page inferred.
|
|
for (const [offset, confidence] of [
|
|
[0, "inferred"],
|
|
[11, "inferred"],
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind: "api-surface", offset, limit: 1 },
|
|
});
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.confidence).toBe(confidence);
|
|
expect(result.value.subject).toBeNull();
|
|
expect(parseEvidence(result.value)).toEqual(result.value);
|
|
}
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
|
|
view: { kind: "api-surface" },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisUnsupportedTargetError" },
|
|
});
|
|
});
|
|
|
|
it("rejects a null projected digest under a present parent subject", async () => {
|
|
const capture = analysisViewCaptureFixture();
|
|
capture.artifact.sha256 = null;
|
|
const parent = createEvidence(
|
|
{ path: capture.artifact.path, sha256: "a".repeat(64), format: "file" },
|
|
{ id: "fixture", name: "fixture", version: "1" },
|
|
{
|
|
operation: "inspect_web_network_capture",
|
|
parameters: { sensitive_value_count: 0 },
|
|
result: capture,
|
|
confidence: "observed",
|
|
},
|
|
);
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind: "api-surface" },
|
|
}),
|
|
).toMatchObject({ ok: false, error: { _tag: "EvidenceIntegrityError" } });
|
|
});
|
|
|
|
it("refuses an object-dense borrowed capture before making a full schema clone", async () => {
|
|
const capture = analysisViewObjectDenseCapture();
|
|
expect(Buffer.byteLength(JSON.stringify(capture))).toBeLessThan(
|
|
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
|
);
|
|
const parent = analysisViewCaptureEvidence(capture);
|
|
const ledger = new EvidenceLedger();
|
|
const recorded = ledger.record(parent);
|
|
if (!recorded.ok) throw recorded.error;
|
|
const borrowed = ledger.forAnalysis(parent.evidence_id)!;
|
|
expect(Object.isFrozen(borrowed.normalized_result)).toBe(true);
|
|
for (const view of [
|
|
{ kind: "api-surface", limit: 1 },
|
|
{ kind: "environment-manifest" },
|
|
{ kind: "environment-state" },
|
|
] as const) {
|
|
const result = await inspectAnalysisView(
|
|
{
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view,
|
|
},
|
|
(id) => ledger.forAnalysis(id),
|
|
);
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisResourceConstraintError",
|
|
resource: "memory",
|
|
},
|
|
});
|
|
}
|
|
expect(ledger.forAnalysis(parent.evidence_id)).toBe(borrowed);
|
|
});
|
|
|
|
it("seals an inferred environment manifest and a derived manifest without templated groups", async () => {
|
|
const parent = analysisViewCaptureEvidence(
|
|
environmentManifestCaptureFixture(),
|
|
);
|
|
const inferred = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind: "environment-manifest", template_rules: ["opaque-token"] },
|
|
});
|
|
if (!inferred.ok) throw inferred.error;
|
|
expect(inferred.value.confidence).toBe("inferred");
|
|
expect(inferred.value.authority).toBe(parent.authority);
|
|
expect(inferred.value.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(inferred.value.parameters).toMatchObject({
|
|
view: {
|
|
kind: "environment-manifest",
|
|
template_rules: ["opaque-token"],
|
|
include_query_parameter_names: true,
|
|
},
|
|
});
|
|
expect(inferred.value.normalized_result).toMatchObject({
|
|
kind: "environment-manifest",
|
|
name: "grafana-example",
|
|
parent_evidence_id: parent.evidence_id,
|
|
});
|
|
expect(parseEvidence(inferred.value)).toEqual(inferred.value);
|
|
const literal = environmentManifestCaptureFixture();
|
|
literal.artifact.sha256 = null;
|
|
literal.records = [3, 4, 8].map((ordinal) => literal.records[ordinal]!);
|
|
const derived = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: analysisViewCaptureEvidence(literal) },
|
|
view: { kind: "environment-manifest" },
|
|
});
|
|
if (!derived.ok) throw derived.error;
|
|
expect(derived.value.confidence).toBe("derived");
|
|
expect(derived.value.subject).toBeNull();
|
|
expect(derived.value.normalized_result).toMatchObject({
|
|
templated_groups: 0,
|
|
tools: [{ name: "get_org" }, { name: "get_search" }, { name: "get_user" }],
|
|
limitations: expect.arrayContaining([
|
|
"Parent contains an ordinal subset; the manifest covers only retained records.",
|
|
]),
|
|
});
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
|
|
view: { kind: "environment-manifest" },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisUnsupportedTargetError" },
|
|
});
|
|
});
|
|
|
|
it("seals an inferred environment state whose values are the recorded ones", async () => {
|
|
const parent = analysisViewCaptureEvidence(environmentStateCaptureFixture());
|
|
const sealed = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind: "environment-state", template_rules: ["opaque-token"] },
|
|
});
|
|
if (!sealed.ok) throw sealed.error;
|
|
expect(sealed.value.confidence).toBe("inferred");
|
|
expect(sealed.value.authority).toBe(parent.authority);
|
|
expect(sealed.value.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(sealed.value.parameters).toMatchObject({
|
|
view: { kind: "environment-state", template_rules: ["opaque-token"] },
|
|
});
|
|
expect(sealed.value.normalized_result).toMatchObject({
|
|
kind: "environment-state",
|
|
name: "grafana-example",
|
|
parent_evidence_id: parent.evidence_id,
|
|
timeline: "recorded-start-time",
|
|
});
|
|
expect(JSON.stringify(sealed.value.normalized_result)).toContain(
|
|
"probe folder",
|
|
);
|
|
expect(parseEvidence(sealed.value)).toEqual(sealed.value);
|
|
});
|
|
|
|
it.each([
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const)(
|
|
"rejects inline accessors before parsing a %s view",
|
|
async (kind) => {
|
|
let accessed = false;
|
|
const evidence = {
|
|
get normalized_result() {
|
|
accessed = true;
|
|
throw new Error("Evidence must be admitted before parsing");
|
|
},
|
|
};
|
|
const input = {
|
|
source: { kind: "inline", evidence },
|
|
view: { kind },
|
|
};
|
|
const parsed = inspectAnalysisViewInputSchema.parse(input);
|
|
if (parsed.source.kind !== "inline")
|
|
throw new Error("Expected inline input");
|
|
expect(parsed.source.evidence).toBe(evidence);
|
|
expect(await inspectAnalysisView(input)).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisInputError",
|
|
issues: [{ path: ["source", "evidence", "normalized_result"] }],
|
|
},
|
|
});
|
|
expect(accessed).toBe(false);
|
|
const ordinary = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: analysisViewCaptureEvidence() },
|
|
view: { kind },
|
|
});
|
|
expect(ordinary.ok).toBe(true);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const)(
|
|
"rejects nested, hidden and inherited inline accessors for %s",
|
|
async (kind) => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
let accessed = false;
|
|
const getter = () => {
|
|
accessed = true;
|
|
throw new Error("Inline accessors must remain inert");
|
|
};
|
|
const nested = {
|
|
get value() {
|
|
return getter();
|
|
},
|
|
};
|
|
const hidden = Object.defineProperty({}, "value", { get: getter });
|
|
const array = Object.defineProperty([null], 0, { get: getter });
|
|
const inherited: unknown = Object.create({
|
|
get value() {
|
|
return getter();
|
|
},
|
|
});
|
|
const cyclic: Record<string, unknown> = {};
|
|
cyclic["self"] = cyclic;
|
|
const cases: { data: unknown; path: (string | number)[] }[] = [
|
|
{ data: nested, path: ["value"] },
|
|
{ data: hidden, path: ["value"] },
|
|
{ data: array, path: [0] },
|
|
{ data: inherited, path: [] },
|
|
{ data: cyclic, path: ["self"] },
|
|
];
|
|
for (const { data, path } of cases) {
|
|
// A complete envelope reaches payload parsing and Evidence authentication.
|
|
const input = {
|
|
source: {
|
|
kind: "inline" as const,
|
|
evidence: { ...parent, raw_result: data },
|
|
},
|
|
view: { kind },
|
|
};
|
|
for (const result of [
|
|
await inspectAnalysisView(input),
|
|
inspectAnalysisViewValidated({
|
|
source: input.source,
|
|
view: inspectAnalysisViewInputSchema.parse(input).view,
|
|
}),
|
|
])
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisInputError",
|
|
issues: [{ path: ["source", "evidence", "raw_result", ...path] }],
|
|
},
|
|
});
|
|
}
|
|
expect(accessed).toBe(false);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
["own map", "map", false],
|
|
["own iterator", Symbol.iterator, false],
|
|
["own constructor", "constructor", false],
|
|
["inherited map", "map", true],
|
|
["inherited iterator", Symbol.iterator, true],
|
|
] as const)(
|
|
"rejects array %s accessors without invoking them",
|
|
async (_name, key, inherited) => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
let accessed = false;
|
|
const array: unknown[] = [];
|
|
const owner: object = inherited ? Object.create(Array.prototype) : array;
|
|
Object.defineProperty(owner, key, {
|
|
get() {
|
|
accessed = true;
|
|
throw new Error("Array behavior must remain inert");
|
|
},
|
|
});
|
|
if (inherited) Object.setPrototypeOf(array, owner);
|
|
for (const kind of [
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: { ...parent, raw_result: array } },
|
|
view: { kind },
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisInputError" },
|
|
});
|
|
}
|
|
expect(accessed).toBe(false);
|
|
},
|
|
);
|
|
|
|
it("rejects callable array overrides and subclass species before parsing", async () => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
let invoked = false;
|
|
const callback = () => {
|
|
invoked = true;
|
|
throw new Error("Array callbacks must remain inert");
|
|
};
|
|
class CustomArray extends Array<unknown> {
|
|
static override get [Symbol.species](): ArrayConstructor {
|
|
return callback();
|
|
}
|
|
}
|
|
for (const array of [
|
|
Object.defineProperty([], "map", { value: callback }),
|
|
Object.defineProperty([], Symbol.iterator, { value: callback }),
|
|
new CustomArray(),
|
|
])
|
|
for (const kind of [
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: { ...parent, raw_result: array } },
|
|
view: { kind },
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisInputError" },
|
|
});
|
|
}
|
|
expect(invoked).toBe(false);
|
|
});
|
|
|
|
it.each([
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const)("preserves ordinary inline Evidence for %s", async (kind) => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
const before = JSON.stringify(parent);
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind },
|
|
});
|
|
if (!result.ok) throw result.error;
|
|
expect(parseEvidence(result.value)).toEqual(result.value);
|
|
expect(result.value.evidence_links).toEqual([parent.evidence_id]);
|
|
expect(result.value.normalized_result).toMatchObject({
|
|
kind,
|
|
parent_evidence_id: parent.evidence_id,
|
|
});
|
|
expect(JSON.stringify(parent)).toBe(before);
|
|
expect(Object.isFrozen(parent)).toBe(false);
|
|
});
|
|
|
|
it("rejects executable constructor values before schema plain-object checks", async () => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
let invoked = false;
|
|
const constructor = () => undefined;
|
|
Object.defineProperty(constructor, "prototype", {
|
|
get() {
|
|
invoked = true;
|
|
throw new Error("Constructor metadata must remain inert");
|
|
},
|
|
});
|
|
for (const kind of [
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: {
|
|
kind: "inline",
|
|
evidence: { ...parent, raw_result: { constructor } },
|
|
},
|
|
view: { kind },
|
|
}),
|
|
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
|
}
|
|
expect(invoked).toBe(false);
|
|
});
|
|
|
|
it("rejects inline proxy values before reflection or parsing can run traps", async () => {
|
|
const parent = analysisViewCaptureEvidence();
|
|
let invoked = false;
|
|
const trap = () => {
|
|
invoked = true;
|
|
throw new Error("Proxy behavior must remain inert");
|
|
};
|
|
const revoked = Proxy.revocable([], {});
|
|
revoked.revoke();
|
|
for (const value of [
|
|
new Proxy({}, { getPrototypeOf: trap, ownKeys: trap, get: trap }),
|
|
new Proxy(() => undefined, { get: trap }),
|
|
revoked.proxy,
|
|
])
|
|
for (const kind of [
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: { ...parent, raw_result: value } },
|
|
view: { kind },
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisInputError" },
|
|
});
|
|
}
|
|
expect(invoked).toBe(false);
|
|
});
|
|
|
|
it("keeps ignored array metadata inert through parsing and projection", async () => {
|
|
const capture = analysisViewCaptureFixture();
|
|
const parent = createEvidence(
|
|
{
|
|
path: capture.artifact.path,
|
|
sha256: capture.artifact.sha256!,
|
|
format: "file",
|
|
},
|
|
{ id: "fixture", name: "fixture", version: "1" },
|
|
{
|
|
operation: "inspect_web_network_capture",
|
|
parameters: { sensitive_value_count: 0 },
|
|
result: capture,
|
|
rawResult: [],
|
|
},
|
|
);
|
|
if (!Array.isArray(parent.raw_result)) throw new Error("Expected raw array");
|
|
const array = parent.raw_result;
|
|
let invoked = false;
|
|
const getter = () => {
|
|
invoked = true;
|
|
throw new Error("Ignored array metadata must remain inert");
|
|
};
|
|
for (let index = 0; index < 10_000; index += 1)
|
|
Object.defineProperty(array, `metadata-${index}`, { get: getter });
|
|
Object.defineProperty(array, Symbol("metadata"), { get: getter });
|
|
for (const kind of [
|
|
"summary",
|
|
"capture",
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind },
|
|
});
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.evidence_links).toEqual([parent.evidence_id]);
|
|
}
|
|
expect(invoked).toBe(false);
|
|
expect(parseEvidence(parent).raw_result).toEqual([]);
|
|
});
|
|
|
|
it("keeps inline-envelope admission live alongside capture validation and grouping", async () => {
|
|
// Each clone alone fits; both graphs coexist while the view is projected.
|
|
const capture = analysisViewObjectDenseCapture(40_000);
|
|
const parent = analysisViewCaptureEvidence(capture);
|
|
for (const kind of ["summary", "capture"] as const) {
|
|
const projected = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind },
|
|
});
|
|
if (!projected.ok) throw projected.error;
|
|
expect(projected.value.evidence_links).toEqual([parent.evidence_id]);
|
|
}
|
|
const retained = await inspectAnalysisView(
|
|
{
|
|
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
|
view: { kind: "api-surface" },
|
|
},
|
|
() => parent,
|
|
);
|
|
if (!retained.ok) throw retained.error;
|
|
expect(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view: { kind: "api-surface" },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
|
|
});
|
|
});
|
|
|
|
it("admits raw_result and parameters before authenticating a portable capture", async () => {
|
|
const dense = analysisViewObjectDenseCapture();
|
|
const parent = analysisViewCaptureEvidence();
|
|
for (const field of ["raw_result", "parameters"] as const)
|
|
for (const kind of [
|
|
"api-surface",
|
|
"environment-manifest",
|
|
"environment-state",
|
|
] as const) {
|
|
const result = await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: { ...parent, [field]: dense } },
|
|
view: { kind },
|
|
});
|
|
// Refuse expansion before hashing can report the deliberately stale ID.
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
|
|
});
|
|
}
|
|
});
|
|
|
|
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("inspectAnalysisView", () => {
|
|
const view = manifestView;
|
|
|
|
it("projects an Evidence file exactly as the same Evidence inline", async () => {
|
|
const parent = analysisViewCaptureEvidence(
|
|
environmentManifestCaptureFixture(),
|
|
);
|
|
const fromFile = await inspectAnalysisView({
|
|
source: { kind: "evidence-file", path: await writeEvidenceFile(parent) },
|
|
view,
|
|
});
|
|
const inline = await 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(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
|
|
});
|
|
const fromFile = await inspectAnalysisView({
|
|
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 inspectAnalysisView({
|
|
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 inspectAnalysisView({
|
|
source: { kind: "evidence-file", path: missing },
|
|
view,
|
|
}),
|
|
).toMatchObject({ ok: false, error: { _tag: "EvidenceFileError" } });
|
|
const notEvidence = await inspectAnalysisView({
|
|
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();
|
|
const reason = Object.freeze({ requested: "view-stop" });
|
|
controller.abort(reason);
|
|
const parent = analysisViewCaptureEvidence(
|
|
environmentManifestCaptureFixture(),
|
|
);
|
|
const result = await inspectAnalysisView(
|
|
{
|
|
source: {
|
|
kind: "evidence-file",
|
|
path: await writeEvidenceFile(parent),
|
|
},
|
|
view,
|
|
},
|
|
undefined,
|
|
{ signal: controller.signal },
|
|
);
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError" },
|
|
});
|
|
expect(result.ok ? undefined : result.error.cause).toBe(reason);
|
|
});
|
|
|
|
it("returns typed cancellation when a running file request is aborted", async () => {
|
|
const controller = new AbortController();
|
|
const reason = Object.freeze({ requested: "running-view-stop" });
|
|
const parent = analysisViewCaptureEvidence(
|
|
environmentManifestCaptureFixture(),
|
|
);
|
|
const path = await writeEvidenceFile(parent);
|
|
const running = inspectAnalysisView(
|
|
{ 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(reason));
|
|
const result = await running;
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError" },
|
|
});
|
|
expect(result.ok ? undefined : result.error.cause).toBe(reason);
|
|
});
|
|
});
|
|
|
|
describe("inspectAnalysisView scenario parents", () => {
|
|
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(
|
|
await inspectAnalysisView({
|
|
source: { kind: "inline", evidence: parent },
|
|
view,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisResourceConstraintError", resource: "memory" },
|
|
});
|
|
const fromFile = await inspectAnalysisView({
|
|
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,
|
|
});
|
|
});
|
|
});
|