fix(snapshot): preserve complete investigation revision histories (#1354)

Select residual unknown histories as complete units and retain referenced registry mutation Evidence regardless of the active target at edit time. Prune incompatible dependency histories atomically instead of retaining stale dispositions.

Verify public MCP save/read/reopen for verified, withdrawn, and out-of-scope resolutions, and document target scope rules.
This commit is contained in:
You Wish
2026-10-10 06:39:29 +08:00
committed by GitHub
parent f504c2a351
commit 1c0cc8a675
4 changed files with 322 additions and 46 deletions
+6
View File
@@ -96,6 +96,12 @@ an exact result when the target bytes, operation, parameters, provider and
settings match. Mutations and cursor-dependent calls are excluded from the
cache. Snapshot files are local and use owner-only permissions.
Snapshots retain eligible target-scoped question histories in full, including
mutation Evidence recorded while another target was active. Observations and
related questions must still belong to the saved target. If those dependencies
cannot be retained, the entire history is excluded instead of reverting the
question to an earlier revision or disposition.
```bash
rea analyze /absolute/path/to/program --provider ghidra --snapshot /absolute/path/to/analysis/program.json
# Repeat the same query to reuse its saved result.
+130
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "./evidence.js";
import { ANALYSIS_SNAPSHOT_TARGET } from "./analysisSnapshot.fixture.js";
import {
createEvidenceBundle,
createImmutableEvidenceBundle,
@@ -10,6 +11,7 @@ import {
import {
createResidualUnknown,
recordUnknownInputSchema,
updateResidualUnknown,
} from "./residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
@@ -46,12 +48,140 @@ const makeUnknown = (
},
});
return {
input,
evidence: mutation,
unknown: createResidualUnknown(input, mutation.evidence_id, scopeDigest),
};
};
describe("evidenceBundleForTarget", () => {
it("retains mutation evidence from other targets for complete revision histories", () => {
const first = makeUnknown(
"Target question updated elsewhere",
targetDigest,
);
const update = createEvidence(
{ ...ANALYSIS_SNAPSHOT_TARGET, sha256: foreignDigest },
provider,
{
predicateType: "rea.residual-unknown-mutation",
operation: "update_unknown",
parameters: {
unknown_id: first.unknown.unknown_id,
expected_revision: 1,
},
result: { status: "resolved" },
},
);
const resolved = updateResidualUnknown(
first.unknown,
{
...first.input,
unknown_id: first.unknown.unknown_id,
expected_revision: 1,
status: "resolved",
resolution: {
disposition: "withdrawn",
rationale: "Withdrawn by the analyst",
evidence_ids: [],
},
},
update.evidence_id,
);
const unrelated = makeUnknown("Unrelated foreign question", foreignDigest);
const bundle = parseEvidenceBundle(
createEvidenceBundle(
[first.evidence, update, unrelated.evidence],
[first.unknown, resolved, unrelated.unknown],
),
);
const projected = evidenceBundleForTarget(bundle, targetDigest);
expect(parseEvidenceBundle(projected)).toEqual(
createEvidenceBundle([first.evidence, update], [first.unknown, resolved]),
);
expect(evidenceBundleForTarget(projected, targetDigest)).toEqual(projected);
});
it.each(["evidence", "relationship"])(
"removes whole histories and their dependents when a revision requires foreign %s",
(excluded) => {
const first = makeUnknown(
"Target history with an excluded revision",
targetDigest,
);
const foreign = makeUnknown("Excluded foreign context", foreignDigest);
const evidence = createEvidence(
{ ...ANALYSIS_SNAPSHOT_TARGET, sha256: foreignDigest },
provider,
{ operation: "foreign_observation", parameters: {}, result: true },
);
const updated = updateResidualUnknown(
first.unknown,
{
...first.input,
unknown_id: first.unknown.unknown_id,
expected_revision: 1,
status: "investigating",
supporting_evidence_ids:
excluded === "evidence" ? [evidence.evidence_id] : [],
relationships:
excluded === "relationship"
? [{ type: "related-to", unknown_id: foreign.unknown.unknown_id }]
: [],
resolution: null,
},
first.evidence.evidence_id,
);
const resolved = updateResidualUnknown(
updated,
{
...first.input,
unknown_id: first.unknown.unknown_id,
expected_revision: 2,
status: "resolved",
resolution: {
disposition: "withdrawn",
rationale: "Foreign context removed from the latest revision",
evidence_ids: [],
},
},
first.evidence.evidence_id,
);
const child = makeUnknown(
"Dependent target history",
targetDigest,
first.unknown.unknown_id,
);
const unrelated = makeUnknown("Independent target history", targetDigest);
const bundle = parseEvidenceBundle(
createEvidenceBundle(
[
first.evidence,
foreign.evidence,
evidence,
child.evidence,
unrelated.evidence,
],
[
first.unknown,
updated,
resolved,
foreign.unknown,
child.unknown,
unrelated.unknown,
],
),
);
expect(
parseEvidenceBundle(evidenceBundleForTarget(bundle, targetDigest)),
).toEqual(
createEvidenceBundle([unrelated.evidence], [unrelated.unknown]),
);
},
);
});
describe("evidenceBundleForTarget relationship pruning", () => {
it("removes dependent unknowns when their foreign-scope root is excluded", () => {
const foreignRoot = makeUnknown("Foreign root", foreignDigest);
const child = makeUnknown(
+44 -45
View File
@@ -126,7 +126,7 @@ export const createEvidenceBundle = (
};
};
/** Restrict a bundle to records and complete unknown histories for one artifact. */
/** Retain target records and eligible complete unknown histories with their mutation evidence. */
export const evidenceBundleForTarget = (
bundle: EvidenceBundle,
sha256: string,
@@ -134,57 +134,56 @@ export const evidenceBundleForTarget = (
const recordsById = new Map(
bundle.records.map((record) => [record.evidence_id, record]),
);
const candidates = bundle.unknowns.filter(
({ scope_digest: scopeDigest }) => scopeDigest === sha256,
);
const retained = new Set<ResidualUnknown>();
const revisionsById = new Map<string, number>();
const dependents = new Map<string, Set<ResidualUnknown>>();
for (const unknown of candidates) {
const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids);
const evidenceAvailable = referencedEvidenceIds(unknown).every((id) => {
const record = recordsById.get(id);
return (
record?.subject?.digest.sha256 === sha256 ||
(mutationEvidenceIds.has(id) &&
record?.subject === null &&
record.predicate_type === "rea.residual-unknown-mutation")
);
const histories = new Map<string, ResidualUnknown[]>();
for (const unknown of bundle.unknowns) {
const history = histories.get(unknown.unknown_id) ?? [];
history.push(unknown);
histories.set(unknown.unknown_id, history);
}
const retained = new Set<string>();
const dependents = new Map<string, Set<string>>();
const relationships = new Map<string, Set<string>>();
for (const [id, history] of histories) {
const eligible = history.every((unknown) => {
if (unknown.scope_digest !== sha256) return false;
const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids);
return referencedEvidenceIds(unknown).every((evidenceId) => {
const record = recordsById.get(evidenceId);
// Mutation subjects record the target active at the time of an edit,
// which need not be the question's immutable investigation scope.
return (
record?.subject?.digest.sha256 === sha256 ||
(mutationEvidenceIds.has(evidenceId) &&
record?.predicate_type === "rea.residual-unknown-mutation")
);
});
});
if (!evidenceAvailable) continue;
retained.add(unknown);
revisionsById.set(
unknown.unknown_id,
(revisionsById.get(unknown.unknown_id) ?? 0) + 1,
if (!eligible) continue;
retained.add(id);
const relatedIds = new Set(
history.flatMap((unknown) =>
unknown.relationships.map(({ unknown_id }) => unknown_id),
),
);
for (const relatedId of new Set(
unknown.relationships.map(({ unknown_id: id }) => id),
)) {
const references =
dependents.get(relatedId) ?? new Set<ResidualUnknown>();
references.add(unknown);
relationships.set(id, relatedIds);
for (const relatedId of relatedIds) {
const references = dependents.get(relatedId) ?? new Set<string>();
references.add(id);
dependents.set(relatedId, references);
}
}
const pending: ResidualUnknown[] = [];
for (const unknown of retained)
if (
unknown.relationships.some(({ unknown_id: id }) => !revisionsById.has(id))
)
pending.push(unknown);
const pending: string[] = [];
for (const [id, relatedIds] of relationships)
if ([...relatedIds].some((relatedId) => !retained.has(relatedId)))
pending.push(id);
for (let index = 0; index < pending.length; index += 1) {
const unknown = pending[index];
if (unknown === undefined || !retained.delete(unknown)) continue;
const remaining = (revisionsById.get(unknown.unknown_id) ?? 1) - 1;
if (remaining > 0) {
revisionsById.set(unknown.unknown_id, remaining);
continue;
}
revisionsById.delete(unknown.unknown_id);
for (const dependent of dependents.get(unknown.unknown_id) ?? [])
pending.push(dependent);
const id = pending[index];
if (id === undefined || !retained.delete(id)) continue;
for (const dependent of dependents.get(id) ?? []) pending.push(dependent);
}
const unknowns = candidates.filter((unknown) => retained.has(unknown));
const unknowns = bundle.unknowns.filter((unknown) =>
retained.has(unknown.unknown_id),
);
const mutationIds = new Set(
unknowns.flatMap(({ mutation_evidence_ids: ids }) => ids),
);
@@ -24,6 +24,7 @@ import { ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { recordUnknownInputSchema } from "../../../src/domain/residualUnknown.js";
const identity = { id: "fixture", name: "Fixture", version: "1" } as const;
const profile = createAnalysisProfile(identity, { fixture: true });
@@ -217,6 +218,146 @@ describe("MCP composed workflow snapshot replay", () => {
});
});
describe("MCP investigation history snapshot replay", () => {
it.each(["verified", "withdrawn", "out-of-scope"] as const)(
"preserves a target's %s resolution recorded while another target is active",
async (disposition) => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
"rea-mcp-investigation-history-",
["first.hop", "second.hop"],
);
const firstPath = targetPaths[0];
const secondPath = targetPaths[1];
if (firstPath === undefined || secondPath === undefined)
throw new Error("Expected two investigation targets");
const session = createWorkflowSession(makeProvider([], []));
const { mcp } = await connectWorkflowMcp(
session,
"investigation-history",
);
await openWorkflowTarget(mcp, firstPath);
const input = recordUnknownInputSchema.parse({
question: "Has the string inventory been inspected for this target?",
severity: "medium",
domain: "investigation-history",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
});
const recorded = await mcp.callTool({
name: "record_unknown",
arguments: input,
});
expect(recorded.isError).not.toBe(true);
const unknown = toolContract("record_unknown").outputSchema.parse(
recorded.structuredContent,
).result;
const resolutionEvidenceIds: string[] = [];
if (disposition === "verified") {
const inspected = await mcp.callTool({
name: "list_strings",
arguments: {},
});
expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(
true,
);
resolutionEvidenceIds.push(
z
.string()
.parse(
toolContract("list_strings").outputSchema.parse(
inspected.structuredContent,
).evidence_id,
),
);
}
await openWorkflowTarget(mcp, secondPath);
const unrelated = await mcp.callTool({
name: "list_strings",
arguments: {},
});
expect(unrelated.isError).not.toBe(true);
const foreignEvidence = toolContract("list_strings").outputSchema.parse(
unrelated.structuredContent,
);
const updated = await mcp.callTool({
name: "update_unknown",
arguments: {
unknown_id: unknown.unknown_id,
expected_revision: unknown.revision,
status: "resolved",
severity: input.severity,
supporting_evidence_ids: resolutionEvidenceIds,
contradicting_evidence_ids: input.contradicting_evidence_ids,
required_authority: input.required_authority,
required_confidence: input.required_confidence,
required_environment: input.required_environment,
recommended_probes: input.recommended_probes,
relationships: input.relationships,
resolution: {
disposition,
rationale: "Disposition recorded after further investigation.",
evidence_ids: resolutionEvidenceIds,
},
},
});
expect(updated.isError, JSON.stringify(updated.content)).not.toBe(true);
const resolved = toolContract("update_unknown").outputSchema.parse(
updated.structuredContent,
).result;
expect(resolved).toMatchObject({
revision: 2,
status: "resolved",
scope_digest: unknown.scope_digest,
});
await openWorkflowTarget(mcp, firstPath);
const closed = await mcp.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
});
expect(closed.isError, JSON.stringify(closed.content)).not.toBe(true);
const snapshot = await readAnalysisSnapshot(snapshotPath);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.evidence_bundle.unknowns).toEqual([
unknown,
resolved,
]);
expect(snapshot.value.evidence_bundle.records).toContainEqual(
expect.objectContaining({
operation: "update_unknown",
subject: expect.objectContaining({ local_path: secondPath }),
}),
);
expect(snapshot.value.evidence_bundle.records).not.toContainEqual(
foreignEvidence,
);
const replay = createWorkflowSession(makeProvider([], []));
const { mcp: replayMcp } = await connectWorkflowMcp(
replay,
"investigation-history-replay",
);
const reopened = await replayMcp.callTool({
name: "open_binary",
arguments: { path: firstPath, snapshot_path: snapshotPath },
});
expect(reopened.isError, JSON.stringify(reopened.content)).not.toBe(true);
const listed = await replayMcp.callTool({
name: "list_unknowns",
arguments: {},
});
expect(listed.isError).not.toBe(true);
expect(
toolContract("list_unknowns").outputSchema.parse(
listed.structuredContent,
).result,
).toEqual({ items: [resolved], total: 1 });
},
);
});
const createWorkflowFiles = async (
prefix: string,
filenames: readonly string[],
@@ -322,7 +463,7 @@ const makeProvider = (
? ["fixture"]
: operation === "list_procedures"
? ["0x1000"]
: { "0x1000": "fixture" };
: [{ address: "0x1000", value: "fixture" }];
return ok(createAnalysisExecution(result, identity));
},
close: () => Promise.resolve(ok(null)),